@adatechnology/game-player 0.13.0 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.global.js.map +1 -1
- package/package.json +4 -4
package/dist/index.global.js.map
CHANGED
|
@@ -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/data/defaults.json","../src/needs.ts","../src/rng.ts","../src/vitals.ts","../src/player.ts","../src/physics-controller.ts","../src/foot-rest.ts","../src/walker.ts","../src/furniture-push.ts","../src/locales/index.ts","../src/bench/locale.ts","../src/bench/module.ts","../src/door-use.ts","../src/hands.ts","../src/lift.ts","../src/hand-math.ts","../src/item-grip.ts","../src/take-sequence.ts","../src/step-pose.ts"],"sourcesContent":["export { PLAYER_DEFAULTS, createPlayer, deriveVitals, drawWound } from './player'\nexport type { Player, PlayerCollider, PlayerOptions } from './player'\nexport { PLAYER_MASS_KG, PLAYER_PUSH_STRENGTH_NEWTONS, PLAYER_WALK_PUSH_NEWTONS, createPhysicsController } from './physics-controller'\nexport type { PhysicsControllerOptions, PhysicsPlayerController, PlayerPhysicsWorld } from './physics-controller'\nexport { footRestHeight } from './foot-rest'\nexport { WALKER_JUMP_SPEED, createWalker } from './walker'\nexport type { Walker, WalkerOptions, WalkerServices, WalkerStance } from './walker'\nexport { createRng } from './rng'\nexport { FURNITURE_PUSH_DEFAULTS, canPush, createFurniturePush, dragMarkFor, frictionFor, gripSecondsFor, pushAccelerationFor, pushSpeedFor, slipsOnTop } from './furniture-push'\nexport type { DragMark, FurniturePush, FurniturePushBlock, FurniturePushLoad, FurniturePushInput, FurniturePushPhase, FurniturePushRules, FurniturePushStep, FurniturePushTarget } from './furniture-push'\nexport { PLAYER_TEXT, playerTextOf } from './locales'\nexport type { PlayerText } from './locales'\n/** @deprecated import from '@adatechnology/game-player/testing' */\nexport { createPlayerTestModule } from './testing'\n/** @deprecated import from '@adatechnology/game-player/testing' */\nexport type { PlayerTestModule, PlayerTestModuleOptions } from './testing'\nexport type * from './types'\nexport { DOOR_ARM_REACH, DOOR_SHOULDER_HEIGHT, DOOR_USE_DEFAULTS, createDoorUse, swingSecondsFor } from './door-use'\nexport type { DoorUse, DoorUseBlock, DoorUseHand, DoorUsePhase, DoorUseRules, DoorUseStep, DoorUseTarget } from './door-use'\nexport { BELT_SLOT, HANDS_DEFAULTS, SLING_SLOT, SLOT_FALLBACKS, drawBackOf, interactionHandsFor, planHands } from './hands'\nexport type { BodyHand, HandWeapon, HandsMove, HandsMoveKind, HandsPlan, HandsRules, PlanHandsParams } from './hands'\nexport { LIFT_DEFAULTS, liftCheckFor } from './lift'\nexport type { LiftCheck, LiftRules, LiftVerdict } from './lift'\nexport { blendPoses, composePose, conjugateQuaternion, easeInOut, multiplyQuaternions, poseHolding, quaternionOfBasis, rotateVector } from './hand-math'\nexport type { Pose, QuatTuple, Vec3Tuple } from './hand-math'\nexport { ITEM_GRIP, gripOfItem, handPoseOnItem, itemPoseInHand } from './item-grip'\nexport type { ItemGrip } from './item-grip'\nexport { HANDS_TIMING, createTakeTimeline, planDrawSequence, planTakeSequence } from './take-sequence'\nexport type { HandsTiming, TakeProgress, TakeSequence, TakeStep, TakeStepKind, TakeTimeline } from './take-sequence'\nexport { STEP_POSE_DEFAULTS, createStepPose } from './step-pose'\nexport type { StepPose, StepPoseOptions, StepPosition } from './step-pose'\nexport { NEEDS_DEFAULTS, advanceNeeds, createNeedsState, isStarving, needsHoursOf, nourish } from './needs'\nexport type { NeedsRules, NeedsState, Nourishment } from './needs'\nexport { applyItemEffect, createBodyVitals } from './vitals'\nexport type { BodyVitals, BodyVitalsOptions, BodyVitalsState, ItemEffect, ItemEffectResult, VitalsBody } from './vitals'\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', '+', '-']\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 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 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 { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleItemUse, ModuleScenario, PlayerState, ItemSeat, 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","{\n \"sources\": {\n \"game\": \"specs/001-migracao-entregas-dos-times/artefatos/2UG1Mhe9LqJkQKKVsJkTWR/jogo.js\",\n \"attributes\": \"G 62004 FICHA (Personagens 3.2: every attribute 5, no traits)\",\n \"derived\": \"G 62005-62012 DERIV\",\n \"wounds\": \"G 62016 FERIDA (Personagens 3.7): share of each wound kind, and its infection chance (used only when an infection rule is on)\",\n \"infection\": \"G 62015 INFEC (the slice's accelerated clock: fever 30 s, delirium 70 s, death 120 s, reanimation 8 s after); G 68509 fever noise\",\n \"numbers\": \"G 68427-68640 player, playerUpdate, frontZombies, shove, knife; G 68678-68681 the aim spread modifiers; G 65507 walkCad\",\n \"needs\": \"G 57255 needs (fome 20, sede 20 at the start; 0 is fed, 100 starving), G 57271 useItem (food takes off its f, drink its s), G 57341-57344 (1 game hour = 50 s of the slice; hunger 2.5/h, 4/h running, thirst 4/h, times 1.1 - 0.02 x vigor; over 90 the body loses 0.2 health a second)\"\n },\n \"needs\": {\n \"start\": { \"hunger\": 20, \"thirst\": 20 },\n \"max\": 100,\n \"gameHourSeconds\": 50,\n \"hungerPerHour\": 2.5,\n \"hungerRunningPerHour\": 4,\n \"thirstPerHour\": 4,\n \"vigorBase\": 1.1,\n \"vigorPerPoint\": -0.02,\n \"starvingAt\": 90,\n \"starvingDamagePerSecond\": 0.2\n },\n \"attributes\": { \"strength\": 5, \"vigor\": 5, \"agility\": 5, \"perception\": 5, \"intellect\": 5, \"presence\": 5 },\n \"derived\": {\n \"maxHealth\": { \"base\": 70, \"terms\": [[\"vigor\", 6]] },\n \"maxStamina\": { \"base\": 40, \"terms\": [[\"vigor\", 6], [\"agility\", 4]] },\n \"runSpeed\": { \"base\": 5.2, \"terms\": [[\"agility\", 0.12]] },\n \"walkSpeed\": { \"base\": 1.6, \"terms\": [] },\n \"footstepNoise\": { \"base\": 100, \"terms\": [[\"agility\", -4]], \"divide\": 100 },\n \"composure\": { \"base\": 20, \"terms\": [[\"vigor\", 3], [\"presence\", 4]] }\n },\n \"wounds\": {\n \"scratch\": { \"share\": 0.6, \"infectionChance\": 0.06, \"bleeds\": false },\n \"laceration\": { \"share\": 0.3, \"infectionChance\": 0.22, \"bleeds\": true },\n \"bite\": { \"share\": 0.1, \"infectionChance\": 1, \"bleeds\": true }\n },\n \"infection\": {\n \"feverSeconds\": 30,\n \"deliriumSeconds\": 70,\n \"deathSeconds\": 120,\n \"reanimateSeconds\": 8,\n \"feverNoiseEvery\": 2,\n \"feverNoiseChance\": 0.5,\n \"feverNoiseRadius\": 10,\n \"feverNoiseVolume\": 2,\n \"feverSpeed\": 0.85,\n \"feverSpread\": 1.5\n },\n \"numbers\": {\n \"hurtFlash\": 0.4,\n \"hurtVolume\": 0.8,\n \"biteDamage\": 25,\n \"biteFlash\": 0.8,\n \"biteVolume\": 1.2,\n \"burnPerSecond\": 3,\n \"bleedPerSecond\": 0.15,\n \"grabSeconds\": 3,\n \"grabVolume\": 1,\n \"grabFollow\": 12,\n \"grabOffset\": 0.55,\n \"grabPushCost\": 6,\n \"grabPushMinStamina\": 5,\n \"grabPushVolume\": 1.5,\n \"grabPushes\": 6,\n \"grabPushStun\": 1.2,\n \"grabPushSpeed\": 3,\n \"grabKnifeChance\": 0.7,\n \"grabKnifeRegion\": 0,\n \"grabKnifeDamage\": 22,\n \"grabKnifeDistance\": 0.5,\n \"grabKnifeCut\": 0.7,\n \"drownDamage\": 30,\n \"drownFlash\": 0.8,\n \"noJawDamage\": 8,\n \"grabAttackCooldown\": 2,\n \"vaultSeconds\": 0.7,\n \"vaultCost\": 15,\n \"vaultHeight\": 1.9,\n \"vaultScanFrom\": 0.3,\n \"vaultScanTo\": 1.0,\n \"vaultScanStep\": 0.1,\n \"vaultLandFrom\": 0.4,\n \"vaultLandTo\": 1.4,\n \"vaultClearance\": 0.3,\n \"vaultCheckHeight\": 0.4,\n \"vaultNoise\": 6,\n \"vaultStartVolume\": 0.8,\n \"vaultLandVolume\": 1,\n \"crouchSpeed\": 1.0,\n \"walkFactor\": 1.35,\n \"aimSpeedCap\": 1.4,\n \"waterSpeed\": 0.55,\n \"runMinStamina\": 1,\n \"runDrain\": 12,\n \"regenMoving\": 4,\n \"regenStill\": 8,\n \"acceleration\": 10,\n \"heightMetres\": 1.8,\n \"crouchHeightRatio\": 0.65,\n \"radius\": 0.3,\n \"blockHeight\": 0.4,\n \"pushApartRadius\": 0.55,\n \"pushApartHeight\": 1.2,\n \"hipFollow\": 10,\n \"hipMinSpeed\": 0.3,\n \"hipLimit\": 0.9,\n \"backwardsBelow\": -0.1,\n \"cadenceBase\": 0.5,\n \"cadencePerSpeed\": 0.3,\n \"cadenceMinSpeed\": 0.05,\n \"turnFollow\": 12,\n \"stepEvery\": 0.75,\n \"stepMinSpeed\": 0.3,\n \"stepNoiseRun\": 8,\n \"stepNoiseWalk\": 3,\n \"stepNoiseCrouch\": 1,\n \"stepNoiseWater\": 2,\n \"stepVolumeRun\": 0.6,\n \"stepVolumeWalk\": 0.3,\n \"shoveCost\": 10,\n \"shoveVolume\": 1.2,\n \"shoveRange\": 1.6,\n \"shoveCone\": 0.3,\n \"shoveStun\": 0.9,\n \"shoveSpeed\": 2.5,\n \"meleeMinStamina\": 5,\n \"meleeCostLight\": 5,\n \"meleeCostHeavy\": 12,\n \"meleeHeavyKg\": 1.5,\n \"meleeVolume\": 0.6,\n \"meleeRangeBase\": 0.9,\n \"meleeCone\": 0.5,\n \"meleeHeadChance\": 0.35,\n \"meleeArmChance\": 0.5,\n \"meleeStrengthPerPoint\": 0.06,\n \"meleeStrengthBase\": 5,\n \"meleeCritToCut\": 60,\n \"panicGain\": 1.2,\n \"panicDecay\": 3,\n \"panicMax\": 100,\n \"panicSpreadAt\": 0.6,\n \"panicSpread\": 1.4,\n \"moveSpread\": 0.4\n },\n \"fist\": { \"damage\": 8, \"crit\": 0, \"reach\": 0.5, \"noise\": 1 }\n}\n","/**\n * Hunger and thirst of a body (the team game's `needs`, G 57255-57344): two levels from 0 (fed, quenched) to `max` (starving, parched) that rise with the game's\n * clock, faster when running and slower for a stronger body, and fall by what the body eats and drinks (`satiety` and `hydration` of an item, the thirst a litre\n * of a liquid quenches). Past `starvingAt` either one costs health every second. Pure and allocation-free: the host keeps one `NeedsState` and passes it in.\n */\nimport defaults from './data/defaults.json'\n\nexport type NeedsRules = typeof defaults.needs\n\n/** The rules the team game shipped. */\nexport const NEEDS_DEFAULTS: NeedsRules = defaults.needs\n\n/** Where a body stands: `hunger` and `thirst`, 0 fed and quenched, `NeedsRules.max` starving. */\nexport interface NeedsState {\n hunger: number\n thirst: number\n}\n\n/** What the body ate or drank: points of hunger (`satiety`) and of thirst (`hydration`) it takes off; a negative number adds (salted fish makes you thirsty). */\nexport interface Nourishment {\n readonly satiety?: number\n readonly hydration?: number\n}\n\n/** A fresh body's needs (`rules.start`). */\nexport const createNeedsState = (rules: NeedsRules = NEEDS_DEFAULTS): NeedsState => ({ hunger: rules.start.hunger, thirst: rules.start.thirst })\n\nconst clamp = (value: number, max: number): number => (value < 0 ? 0 : value > max ? max : value)\n\n/** Game hours `dt` seconds are for a body of `vigor` (the vigor factor of the team game: 1.1 − 0.02 × vigor; never below zero). */\nexport const needsHoursOf = (dt: number, vigor: number, rules: NeedsRules = NEEDS_DEFAULTS): number =>\n (Math.max(0, dt) / rules.gameHourSeconds) * Math.max(0, rules.vigorBase + rules.vigorPerPoint * vigor)\n\n/** Either need is past `starvingAt`. */\nexport const isStarving = (state: NeedsState, rules: NeedsRules = NEEDS_DEFAULTS): boolean => state.hunger > rules.starvingAt || state.thirst > rules.starvingAt\n\n/** Moves `state` on by `dt` seconds and answers the health it costs in that time (0 unless the body is starving or parched). */\nexport function advanceNeeds(state: NeedsState, dt: number, body: { readonly running?: boolean; readonly vigor: number }, rules: NeedsRules = NEEDS_DEFAULTS): number {\n const hours = needsHoursOf(dt, body.vigor, rules)\n state.hunger = clamp(state.hunger + (body.running ? rules.hungerRunningPerHour : rules.hungerPerHour) * hours, rules.max)\n state.thirst = clamp(state.thirst + rules.thirstPerHour * hours, rules.max)\n return isStarving(state, rules) ? rules.starvingDamagePerSecond * Math.max(0, dt) : 0\n}\n\n/** Takes what was eaten or drunk off `state` (kept within 0 and `max`) and answers how much each level moved (negative: it went down). */\nexport function nourish(state: NeedsState, food: Nourishment, rules: NeedsRules = NEEDS_DEFAULTS): { hunger: number; thirst: number } {\n const hunger = state.hunger\n const thirst = state.thirst\n state.hunger = clamp(hunger - (food.satiety ?? 0), rules.max)\n state.thirst = clamp(thirst - (food.hydration ?? 0), rules.max)\n return { hunger: state.hunger - hunger, thirst: state.thirst - thirst }\n}\n","const FNV_OFFSET = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\nconst MIX = 0x9e3779b1\n\n/** Deterministic mulberry32 generator; returns floats in [0, 1). */\nexport function createRng(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let mixed = Math.imul(state ^ (state >>> 15), state | 1)\n mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61)\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** A seed for the stream called `name`: the same seed gives each name its own sequence, so lightning never shifts the schedule. */\nexport function streamSeed(seed: number, name: string): number {\n let hash = FNV_OFFSET\n for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), FNV_PRIME) >>> 0\n return Math.imul((seed >>> 0) ^ hash, MIX) >>> 0\n}\n\nexport function createStream(seed: number, name: string): () => number {\n return createRng(streamSeed(seed, name))\n}\n\nexport function drawBetween(rng: () => number, range: readonly [min: number, max: number]): number {\n return range[0] + rng() * (range[1] - range[0])\n}\n","/**\n * What an item used in the hand does to the body (the team game's `useItem`, G 57269-57279): food and drink take their satiety and hydration off hunger and thirst,\n * a painkiller gives back health, a dressing stops the bleeding, alcohol or iodine cleans the last wound, a sedative takes the panic away. The effect comes as the\n * catalogue resolved it (`ModuleItemUse.effect` of game-contracts, from `resolveUse` of game-items), so the numbers are the item's own. `createBodyVitals` is the\n * same body for a host that has no `createPlayer` (a test room): health, bleeding, wounds, panic and the needs, on the same rules.\n */\nimport type { ModuleItemUse } from '@adatechnology/game-contracts'\n\nimport { NEEDS_DEFAULTS, advanceNeeds, createNeedsState, nourish } from './needs'\nimport type { NeedsRules, NeedsState } from './needs'\n\n/** The effect of an item as the catalogue gives it (`ModuleItemUse.effect`). */\nexport type ItemEffect = NonNullable<ModuleItemUse['effect']>\n\n/** The part of a body an item's effect changes: `createPlayer`'s state has it all, and so does `createBodyVitals`. */\nexport interface VitalsBody extends NeedsState {\n health: number\n bleeding: number\n panic: number\n wounds: string[]\n}\n\n/** What an effect did: `applied` false when it means nothing to the body (washing, a light) or found nothing to do (no wound to clean). */\nexport interface ItemEffectResult {\n readonly applied: boolean\n /** How much each moved (negative: down). */\n readonly health: number\n readonly hunger: number\n readonly thirst: number\n readonly stoppedBleeding: boolean\n /** The wound kind cleaned, if one was. */\n readonly cleaned?: string\n readonly calmed: boolean\n}\n\nconst NOTHING: ItemEffectResult = { applied: false, health: 0, hunger: 0, thirst: 0, stoppedBleeding: false, calmed: false }\n\nconst numberOf = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)\n\n/** Applies an item's effect to `body` and answers what changed. `maxHealth` caps a heal. */\nexport function applyItemEffect(body: VitalsBody, effect: ItemEffect, limits: { readonly maxHealth: number; readonly needs?: NeedsRules }): ItemEffectResult {\n switch (effect.id) {\n case 'consume_nutrition': {\n const moved = nourish(body, { satiety: numberOf(effect.satiety), hydration: numberOf(effect.hydration) }, limits.needs ?? NEEDS_DEFAULTS)\n return { ...NOTHING, applied: true, hunger: moved.hunger, thirst: moved.thirst }\n }\n case 'heal': {\n const before = body.health\n body.health = Math.min(limits.maxHealth, before + Math.max(0, numberOf(effect.params?.amount)))\n return { ...NOTHING, applied: true, health: body.health - before }\n }\n case 'stop_bleeding': {\n const stopped = body.bleeding > 0\n body.bleeding = 0\n return { ...NOTHING, applied: true, stoppedBleeding: stopped }\n }\n case 'clean_wound': {\n const cleaned = body.wounds.pop()\n return cleaned === undefined ? NOTHING : { ...NOTHING, applied: true, cleaned }\n }\n case 'calm': {\n const calmed = body.panic > 0\n body.panic = 0\n return { ...NOTHING, applied: true, calmed }\n }\n default:\n return NOTHING\n }\n}\n\nexport interface BodyVitalsOptions {\n /** Health the body starts with and can be healed to. Default 100. */\n readonly maxHealth?: number\n /** Health lost per second while bleeding (`numbers.bleedPerSecond` of the player, 0.15). */\n readonly bleedPerSecond?: number\n /** Vigor of the body (the attribute, default 5): a stronger body gets hungry and thirsty slower. */\n readonly vigor?: number\n readonly needs?: Partial<NeedsRules>\n}\n\nexport interface BodyVitalsState extends VitalsBody {\n alive: boolean\n /** Why it died (`hunger_thirst`, `bled_out`), empty while alive. */\n cause: string\n}\n\n/** A body's vitals without the rest of the player: the needs on the game clock, the bleeding, and the item effects. */\nexport interface BodyVitals {\n readonly state: BodyVitalsState\n readonly maxHealth: number\n readonly rules: NeedsRules\n /** Moves the body on `dt` seconds of the game. */\n update(dt: number, input?: { readonly running?: boolean }): void\n apply(effect: ItemEffect): ItemEffectResult\n reset(): void\n}\n\nexport function createBodyVitals(options: BodyVitalsOptions = {}): BodyVitals {\n const maxHealth = options.maxHealth ?? 100\n const bleedPerSecond = options.bleedPerSecond ?? 0.15\n const vigor = options.vigor ?? 5\n const rules: NeedsRules = { ...NEEDS_DEFAULTS, ...options.needs, start: { ...NEEDS_DEFAULTS.start, ...options.needs?.start } }\n const fresh = (): BodyVitalsState => ({ ...createNeedsState(rules), health: maxHealth, bleeding: 0, panic: 0, wounds: [], alive: true, cause: '' })\n const state = fresh()\n return {\n state,\n maxHealth,\n rules,\n update(dt, input = {}) {\n if (!state.alive || dt <= 0) return\n state.health -= advanceNeeds(state, dt, { running: input.running ?? false, vigor }, rules)\n if (state.bleeding > 0) state.health -= bleedPerSecond * dt\n if (state.health <= 0) {\n state.health = 0\n state.alive = false\n state.cause = state.bleeding > 0 ? 'bled_out' : 'hunger_thirst'\n }\n },\n apply: (effect) => (state.alive ? applyItemEffect(state, effect, { maxHealth, needs: rules }) : NOTHING),\n reset() {\n Object.assign(state, fresh())\n },\n }\n}\n","import { SWING_LEAD_SECONDS, footstepSoundId, hitSoundId, landSoundId, surfaceOfMaterial, swingSoundId } from '@adatechnology/game-contracts'\nimport type { BlowId, BodyFoleyId, SurfaceId } from '@adatechnology/game-contracts'\n\nimport defaults from './data/defaults.json'\nimport { NEEDS_DEFAULTS, advanceNeeds } from './needs'\nimport type { NeedsRules } from './needs'\nimport { createRng } from './rng'\nimport { applyItemEffect } from './vitals'\nimport type { ItemEffect, ItemEffectResult } from './vitals'\nimport type {\n Attributes,\n DeathCause,\n Derived,\n DerivedFormulas,\n DerivedId,\n InfectionRule,\n LinearFormula,\n MeleeItem,\n PlayerAction,\n PlayerCrowd,\n PlayerEventMap,\n PlayerEventName,\n PlayerInput,\n PlayerMessageId,\n PlayerNumbers,\n PlayerSave,\n PlayerSoundId,\n PlayerState,\n PlayerWorld,\n WoundTable,\n} from './types'\n\nexport const PLAYER_DEFAULTS = defaults as unknown as {\n readonly sources: Readonly<Record<string, string>>\n readonly attributes: Attributes\n readonly derived: DerivedFormulas\n readonly wounds: WoundTable\n readonly infection: InfectionRule\n readonly numbers: PlayerNumbers\n readonly fist: MeleeItem\n}\n\nexport type PlayerOptions = {\n /** The random stream (the game passes its single stream). Default `createRng(seed)`. */\n readonly random?: () => number\n readonly seed?: number\n /** The sheet: every attribute 5 by default. */\n readonly attributes?: Partial<Attributes>\n readonly derived?: Partial<DerivedFormulas>\n readonly wounds?: WoundTable\n /** An individual infection (`true` uses the defaults; an object patches them). Off by default: the normal world comes first. */\n readonly infection?: boolean | Partial<InfectionRule>\n readonly numbers?: Partial<PlayerNumbers>\n /** Hunger and thirst (`NEEDS_DEFAULTS`, the team game's): an object patches them, `false` keeps them still. */\n readonly needs?: boolean | Partial<NeedsRules>\n readonly fist?: MeleeItem\n readonly position?: { readonly x?: number; readonly z?: number; readonly yaw?: number }\n /** Standing skull-top height in metres (default `numbers.heightMetres`, 1.80 m). Scales collider height and radius (Spec 012 R3/H5). */\n readonly heightMetres?: number\n readonly world?: PlayerWorld\n}\n\n/** Player capsule/cylinder collider dimensions in metres (follows standing vs crouched state and `heightMetres`). */\nexport type PlayerCollider = {\n readonly heightMetres: number\n readonly radiusMetres: number\n}\n\nexport type Player = {\n readonly state: PlayerState\n /** Declared standing height in metres. */\n readonly heightMetres: number\n /** Current collider height and radius in metres (adapts to crouch and `heightMetres`). */\n collider(): PlayerCollider\n readonly attributes: Attributes\n readonly derived: Derived\n readonly numbers: PlayerNumbers\n readonly infection: InfectionRule | null\n /** The hunger and thirst rules, or null when they are off. */\n readonly needs: NeedsRules | null\n /** An item used in the hand (`ModuleItemUse.effect`): food and drink feed, a painkiller heals, a dressing stops the bleeding. */\n use(effect: ItemEffect): ItemEffectResult\n update(dt: number, input?: PlayerInput, world?: PlayerWorld): void\n /** A hit that opens a wound (drawn from the wound table) and may infect. `by` is the agent that hit, if any. */\n hurt(amount: number, by?: number): void\n /** A bite: damage, bleeding, a bite wound and (with an infection rule) the infection. */\n bite(by?: number): void\n grab(by: number, noJaw?: boolean, drown?: boolean): void\n release(): void\n knock(seconds: number): void\n infect(source: string): void\n /** Kills the player with a cause (the host's deaths: a fall, a fire). */\n die(cause: DeathCause): void\n /** Infection stage: `none`, `malaise`, `fever`, `delirium`. */\n stage(): 'none' | 'malaise' | 'fever' | 'delirium'\n /** Seconds the infection has left, or null. */\n timeLeft(): number | null\n /** What the player's state does to aim spread (panic, fever, moving); the weapon multiplies its own spread by it. */\n spreadFactor(): number\n /** The agents in front (nearest first) within `range` m and a cone of `cosMin`, as `[distance, index]`. */\n front(range: number, cosMin: number, yaw: number, crowd?: PlayerCrowd): [number, number][]\n on<K extends PlayerEventName>(event: K, listener: (event: PlayerEventMap[K]) => void): () => void\n save(): PlayerSave\n load(save: PlayerSave): void\n /** The world `update` uses when it is given none. */\n setWorld(world: PlayerWorld): void\n}\n\nconst TAU_APPROX = 6.2832\n\nconst evaluate = (formula: LinearFormula, attributes: Attributes): number => {\n let value = formula.base\n for (const [attribute, coefficient] of formula.terms) value += coefficient * attributes[attribute]\n return formula.divide === undefined ? value : value / formula.divide\n}\n\n/** The derived values of a sheet (the game's `DERIV`). */\nexport const deriveVitals = (attributes: Attributes, formulas: DerivedFormulas = PLAYER_DEFAULTS.derived): Derived => {\n const out = {} as Record<DerivedId, number>\n for (const id of Object.keys(formulas) as DerivedId[]) out[id] = evaluate(formulas[id], attributes)\n return out\n}\n\n/** Which wound a hit opens: one draw, the kinds in the listed order, the last one takes the rest (the game's `FERIDA` draw). */\nexport const drawWound = (wounds: WoundTable, random: () => number): string => {\n const kinds = Object.keys(wounds)\n const draw = random()\n let acc = 0\n for (let k = 0; k < kinds.length - 1; k++) {\n acc += wounds[kinds[k]!]!.share\n if (draw < acc) return kinds[k]!\n }\n return kinds[kinds.length - 1]!\n}\n\nconst clamp = (v: number, a: number, b: number): number => (v < a ? a : v > b ? b : v)\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\nconst freshState = (derived: Derived, position: PlayerOptions['position'], needs: NeedsRules | null): PlayerState => ({\n x: position?.x ?? 0,\n z: position?.z ?? 0,\n y: 0,\n vx: 0,\n vz: 0,\n yaw: position?.yaw ?? 0,\n floor: 0,\n alive: true,\n turned: false,\n health: derived.maxHealth,\n stamina: derived.maxStamina,\n hunger: needs?.start.hunger ?? 0,\n thirst: needs?.start.thirst ?? 0,\n crouch: false,\n running: false,\n stepTimer: 0,\n phase: 0,\n hip: 0,\n grabbedBy: -1,\n grabTimer: 0,\n grabPushes: 0,\n grabNoJaw: false,\n grabDrown: false,\n infected: false,\n infectionTime: 0,\n infectionSource: '',\n wounds: [],\n bleeding: 0,\n blind: 0,\n screamBoost: 0,\n panic: 0,\n hurtFlash: 0,\n deathTime: 0,\n cause: '',\n downTimer: 0,\n burnTimer: 0,\n scentTimer: 0,\n vaultTimer: 0,\n vault: null,\n})\n\n/**\n * The player body: a literal port of the team game's `player` and `playerUpdate` (G 68427-68640) with the world, the crowd and the input as\n * arguments instead of globals. The draws on `random` happen in the game's order (wound kind, infection, the fever cough, the knife when grabbed,\n * the melee region), so a game that passes its own stream keeps its sequence.\n */\nexport function createPlayer(options: PlayerOptions = {}): Player {\n const random = options.random ?? createRng(options.seed ?? 1)\n const attributes: Attributes = { ...PLAYER_DEFAULTS.attributes, ...options.attributes }\n const formulas: DerivedFormulas = { ...PLAYER_DEFAULTS.derived, ...options.derived }\n const derived = deriveVitals(attributes, formulas)\n const numbers: PlayerNumbers = { ...PLAYER_DEFAULTS.numbers, ...options.numbers }\n const heightMetres = options.heightMetres ?? numbers.heightMetres\n if (!Number.isFinite(heightMetres) || heightMetres < 0.8 || heightMetres > 3.0) {\n throw new RangeError(`Player height ${String(heightMetres)} m is outside supported range [0.8, 3.0] m.`)\n }\n const heightScale = heightMetres / numbers.heightMetres\n const wounds = options.wounds ?? PLAYER_DEFAULTS.wounds\n const infection: InfectionRule | null =\n options.infection === undefined || options.infection === false ? null : options.infection === true ? PLAYER_DEFAULTS.infection : { ...PLAYER_DEFAULTS.infection, ...options.infection }\n const needs: NeedsRules | null =\n options.needs === false ? null : options.needs === undefined || options.needs === true ? NEEDS_DEFAULTS : { ...NEEDS_DEFAULTS, ...options.needs, start: { ...NEEDS_DEFAULTS.start, ...options.needs.start } }\n const fist = options.fist ?? PLAYER_DEFAULTS.fist\n const listeners = new Map<PlayerEventName, Set<(event: never) => void>>()\n let P = freshState(derived, options.position, needs)\n // the controller's feet, read every step it walks: a vault lifts the body over them\n const feet = new Float64Array(3)\n let defaultWorld: PlayerWorld = options.world ?? {}\n let world: PlayerWorld = defaultWorld\n\n const emit = <K extends PlayerEventName>(event: K, payload: PlayerEventMap[K]): void => {\n const set = listeners.get(event)\n if (set) for (const listener of set) (listener as (event: PlayerEventMap[K]) => void)(payload)\n }\n const sound = (id: PlayerSoundId, volume: number, ids: readonly BodyFoleyId[], surface?: SurfaceId, at?: readonly number[]): void =>\n emit('sound', { sound: id, ids, volume, position: [P.x, P.y, P.z], ...(surface ? { surface } : {}), ...(at ? { at } : {}) })\n // what is under the feet: the host's word this frame, else the world's, else concrete; water wins over everything\n let surfaceHint: string | undefined\n const surfaceHere = (): SurfaceId => (inWater(P.x, P.z) ? 'water' : surfaceOfMaterial(surfaceHint ?? world.surfaceAt?.(P.x, P.z)))\n // set by the first `footfall` the host sends: from then on its feet, not the stride timer, decide the footsteps\n let hostFeet = false\n const blowOf = (item: MeleeItem): BlowId => item.blow ?? (item === fist ? 'punch' : (item.crit ?? 0) > 0 ? 'blade' : 'blunt')\n const noise = (x: number, z: number, radius: number): void => emit('noise', { x, z, radius })\n const message = (id: PlayerMessageId | DeathCause, seconds: number): void => emit('message', { id, seconds })\n const inWater = (x: number, z: number): boolean => world.inWater?.(x, z) ?? false\n const solidAt = (x: number, z: number, y: number): boolean => world.solidAt?.(x, z, y) ?? false\n const cellKind = (x: number, z: number): number => world.cellKind?.(x, z) ?? 0\n const blocked = (x: number, z: number): boolean => (world.blocked ? world.blocked(x, z) : solidAt(x, z, numbers.blockHeight))\n const chanceOf = (kind: string): number => infection?.chances?.[kind] ?? wounds[kind]?.infectionChance ?? 0\n\n const die = (cause: DeathCause): void => {\n if (!P.alive) return\n P.alive = false\n P.cause = cause\n P.deathTime = 0\n P.grabbedBy = -1\n message(cause, 6)\n emit('died', { cause })\n }\n const infect = (source: string): void => {\n if (P.infected || !infection) return\n P.infected = true\n P.infectionTime = 0\n P.infectionSource = source\n emit('infected', { source })\n }\n const release = (how: PlayerEventMap['released']['how'] = 'free'): void => {\n const by = P.grabbedBy\n P.grabbedBy = -1\n if (by >= 0) emit('released', { by, how })\n }\n const hurt = (amount: number): void => {\n if (!P.alive) return\n P.health -= amount\n P.hurtFlash = numbers.hurtFlash\n sound('flesh', numbers.hurtVolume, ['player_hurt'])\n const kind = drawWound(wounds, random)\n P.wounds.push(kind)\n if (wounds[kind]?.bleeds) P.bleeding = 1\n emit('hurt', { amount, wound: kind })\n if (infection && !P.infected && random() < chanceOf(kind)) infect(kind)\n if (P.health <= 0) die(P.infected ? 'infected' : 'killed')\n }\n const bite = (): void => {\n P.health -= numbers.biteDamage\n P.hurtFlash = numbers.biteFlash\n P.bleeding = 1\n P.wounds.push('bite')\n sound('flesh', numbers.biteVolume, ['bite', 'player_hurt'])\n emit('hurt', { amount: numbers.biteDamage, wound: 'bite' })\n infect('bite')\n message('bitten', 5)\n if (P.health <= 0) die('bitten_to_death')\n }\n const grab = (by: number, noJaw = false, drown = false): void => {\n P.grabbedBy = by\n P.grabTimer = numbers.grabSeconds\n P.grabPushes = 0\n P.grabNoJaw = noJaw\n P.grabDrown = drown\n message(drown ? 'grabbed_drown' : 'grabbed', 3)\n sound('flesh', numbers.grabVolume, ['grab'])\n emit('grabbed', { by, noJaw, drown })\n }\n\n const front = (range: number, cosMin: number, yaw: number, crowd: PlayerCrowd | undefined = world.crowd): [number, number][] => {\n const out: [number, number][] = []\n if (!crowd) return out\n const fx = -Math.sin(yaw)\n const fz = -Math.cos(yaw)\n const n = crowd.count()\n for (let i = 0; i < n; i++) {\n if (!crowd.active(i) || crowd.floor(i) !== P.floor) continue\n const ex = crowd.x(i) - P.x\n const ez = crowd.z(i) - P.z\n const d = Math.hypot(ex, ez)\n if (d < range && (ex * fx + ez * fz) / (d || 1) > cosMin) out.push([d, i])\n }\n return out.sort((a, b) => a[0] - b[0])\n }\n\n const shove = (yaw: number): void => {\n sound('step', numbers.shoveVolume, ['shove_two_hands'])\n const crowd = world.crowd\n const targets: number[] = []\n for (const [d, i] of front(numbers.shoveRange, numbers.shoveCone, yaw)) {\n crowd!.stun(i, numbers.shoveStun, ((crowd!.x(i) - P.x) / d) * numbers.shoveSpeed, ((crowd!.z(i) - P.z) / d) * numbers.shoveSpeed)\n targets.push(i)\n }\n emit('shove', { targets })\n }\n\n const melee = (item: MeleeItem, yaw: number): void => {\n const t = front(numbers.meleeRangeBase + (item.reach ?? 0), numbers.meleeCone, yaw)[0]\n const blow = blowOf(item)\n const swing = swingSoundId(blow)\n if (!t) {\n sound('flesh', numbers.meleeVolume, swing ? [swing] : [])\n noise(P.x, P.z, item.noise || 1)\n return\n }\n const crowd = world.crowd!\n const i = t[1]\n // a blow to the head is x3 in melee; on the ground or crawling it is an execution\n const region = crowd.down(i) ? 0 : random() < numbers.meleeHeadChance ? 0 : random() < numbers.meleeArmChance ? 1 : 2 + Math.floor(random() * 2)\n const hit = hitSoundId(blow, region === 0 ? 'head' : 'body')\n if (swing) sound('flesh', numbers.meleeVolume, [swing, hit], undefined, [0, SWING_LEAD_SECONDS[blow]])\n else sound('flesh', numbers.meleeVolume, [hit])\n noise(P.x, P.z, item.noise || 1)\n const damage = item.damage * (1 + (attributes.strength - numbers.meleeStrengthBase) * numbers.meleeStrengthPerPoint)\n const cut = Math.min(1, (item.crit || 0) / numbers.meleeCritToCut)\n crowd.damage(i, { region, amount: damage, distance: t[0], cut })\n emit('melee', { target: i, region, damage, distance: t[0], cut })\n }\n\n const update = (dt: number, input: PlayerInput = {}, frameWorld?: PlayerWorld): void => {\n world = frameWorld ?? defaultWorld\n surfaceHint = input.surface\n if (!P.alive) {\n P.deathTime += dt\n if (P.infected && infection && !P.turned && P.deathTime >= infection.reanimateSeconds) {\n P.turned = true\n emit('turned', { x: P.x, z: P.z, floor: P.floor })\n }\n return\n }\n const pressed: Partial<Record<PlayerAction, boolean>> = { ...input.pressed }\n const wasPressed = (action: PlayerAction): boolean => {\n const v = pressed[action] === true\n pressed[action] = false\n return v\n }\n const viewYaw = input.yaw ?? 0\n const crowd = world.crowd\n P.screamBoost = Math.max(0, P.screamBoost - dt)\n P.blind = Math.max(0, P.blind - dt)\n P.hurtFlash = Math.max(0, P.hurtFlash - dt)\n // infection on its own clock\n if (P.infected && infection) {\n const before = P.infectionTime\n P.infectionTime += dt\n if (before <= infection.feverSeconds && P.infectionTime > infection.feverSeconds) emit('stage', { stage: 'fever' })\n if (before <= infection.deliriumSeconds && P.infectionTime > infection.deliriumSeconds) emit('stage', { stage: 'delirium' })\n const every = 1 / infection.feverNoiseEvery\n if (P.infectionTime > infection.feverSeconds && Math.floor(P.infectionTime * every) !== Math.floor((P.infectionTime - dt) * every) && random() < infection.feverNoiseChance) {\n noise(P.x, P.z, infection.feverNoiseRadius)\n sound('step', infection.feverNoiseVolume, ['cloth_rustle'])\n }\n if (P.infectionTime > infection.deathSeconds) {\n P.health = 0\n die('infection')\n return\n }\n }\n if (P.burnTimer > 0) {\n P.burnTimer -= dt\n P.health -= numbers.burnPerSecond * dt\n if (inWater(P.x, P.z)) P.burnTimer = 0\n }\n P.scentTimer = Math.max(0, P.scentTimer - dt)\n if (P.bleeding) {\n P.health -= dt * numbers.bleedPerSecond\n if (input.bandage && P.bleeding) {\n P.bleeding = 0\n message('bandaged', 2)\n }\n }\n if (needs) P.health -= advanceNeeds(P, dt, { running: P.running, vigor: attributes.vigor }, needs)\n if (P.health <= 0) {\n die(P.infected ? 'infected' : P.bleeding ? 'bled_out' : 'hunger_thirst')\n return\n }\n // grabbed: seconds to react\n if (P.grabbedBy >= 0) {\n const i = P.grabbedBy\n P.grabTimer -= dt\n if (crowd) {\n const k = 1 - Math.exp(-dt * numbers.grabFollow) // glued to the body without a jump\n crowd.hold(i, P.x - Math.sin(P.yaw) * numbers.grabOffset, P.z - Math.cos(P.yaw) * numbers.grabOffset, k, P.x, P.z)\n }\n if (wasPressed('push') && P.stamina > numbers.grabPushMinStamina) {\n P.grabPushes++\n P.stamina -= numbers.grabPushCost\n sound('step', numbers.grabPushVolume, ['shove_two_hands'])\n }\n if (wasPressed('knife')) {\n if (random() < numbers.grabKnifeChance) {\n crowd?.damage(i, { region: numbers.grabKnifeRegion, amount: numbers.grabKnifeDamage, distance: numbers.grabKnifeDistance, cut: numbers.grabKnifeCut })\n message('knife_head', 1.5)\n release('knife')\n return\n } else message('knife_miss', 1)\n }\n if (P.grabPushes >= numbers.grabPushes) {\n crowd?.stun(i, numbers.grabPushStun, -Math.sin(viewYaw) * numbers.grabPushSpeed, -Math.cos(viewYaw) * numbers.grabPushSpeed)\n release('push')\n message('pushed_off', 1.2)\n return\n }\n if (P.grabTimer <= 0) {\n if (P.grabDrown) {\n P.health -= numbers.drownDamage\n P.hurtFlash = numbers.drownFlash\n message('drowning', 2)\n if (P.health <= 0) {\n die('drowned')\n return\n }\n P.grabTimer = numbers.grabSeconds\n P.grabPushes = 0\n return\n }\n if (P.grabNoJaw) {\n hurt(numbers.noJawDamage)\n message('no_jaw', 2)\n } else bite()\n crowd?.chase(i, numbers.grabAttackCooldown)\n release(P.grabNoJaw ? 'scratch' : 'bite')\n }\n return\n }\n // knocked down\n if (P.downTimer > 0) {\n P.downTimer -= dt\n P.vx = P.vz = 0\n if (P.downTimer <= 0) message('stood_up', 0.8)\n return\n }\n if (world.busy?.(dt)) return\n // vaulting a low wall\n if (P.vaultTimer > 0 && P.vault) {\n P.vaultTimer -= dt\n const k = 1 - P.vaultTimer / numbers.vaultSeconds\n P.x = lerp(P.vault[0], P.vault[2], k)\n P.z = lerp(P.vault[1], P.vault[3], k)\n P.y = feet[1] + Math.sin(k * Math.PI) * numbers.vaultHeight\n if (P.vaultTimer <= 0) {\n P.y = feet[1]\n world.controller?.teleport(P.x, P.y, P.z)\n noise(P.x, P.z, numbers.vaultNoise)\n const surface = surfaceHere()\n sound('step', numbers.vaultLandVolume, [landSoundId(surface, 0)], surface)\n }\n return\n }\n if (wasPressed('vault') && P.stamina > numbers.vaultCost && (world.canVault?.() ?? !P.floor)) {\n const fx0 = -Math.sin(viewYaw)\n const fz0 = -Math.cos(viewYaw)\n for (let a = numbers.vaultScanFrom; a <= numbers.vaultScanTo; a += numbers.vaultScanStep) {\n const c = cellKind(P.x + fx0 * a, P.z + fz0 * a)\n if (c === 2) {\n for (let e = a + numbers.vaultLandFrom; e <= a + numbers.vaultLandTo; e += numbers.vaultScanStep) {\n const ex = P.x + fx0 * e\n const ez = P.z + fz0 * e\n if (!solidAt(ex, ez, numbers.vaultCheckHeight) && !solidAt(ex + fx0 * numbers.vaultClearance, ez + fz0 * numbers.vaultClearance, numbers.vaultCheckHeight)) {\n P.vault = [P.x, P.z, ex, ez]\n P.vaultTimer = numbers.vaultSeconds\n P.stamina -= numbers.vaultCost\n sound('step', numbers.vaultStartVolume, ['jump'])\n emit('vault', { from: [P.x, P.z], to: [ex, ez] })\n return\n }\n }\n break\n }\n if (c > 0 && c !== 3) break\n }\n }\n // movement\n const f = input.forward ?? 0\n const s = input.right ?? 0\n if (wasPressed('crouch')) P.crouch = !P.crouch\n const want = f || s\n P.running = !!(input.run && want && P.stamina > numbers.runMinStamina && !input.aim && !P.crouch)\n const fever = P.infected && infection !== null && P.infectionTime > infection.feverSeconds\n let sp = P.running ? derived.runSpeed : P.crouch ? numbers.crouchSpeed : derived.walkSpeed * numbers.walkFactor\n if (fever) sp *= infection!.feverSpeed\n if (input.aim) sp = Math.min(sp, numbers.aimSpeedCap)\n const wet = inWater(P.x, P.z)\n if (wet) sp *= numbers.waterSpeed\n if (P.running) P.stamina = Math.max(0, P.stamina - numbers.runDrain * dt)\n else P.stamina = Math.min(derived.maxStamina, P.stamina + (want ? numbers.regenMoving : numbers.regenStill) * dt)\n const fx = -Math.sin(viewYaw)\n const fz = -Math.cos(viewYaw)\n const mx = fx * f - fz * s\n const mz = fz * f + fx * s\n const ml = Math.hypot(mx, mz) || 1\n const tvx = want ? (mx / ml) * sp : 0\n const tvz = want ? (mz / ml) * sp : 0\n P.vx = lerp(P.vx, tvx, Math.min(1, dt * numbers.acceleration))\n P.vz = lerp(P.vz, tvz, Math.min(1, dt * numbers.acceleration))\n const controller = world.controller\n if (controller) {\n controller.move(P.vx, P.vz, dt)\n controller.read(feet)\n P.x = feet[0] ?? P.x\n P.y = feet[1] ?? P.y\n P.z = feet[2] ?? P.z\n } else {\n const r = numbers.radius * heightScale\n const nx = P.x + P.vx * dt\n const nz = P.z + P.vz * dt\n if (!blocked(nx + Math.sign(P.vx) * r, P.z)) P.x = nx\n if (!blocked(P.x, nz + Math.sign(P.vz) * r)) P.z = nz\n }\n world.afterMove?.(P)\n // the player does not walk through the crowd: agents pressed against the body push it out\n if (crowd) {\n const n = crowd.count()\n const rr = numbers.pushApartRadius\n for (let i = 0; i < n; i++) {\n if (!crowd.active(i) || Math.abs(crowd.y(i) - P.y) > numbers.pushApartHeight) continue\n const ex = P.x - crowd.x(i)\n const ez = P.z - crowd.z(i)\n const e2 = ex * ex + ez * ez\n if (e2 < rr * rr && e2 > 1e-5) {\n const e = Math.sqrt(e2)\n const k = ((rr - e) / e) * 0.5\n if (!solidAt(P.x + ex * k, P.z + ez * k, numbers.blockHeight)) {\n P.x += ex * k\n P.z += ez * k\n }\n }\n }\n }\n const spd = Math.hypot(P.vx, P.vz)\n // the legs follow the move even with the torso on the aim; walking backwards flips the stride\n {\n const cy = Math.cos(P.yaw)\n const sy = Math.sin(P.yaw)\n const lx = P.vx * cy - P.vz * sy\n const lz = P.vx * sy + P.vz * cy\n const back = lz < numbers.backwardsBelow ? -1 : 1\n const hip = spd > numbers.hipMinSpeed ? clamp(Math.atan2(lx * back, lz * back), -numbers.hipLimit, numbers.hipLimit) : 0\n P.hip = P.hip + (hip - P.hip) * Math.min(1, dt * numbers.hipFollow)\n P.phase += dt * (spd < numbers.cadenceMinSpeed ? 0 : numbers.cadenceBase + numbers.cadencePerSpeed * spd) * back\n }\n // the body follows the view (fast, no snap); aiming or firing, at once\n {\n const target = viewYaw + Math.PI\n let dy = target - P.yaw\n dy -= Math.round(dy / TAU_APPROX) * TAU_APPROX\n P.yaw += input.aim || input.firing ? dy : dy * Math.min(1, dt * numbers.turnFollow)\n }\n // footsteps make noise: walk 3 m, run 8 m, crouched 1 m (x the sheet's footstep noise, x2 in water)\n // the host's feet (`input.footfall`) once it sends them, else the stride timer\n if (input.footfall) hostFeet = true\n P.stepTimer -= dt * spd\n const stepNow = hostFeet ? input.footfall === true : P.stepTimer <= 0 && spd > numbers.stepMinSpeed\n if (stepNow) {\n P.stepTimer = numbers.stepEvery\n noise(P.x, P.z, (P.running ? numbers.stepNoiseRun : P.crouch ? numbers.stepNoiseCrouch : numbers.stepNoiseWalk) * derived.footstepNoise * (wet ? numbers.stepNoiseWater : 1))\n const surface = surfaceHere()\n sound('step', P.running ? numbers.stepVolumeRun : numbers.stepVolumeWalk, [footstepSoundId(surface, P.running ? 'run' : 'walk')], surface)\n emit('step', { x: P.x, z: P.z, yaw: P.yaw })\n }\n // shove and melee\n if (wasPressed('push') && P.stamina > numbers.shoveCost) {\n P.stamina -= numbers.shoveCost\n shove(viewYaw)\n }\n if (wasPressed('throw')) emit('throw', {})\n if (wasPressed('knife') && P.stamina > numbers.meleeMinStamina) {\n const item = input.melee ?? fist\n P.stamina -= (item.kg ?? 0) > numbers.meleeHeavyKg ? numbers.meleeCostHeavy : numbers.meleeCostLight\n melee(item, viewYaw)\n }\n // panic: chasing agents in sight nearby\n let near = 0\n if (crowd) {\n const n = crowd.count()\n for (let i = 0; i < n; i++) if (crowd.active(i) && crowd.chasing(i)) near += crowd.panicWeight?.(i) ?? 1\n }\n P.panic = clamp(P.panic + (near * numbers.panicGain - (near ? 0 : numbers.panicDecay)) * dt, 0, numbers.panicMax)\n }\n\n return {\n get state() {\n return P\n },\n heightMetres,\n collider: () => ({\n heightMetres: P.crouch ? heightMetres * numbers.crouchHeightRatio : heightMetres,\n radiusMetres: numbers.radius * heightScale,\n }),\n attributes,\n derived,\n numbers,\n infection,\n needs,\n use: (effect) => (P.alive ? applyItemEffect(P, effect, { maxHealth: derived.maxHealth, ...(needs ? { needs } : {}) }) : { applied: false, health: 0, hunger: 0, thirst: 0, stoppedBleeding: false, calmed: false }),\n update,\n hurt: (amount) => hurt(amount),\n bite: () => bite(),\n grab,\n release: () => release('free'),\n knock(seconds) {\n if (!P.alive) return\n P.downTimer = Math.max(P.downTimer, seconds)\n P.crouch = false\n },\n infect,\n die,\n stage() {\n if (!P.infected || !infection) return 'none'\n return P.infectionTime > infection.deliriumSeconds ? 'delirium' : P.infectionTime > infection.feverSeconds ? 'fever' : 'malaise'\n },\n timeLeft: () => (P.infected && infection ? Math.max(0, infection.deathSeconds - P.infectionTime) : null),\n spreadFactor() {\n const panic = P.panic > derived.composure * numbers.panicSpreadAt ? numbers.panicSpread : 1\n const fever = P.infected && infection && P.infectionTime > infection.feverSeconds ? infection.feverSpread : 1\n return panic * fever * (1 + Math.hypot(P.vx, P.vz) * numbers.moveSpread)\n },\n front,\n on(event, listener) {\n let set = listeners.get(event)\n if (!set) listeners.set(event, (set = new Set()))\n set.add(listener as (event: never) => void)\n return () => void set.delete(listener as (event: never) => void)\n },\n save: () => ({ state: structuredClone(P), attributes }),\n load(save) {\n P = structuredClone(save.state)\n // a save from before the needs: the body starts fed\n P.hunger ??= needs?.start.hunger ?? 0\n P.thirst ??= needs?.start.thirst ?? 0\n world.controller?.teleport(P.x, P.y, P.z)\n },\n setWorld(next) {\n defaultWorld = next\n },\n }\n}\n","import type { CharacterId, PhysicsWorld, Vec3 } from '@adatechnology/game-physics'\n\nimport type { PlayerCollider } from './player'\nimport type { PlayerController } from './types'\n\n/** The part of the physics contract the player's body uses: any `PhysicsWorld` (or the loop's `SeamWorld`) has it. */\nexport type PlayerPhysicsWorld = Pick<PhysicsWorld, 'createCharacter' | 'moveCharacter' | 'pushCharacter' | 'readCharacter' | 'teleportCharacter' | 'removeCharacter' | 'characterSupported'>\n\nexport type PhysicsControllerOptions = {\n /** Where the feet are. */\n readonly position: Vec3\n /** What `player.collider()` says: the capsule is made as tall and as wide as the standing body. */\n readonly collider: PlayerCollider\n /** Kilograms, default 75. */\n readonly mass?: number\n /** Most force (N) it pushes a prop with, default 400: a 30 kg crate over wood, not a wardrobe. */\n readonly strength?: number\n}\n\nexport type PhysicsPlayerController = PlayerController & {\n readonly id: CharacterId\n /** Shoves the body: `impulse` in N s (a blow, a blast, a car's bumper); the controller feels it as impulse / mass, fading in a quarter of a second. */\n push(impulse: Vec3): void\n supported(): boolean\n dispose(): void\n}\n\nexport const PLAYER_MASS_KG = 75\nexport const PLAYER_PUSH_STRENGTH_NEWTONS = 400\n/** The most a person puts into what is in the way just by walking into it, without leaning on it on purpose: about the sustained push force of ISO 11228-2 for a man (100 N), the order of what a walk can keep up. A thing whose floor grip is above it (a 28 kg sofa on wood: 115 N) stops the walk; a lighter one is shoved along. */\nexport const PLAYER_WALK_PUSH_NEWTONS = 100\n\n/**\n * The player's controller in a physics world: a capsule as tall as the standing body (a crouch does not shrink it) that steps up, climbs, pushes props and is\n * pushed. Put it in `PlayerWorld.controller` and call `player.update(h, input)` from a `beforeStep(h)` of the loop's `actors` phase, never with the frame's `dt`.\n */\nexport const createPhysicsController = (world: PlayerPhysicsWorld, options: PhysicsControllerOptions): PhysicsPlayerController => {\n const { radiusMetres, heightMetres } = options.collider\n const id = world.createCharacter({\n position: options.position,\n radius: radiusMetres,\n halfHeight: Math.max(0, (heightMetres - 2 * radiusMetres) / 2),\n mass: options.mass ?? PLAYER_MASS_KG,\n strength: options.strength ?? PLAYER_PUSH_STRENGTH_NEWTONS,\n })\n return {\n id,\n move: (velocityX, velocityZ, dt) => world.moveCharacter(id, velocityX, velocityZ, dt),\n read: (out) => world.readCharacter(id, out, 0),\n teleport: (x, y, z) => world.teleportCharacter(id, [x, y, z]),\n push: (impulse) => world.pushCharacter(id, impulse),\n supported: () => world.characterSupported(id),\n dispose: () => world.removeCharacter(id),\n }\n}\n","/** Samples of the ground across the foot's disc, per radius: the disc is walked in rings of this many steps. */\nconst RINGS = 32\nconst SAMPLES_PER_RING = 48\n\n/**\n * The height a round foot of `radius` comes to rest at over ground `heightAt` (the lower sphere of the capsule): the highest, over the points of the disc under it, of\n * the ground there less how far the sphere's underside rises above its lowest point at that distance. Flat ground gives its own height; a bowl holds the foot above its middle.\n */\nexport const footRestHeight = (heightAt: (x: number, z: number) => number, x: number, z: number, radius: number): number => {\n let rest = heightAt(x, z)\n for (let ring = 1; ring <= RINGS; ring++) {\n const distance = (radius * ring) / RINGS\n const lift = radius - Math.sqrt(radius * radius - distance * distance)\n for (let sample = 0; sample < SAMPLES_PER_RING; sample++) {\n const angle = (2 * Math.PI * sample) / SAMPLES_PER_RING\n rest = Math.max(rest, heightAt(x + distance * Math.cos(angle), z + distance * Math.sin(angle)) - lift)\n }\n }\n return rest\n}\n","import type { BodyId, CharacterId, CharacterShape, Layer, PhysicsServices, Quat, Vec3 } from '@adatechnology/game-physics'\n\nimport { PLAYER_MASS_KG, PLAYER_PUSH_STRENGTH_NEWTONS } from './physics-controller'\nimport type { PlayerCollider } from './player'\n\n/** The vertical speed (m/s) of a jump under the world's 9.81: it rises 0.81 m, as high as the walker's own jump always did. */\nexport const WALKER_JUMP_SPEED = 3.99\n\nexport type WalkerStance = 'standing' | 'crouched' | 'prone'\n\n/** A stance is this fraction of the standing height: 1.80, 1.20 and 0.60 m for a person 1.80 m tall. */\nconst STANCE_HEIGHT_RATIO: Readonly<Record<WalkerStance, number>> = { standing: 1, crouched: 2 / 3, prone: 1 / 3 }\nconst NO_ROTATION: Quat = [0, 0, 0, 1]\n/** The probe sits this much (m) above the feet: the floor it will stand on touches the capsule and is not an overlap. */\nconst PROBE_LIFT = 0.03\nconst SOLID_LAYERS: readonly Layer[] = ['static', 'debris', 'prop', 'vehicle', 'character']\n\nexport type WalkerOptions = {\n /** Where the feet are. */\n readonly position: Vec3\n /** The standing body: `player.collider()` while standing. */\n readonly collider: PlayerCollider\n /** Kilograms, default 75. */\n readonly mass?: number\n /** Most force (N) it pushes a prop with, default 400. */\n readonly strength?: number\n /** Default 0.4 m. */\n readonly stepHeight?: number\n readonly maxSlopeDegrees?: number\n /** Default 9.81. */\n readonly gravity?: number\n /** The layer of the body the world sees of the walker (`agent`: a vehicle does not stop on it). */\n readonly shadow?: Layer\n /** The shadow's `user`. */\n readonly user?: number\n /** What `unpark` may not stand in (default static, debris, prop, vehicle and character). */\n readonly solidLayers?: readonly Layer[]\n}\n\nexport type Walker = {\n /** The character in the world: another one after `unpark`. */\n readonly id: CharacterId\n readonly stance: WalkerStance\n readonly parked: boolean\n /** The wanted horizontal velocity (m/s, world x and z), kept until it is changed: the key of the frame, not of the step. */\n setIntent(velocityX: number, velocityZ: number): void\n /** A jump when the feet stand on something; false in the air or parked. */\n jump(): boolean\n /** Changes the stance; false (the stance stays) when the new capsule would penetrate something. */\n setStance(stance: WalkerStance): boolean\n /** Shoves the body: `impulse` in N s. */\n push(impulse: Vec3): void\n supported(): boolean\n /** The feet of the last fixed step into `out` (x, y, z). */\n read(out: Float32Array | Float64Array): void\n /** The feet between the last two fixed steps, `alpha` (0 to 1) of the way: the scheduler's alpha, not the loop's (`stepFixed` zeroes that one). */\n drawn(alpha: number, out: Float32Array | Float64Array): void\n /** Puts the feet here at once, with no sweep and no speed carried over, and the drawn feet with them (a respawn, a scripted step). Nothing happens while parked. */\n teleport(feet: Vec3): void\n /** Takes the body out of the world (a seat, an aircraft, a vehicle): it no longer moves or blocks. */\n park(): void\n /** Puts the body back at the first of `candidates` (feet) where the capsule overlaps nothing solid, in this order (the door, the far side, the roof); false, still parked, when none fits. */\n unpark(candidates: readonly Vec3[]): boolean\n /** Leaves the loop and the world. */\n dispose(): void\n}\n\nexport type WalkerServices = Pick<PhysicsServices, 'loop' | 'world'>\n\nconst shapeOf = (collider: PlayerCollider, stance: WalkerStance): CharacterShape => {\n const height = collider.heightMetres * STANCE_HEIGHT_RATIO[stance]\n const radius = Math.min(collider.radiusMetres, height / 3)\n return { radius, halfHeight: (height - 2 * radius) / 2 }\n}\n\n/**\n * The player's body in the physics world, walking in the loop's `actors` phase: the intent is set when the key changes, every fixed step walks it with the step's\n * `h`, and the feet of the last two steps are kept for drawing between them. No allocation after the first call.\n */\nexport const createWalker = (services: WalkerServices, options: WalkerOptions): Walker => {\n const { loop, world } = services\n const mass = options.mass ?? PLAYER_MASS_KG\n const shapes: Readonly<Record<WalkerStance, CharacterShape>> = { standing: shapeOf(options.collider, 'standing'), crouched: shapeOf(options.collider, 'crouched'), prone: shapeOf(options.collider, 'prone') }\n const solid = options.solidLayers ?? SOLID_LAYERS\n const found: BodyId[] = []\n const previous = new Float64Array(3)\n const current = new Float64Array(3)\n let intentX = 0\n let intentZ = 0\n let stance: WalkerStance = 'standing'\n let parked = false\n\n const create = (feet: Vec3): CharacterId =>\n world.createCharacter({\n position: feet,\n radius: shapes[stance].radius,\n halfHeight: shapes[stance].halfHeight,\n mass,\n strength: options.strength ?? PLAYER_PUSH_STRENGTH_NEWTONS,\n ...(options.stepHeight !== undefined ? { stepHeight: options.stepHeight } : {}),\n ...(options.maxSlopeDegrees !== undefined ? { maxSlopeDegrees: options.maxSlopeDegrees } : {}),\n ...(options.gravity !== undefined ? { gravity: options.gravity } : {}),\n ...(options.shadow !== undefined ? { shadow: options.shadow } : {}),\n ...(options.user !== undefined ? { user: options.user } : {}),\n })\n\n let id = create(options.position)\n world.readCharacter(id, current, 0)\n previous.set(current)\n\n const stopLoop = loop.add(\n {\n beforeStep: (h) => {\n if (parked) return\n previous.set(current)\n world.moveCharacter(id, intentX, intentZ, h)\n world.readCharacter(id, current, 0)\n },\n },\n 'actors',\n )\n\n const fitsAt = (feet: Vec3): boolean => {\n const shape = shapes[stance]\n const centre: Vec3 = [feet[0], feet[1] + PROBE_LIFT + shape.halfHeight + shape.radius, feet[2]]\n return world.overlapShape({ kind: 'capsule', halfHeight: shape.halfHeight, radius: shape.radius }, centre, NO_ROTATION, found, { layers: solid }) === 0\n }\n\n return {\n get id() {\n return id\n },\n get stance() {\n return stance\n },\n get parked() {\n return parked\n },\n setIntent: (velocityX, velocityZ) => {\n intentX = velocityX\n intentZ = velocityZ\n },\n jump: () => {\n if (parked || !world.characterSupported(id)) return false\n world.pushCharacter(id, [0, mass * WALKER_JUMP_SPEED, 0])\n return true\n },\n setStance: (next) => {\n if (parked) return false\n if (!world.setCharacterShape(id, shapes[next])) return false\n stance = next\n return true\n },\n push: (impulse) => world.pushCharacter(id, impulse),\n supported: () => world.characterSupported(id),\n read: (out) => {\n out[0] = current[0] as number\n out[1] = current[1] as number\n out[2] = current[2] as number\n },\n drawn: (alpha, out) => {\n const t = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha\n for (let axis = 0; axis < 3; axis++) out[axis] = (previous[axis] as number) + ((current[axis] as number) - (previous[axis] as number)) * t\n },\n teleport: (feet) => {\n if (parked) return\n world.teleportCharacter(id, feet)\n world.readCharacter(id, current, 0)\n previous.set(current)\n },\n park: () => {\n if (parked) return\n parked = true\n world.removeCharacter(id)\n },\n unpark: (candidates) => {\n if (!parked) return true\n for (const feet of candidates) {\n if (!fitsAt(feet)) continue\n id = create(feet)\n parked = false\n world.readCharacter(id, current, 0)\n previous.set(current)\n return true\n }\n return false\n },\n dispose: () => {\n stopLoop()\n if (!parked) world.removeCharacter(id)\n parked = true\n },\n }\n}\n","/**\n * Pushing furniture on foot: hold the interaction button against a piece, a timer that grows with its mass fills, and the player then walks with it.\n * Engine-agnostic: the host says where the player wants to go and answers whether the volume of the piece can go there; this says how fast, and when it locks.\n */\n\nimport type { SurfaceId } from '@adatechnology/game-contracts'\n\n/** What dragging a piece leaves on a floor: a strip of this colour and width (metres) under each side of its base. */\nexport type DragMark = { readonly color: number; readonly width: number }\n\nexport type FurniturePushPhase = 'idle' | 'grip' | 'push' | 'strain'\nexport type FurniturePushBlock = 'too_heavy' | 'obstacle' | null\n\n/** Every number of the push; a game overrides what it wants (`createFurniturePush(rules)`). */\nexport interface FurniturePushRules {\n /** The most the player's legs put on the floor, newtons: with the friction it says the heaviest thing that moves. */\n readonly forceN: number\n readonly gravity: number\n /** Static friction of a base on a floor, by the material of the piece. */\n readonly frictionByMaterial: Readonly<Record<string, number>>\n readonly defaultFriction: number\n /** The hold before the push: `base + perKg * mass`, at most `max` seconds. */\n readonly gripSeconds: { readonly base: number; readonly perKg: number; readonly max: number }\n /** Metres per second: `max` with nothing on the hands, `min` at the limit of the force. */\n readonly speed: { readonly max: number; readonly min: number }\n /**\n * How fast the walk with the piece changes, m/s²: `max` the most a person speeds it up (the force left over the friction, over the mass, may give less), `brake` the\n * most it slows it (stopping, turning back). Below what holds a thing on top (friction × g, about 3.4 m/s² for the softest), so a cup on a pushed table rides along.\n */\n readonly accel: { readonly max: number; readonly brake: number; readonly min: number }\n /** A press shorter than this is not a push (the host keeps it for a tap, such as grabbing). */\n readonly tapSeconds: number\n /** How long the effort stays after the last step that was refused, so that it does not flicker. */\n readonly strainHoldSeconds: number\n /**\n * The scratch a dragged piece leaves, by the floor it is dragged on (`SurfaceId` of game-contracts): wood and tile scratch lighter, concrete scuffs darker,\n * dirt and sand take a furrow; a floor left out (carpet, grass, gravel, asphalt, water) keeps no mark.\n */\n readonly dragMarks: Readonly<Partial<Record<SurfaceId, DragMark>>>\n}\n\nexport const FURNITURE_PUSH_DEFAULTS: FurniturePushRules = {\n forceN: 500,\n gravity: 9.81,\n frictionByMaterial: { wood_soft: 0.4, wood_hard: 0.4, mdf: 0.4, plywood: 0.4, steel: 0.35, aluminium: 0.35, cast_iron: 0.4, copper: 0.35, plastic: 0.35, rubber: 0.8, fabric: 0.45, foam: 0.5, ceramic: 0.5, glass: 0.3, tempered_glass: 0.3, brick: 0.6, concrete: 0.65 },\n defaultFriction: 0.45,\n gripSeconds: { base: 0.4, perKg: 0.015, max: 2.5 },\n speed: { max: 1.8, min: 0.35 },\n accel: { max: 1.5, brake: 3, min: 0.2 },\n tapSeconds: 0.2,\n strainHoldSeconds: 0.25,\n dragMarks: {\n wood: { color: 0xd8c4a0, width: 0.012 },\n tile: { color: 0x9a9a96, width: 0.01 },\n concrete: { color: 0x45433f, width: 0.02 },\n metal: { color: 0xd0d4d8, width: 0.008 },\n glass: { color: 0xf2f2f2, width: 0.006 },\n dirt: { color: 0x4a3524, width: 0.04 },\n sand: { color: 0x8d7a5c, width: 0.05 },\n },\n}\n\nexport type FurniturePushTarget = { readonly massKg: number; readonly material?: string }\n\n/** Static friction of a thing of `material` on what it stands on (the floor, a table top). */\nexport const frictionFor = (material: string | undefined, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => (material !== undefined ? rules.frictionByMaterial[material] : undefined) ?? rules.defaultFriction\n\nconst frictionOf = (target: FurniturePushTarget, rules: FurniturePushRules): number => frictionFor(target.material, rules)\n\n/** A piece, or a row of pieces pushed one against the next (a sofa shoving a chair): their frictions on the floor add up against the legs. */\nexport type FurniturePushLoad = FurniturePushTarget | readonly FurniturePushTarget[]\n\nconst piecesOf = (load: FurniturePushLoad): readonly FurniturePushTarget[] => (Array.isArray(load) ? load : [load as FurniturePushTarget])\nconst frictionForceOf = (load: FurniturePushLoad, rules: FurniturePushRules): number => piecesOf(load).reduce((sum, t) => sum + frictionOf(t, rules) * t.massKg * rules.gravity, 0)\nconst massOf = (load: FurniturePushLoad): number => piecesOf(load).reduce((sum, t) => sum + t.massKg, 0)\nconst loadShare = (load: FurniturePushLoad, rules: FurniturePushRules): number => frictionForceOf(load, rules) / rules.forceN\n\nexport const gripSecondsFor = (massKg: number, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => Math.min(rules.gripSeconds.max, rules.gripSeconds.base + rules.gripSeconds.perKg * Math.max(0, massKg))\n\n/** Whether the legs overcome the friction of the piece (or of the row of pieces) on the floor. */\nexport const canPush = (target: FurniturePushLoad, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): boolean => loadShare(target, rules) <= 1\n\n/** Metres per second with the piece on the hands: slower the closer it is to the limit of the force, 0 past it. */\nexport const pushSpeedFor = (target: FurniturePushLoad, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => {\n const share = loadShare(target, rules)\n return share > 1 ? 0 : rules.speed.max + (rules.speed.min - rules.speed.max) * share\n}\n\n/** How fast the walk with the piece speeds up, m/s²: the force left over its friction, over its mass, at most what a person does (`accel.max`). */\nexport const pushAccelerationFor = (target: FurniturePushLoad, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => {\n const spare = (rules.forceN - frictionForceOf(target, rules)) / Math.max(1e-3, massOf(target))\n return Math.max(rules.accel.min, Math.min(rules.accel.max, spare))\n}\n\n/** The scratch dragging leaves on `surface`, or null where the floor keeps none (carpet, grass). */\nexport const dragMarkFor = (surface: SurfaceId, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): DragMark | null => rules.dragMarks[surface] ?? null\n\n/** Whether a thing resting on a moving piece slides on it: the piece changes speed faster than the friction under the thing can follow (`accelMps2` > friction × g). */\nexport const slipsOnTop = (accelMps2: number, friction: number, gravity = FURNITURE_PUSH_DEFAULTS.gravity): boolean => accelMps2 > friction * gravity\n\nexport type FurniturePushInput = {\n /** Where the player wants to go on the floor: a unit vector, or `[0, 0]` standing. */\n readonly walk: readonly [number, number]\n /** Whether the volume of the piece (and the player behind it) can move by this offset. */\n readonly isFree: (dx: number, dz: number) => boolean\n}\n\nexport type FurniturePushStep = {\n readonly dx: number\n readonly dz: number\n /** The grip closed on this update. */\n readonly engaged: boolean\n /** A step was refused now and the one before was not: the moment the piece hits something. */\n readonly hitObstacle: boolean\n /** The velocity of the piece after this update, m/s on the floor. */\n readonly velocity: readonly [number, number]\n /** How fast its velocity changed in this update, m/s²: what a thing on top feels. */\n readonly acceleration: number\n /** The velocity it had when it hit something and stopped at once (what rests on it keeps it and slides on), or null. */\n readonly stoppedFrom: readonly [number, number] | null\n}\n\nexport interface FurniturePush {\n readonly phase: FurniturePushPhase\n /** How far the hold timer is, 0 to 1. */\n readonly progress: number\n readonly block: FurniturePushBlock\n readonly heldSeconds: number\n /** Whether the hold is still short enough to be a tap. */\n readonly isTap: boolean\n /** The velocity of the piece now, m/s on the floor. */\n readonly velocity: readonly [number, number]\n begin(target: FurniturePushTarget): void\n /** The load changed while pushing (the piece met another and shoves it along): the speed and the speeding up follow the whole row. */\n setLoad(load: FurniturePushLoad): void\n release(): void\n update(dt: number, input: FurniturePushInput): FurniturePushStep\n}\n\nconst STILL: FurniturePushStep = { dx: 0, dz: 0, engaged: false, hitObstacle: false, velocity: [0, 0], acceleration: 0, stoppedFrom: null }\n\nexport function createFurniturePush(overrides: Partial<FurniturePushRules> = {}): FurniturePush {\n const rules: FurniturePushRules = { ...FURNITURE_PUSH_DEFAULTS, ...overrides }\n let phase: FurniturePushPhase = 'idle'\n let target: FurniturePushTarget = { massKg: 0 }\n let held = 0\n let gripSeconds = 1\n let speed = 0\n let accel = rules.accel.max\n let vx = 0\n let vz = 0\n let block: FurniturePushBlock = null\n let refused = 0\n let wasRefused = false\n\n /** The velocity goes toward the walk, no faster than the push speeds it up (or the legs brake it). Answers the change, m/s². */\n const steer = (dt: number, walk: readonly [number, number]): number => {\n const wantX = walk[0] * speed\n const wantZ = walk[1] * speed\n const braking = wantX * vx + wantZ * vz < vx * vx + vz * vz\n let dvx = wantX - vx\n let dvz = wantZ - vz\n const change = Math.hypot(dvx, dvz)\n const most = (braking ? rules.accel.brake : accel) * dt\n if (change > most) {\n dvx *= most / change\n dvz *= most / change\n }\n vx += dvx\n vz += dvz\n return Math.min(change, most) / dt\n }\n\n const walkWith = (dt: number, input: FurniturePushInput): FurniturePushStep => {\n refused = Math.max(0, refused - dt)\n if (block === 'too_heavy' || dt <= 0) return STILL\n const acceleration = steer(dt, input.walk)\n if (Math.hypot(vx, vz) < 1e-4) {\n vx = vz = 0\n if (refused === 0) {\n phase = 'push'\n block = null\n wasRefused = false\n }\n return { ...STILL, acceleration }\n }\n const dx = vx * dt\n const dz = vz * dt\n if (input.isFree(dx, dz)) {\n if (refused === 0) {\n phase = 'push'\n block = null\n }\n wasRefused = false\n return { dx, dz, engaged: false, hitObstacle: false, velocity: [vx, vz], acceleration, stoppedFrom: null }\n }\n const from: readonly [number, number] = [vx, vz]\n vx = vz = 0\n const hitObstacle = !wasRefused\n wasRefused = true\n refused = rules.strainHoldSeconds\n phase = 'strain'\n block = 'obstacle'\n return { ...STILL, hitObstacle, acceleration: Math.hypot(from[0], from[1]) / dt, stoppedFrom: hitObstacle ? from : null }\n }\n\n return {\n get phase() {\n return phase\n },\n get progress() {\n return phase === 'idle' ? 0 : Math.min(1, held / gripSeconds)\n },\n get block() {\n return block\n },\n get heldSeconds() {\n return held\n },\n get velocity(): readonly [number, number] {\n return [vx, vz]\n },\n get isTap() {\n return phase === 'grip' && held < rules.tapSeconds\n },\n begin(next) {\n target = next\n phase = 'grip'\n held = 0\n block = null\n refused = 0\n wasRefused = false\n gripSeconds = gripSecondsFor(next.massKg, rules)\n speed = pushSpeedFor(next, rules)\n accel = pushAccelerationFor(next, rules)\n vx = vz = 0\n },\n setLoad(load) {\n speed = pushSpeedFor(load, rules)\n accel = pushAccelerationFor(load, rules)\n },\n release() {\n phase = 'idle'\n vx = vz = 0\n held = 0\n block = null\n },\n update(dt, input) {\n if (phase === 'idle') return STILL\n held += dt\n if (phase !== 'grip') return walkWith(dt, input)\n if (held < gripSeconds) return STILL\n if (canPush(target, rules)) phase = 'push'\n else {\n phase = 'strain'\n block = 'too_heavy'\n }\n return { ...STILL, engaged: true }\n },\n }\n}\n","import type { KnownDeathCause, PlayerMessageId } from '../types'\n\nexport type PlayerText = Readonly<Record<PlayerMessageId | KnownDeathCause, string>>\n\n/** The game's own words (G 68434, 68452, 68518, 68525-68541, 68547) and the death causes it shows (G 68448, 68454, 68510, 68519, 68539). */\nconst PT_BR: PlayerText = {\n grabbed: 'AGARRADO! Aperte E várias vezes para empurrar ou F para a faca',\n grabbed_drown: 'O AFOGADO TE PUXA PARA O FUNDO! E várias vezes ou F para a faca',\n bitten: 'Você foi mordido. Não há cura.',\n bandaged: 'Curativo feito',\n knife_head: 'Faca na cabeça!',\n knife_miss: 'Errou a facada',\n pushed_off: 'Empurrou!',\n drowning: 'Afogando! Solte-se!',\n no_jaw: 'Sem mandíbula: só arranhou',\n stood_up: 'De pé!',\n infected: 'Morreu infectado',\n killed: 'Morto pela horda',\n bitten_to_death: 'Mordido',\n infection: 'A infecção venceu',\n bled_out: 'Sangrou até a morte',\n hunger_thirst: 'Fome e sede',\n drowned: 'Afogado',\n burned: 'Queimado',\n}\n\nconst EN: PlayerText = {\n grabbed: 'GRABBED! Press E repeatedly to push or F for the knife',\n grabbed_drown: 'THE DROWNED PULLS YOU UNDER! E repeatedly or F for the knife',\n bitten: 'You were bitten. There is no cure.',\n bandaged: 'Wound dressed',\n knife_head: 'Knife to the head!',\n knife_miss: 'The stab missed',\n pushed_off: 'Pushed off!',\n drowning: 'Drowning! Break free!',\n no_jaw: 'No jaw: only a scratch',\n stood_up: 'Back on your feet!',\n infected: 'Died infected',\n killed: 'Killed by the horde',\n bitten_to_death: 'Bitten',\n infection: 'The infection won',\n bled_out: 'Bled to death',\n hunger_thirst: 'Hunger and thirst',\n drowned: 'Drowned',\n burned: 'Burned',\n}\n\nexport const PLAYER_TEXT: Readonly<Record<'en' | 'pt-BR', PlayerText>> = { en: EN, 'pt-BR': PT_BR }\n\n/** The text of a message or death cause id in a locale (`pt-BR` or `en`, the language part is enough); unknown ids come back as they are. */\nexport const playerTextOf = (id: string, locale = 'pt-BR'): string => {\n const table = locale.toLowerCase().startsWith('en') ? EN : PT_BR\n return (table as Readonly<Record<string, string>>)[id] ?? id\n}\n","export type PlayerBenchText = {\n readonly group: string\n readonly name: string\n readonly controls: Readonly<Record<'infection' | 'agility' | 'vigor' | 'seed' | 'hurt' | 'bite' | 'grab' | 'push' | 'knife' | 'bandage' | 'knock' | 'crouch' | 'reset', string>>\n readonly hints: Readonly<Record<'infection' | 'agility' | 'vigor' | 'seed' | 'grab' | 'push', string>>\n readonly metrics: Readonly<Record<'health' | 'stamina' | 'bleeding' | 'wounds' | 'stage' | 'time_left' | 'panic' | 'spread' | 'grab' | 'noise' | 'steps' | 'message', string>>\n readonly stages: Readonly<Record<'none' | 'malaise' | 'fever' | 'delirium' | 'dead', string>>\n readonly scenarios: Readonly<Record<'stamina' | 'bleed_bandage' | 'normal_world' | 'infection_kills' | 'grab_break_free' | 'determinism', string>>\n readonly yes: string\n readonly no: string\n}\n\nconst EN: PlayerBenchText = {\n group: 'Player',\n name: 'Player area',\n controls: {\n infection: 'Individual infection',\n agility: 'Agility',\n vigor: 'Vigor',\n seed: 'Seed',\n hurt: 'Take a hit (10)',\n bite: 'Bite',\n grab: 'Get grabbed',\n push: 'Push (E)',\n knife: 'Knife (F)',\n bandage: 'Bandage (B)',\n knock: 'Knocked down 1.5 s',\n crouch: 'Crouch (C)',\n reset: 'Start again',\n },\n hints: {\n infection: 'Off: a normal world, wounds never infect. On: the game rule (scratch 6%, laceration 22%, bite 100%; fever at 30 s, death at 120 s).',\n agility: 'The sheet: stamina, run speed and footstep noise come from it.',\n vigor: 'The sheet: health, stamina and composure come from it.',\n seed: 'The same seed gives the same wounds and the same knife rolls.',\n grab: 'Something grabs you from behind: 3 s to push it off (6 pushes) or to land the knife (70%).',\n push: 'Shoves what is in front, or pushes off what holds you.',\n },\n metrics: {\n health: 'Health',\n stamina: 'Stamina',\n bleeding: 'Bleeding',\n wounds: 'Wounds',\n stage: 'Infection',\n time_left: 'Time left',\n panic: 'Panic',\n spread: 'Aim spread x',\n grab: 'Grab timer',\n noise: 'Last noise',\n steps: 'Footsteps',\n message: 'Message',\n },\n stages: { none: 'None', malaise: 'Malaise', fever: 'Fever', delirium: 'Delirium', dead: 'Dead' },\n scenarios: {\n stamina: 'Running drains stamina and resting gives it back',\n bleed_bandage: 'A laceration bleeds until it is dressed',\n normal_world: 'In a normal world a bite hurts and bleeds but never infects',\n infection_kills: 'With the infection on, a bite brings fever and kills at its time',\n grab_break_free: 'Six pushes break a grab before the bite',\n determinism: 'The same seed gives the same wounds',\n },\n yes: 'yes',\n no: 'no',\n}\n\nconst PT_BR: PlayerBenchText = {\n group: 'Jogador',\n name: 'Área do jogador',\n controls: {\n infection: 'Infecção individual',\n agility: 'Agilidade',\n vigor: 'Vigor',\n seed: 'Semente',\n hurt: 'Levar um golpe (10)',\n bite: 'Mordida',\n grab: 'Ser agarrado',\n push: 'Empurrar (E)',\n knife: 'Faca (F)',\n bandage: 'Curativo (B)',\n knock: 'Derrubado 1,5 s',\n crouch: 'Agachar (C)',\n reset: 'Recomeçar',\n },\n hints: {\n infection: 'Desligada: mundo normal, ferida nunca infecta. Ligada: a regra do jogo (arranhão 6%, laceração 22%, mordida 100%; febre aos 30 s, morte aos 120 s).',\n agility: 'A ficha: fôlego, velocidade de corrida e ruído dos passos saem dela.',\n vigor: 'A ficha: vida, fôlego e compostura saem dela.',\n seed: 'A mesma semente dá as mesmas feridas e os mesmos golpes de faca.',\n grab: 'Algo te agarra por trás: 3 s para empurrar (6 empurrões) ou acertar a faca (70%).',\n push: 'Empurra o que está na frente, ou se solta do que te segura.',\n },\n metrics: {\n health: 'Vida',\n stamina: 'Fôlego',\n bleeding: 'Sangrando',\n wounds: 'Feridas',\n stage: 'Infecção',\n time_left: 'Tempo restante',\n panic: 'Pânico',\n spread: 'Dispersão x',\n grab: 'Agarrão',\n noise: 'Último ruído',\n steps: 'Passos',\n message: 'Mensagem',\n },\n stages: { none: 'Nenhuma', malaise: 'Mal-estar', fever: 'Febre', delirium: 'Delírio', dead: 'Morto' },\n scenarios: {\n stamina: 'Correr gasta fôlego e descansar devolve',\n bleed_bandage: 'Uma laceração sangra até o curativo',\n normal_world: 'No mundo normal a mordida machuca e sangra, mas não infecta',\n infection_kills: 'Com a infecção ligada, a mordida dá febre e mata no tempo dela',\n grab_break_free: 'Seis empurrões soltam o agarrão antes da mordida',\n determinism: 'A mesma semente dá as mesmas feridas',\n },\n yes: 'sim',\n no: 'não',\n}\n\nexport const playerBenchTextOf = (locale: string): PlayerBenchText => (locale.toLowerCase().startsWith('en') ? EN : PT_BR)\n","import type { BenchChange, GaitId, ModuleControl, ModuleHost, ModuleMetric, ModuleScenario, SurfaceId, TestableModule } from '@adatechnology/game-contracts'\n\nimport { playerTextOf } from '../locales'\nimport { createPlayer } from '../player'\nimport type { Player, PlayerOptions } from '../player'\nimport type { PlayerAction, PlayerCrowd, PlayerInput } from '../types'\nimport { playerBenchTextOf } from './locale'\n\nexport type PlayerTestModuleOptions = PlayerOptions & { readonly locale?: string }\n\n/** What the scenarios use of the context the test room passes. */\nexport interface PlayerScenarioLike {\n expect(condition: boolean, label: string, data?: Record<string, unknown>): void\n}\n\nexport type PlayerTestModule = TestableModule<PlayerScenarioLike> & {\n /** The player in use (replaced when the bench changes the sheet, the seed or the infection). */\n readonly player: Player\n}\n\ntype CameraLike = { position: { x: number; y: number; z: number }; rotation?: { y: number }; getWorldDirection?(target: unknown): { x: number; z: number } }\ntype ThreeLike = { Vector3?: new () => { x: number; y: number; z: number } }\n\nconst MOVING_SPEED = 0.2\n/** Metres per second above which a move of the view is a jump of the camera, not the body walking. */\nconst TELEPORT_SPEED = 10\nconst SPRINT_SPEED = 3.4\nconst FRAME = 1 / 30\n\n/**\n * One agent standing behind the player for the grab test: the bench has no crowd, so this is the hand that holds. It follows `hold`, takes\n * the shove and the knife, and leaves the count once it lets go.\n */\nconst createGrabber = () => {\n const agent = { x: 0, z: 0, on: false, stunned: 0, hits: 0 }\n const crowd: PlayerCrowd = {\n count: () => (agent.on ? 1 : 0),\n active: () => agent.on,\n x: () => agent.x,\n z: () => agent.z,\n y: () => 0,\n floor: () => 0,\n chasing: () => agent.on,\n down: () => agent.stunned > 0,\n hold(_i, x, z, k) {\n agent.x += (x - agent.x) * k\n agent.z += (z - agent.z) * k\n },\n stun(_i, seconds) {\n agent.stunned = seconds\n agent.on = false\n },\n chase() {\n agent.on = false\n },\n damage() {\n agent.hits += 1\n agent.on = false\n },\n }\n return { agent, crowd }\n}\n\n/**\n * The player area of a test room, against the generic contracts only. The room's camera is the player: where it walks, the player walks; its speed\n * decides walking or running, so stamina, footsteps and their noise follow the viewer. The bench hurts, bites, grabs and knocks the player down,\n * switches the individual infection (off by default: a normal world) and sets the sheet. Footsteps and flesh sounds go to `host.audio`.\n */\nexport function createPlayerTestModule(options: PlayerTestModuleOptions = {}): PlayerTestModule {\n const locale = options.locale ?? 'pt-BR'\n const text = playerBenchTextOf(locale)\n const { locale: _locale, ...playerOptions } = options\n void _locale\n const settings = { infection: options.infection === undefined ? false : options.infection !== false, agility: options.attributes?.agility ?? 5, vigor: options.attributes?.vigor ?? 5, seed: options.seed ?? 1 }\n let host: ModuleHost | null = null\n const grabber = createGrabber()\n let lastNoise = 0\n let steps = 0\n let lastMessage = ''\n let pending: Partial<Record<PlayerAction, boolean>> = {}\n let bandage = false\n let footfall = false\n let surface: SurfaceId | undefined\n let gait: GaitId | undefined\n let last: { x: number; z: number } | null = null\n const offs: (() => void)[] = []\n\n const build = (): Player => {\n for (const off of offs.splice(0)) off()\n const made = createPlayer({ ...playerOptions, seed: settings.seed, infection: settings.infection, attributes: { ...playerOptions.attributes, agility: settings.agility, vigor: settings.vigor } })\n offs.push(made.on('noise', (e) => void (lastNoise = e.radius)))\n offs.push(made.on('step', () => void (steps += 1)))\n offs.push(made.on('message', (e) => void (lastMessage = playerTextOf(e.id, locale))))\n // the body sounds of each event (a footstep on its surface, the swing and then the hit of a blow); the team's class only when it names none\n offs.push(\n made.on('sound', (e) => {\n if (e.ids.length === 0) return\n e.ids.forEach((id, index) => {\n const delay = e.at?.[index] ?? 0\n host?.audio?.play({ sound: id, volume: e.volume, position: e.position, urgent: true, ...(delay > 0 ? { delay } : {}) })\n })\n }),\n )\n offs.push(made.on('died', (e) => host?.log(`player died: ${e.cause}`, { cause: e.cause })))\n lastNoise = 0\n steps = 0\n lastMessage = ''\n return made\n }\n let player = build()\n\n const view = (): { x: number; z: number; yaw: number } | null => {\n const camera = host?.camera as CameraLike | undefined\n if (!camera?.position) return null\n const Vector3 = (host?.THREE as ThreeLike | undefined)?.Vector3\n if (camera.getWorldDirection && Vector3) {\n const look = camera.getWorldDirection(new Vector3())\n return { x: camera.position.x, z: camera.position.z, yaw: Math.atan2(-look.x, -look.z) }\n }\n return { x: camera.position.x, z: camera.position.z, yaw: camera.rotation?.y ?? 0 }\n }\n\n const frame = (dt: number): void => {\n const here = view()\n const raw = here && last && dt > 0 ? Math.hypot(here.x - last.x, here.z - last.z) / dt : 0\n // faster than anyone runs is the view put somewhere else (an area opening, a scripted look), not a walk: no footstep for it\n const speed = raw > TELEPORT_SPEED ? 0 : raw\n if (here) {\n player.state.x = here.x\n player.state.z = here.z\n }\n const input: PlayerInput = { forward: speed > MOVING_SPEED ? 1 : 0, run: gait ? gait === 'run' : speed > SPRINT_SPEED, yaw: here?.yaw ?? 0, bandage, pressed: pending, footfall, ...(surface ? { surface } : {}) }\n pending = {}\n footfall = false\n bandage = false\n player.update(dt, input, { crowd: grabber.crowd })\n if (here) {\n player.state.x = here.x\n player.state.z = here.z\n last = { x: here.x, z: here.z }\n }\n if (grabber.agent.stunned > 0) grabber.agent.stunned = Math.max(0, grabber.agent.stunned - dt)\n }\n\n const grab = (): void => {\n const P = player.state\n grabber.agent.on = true\n grabber.agent.x = P.x - Math.sin(P.yaw) * player.numbers.grabOffset\n grabber.agent.z = P.z - Math.cos(P.yaw) * player.numbers.grabOffset\n player.grab(0)\n }\n\n const onChange = (change: BenchChange): void => {\n if (change.kind === 'action') {\n const id = change.id\n if (id === 'hurt') player.hurt(10)\n else if (id === 'bite') player.bite()\n else if (id === 'grab') grab()\n else if (id === 'knock') player.knock(1.5)\n else if (id === 'bandage') bandage = true\n else if (id === 'push' || id === 'knife' || id === 'crouch') pending = { ...pending, [id]: true }\n else if (id === 'reset') player = build()\n return\n }\n if (change.kind !== 'control') return\n const { id, value } = change\n if (id === 'infection' && typeof value === 'boolean' && value !== settings.infection) settings.infection = value\n else if ((id === 'agility' || id === 'vigor' || id === 'seed') && typeof value === 'number' && value !== settings[id]) settings[id] = value\n else return\n player = build()\n }\n\n const controls = (): ModuleControl[] => [\n { kind: 'boolean', id: 'infection', name: text.controls.infection, hint: text.hints.infection, default: settings.infection },\n { kind: 'number', id: 'agility', name: text.controls.agility, hint: text.hints.agility, min: 1, max: 8, step: 1, default: settings.agility },\n { kind: 'number', id: 'vigor', name: text.controls.vigor, hint: text.hints.vigor, min: 1, max: 8, step: 1, default: settings.vigor },\n { kind: 'number', id: 'seed', name: text.controls.seed, hint: text.hints.seed, min: 1, max: 9999, step: 1, default: settings.seed },\n { kind: 'action', id: 'hurt', name: text.controls.hurt },\n { kind: 'action', id: 'bite', name: text.controls.bite },\n { kind: 'action', id: 'grab', name: text.controls.grab, hint: text.hints.grab },\n { kind: 'action', id: 'push', name: text.controls.push, hint: text.hints.push },\n { kind: 'action', id: 'knife', name: text.controls.knife },\n { kind: 'action', id: 'bandage', name: text.controls.bandage },\n { kind: 'action', id: 'knock', name: text.controls.knock },\n { kind: 'action', id: 'crouch', name: text.controls.crouch },\n { kind: 'action', id: 'reset', name: text.controls.reset },\n ]\n\n const stageName = (): string => (player.state.alive ? text.stages[player.stage()] : text.stages.dead)\n const metrics = (): ModuleMetric[] => [\n { id: 'health', name: text.metrics.health, digits: 1, max: player.derived.maxHealth, read: () => Math.max(0, player.state.health) },\n { id: 'stamina', name: text.metrics.stamina, digits: 1, max: player.derived.maxStamina, read: () => player.state.stamina },\n { id: 'bleeding', name: text.metrics.bleeding, read: () => (player.state.bleeding ? text.yes : text.no) },\n { id: 'wounds', name: text.metrics.wounds, digits: 0, read: () => player.state.wounds.length },\n { id: 'stage', name: text.metrics.stage, read: stageName },\n { id: 'time_left', name: text.metrics.time_left, unit: 's', digits: 0, read: () => player.timeLeft() ?? 0 },\n { id: 'panic', name: text.metrics.panic, digits: 1, read: () => player.state.panic },\n { id: 'spread', name: text.metrics.spread, digits: 2, read: () => player.spreadFactor() },\n { id: 'grab_timer', name: text.metrics.grab, unit: 's', digits: 1, read: () => (player.state.grabbedBy >= 0 ? player.state.grabTimer : 0) },\n { id: 'noise', name: text.metrics.noise, unit: 'm', digits: 1, read: () => lastNoise },\n { id: 'steps', name: text.metrics.steps, digits: 0, read: () => steps },\n { id: 'message', name: text.metrics.message, read: () => lastMessage },\n ]\n\n // each scenario runs its own player, so the bench's live one is not touched\n const fresh = (extra: PlayerOptions = {}): Player => createPlayer({ ...playerOptions, ...extra })\n const run = (made: Player, seconds: number, input: PlayerInput = {}, crowd?: PlayerCrowd): void => {\n for (let t = 0; t < seconds; t += FRAME) made.update(FRAME, input, crowd ? { crowd } : undefined)\n }\n const scenarios = (): Array<ModuleScenario<PlayerScenarioLike>> => [\n {\n id: 'player_stamina',\n name: text.scenarios.stamina,\n run: ({ expect }) => {\n const made = fresh({ seed: 1 })\n const full = made.state.stamina\n run(made, 4, { forward: 1, run: true })\n const tired = made.state.stamina\n expect(tired < full - 40, 'four seconds of running spend 48 of stamina', { full, tired })\n run(made, 3)\n expect(made.state.stamina > tired, 'standing still gives it back', { tired, rested: made.state.stamina })\n },\n },\n {\n id: 'player_bleed_bandage',\n name: text.scenarios.bleed_bandage,\n run: ({ expect }) => {\n const made = fresh({ seed: 1 })\n made.bite()\n const after = made.state.health\n run(made, 2)\n expect(made.state.bleeding === 1 && made.state.health < after, 'the wound bleeds', { health: made.state.health })\n run(made, FRAME, { bandage: true })\n const dressed = made.state.health\n run(made, 2)\n expect(made.state.bleeding === 0 && made.state.health === dressed, 'dressed, it stops', { health: made.state.health })\n },\n },\n {\n id: 'player_normal_world',\n name: text.scenarios.normal_world,\n run: ({ expect }) => {\n const made = fresh({ seed: 1, infection: false })\n made.bite()\n run(made, 10)\n expect(!made.state.infected && made.state.health < made.derived.maxHealth, 'bitten, hurt, not infected', { health: made.state.health })\n },\n },\n {\n id: 'player_infection_kills',\n name: text.scenarios.infection_kills,\n run: ({ expect }) => {\n const made = fresh({ seed: 1, infection: true })\n made.bite()\n run(made, FRAME, { bandage: true })\n run(made, 40)\n expect(made.stage() === 'fever', 'fever after 30 s', { stage: made.stage() })\n run(made, 90)\n expect(!made.state.alive && made.state.cause === 'infection', 'dead at 120 s', { cause: made.state.cause })\n },\n },\n {\n id: 'player_grab_break_free',\n name: text.scenarios.grab_break_free,\n run: ({ expect }) => {\n const made = fresh({ seed: 1 })\n const { agent, crowd } = createGrabber()\n agent.on = true\n made.grab(0)\n for (let push = 0; push < 6; push++) {\n made.update(FRAME, { pressed: { push: true } }, { crowd })\n made.update(FRAME, {}, { crowd })\n }\n expect(made.state.grabbedBy === -1 && made.state.wounds.length === 0, 'free, and no bite', { grabbedBy: made.state.grabbedBy })\n },\n },\n {\n id: 'player_determinism',\n name: text.scenarios.determinism,\n run: ({ expect }) => {\n const wounds = (seed: number): string => {\n const made = fresh({ seed })\n for (let k = 0; k < 12; k++) made.hurt(1)\n return made.state.wounds.join(',')\n }\n expect(wounds(4) === wounds(4), 'the same seed gives the same wounds')\n expect(wounds(4) !== wounds(5), 'another seed gives others')\n },\n },\n ]\n\n const module: PlayerTestModule = {\n id: 'player_area',\n name: text.name,\n ground: { surface: 'dirt' },\n group: text.group,\n get player() {\n return player\n },\n items: () => [],\n controls: () => controls(),\n metrics: () => metrics(),\n scenarios: () => scenarios(),\n attach(lent) {\n host = lent\n last = null\n const off = lent.bench?.onChange(onChange)\n const offFrame = lent.onFrame(frame)\n // the host's body puts its feet down: the footsteps follow it (and what it says is under them)\n const offFeet = lent.on((event) => {\n if (event.type !== 'footfall') return\n footfall = true\n surface = event.surface\n gait = event.gait\n })\n return () => {\n off?.()\n offFrame()\n offFeet()\n host = null\n }\n },\n }\n return module\n}\n","/**\n * Opening and closing a hinged or sliding leaf by hand (a house door, a wardrobe or fridge door, a drawer, a car door, a hood): the hand reaches the handle, the leaf\n * follows the hand at a speed set by its mass, stops where something is in its way, and a locked leaf only rattles.\n * The player does not follow the leaf: when the handle leaves arm reach a leaf that goes away is shoved on (`push`) and one that comes toward the body is let go (`release`),\n * and either one finishes its swing on its own.\n * Engine-agnostic: the host says how open the leaf is (0 closed, 1 open) and answers whether it can go to a new opening; this says how far it goes each step.\n */\n\nexport type DoorUsePhase = 'idle' | 'reach' | 'swing' | 'push' | 'release' | 'rattle'\nexport type DoorUseBlock = 'locked' | 'obstacle' | null\n\n/** Every number of the use; a game overrides what it wants (`createDoorUse(rules)`). */\nexport interface DoorUseRules {\n /** The hand going to the handle before the leaf moves, seconds. */\n readonly reachSeconds: number\n /** A full swing: `base + perKg * mass` of the leaf, between `min` and `max` seconds (a fridge door is quick, a car door slower, a steel door slower still). */\n readonly swingSeconds: { readonly base: number; readonly perKg: number; readonly min: number; readonly max: number }\n /** The shove of a leaf that goes away once the handle is out of reach, seconds. */\n readonly pushSeconds: number\n /** The hand letting go and coming back, seconds. */\n readonly releaseSeconds: number\n /** How long a locked leaf is shaken before the hand gives up, seconds. */\n readonly rattleSeconds: number\n /** The part of the swing tested at a time against what is around (smaller is finer and costs more). */\n readonly stepFraction: number\n /** Within this of closed or open a leaf counts as there: the last use's way no longer turns it round. */\n readonly endTolerance: number\n}\n\nexport const DOOR_USE_DEFAULTS: DoorUseRules = {\n reachSeconds: 0.3,\n swingSeconds: { base: 0.45, perKg: 0.02, min: 0.45, max: 1.6 },\n pushSeconds: 0.18,\n releaseSeconds: 0.22,\n // the length of the recorded handle shaken (game-audio door_locked_rattle, 0.6 to 0.83 s): the hand lets go as the sound ends\n rattleSeconds: 0.75,\n stepFraction: 0.04,\n endTolerance: 0.02,\n}\n\n/** The body's shoulder, metres over the feet (the avatar's door pose is drawn for it). */\nexport const DOOR_SHOULDER_HEIGHT = 1.42\n/** The farthest a handle is from the shoulder joint for the palm to stay on it (measured on the body in both views: the palm is 0.06 m off up to 0.5, 0.11 at 0.55, 0.24 at 0.65). */\nexport const DOOR_ARM_REACH = 0.55\n\nexport type DoorUseTarget = {\n /** How open the leaf is now, 0 closed to 1 open. */\n readonly opening: number\n readonly massKg: number\n readonly locked?: boolean\n /** Where the last use sent this leaf: a leaf stopped between closed and open goes the other way (a door blocked half open closes). */\n readonly lastGoal?: 0 | 1\n}\n\nexport type DoorUseStep = {\n readonly phase: DoorUsePhase\n /** How open the leaf is after the step. */\n readonly opening: number\n /** The phase's own progress, 0 to 1 (how far the hand is to the handle, how far the swing went, how much of the rattle is left). */\n readonly progress: number\n /** Set on the step the leaf stopped short or would not move. */\n readonly block: DoorUseBlock\n /** The leaf got where it was going on this step (fully open or fully closed). */\n readonly arrived: boolean\n}\n\n/** Seconds of a full swing for a leaf of this mass. */\nexport const swingSecondsFor = (massKg: number, rules: DoorUseRules = DOOR_USE_DEFAULTS): number =>\n Math.min(rules.swingSeconds.max, Math.max(rules.swingSeconds.min, rules.swingSeconds.base + rules.swingSeconds.perKg * Math.max(0, massKg)))\n\nexport type DoorUseHand = { readonly reaches: () => boolean; readonly pull: boolean }\n\nexport interface DoorUse {\n readonly phase: DoorUsePhase\n /** Where the leaf is going: 1 opening, 0 closing. */\n readonly goal: 0 | 1\n readonly opening: number\n /**\n * Starts using a leaf: the other way from where the last use sent it (`lastGoal`), else a closed or half-open leaf opens and an open\n * one closes. A use in the middle of a swing turns it round.\n * Answers the goal (1 open, 0 closed), or null when the leaf is locked (it rattles instead).\n */\n begin(target: DoorUseTarget): 0 | 1 | null\n /**\n * Advances the use; `isFree(from, to)` answers whether the leaf can go from one opening to the other (nothing in the way of its sweep). `hand` says whether the handle is still\n * within arm reach after the step and whether the leaf comes toward the body (`pull`): once the handle is out of reach the swing hands over to `push` (a leaf going away is shoved\n * on) or `release` (a leaf coming toward the body is let go) and the leaf finishes on its own. Without `hand` the hand never lets go.\n */\n step(dt: number, isFree: (from: number, to: number) => boolean, hand?: DoorUseHand): DoorUseStep\n /** Lets go at once. */\n cancel(): void\n}\n\nexport function createDoorUse(rules: Partial<DoorUseRules> = {}): DoorUse {\n const r: DoorUseRules = { ...DOOR_USE_DEFAULTS, ...rules, swingSeconds: { ...DOOR_USE_DEFAULTS.swingSeconds, ...rules.swingSeconds } }\n let phase: DoorUsePhase = 'idle'\n let goal: 0 | 1 = 1\n let opening = 0\n let time = 0\n let swing = 1\n let start = 0\n /** The hand let go and the leaf is still going to its goal on its own. */\n let coasting = false\n\n const out = (progress: number, arrived = false, b: DoorUseBlock = null): DoorUseStep => ({ phase, opening, progress: Math.max(0, Math.min(1, progress)), block: b, arrived })\n\n /** Moves the leaf toward its goal for `dt` seconds, a little at a time so it stops at the first thing in its way and not past it. */\n const advance = (dt: number, isFree: (from: number, to: number) => boolean): 'moving' | 'stopped' | 'arrived' => {\n const want = goal - opening\n const reach = Math.min(Math.abs(want), dt / swing)\n let moved = 0\n while (moved < reach - 1e-9) {\n const inc = Math.min(r.stepFraction, reach - moved)\n const next = opening + Math.sign(want) * inc\n if (!isFree(opening, next)) return 'stopped'\n opening = next\n moved += inc\n }\n return Math.abs(goal - opening) < 1e-6 ? 'arrived' : 'moving'\n }\n\n /** The hand coming back to rest; it waits there (progress 1) while the leaf still goes on its own. */\n const releaseOut = (arrived: boolean, b: DoorUseBlock = null): DoorUseStep => {\n const p = time / r.releaseSeconds\n if (p >= 1 && !coasting) phase = 'idle'\n return out(p, arrived, b)\n }\n\n return {\n get phase() {\n return phase\n },\n get goal() {\n return goal\n },\n get opening() {\n return opening\n },\n begin(target) {\n opening = Math.max(0, Math.min(1, target.opening))\n time = 0\n coasting = false\n if (target.locked) {\n phase = 'rattle'\n return null\n }\n // in the middle of a swing the hand is already on the handle: the leaf turns round at once\n if (phase === 'swing' || phase === 'reach') goal = goal === 1 ? 0 : 1\n else if (target.lastGoal !== undefined && opening > r.endTolerance && opening < 1 - r.endTolerance) goal = target.lastGoal === 1 ? 0 : 1\n else goal = opening > 0.5 ? 0 : 1\n swing = swingSecondsFor(target.massKg, r)\n start = opening\n phase = phase === 'swing' ? 'swing' : 'reach'\n return goal\n },\n step(dt, isFree, hand) {\n if (phase === 'idle') return out(0)\n time += dt\n if (phase === 'rattle') {\n const p = time / r.rattleSeconds\n if (p >= 1) {\n phase = 'idle'\n return out(1, false, 'locked')\n }\n return out(p, false, time === dt ? 'locked' : null)\n }\n if (phase === 'reach') {\n const p = time / r.reachSeconds\n if (p < 1) return out(p)\n phase = 'swing'\n time = 0\n start = opening\n }\n if (phase === 'swing' || phase === 'push' || coasting) {\n const result = advance(dt, isFree)\n const travel = Math.abs(goal - start) || 1\n const progress = 1 - Math.abs(goal - opening) / travel\n const inHand = phase !== 'release'\n if (result === 'stopped' || result === 'arrived') {\n if (result === 'arrived') opening = goal\n coasting = false\n if (inHand) {\n phase = 'release'\n time = 0\n }\n if (result === 'arrived') return inHand ? out(1, true) : releaseOut(true)\n return inHand ? out(progress, false, 'obstacle') : releaseOut(false, 'obstacle')\n }\n if (inHand && hand && !hand.reaches()) {\n time = 0\n if (hand.pull) {\n phase = 'release'\n coasting = true\n } else phase = 'push'\n return out(0)\n }\n if (phase === 'push') {\n if (time >= r.pushSeconds) {\n phase = 'release'\n time = 0\n coasting = true\n return out(0)\n }\n return out(time / r.pushSeconds)\n }\n if (phase === 'swing') return out(progress)\n }\n return releaseOut(false)\n },\n cancel() {\n phase = 'idle'\n time = 0\n },\n }\n}\n","/**\n * The hands and the weapon (decision of the owner, 2026-11-24): an interaction of one hand (a small thing picked up, a door, a switch) takes the free hand, the one that does not\n * hold the weapon, and the weapon stays in its hand; one of both hands (a big thing carried, a push, a climb) first puts the weapon away in a slot of the body that takes it\n * (a holster at the hip, a sling or back slot for a long gun) and, with none, lets it fall to the ground. A two-handed weapon (a rifle, a shotgun) leaves no hand free, so any\n * interaction puts it away or drops it. When the interaction ends, what was put away comes back to its hand; what fell stays on the ground.\n * A long gun on its sling (decision of the owner, 2026-11-25) is not put away: it swings onto the sling and hangs on the body (`sling`), and stays there after the interaction until\n * the player brings it back to the hands; with no sling worn it goes to the next slot that takes it (`SLOT_FALLBACKS`: the back).\n * A second weapon of the belt (a pistol or a knife in the other hand, decision of the owner 2026-11-27) is not thrown away when the holster is taken: it is tucked in the\n * belt (`SLOT_FALLBACKS`: hip, then belt) and comes back after, as the holstered one does. Picking something up never drops a weapon the body has a place for.\n * Engine-agnostic: the host says what is in each hand and which slots the body wears; this says which hand acts and what happens to each weapon.\n */\n\n/** `R` the weapon hand, `L` the other one. */\nexport type BodyHand = 'R' | 'L'\n\n/** A weapon in a hand: `hands` it takes (0 the bare hand, 1, 2) and the slot of the body that takes it (`hip`, `back`...), null when none does. */\nexport interface HandWeapon {\n readonly id: string\n readonly hands: 0 | 1 | 2\n readonly slot: string | null\n}\n\nexport interface HandsRules {\n /** A thing up to `maxKg` whose longest side is up to `maxLength` metres goes in one hand; anything bigger or heavier takes both. */\n readonly oneHand: { readonly maxKg: number; readonly maxLength: number }\n}\n\nexport const HANDS_DEFAULTS: HandsRules = { oneHand: { maxKg: 4, maxLength: 0.7 } }\n\n/** The slot a weapon goes to when the body wears none of its own (or it is taken): a long gun with no sling goes across the back, a second handgun or knife into the belt. */\nexport const SLOT_FALLBACKS: Readonly<Record<string, readonly string[]>> = { sling: ['back'], hip: ['belt'] }\n\n/** The belt: where a one-handed weapon is tucked when its own place on the body is taken. */\nexport const BELT_SLOT = 'belt'\n\n/** The slot of a long gun that hangs on its sling. */\nexport const SLING_SLOT = 'sling'\n\n/**\n * What a weapon does when the hands are wanted: `holster` goes to `slot` and comes back after; `sling` hangs on the body by its sling and stays there until it is brought back;\n * `drop` falls to the ground and stays there.\n */\nexport type HandsMoveKind = 'holster' | 'sling' | 'drop'\n\nexport interface HandsMove {\n readonly hand: BodyHand\n readonly weapon: string\n readonly move: HandsMoveKind\n readonly slot?: string\n}\n\nexport interface HandsPlan {\n /** The hand the interaction takes, or `both`. */\n readonly hand: BodyHand | 'both'\n /** What happens to each weapon that is in the way, the weapon hand first. */\n readonly moves: readonly HandsMove[]\n}\n\nexport interface PlanHandsParams {\n /** The hands the interaction takes (`interactionHandsFor` for a thing picked up). */\n readonly hands: 1 | 2\n /** What each hand holds; absent or null is an empty hand. */\n readonly weapons: { readonly R?: HandWeapon | null; readonly L?: HandWeapon | null }\n /** The slots the body wears and that are empty (a holster, a sling); one weapon each. */\n readonly slots: readonly string[]\n /** The slots tried when a weapon's own is not worn; default `SLOT_FALLBACKS`. */\n readonly fallbacks?: Readonly<Record<string, readonly string[]>>\n}\n\n/** How many hands it takes to carry a thing of `massKg` and `size` (metres, any order). */\nexport function interactionHandsFor(thing: { readonly massKg: number; readonly size?: readonly number[] }, rules: HandsRules = HANDS_DEFAULTS): 1 | 2 {\n const longest = Math.max(0, ...(thing.size ?? []))\n return thing.massKg > rules.oneHand.maxKg || longest > rules.oneHand.maxLength ? 2 : 1\n}\n\nconst holds = (weapon: HandWeapon | null | undefined): weapon is HandWeapon => !!weapon && weapon.hands > 0\n\n/** Which hand acts and what happens to each weapon in the way. */\nexport function planHands(params: PlanHandsParams): HandsPlan {\n const { R, L } = params.weapons\n const free = [...params.slots]\n const fallbacks = params.fallbacks ?? SLOT_FALLBACKS\n const stow = (hand: BodyHand, weapon: HandWeapon): HandsMove => {\n const own = weapon.slot === null ? [] : [weapon.slot, ...(fallbacks[weapon.slot] ?? [])]\n // a one-handed weapon (a second handgun, a compact SMG, a hatchet) is tucked in the belt when its own places are taken, never thrown away\n const tried = weapon.hands === 1 && !own.includes(BELT_SLOT) ? [...own, BELT_SLOT] : own\n const slot = tried.find((name) => free.includes(name))\n if (slot === undefined) return { hand, weapon: weapon.id, move: 'drop' }\n free.splice(free.indexOf(slot), 1)\n return { hand, weapon: weapon.id, move: slot === SLING_SLOT ? 'sling' : 'holster', slot }\n }\n if (params.hands === 2) {\n const moves = [...(holds(R) ? [stow('R', R)] : []), ...(holds(L) ? [stow('L', L)] : [])]\n return { hand: 'both', moves }\n }\n if (holds(L)) return { hand: 'L', moves: [stow('L', L)] }\n if (!holds(R)) return { hand: 'R', moves: [] }\n return { hand: 'L', moves: R.hands === 2 ? [stow('R', R)] : [] }\n}\n\n/** What comes back to the hands once the interaction ends: the weapons that were put away, each to its hand; the slung ones stay on the sling and the dropped ones on the ground. */\nexport function drawBackOf(plan: HandsPlan): readonly { readonly hand: BodyHand; readonly weapon: string }[] {\n return plan.moves.filter((move) => move.move === 'holster').map((move) => ({ hand: move.hand, weapon: move.weapon }))\n}\n","/**\n * Whether one person lifts a thing off the floor with the hands, from its mass and its size (the mass comes from the material of the SDK: density times volume, or\n * the real mass of the catalogue). The strength is the most a person lifts held against the body; a bulky thing is held away from it, and the back takes the load\n * times its lever (the horizontal multiplier of the NIOSH lifting equation: what is held at `H` metres from the spine is `closeReach / H` of what is held against\n * it). The thing is held the easiest way: its thinnest side away from the body, the hands around the middle one. A sofa (45 kg, 2 x 0.9 x 0.85 m) is held at\n * 0.58 m and weighs more than the 26 kg a person lifts that far out: it is pushed or dragged, not picked up. A gas bottle (16 kg, 0.36 m across) goes up.\n * Engine-agnostic: the host passes the mass and the box of the thing.\n */\n\nexport interface LiftRules {\n /** The most a person lifts held against the body, kg. */\n readonly maxKg: number\n /** Distance (m) from the spine to a load held against the body: NIOSH's 25 cm, where the lever costs nothing. */\n readonly closeReach: number\n /** Distance (m) from the spine to the near face of what is held: the front of the trunk. */\n readonly bodyDepth: number\n /** The widest a person holds between the hands around a thing, metres: the arms hugging it. */\n readonly maxSpan: number\n}\n\nexport const LIFT_DEFAULTS: LiftRules = { maxKg: 60, closeReach: 0.25, bodyDepth: 0.15, maxSpan: 1.3 }\n\n/** `ok` it goes up; `too_heavy` heavier than the strength even against the body; `too_bulky` too wide for the arms or too far out for its weight. */\nexport type LiftVerdict = 'ok' | 'too_heavy' | 'too_bulky'\n\nexport interface LiftCheck {\n readonly verdict: LiftVerdict\n /** The most this thing could weigh and still go up, held its easiest way, kg. */\n readonly liftableKg: number\n}\n\n/** Whether a thing of `massKg` and `size` (metres, any order; without it, a thing held against the body) goes up in one person's hands. */\nexport function liftCheckFor(thing: { readonly massKg: number; readonly size?: readonly number[] }, rules: Partial<LiftRules> = {}): LiftCheck {\n const r = { ...LIFT_DEFAULTS, ...rules }\n const [, middle = 0, thinnest = 0] = [...(thing.size ?? [])].sort((a, b) => b - a)\n const reach = r.bodyDepth + Math.max(0, thinnest) / 2\n const liftableKg = r.maxKg * Math.min(1, r.closeReach / Math.max(reach, 1e-6))\n if (thing.massKg > r.maxKg) return { verdict: 'too_heavy', liftableKg }\n if (middle > r.maxSpan || thing.massKg > liftableKg) return { verdict: 'too_bulky', liftableKg }\n return { verdict: 'ok', liftableKg }\n}\n","/**\n * The little pose algebra the hands need, engine-agnostic: a pose is a position and a unit quaternion `[x, y, z, w]` (local to world), as `HandPose` of game-contracts.\n */\n\nexport type Vec3Tuple = readonly [number, number, number]\nexport type QuatTuple = readonly [number, number, number, number]\n\nexport interface Pose {\n readonly position: Vec3Tuple\n readonly quaternion: QuatTuple\n}\n\n/** The rotation whose local x, y and z go to `x`, `y` and `z` (an orthonormal, right-handed basis). */\nexport function quaternionOfBasis(x: readonly number[], y: readonly number[], z: readonly number[]): [number, number, number, number] {\n const [m00, m10, m20] = [x[0] ?? 0, x[1] ?? 0, x[2] ?? 0]\n const [m01, m11, m21] = [y[0] ?? 0, y[1] ?? 0, y[2] ?? 0]\n const [m02, m12, m22] = [z[0] ?? 0, z[1] ?? 0, z[2] ?? 0]\n const trace = m00 + m11 + m22\n if (trace > 0) {\n const s = 0.5 / Math.sqrt(trace + 1)\n return [(m21 - m12) * s, (m02 - m20) * s, (m10 - m01) * s, 0.25 / s]\n }\n if (m00 > m11 && m00 > m22) {\n const s = 2 * Math.sqrt(1 + m00 - m11 - m22)\n return [0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s]\n }\n if (m11 > m22) {\n const s = 2 * Math.sqrt(1 + m11 - m00 - m22)\n return [(m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s]\n }\n const s = 2 * Math.sqrt(1 + m22 - m00 - m11)\n return [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s]\n}\n\nexport function multiplyQuaternions(a: QuatTuple, b: QuatTuple): [number, number, number, number] {\n const [ax, ay, az, aw] = a\n const [bx, by, bz, bw] = b\n return [ax * bw + aw * bx + ay * bz - az * by, ay * bw + aw * by + az * bx - ax * bz, az * bw + aw * bz + ax * by - ay * bx, aw * bw - ax * bx - ay * by - az * bz]\n}\n\nexport function conjugateQuaternion(q: QuatTuple): [number, number, number, number] {\n return [-q[0], -q[1], -q[2], q[3]]\n}\n\nexport function rotateVector(q: QuatTuple, v: Vec3Tuple): [number, number, number] {\n const [x, y, z, w] = q\n const tx = 2 * (y * v[2] - z * v[1])\n const ty = 2 * (z * v[0] - x * v[2])\n const tz = 2 * (x * v[1] - y * v[0])\n return [v[0] + w * tx + (y * tz - z * ty), v[1] + w * ty + (z * tx - x * tz), v[2] + w * tz + (x * ty - y * tx)]\n}\n\n/** `parent` then `local`: the pose of a thing given in the frame of `parent`. */\nexport function composePose(parent: Pose, local: Pose): Pose {\n const offset = rotateVector(parent.quaternion, local.position)\n return {\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\n quaternion: multiplyQuaternions(parent.quaternion, local.quaternion),\n }\n}\n\n/** The pose whose frame puts `local` at `world`: `composePose(result, local)` is `world`. */\nexport function poseHolding(world: Pose, local: Pose): Pose {\n const quaternion = multiplyQuaternions(world.quaternion, conjugateQuaternion(local.quaternion))\n const offset = rotateVector(quaternion, local.position)\n return { position: [world.position[0] - offset[0], world.position[1] - offset[1], world.position[2] - offset[2]], quaternion }\n}\n\n/** Between `a` (k 0) and `b` (k 1): the position on the line, the turn the short way round. */\nexport function blendPoses(a: Pose, b: Pose, k: number): Pose {\n const lerp = (i: 0 | 1 | 2): number => a.position[i] + (b.position[i] - a.position[i]) * k\n const dot = a.quaternion[0] * b.quaternion[0] + a.quaternion[1] * b.quaternion[1] + a.quaternion[2] * b.quaternion[2] + a.quaternion[3] * b.quaternion[3]\n const sign = dot < 0 ? -1 : 1\n const mixed = [0, 1, 2, 3].map((i) => (a.quaternion[i] ?? 0) * (1 - k) + (b.quaternion[i] ?? 0) * sign * k)\n const length = Math.hypot(...mixed) || 1\n return { position: [lerp(0), lerp(1), lerp(2)], quaternion: [(mixed[0] ?? 0) / length, (mixed[1] ?? 0) / length, (mixed[2] ?? 0) / length, (mixed[3] ?? 1) / length] }\n}\n\n/** Slow in, slow out: a hand speeds up off its start and settles on its target. */\nexport function easeInOut(t: number): number {\n const k = Math.min(1, Math.max(0, t))\n return k * k * (3 - 2 * k)\n}\n","/**\n * How a hand closes on a thing it picks up (decision of the owner, 2026-11-25: the hand on the thing's real grip, the fingers closed around it, the thing in the palm, aligned with\n * the hand in both views). Engine-agnostic: the thing is its box (`size`, metres, in its own frame), the hand frame is the one of `HandTargets`: +x along the fingers, +y the back\n * of the hand, the thumb at -z for a right hand and +z for a left one. The thing's longest side runs through the fist along the thumb (a bottle stands up in a hand held thumb up),\n * its thinnest side across the palm (the palm lies on its broad face), and its middle sits a palm's thickness plus half that side under the middle of the palm.\n */\nimport type { BodyHand } from './hands'\nimport { composePose, poseHolding, quaternionOfBasis } from './hand-math'\nimport type { Pose, Vec3Tuple } from './hand-math'\n\nexport const ITEM_GRIP = {\n /** Half the thickness of a palm (m): what lies between the middle of the palm and the thing. */\n palm: 0.011,\n /** The closure of the fingers (0 open, 1 a fist) on a thing this thick (m) or thinner. */\n fistAt: 0.03,\n closed: 0.95,\n /** How much the closure opens per metre the thing is thicker than `fistAt`, and the most it opens to. */\n openPerMetre: 4,\n open: 0.35,\n /** The fingers before they close on it, as the hand comes to the thing. */\n reaching: 0.15,\n} as const\n\nexport interface ItemGrip {\n /** The thing's middle and turn in the frame of the hand. */\n readonly local: Pose\n /** How closed the fingers are on it (`HandTargets.grip`). */\n readonly grip: number\n}\n\nconst AXES: readonly Vec3Tuple[] = [\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n]\n\nconst cross = (a: Vec3Tuple, b: Vec3Tuple): Vec3Tuple => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]\nconst scaled = (v: Vec3Tuple, k: number): Vec3Tuple => [v[0] * k, v[1] * k, v[2] * k]\n\n/** The grip of a hand on a thing of box `size` (its own frame, metres). */\nexport function gripOfItem(size: readonly number[], hand: BodyHand): ItemGrip {\n const sides = [0, 1, 2].map((axis) => ({ axis, length: Math.max(0, size[axis] ?? 0) })).sort((a, b) => b.length - a.length)\n const [long, mid, thin] = sides as [(typeof sides)[0], (typeof sides)[0], (typeof sides)[0]]\n const thumb: Vec3Tuple = hand === 'R' ? [0, 0, -1] : [0, 0, 1]\n // where each of the thing's own axes goes in the hand: the long one along the thumb, the thin one across the palm, the last one keeps the frame right-handed\n const columns: Vec3Tuple[] = [AXES[0] as Vec3Tuple, AXES[1] as Vec3Tuple, AXES[2] as Vec3Tuple]\n columns[long.axis] = thumb\n columns[thin.axis] = [0, 1, 0]\n const next = (axis: number): number => (axis + 1) % 3\n // x × y = z for the thing's frame: the column after `mid` crossed with the one after that names it\n const before = columns[next(next(mid.axis))] as Vec3Tuple\n const after = columns[next(mid.axis)] as Vec3Tuple\n columns[mid.axis] = cross(after, before)\n const quaternion = quaternionOfBasis(columns[0] as Vec3Tuple, columns[1] as Vec3Tuple, columns[2] as Vec3Tuple)\n const depth = ITEM_GRIP.palm + thin.length / 2\n const across = (mid.length + thin.length) / 2\n const grip = Math.max(ITEM_GRIP.open, Math.min(ITEM_GRIP.closed, ITEM_GRIP.closed - ITEM_GRIP.openPerMetre * Math.max(0, across - ITEM_GRIP.fistAt)))\n return { local: { position: scaled([0, -1, 0], depth), quaternion }, grip }\n}\n\n/** Where the thing is with the hand at `hand` holding it by `grip`. */\nexport function itemPoseInHand(hand: Pose, grip: ItemGrip): Pose {\n return composePose(hand, grip.local)\n}\n\n/** Where the hand goes to take the thing where it lies (`item`, its middle and turn) by `grip`. */\nexport function handPoseOnItem(item: Pose, grip: ItemGrip): Pose {\n return poseHolding(item, grip.local)\n}\n","/**\n * The hands take a thing in steps one can see (decision of the owner, 2026-11-25): first each weapon in the way goes off the hands (`stow` to its holster, `sling` onto its sling, or\n * `drop`: tossed to the ground), then the hand `reach`es the thing's grip, the fingers `close` on it, and it is `lift`ed to where it is carried. A weapon comes back to the hands the\n * same way round (`draw`). Engine-agnostic and clock-free: the host advances it by its own frame's `dt` and does what each step says.\n */\nimport type { HandsMove, HandsPlan } from './hands'\nimport { easeInOut } from './hand-math'\n\n/** Seconds each step takes. */\nexport interface HandsTiming {\n readonly stow: number\n readonly sling: number\n readonly drop: number\n readonly reach: number\n readonly close: number\n readonly lift: number\n readonly draw: number\n}\n\nexport const HANDS_TIMING: HandsTiming = { stow: 0.5, sling: 0.45, drop: 0.4, reach: 0.38, close: 0.16, lift: 0.3, draw: 0.5 }\n\nexport type TakeStepKind = 'stow' | 'sling' | 'drop' | 'reach' | 'close' | 'lift' | 'draw'\n\nexport interface TakeStep {\n readonly kind: TakeStepKind\n /** The weapon the step moves (`stow`, `sling`, `drop`, `draw`). */\n readonly move?: HandsMove\n readonly start: number\n readonly end: number\n}\n\nexport interface TakeSequence {\n readonly steps: readonly TakeStep[]\n readonly duration: number\n}\n\nconst KIND_OF_MOVE: Readonly<Record<HandsMove['move'], 'stow' | 'sling' | 'drop'>> = { holster: 'stow', sling: 'sling', drop: 'drop' }\n\nconst lay = (parts: readonly { readonly kind: TakeStepKind; readonly seconds: number; readonly move?: HandsMove }[]): TakeSequence => {\n let at = 0\n const steps = parts.map((part) => {\n const step: TakeStep = { kind: part.kind, start: at, end: at + part.seconds, ...(part.move ? { move: part.move } : {}) }\n at = step.end\n return step\n })\n return { steps, duration: at }\n}\n\n/** The steps of taking a thing with `plan`: the weapons off the hands (the off hand first), then reach, close and lift. `take` false leaves the thing out (a push). */\nexport function planTakeSequence(plan: HandsPlan, options: { readonly timing?: HandsTiming; readonly take?: boolean } = {}): TakeSequence {\n const timing = options.timing ?? HANDS_TIMING\n const moves = [...plan.moves].reverse().map((move) => ({ kind: KIND_OF_MOVE[move.move], seconds: timing[KIND_OF_MOVE[move.move]], move }))\n const take = options.take === false ? [] : [\n { kind: 'reach' as const, seconds: timing.reach },\n { kind: 'close' as const, seconds: timing.close },\n { kind: 'lift' as const, seconds: timing.lift },\n ]\n return lay([...moves, ...take])\n}\n\n/** The steps of bringing weapons back to the hands, one after the other. */\nexport function planDrawSequence(moves: readonly HandsMove[], timing: HandsTiming = HANDS_TIMING): TakeSequence {\n return lay(moves.map((move) => ({ kind: 'draw' as const, seconds: timing.draw, move })))\n}\n\nexport interface TakeProgress {\n /** The step going on now, null once the sequence is over. */\n readonly step: TakeStep | null\n /** How far into it, 0..1, eased (slow in, slow out). */\n readonly progress: number\n /** The steps that began during this advance, in order. */\n readonly started: readonly TakeStep[]\n /** The steps that ended during this advance, in order. */\n readonly ended: readonly TakeStep[]\n readonly done: boolean\n}\n\nexport interface TakeTimeline {\n readonly sequence: TakeSequence\n /** Seconds since it began. */\n readonly time: number\n /** Moves the timeline on by `dt` seconds (the host's frame). The first call with 0 starts the first step. */\n advance(dt: number): TakeProgress\n}\n\nexport function createTakeTimeline(sequence: TakeSequence): TakeTimeline {\n let time = 0\n // the steps already begun and already over: each is reported once\n let begun = 0\n let over = 0\n const steps = sequence.steps\n return {\n sequence,\n get time() {\n return time\n },\n advance(dt) {\n time = Math.min(sequence.duration, time + Math.max(0, dt))\n const startedFrom = begun\n while (begun < steps.length && (steps[begun] as TakeStep).start <= time) begun++\n const endedFrom = over\n while (over < begun && (steps[over] as TakeStep).end <= time) over++\n const started = steps.slice(startedFrom, begun)\n const ended = steps.slice(endedFrom, over)\n const step = steps.find((entry) => time < entry.end) ?? null\n const progress = step ? easeInOut((time - step.start) / Math.max(1e-6, step.end - step.start)) : 1\n return { step, progress, started, ended, done: time >= sequence.duration }\n },\n }\n}\n","/**\n * Draws a body that moves in fixed steps between two of them: remember the last two step poses, blend by the scheduler's `alpha` (CLAUDE.md §15).\n * Drawn at the step pose, a body moves 0, 1 or 2 steps per frame at a display that is not the step's rate: it stutters.\n */\n\nexport type StepPosition = { readonly x: number; readonly y: number; readonly z: number }\n\nexport type StepPoseOptions = {\n /** A step longer than this (metres) is a teleport (a respawn, a placed body): drawn at the new pose at once, never swept across. Default 3. */\n readonly teleportDistance?: number\n}\n\nexport type StepPose = {\n /** The body's pose after a fixed step. */\n record(position: StepPosition): void\n /** Puts both poses on `position`: nothing is blended from where the body was. */\n reset(position: StepPosition): void\n /** The pose to draw: `alpha` in [0, 1] is how far the frame is into the next step. */\n blend(alpha: number): StepPosition\n}\n\nexport const STEP_POSE_DEFAULTS = { teleportDistance: 3 } as const\n\nexport function createStepPose(start: StepPosition, options: StepPoseOptions = {}): StepPose {\n const teleportDistance = options.teleportDistance ?? STEP_POSE_DEFAULTS.teleportDistance\n let previous = { x: start.x, y: start.y, z: start.z }\n let current = { x: start.x, y: start.y, z: start.z }\n return {\n record(position) {\n previous = current\n current = { x: position.x, y: position.y, z: position.z }\n if (Math.hypot(current.x - previous.x, current.y - previous.y, current.z - previous.z) > teleportDistance) previous = current\n },\n reset(position) {\n previous = { x: position.x, y: position.y, z: position.z }\n current = previous\n },\n blend(alpha) {\n const k = Math.min(1, Math.max(0, alpha))\n return { x: previous.x + (current.x - previous.x) * k, y: previous.y + (current.y - previous.y) * k, z: previous.z + (current.z - previous.z) * k }\n },\n }\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;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;IAC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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/data/defaults.json","../src/needs.ts","../src/rng.ts","../src/vitals.ts","../src/player.ts","../src/physics-controller.ts","../src/foot-rest.ts","../src/walker.ts","../src/furniture-push.ts","../src/locales/index.ts","../src/bench/locale.ts","../src/bench/module.ts","../src/door-use.ts","../src/hands.ts","../src/lift.ts","../src/hand-math.ts","../src/item-grip.ts","../src/take-sequence.ts","../src/step-pose.ts"],"sourcesContent":["export { PLAYER_DEFAULTS, createPlayer, deriveVitals, drawWound } from './player'\nexport type { Player, PlayerCollider, PlayerOptions } from './player'\nexport { PLAYER_MASS_KG, PLAYER_PUSH_STRENGTH_NEWTONS, PLAYER_WALK_PUSH_NEWTONS, createPhysicsController } from './physics-controller'\nexport type { PhysicsControllerOptions, PhysicsPlayerController, PlayerPhysicsWorld } from './physics-controller'\nexport { footRestHeight } from './foot-rest'\nexport { WALKER_JUMP_SPEED, createWalker } from './walker'\nexport type { Walker, WalkerOptions, WalkerServices, WalkerStance } from './walker'\nexport { createRng } from './rng'\nexport { FURNITURE_PUSH_DEFAULTS, canPush, createFurniturePush, dragMarkFor, frictionFor, gripSecondsFor, pushAccelerationFor, pushSpeedFor, slipsOnTop } from './furniture-push'\nexport type { DragMark, FurniturePush, FurniturePushBlock, FurniturePushLoad, FurniturePushInput, FurniturePushPhase, FurniturePushRules, FurniturePushStep, FurniturePushTarget } from './furniture-push'\nexport { PLAYER_TEXT, playerTextOf } from './locales'\nexport type { PlayerText } from './locales'\n/** @deprecated import from '@adatechnology/game-player/testing' */\nexport { createPlayerTestModule } from './testing'\n/** @deprecated import from '@adatechnology/game-player/testing' */\nexport type { PlayerTestModule, PlayerTestModuleOptions } from './testing'\nexport type * from './types'\nexport { DOOR_ARM_REACH, DOOR_SHOULDER_HEIGHT, DOOR_USE_DEFAULTS, createDoorUse, swingSecondsFor } from './door-use'\nexport type { DoorUse, DoorUseBlock, DoorUseHand, DoorUsePhase, DoorUseRules, DoorUseStep, DoorUseTarget } from './door-use'\nexport { BELT_SLOT, HANDS_DEFAULTS, SLING_SLOT, SLOT_FALLBACKS, drawBackOf, interactionHandsFor, planHands } from './hands'\nexport type { BodyHand, HandWeapon, HandsMove, HandsMoveKind, HandsPlan, HandsRules, PlanHandsParams } from './hands'\nexport { LIFT_DEFAULTS, liftCheckFor } from './lift'\nexport type { LiftCheck, LiftRules, LiftVerdict } from './lift'\nexport { blendPoses, composePose, conjugateQuaternion, easeInOut, multiplyQuaternions, poseHolding, quaternionOfBasis, rotateVector } from './hand-math'\nexport type { Pose, QuatTuple, Vec3Tuple } from './hand-math'\nexport { ITEM_GRIP, gripOfItem, handPoseOnItem, itemPoseInHand } from './item-grip'\nexport type { ItemGrip } from './item-grip'\nexport { HANDS_TIMING, createTakeTimeline, planDrawSequence, planTakeSequence } from './take-sequence'\nexport type { HandsTiming, TakeProgress, TakeSequence, TakeStep, TakeStepKind, TakeTimeline } from './take-sequence'\nexport { STEP_POSE_DEFAULTS, createStepPose } from './step-pose'\nexport type { StepPose, StepPoseOptions, StepPosition } from './step-pose'\nexport { NEEDS_DEFAULTS, advanceNeeds, createNeedsState, isStarving, needsHoursOf, nourish } from './needs'\nexport type { NeedsRules, NeedsState, Nourishment } from './needs'\nexport { applyItemEffect, createBodyVitals } from './vitals'\nexport type { BodyVitals, BodyVitalsOptions, BodyVitalsState, ItemEffect, ItemEffectResult, VitalsBody } from './vitals'\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', '+', '-']\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 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 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 { 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","{\n \"sources\": {\n \"game\": \"specs/001-migracao-entregas-dos-times/artefatos/2UG1Mhe9LqJkQKKVsJkTWR/jogo.js\",\n \"attributes\": \"G 62004 FICHA (Personagens 3.2: every attribute 5, no traits)\",\n \"derived\": \"G 62005-62012 DERIV\",\n \"wounds\": \"G 62016 FERIDA (Personagens 3.7): share of each wound kind, and its infection chance (used only when an infection rule is on)\",\n \"infection\": \"G 62015 INFEC (the slice's accelerated clock: fever 30 s, delirium 70 s, death 120 s, reanimation 8 s after); G 68509 fever noise\",\n \"numbers\": \"G 68427-68640 player, playerUpdate, frontZombies, shove, knife; G 68678-68681 the aim spread modifiers; G 65507 walkCad\",\n \"needs\": \"G 57255 needs (fome 20, sede 20 at the start; 0 is fed, 100 starving), G 57271 useItem (food takes off its f, drink its s), G 57341-57344 (1 game hour = 50 s of the slice; hunger 2.5/h, 4/h running, thirst 4/h, times 1.1 - 0.02 x vigor; over 90 the body loses 0.2 health a second)\"\n },\n \"needs\": {\n \"start\": { \"hunger\": 20, \"thirst\": 20 },\n \"max\": 100,\n \"gameHourSeconds\": 50,\n \"hungerPerHour\": 2.5,\n \"hungerRunningPerHour\": 4,\n \"thirstPerHour\": 4,\n \"vigorBase\": 1.1,\n \"vigorPerPoint\": -0.02,\n \"starvingAt\": 90,\n \"starvingDamagePerSecond\": 0.2\n },\n \"attributes\": { \"strength\": 5, \"vigor\": 5, \"agility\": 5, \"perception\": 5, \"intellect\": 5, \"presence\": 5 },\n \"derived\": {\n \"maxHealth\": { \"base\": 70, \"terms\": [[\"vigor\", 6]] },\n \"maxStamina\": { \"base\": 40, \"terms\": [[\"vigor\", 6], [\"agility\", 4]] },\n \"runSpeed\": { \"base\": 5.2, \"terms\": [[\"agility\", 0.12]] },\n \"walkSpeed\": { \"base\": 1.6, \"terms\": [] },\n \"footstepNoise\": { \"base\": 100, \"terms\": [[\"agility\", -4]], \"divide\": 100 },\n \"composure\": { \"base\": 20, \"terms\": [[\"vigor\", 3], [\"presence\", 4]] }\n },\n \"wounds\": {\n \"scratch\": { \"share\": 0.6, \"infectionChance\": 0.06, \"bleeds\": false },\n \"laceration\": { \"share\": 0.3, \"infectionChance\": 0.22, \"bleeds\": true },\n \"bite\": { \"share\": 0.1, \"infectionChance\": 1, \"bleeds\": true }\n },\n \"infection\": {\n \"feverSeconds\": 30,\n \"deliriumSeconds\": 70,\n \"deathSeconds\": 120,\n \"reanimateSeconds\": 8,\n \"feverNoiseEvery\": 2,\n \"feverNoiseChance\": 0.5,\n \"feverNoiseRadius\": 10,\n \"feverNoiseVolume\": 2,\n \"feverSpeed\": 0.85,\n \"feverSpread\": 1.5\n },\n \"numbers\": {\n \"hurtFlash\": 0.4,\n \"hurtVolume\": 0.8,\n \"biteDamage\": 25,\n \"biteFlash\": 0.8,\n \"biteVolume\": 1.2,\n \"burnPerSecond\": 3,\n \"bleedPerSecond\": 0.15,\n \"grabSeconds\": 3,\n \"grabVolume\": 1,\n \"grabFollow\": 12,\n \"grabOffset\": 0.55,\n \"grabPushCost\": 6,\n \"grabPushMinStamina\": 5,\n \"grabPushVolume\": 1.5,\n \"grabPushes\": 6,\n \"grabPushStun\": 1.2,\n \"grabPushSpeed\": 3,\n \"grabKnifeChance\": 0.7,\n \"grabKnifeRegion\": 0,\n \"grabKnifeDamage\": 22,\n \"grabKnifeDistance\": 0.5,\n \"grabKnifeCut\": 0.7,\n \"drownDamage\": 30,\n \"drownFlash\": 0.8,\n \"noJawDamage\": 8,\n \"grabAttackCooldown\": 2,\n \"vaultSeconds\": 0.7,\n \"vaultCost\": 15,\n \"vaultHeight\": 1.9,\n \"vaultScanFrom\": 0.3,\n \"vaultScanTo\": 1.0,\n \"vaultScanStep\": 0.1,\n \"vaultLandFrom\": 0.4,\n \"vaultLandTo\": 1.4,\n \"vaultClearance\": 0.3,\n \"vaultCheckHeight\": 0.4,\n \"vaultNoise\": 6,\n \"vaultStartVolume\": 0.8,\n \"vaultLandVolume\": 1,\n \"crouchSpeed\": 1.0,\n \"walkFactor\": 1.35,\n \"aimSpeedCap\": 1.4,\n \"waterSpeed\": 0.55,\n \"runMinStamina\": 1,\n \"runDrain\": 12,\n \"regenMoving\": 4,\n \"regenStill\": 8,\n \"acceleration\": 10,\n \"heightMetres\": 1.8,\n \"crouchHeightRatio\": 0.65,\n \"radius\": 0.3,\n \"blockHeight\": 0.4,\n \"pushApartRadius\": 0.55,\n \"pushApartHeight\": 1.2,\n \"hipFollow\": 10,\n \"hipMinSpeed\": 0.3,\n \"hipLimit\": 0.9,\n \"backwardsBelow\": -0.1,\n \"cadenceBase\": 0.5,\n \"cadencePerSpeed\": 0.3,\n \"cadenceMinSpeed\": 0.05,\n \"turnFollow\": 12,\n \"stepEvery\": 0.75,\n \"stepMinSpeed\": 0.3,\n \"stepNoiseRun\": 8,\n \"stepNoiseWalk\": 3,\n \"stepNoiseCrouch\": 1,\n \"stepNoiseWater\": 2,\n \"stepVolumeRun\": 0.6,\n \"stepVolumeWalk\": 0.3,\n \"shoveCost\": 10,\n \"shoveVolume\": 1.2,\n \"shoveRange\": 1.6,\n \"shoveCone\": 0.3,\n \"shoveStun\": 0.9,\n \"shoveSpeed\": 2.5,\n \"meleeMinStamina\": 5,\n \"meleeCostLight\": 5,\n \"meleeCostHeavy\": 12,\n \"meleeHeavyKg\": 1.5,\n \"meleeVolume\": 0.6,\n \"meleeRangeBase\": 0.9,\n \"meleeCone\": 0.5,\n \"meleeHeadChance\": 0.35,\n \"meleeArmChance\": 0.5,\n \"meleeStrengthPerPoint\": 0.06,\n \"meleeStrengthBase\": 5,\n \"meleeCritToCut\": 60,\n \"panicGain\": 1.2,\n \"panicDecay\": 3,\n \"panicMax\": 100,\n \"panicSpreadAt\": 0.6,\n \"panicSpread\": 1.4,\n \"moveSpread\": 0.4\n },\n \"fist\": { \"damage\": 8, \"crit\": 0, \"reach\": 0.5, \"noise\": 1 }\n}\n","/**\n * Hunger and thirst of a body (the team game's `needs`, G 57255-57344): two levels from 0 (fed, quenched) to `max` (starving, parched) that rise with the game's\n * clock, faster when running and slower for a stronger body, and fall by what the body eats and drinks (`satiety` and `hydration` of an item, the thirst a litre\n * of a liquid quenches). Past `starvingAt` either one costs health every second. Pure and allocation-free: the host keeps one `NeedsState` and passes it in.\n */\nimport defaults from './data/defaults.json'\n\nexport type NeedsRules = typeof defaults.needs\n\n/** The rules the team game shipped. */\nexport const NEEDS_DEFAULTS: NeedsRules = defaults.needs\n\n/** Where a body stands: `hunger` and `thirst`, 0 fed and quenched, `NeedsRules.max` starving. */\nexport interface NeedsState {\n hunger: number\n thirst: number\n}\n\n/** What the body ate or drank: points of hunger (`satiety`) and of thirst (`hydration`) it takes off; a negative number adds (salted fish makes you thirsty). */\nexport interface Nourishment {\n readonly satiety?: number\n readonly hydration?: number\n}\n\n/** A fresh body's needs (`rules.start`). */\nexport const createNeedsState = (rules: NeedsRules = NEEDS_DEFAULTS): NeedsState => ({ hunger: rules.start.hunger, thirst: rules.start.thirst })\n\nconst clamp = (value: number, max: number): number => (value < 0 ? 0 : value > max ? max : value)\n\n/** Game hours `dt` seconds are for a body of `vigor` (the vigor factor of the team game: 1.1 − 0.02 × vigor; never below zero). */\nexport const needsHoursOf = (dt: number, vigor: number, rules: NeedsRules = NEEDS_DEFAULTS): number =>\n (Math.max(0, dt) / rules.gameHourSeconds) * Math.max(0, rules.vigorBase + rules.vigorPerPoint * vigor)\n\n/** Either need is past `starvingAt`. */\nexport const isStarving = (state: NeedsState, rules: NeedsRules = NEEDS_DEFAULTS): boolean => state.hunger > rules.starvingAt || state.thirst > rules.starvingAt\n\n/** Moves `state` on by `dt` seconds and answers the health it costs in that time (0 unless the body is starving or parched). */\nexport function advanceNeeds(state: NeedsState, dt: number, body: { readonly running?: boolean; readonly vigor: number }, rules: NeedsRules = NEEDS_DEFAULTS): number {\n const hours = needsHoursOf(dt, body.vigor, rules)\n state.hunger = clamp(state.hunger + (body.running ? rules.hungerRunningPerHour : rules.hungerPerHour) * hours, rules.max)\n state.thirst = clamp(state.thirst + rules.thirstPerHour * hours, rules.max)\n return isStarving(state, rules) ? rules.starvingDamagePerSecond * Math.max(0, dt) : 0\n}\n\n/** Takes what was eaten or drunk off `state` (kept within 0 and `max`) and answers how much each level moved (negative: it went down). */\nexport function nourish(state: NeedsState, food: Nourishment, rules: NeedsRules = NEEDS_DEFAULTS): { hunger: number; thirst: number } {\n const hunger = state.hunger\n const thirst = state.thirst\n state.hunger = clamp(hunger - (food.satiety ?? 0), rules.max)\n state.thirst = clamp(thirst - (food.hydration ?? 0), rules.max)\n return { hunger: state.hunger - hunger, thirst: state.thirst - thirst }\n}\n","const FNV_OFFSET = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\nconst MIX = 0x9e3779b1\n\n/** Deterministic mulberry32 generator; returns floats in [0, 1). */\nexport function createRng(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let mixed = Math.imul(state ^ (state >>> 15), state | 1)\n mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61)\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** A seed for the stream called `name`: the same seed gives each name its own sequence, so lightning never shifts the schedule. */\nexport function streamSeed(seed: number, name: string): number {\n let hash = FNV_OFFSET\n for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), FNV_PRIME) >>> 0\n return Math.imul((seed >>> 0) ^ hash, MIX) >>> 0\n}\n\nexport function createStream(seed: number, name: string): () => number {\n return createRng(streamSeed(seed, name))\n}\n\nexport function drawBetween(rng: () => number, range: readonly [min: number, max: number]): number {\n return range[0] + rng() * (range[1] - range[0])\n}\n","/**\n * What an item used in the hand does to the body (the team game's `useItem`, G 57269-57279): food and drink take their satiety and hydration off hunger and thirst,\n * a painkiller gives back health, a dressing stops the bleeding, alcohol or iodine cleans the last wound, a sedative takes the panic away. The effect comes as the\n * catalogue resolved it (`ModuleItemUse.effect` of game-contracts, from `resolveUse` of game-items), so the numbers are the item's own. `createBodyVitals` is the\n * same body for a host that has no `createPlayer` (a test room): health, bleeding, wounds, panic and the needs, on the same rules.\n */\nimport type { ModuleItemUse } from '@adatechnology/game-contracts'\n\nimport { NEEDS_DEFAULTS, advanceNeeds, createNeedsState, nourish } from './needs'\nimport type { NeedsRules, NeedsState } from './needs'\n\n/** The effect of an item as the catalogue gives it (`ModuleItemUse.effect`). */\nexport type ItemEffect = NonNullable<ModuleItemUse['effect']>\n\n/** The part of a body an item's effect changes: `createPlayer`'s state has it all, and so does `createBodyVitals`. */\nexport interface VitalsBody extends NeedsState {\n health: number\n bleeding: number\n panic: number\n wounds: string[]\n}\n\n/** What an effect did: `applied` false when it means nothing to the body (washing, a light) or found nothing to do (no wound to clean). */\nexport interface ItemEffectResult {\n readonly applied: boolean\n /** How much each moved (negative: down). */\n readonly health: number\n readonly hunger: number\n readonly thirst: number\n readonly stoppedBleeding: boolean\n /** The wound kind cleaned, if one was. */\n readonly cleaned?: string\n readonly calmed: boolean\n}\n\nconst NOTHING: ItemEffectResult = { applied: false, health: 0, hunger: 0, thirst: 0, stoppedBleeding: false, calmed: false }\n\nconst numberOf = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)\n\n/** Applies an item's effect to `body` and answers what changed. `maxHealth` caps a heal. */\nexport function applyItemEffect(body: VitalsBody, effect: ItemEffect, limits: { readonly maxHealth: number; readonly needs?: NeedsRules }): ItemEffectResult {\n switch (effect.id) {\n case 'consume_nutrition': {\n const moved = nourish(body, { satiety: numberOf(effect.satiety), hydration: numberOf(effect.hydration) }, limits.needs ?? NEEDS_DEFAULTS)\n return { ...NOTHING, applied: true, hunger: moved.hunger, thirst: moved.thirst }\n }\n case 'heal': {\n const before = body.health\n body.health = Math.min(limits.maxHealth, before + Math.max(0, numberOf(effect.params?.amount)))\n return { ...NOTHING, applied: true, health: body.health - before }\n }\n case 'stop_bleeding': {\n const stopped = body.bleeding > 0\n body.bleeding = 0\n return { ...NOTHING, applied: true, stoppedBleeding: stopped }\n }\n case 'clean_wound': {\n const cleaned = body.wounds.pop()\n return cleaned === undefined ? NOTHING : { ...NOTHING, applied: true, cleaned }\n }\n case 'calm': {\n const calmed = body.panic > 0\n body.panic = 0\n return { ...NOTHING, applied: true, calmed }\n }\n default:\n return NOTHING\n }\n}\n\nexport interface BodyVitalsOptions {\n /** Health the body starts with and can be healed to. Default 100. */\n readonly maxHealth?: number\n /** Health lost per second while bleeding (`numbers.bleedPerSecond` of the player, 0.15). */\n readonly bleedPerSecond?: number\n /** Vigor of the body (the attribute, default 5): a stronger body gets hungry and thirsty slower. */\n readonly vigor?: number\n readonly needs?: Partial<NeedsRules>\n}\n\nexport interface BodyVitalsState extends VitalsBody {\n alive: boolean\n /** Why it died (`hunger_thirst`, `bled_out`), empty while alive. */\n cause: string\n}\n\n/** A body's vitals without the rest of the player: the needs on the game clock, the bleeding, and the item effects. */\nexport interface BodyVitals {\n readonly state: BodyVitalsState\n readonly maxHealth: number\n readonly rules: NeedsRules\n /** Moves the body on `dt` seconds of the game. */\n update(dt: number, input?: { readonly running?: boolean }): void\n apply(effect: ItemEffect): ItemEffectResult\n reset(): void\n}\n\nexport function createBodyVitals(options: BodyVitalsOptions = {}): BodyVitals {\n const maxHealth = options.maxHealth ?? 100\n const bleedPerSecond = options.bleedPerSecond ?? 0.15\n const vigor = options.vigor ?? 5\n const rules: NeedsRules = { ...NEEDS_DEFAULTS, ...options.needs, start: { ...NEEDS_DEFAULTS.start, ...options.needs?.start } }\n const fresh = (): BodyVitalsState => ({ ...createNeedsState(rules), health: maxHealth, bleeding: 0, panic: 0, wounds: [], alive: true, cause: '' })\n const state = fresh()\n return {\n state,\n maxHealth,\n rules,\n update(dt, input = {}) {\n if (!state.alive || dt <= 0) return\n state.health -= advanceNeeds(state, dt, { running: input.running ?? false, vigor }, rules)\n if (state.bleeding > 0) state.health -= bleedPerSecond * dt\n if (state.health <= 0) {\n state.health = 0\n state.alive = false\n state.cause = state.bleeding > 0 ? 'bled_out' : 'hunger_thirst'\n }\n },\n apply: (effect) => (state.alive ? applyItemEffect(state, effect, { maxHealth, needs: rules }) : NOTHING),\n reset() {\n Object.assign(state, fresh())\n },\n }\n}\n","import { SWING_LEAD_SECONDS, footstepSoundId, hitSoundId, landSoundId, surfaceOfMaterial, swingSoundId } from '@adatechnology/game-contracts'\nimport type { BlowId, BodyFoleyId, SurfaceId } from '@adatechnology/game-contracts'\n\nimport defaults from './data/defaults.json'\nimport { NEEDS_DEFAULTS, advanceNeeds } from './needs'\nimport type { NeedsRules } from './needs'\nimport { createRng } from './rng'\nimport { applyItemEffect } from './vitals'\nimport type { ItemEffect, ItemEffectResult } from './vitals'\nimport type {\n Attributes,\n DeathCause,\n Derived,\n DerivedFormulas,\n DerivedId,\n InfectionRule,\n LinearFormula,\n MeleeItem,\n PlayerAction,\n PlayerCrowd,\n PlayerEventMap,\n PlayerEventName,\n PlayerInput,\n PlayerMessageId,\n PlayerNumbers,\n PlayerSave,\n PlayerSoundId,\n PlayerState,\n PlayerWorld,\n WoundTable,\n} from './types'\n\nexport const PLAYER_DEFAULTS = defaults as unknown as {\n readonly sources: Readonly<Record<string, string>>\n readonly attributes: Attributes\n readonly derived: DerivedFormulas\n readonly wounds: WoundTable\n readonly infection: InfectionRule\n readonly numbers: PlayerNumbers\n readonly fist: MeleeItem\n}\n\nexport type PlayerOptions = {\n /** The random stream (the game passes its single stream). Default `createRng(seed)`. */\n readonly random?: () => number\n readonly seed?: number\n /** The sheet: every attribute 5 by default. */\n readonly attributes?: Partial<Attributes>\n readonly derived?: Partial<DerivedFormulas>\n readonly wounds?: WoundTable\n /** An individual infection (`true` uses the defaults; an object patches them). Off by default: the normal world comes first. */\n readonly infection?: boolean | Partial<InfectionRule>\n readonly numbers?: Partial<PlayerNumbers>\n /** Hunger and thirst (`NEEDS_DEFAULTS`, the team game's): an object patches them, `false` keeps them still. */\n readonly needs?: boolean | Partial<NeedsRules>\n readonly fist?: MeleeItem\n readonly position?: { readonly x?: number; readonly z?: number; readonly yaw?: number }\n /** Standing skull-top height in metres (default `numbers.heightMetres`, 1.80 m). Scales collider height and radius (Spec 012 R3/H5). */\n readonly heightMetres?: number\n readonly world?: PlayerWorld\n}\n\n/** Player capsule/cylinder collider dimensions in metres (follows standing vs crouched state and `heightMetres`). */\nexport type PlayerCollider = {\n readonly heightMetres: number\n readonly radiusMetres: number\n}\n\nexport type Player = {\n readonly state: PlayerState\n /** Declared standing height in metres. */\n readonly heightMetres: number\n /** Current collider height and radius in metres (adapts to crouch and `heightMetres`). */\n collider(): PlayerCollider\n readonly attributes: Attributes\n readonly derived: Derived\n readonly numbers: PlayerNumbers\n readonly infection: InfectionRule | null\n /** The hunger and thirst rules, or null when they are off. */\n readonly needs: NeedsRules | null\n /** An item used in the hand (`ModuleItemUse.effect`): food and drink feed, a painkiller heals, a dressing stops the bleeding. */\n use(effect: ItemEffect): ItemEffectResult\n update(dt: number, input?: PlayerInput, world?: PlayerWorld): void\n /** A hit that opens a wound (drawn from the wound table) and may infect. `by` is the agent that hit, if any. */\n hurt(amount: number, by?: number): void\n /** A bite: damage, bleeding, a bite wound and (with an infection rule) the infection. */\n bite(by?: number): void\n grab(by: number, noJaw?: boolean, drown?: boolean): void\n release(): void\n knock(seconds: number): void\n infect(source: string): void\n /** Kills the player with a cause (the host's deaths: a fall, a fire). */\n die(cause: DeathCause): void\n /** Infection stage: `none`, `malaise`, `fever`, `delirium`. */\n stage(): 'none' | 'malaise' | 'fever' | 'delirium'\n /** Seconds the infection has left, or null. */\n timeLeft(): number | null\n /** What the player's state does to aim spread (panic, fever, moving); the weapon multiplies its own spread by it. */\n spreadFactor(): number\n /** The agents in front (nearest first) within `range` m and a cone of `cosMin`, as `[distance, index]`. */\n front(range: number, cosMin: number, yaw: number, crowd?: PlayerCrowd): [number, number][]\n on<K extends PlayerEventName>(event: K, listener: (event: PlayerEventMap[K]) => void): () => void\n save(): PlayerSave\n load(save: PlayerSave): void\n /** The world `update` uses when it is given none. */\n setWorld(world: PlayerWorld): void\n}\n\nconst TAU_APPROX = 6.2832\n\nconst evaluate = (formula: LinearFormula, attributes: Attributes): number => {\n let value = formula.base\n for (const [attribute, coefficient] of formula.terms) value += coefficient * attributes[attribute]\n return formula.divide === undefined ? value : value / formula.divide\n}\n\n/** The derived values of a sheet (the game's `DERIV`). */\nexport const deriveVitals = (attributes: Attributes, formulas: DerivedFormulas = PLAYER_DEFAULTS.derived): Derived => {\n const out = {} as Record<DerivedId, number>\n for (const id of Object.keys(formulas) as DerivedId[]) out[id] = evaluate(formulas[id], attributes)\n return out\n}\n\n/** Which wound a hit opens: one draw, the kinds in the listed order, the last one takes the rest (the game's `FERIDA` draw). */\nexport const drawWound = (wounds: WoundTable, random: () => number): string => {\n const kinds = Object.keys(wounds)\n const draw = random()\n let acc = 0\n for (let k = 0; k < kinds.length - 1; k++) {\n acc += wounds[kinds[k]!]!.share\n if (draw < acc) return kinds[k]!\n }\n return kinds[kinds.length - 1]!\n}\n\nconst clamp = (v: number, a: number, b: number): number => (v < a ? a : v > b ? b : v)\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t\n\nconst freshState = (derived: Derived, position: PlayerOptions['position'], needs: NeedsRules | null): PlayerState => ({\n x: position?.x ?? 0,\n z: position?.z ?? 0,\n y: 0,\n vx: 0,\n vz: 0,\n yaw: position?.yaw ?? 0,\n floor: 0,\n alive: true,\n turned: false,\n health: derived.maxHealth,\n stamina: derived.maxStamina,\n hunger: needs?.start.hunger ?? 0,\n thirst: needs?.start.thirst ?? 0,\n crouch: false,\n running: false,\n stepTimer: 0,\n phase: 0,\n hip: 0,\n grabbedBy: -1,\n grabTimer: 0,\n grabPushes: 0,\n grabNoJaw: false,\n grabDrown: false,\n infected: false,\n infectionTime: 0,\n infectionSource: '',\n wounds: [],\n bleeding: 0,\n blind: 0,\n screamBoost: 0,\n panic: 0,\n hurtFlash: 0,\n deathTime: 0,\n cause: '',\n downTimer: 0,\n burnTimer: 0,\n scentTimer: 0,\n vaultTimer: 0,\n vault: null,\n})\n\n/**\n * The player body: a literal port of the team game's `player` and `playerUpdate` (G 68427-68640) with the world, the crowd and the input as\n * arguments instead of globals. The draws on `random` happen in the game's order (wound kind, infection, the fever cough, the knife when grabbed,\n * the melee region), so a game that passes its own stream keeps its sequence.\n */\nexport function createPlayer(options: PlayerOptions = {}): Player {\n const random = options.random ?? createRng(options.seed ?? 1)\n const attributes: Attributes = { ...PLAYER_DEFAULTS.attributes, ...options.attributes }\n const formulas: DerivedFormulas = { ...PLAYER_DEFAULTS.derived, ...options.derived }\n const derived = deriveVitals(attributes, formulas)\n const numbers: PlayerNumbers = { ...PLAYER_DEFAULTS.numbers, ...options.numbers }\n const heightMetres = options.heightMetres ?? numbers.heightMetres\n if (!Number.isFinite(heightMetres) || heightMetres < 0.8 || heightMetres > 3.0) {\n throw new RangeError(`Player height ${String(heightMetres)} m is outside supported range [0.8, 3.0] m.`)\n }\n const heightScale = heightMetres / numbers.heightMetres\n const wounds = options.wounds ?? PLAYER_DEFAULTS.wounds\n const infection: InfectionRule | null =\n options.infection === undefined || options.infection === false ? null : options.infection === true ? PLAYER_DEFAULTS.infection : { ...PLAYER_DEFAULTS.infection, ...options.infection }\n const needs: NeedsRules | null =\n options.needs === false ? null : options.needs === undefined || options.needs === true ? NEEDS_DEFAULTS : { ...NEEDS_DEFAULTS, ...options.needs, start: { ...NEEDS_DEFAULTS.start, ...options.needs.start } }\n const fist = options.fist ?? PLAYER_DEFAULTS.fist\n const listeners = new Map<PlayerEventName, Set<(event: never) => void>>()\n let P = freshState(derived, options.position, needs)\n // the controller's feet, read every step it walks: a vault lifts the body over them\n const feet = new Float64Array(3)\n let defaultWorld: PlayerWorld = options.world ?? {}\n let world: PlayerWorld = defaultWorld\n\n const emit = <K extends PlayerEventName>(event: K, payload: PlayerEventMap[K]): void => {\n const set = listeners.get(event)\n if (set) for (const listener of set) (listener as (event: PlayerEventMap[K]) => void)(payload)\n }\n const sound = (id: PlayerSoundId, volume: number, ids: readonly BodyFoleyId[], surface?: SurfaceId, at?: readonly number[]): void =>\n emit('sound', { sound: id, ids, volume, position: [P.x, P.y, P.z], ...(surface ? { surface } : {}), ...(at ? { at } : {}) })\n // what is under the feet: the host's word this frame, else the world's, else concrete; water wins over everything\n let surfaceHint: string | undefined\n const surfaceHere = (): SurfaceId => (inWater(P.x, P.z) ? 'water' : surfaceOfMaterial(surfaceHint ?? world.surfaceAt?.(P.x, P.z)))\n // set by the first `footfall` the host sends: from then on its feet, not the stride timer, decide the footsteps\n let hostFeet = false\n const blowOf = (item: MeleeItem): BlowId => item.blow ?? (item === fist ? 'punch' : (item.crit ?? 0) > 0 ? 'blade' : 'blunt')\n const noise = (x: number, z: number, radius: number): void => emit('noise', { x, z, radius })\n const message = (id: PlayerMessageId | DeathCause, seconds: number): void => emit('message', { id, seconds })\n const inWater = (x: number, z: number): boolean => world.inWater?.(x, z) ?? false\n const solidAt = (x: number, z: number, y: number): boolean => world.solidAt?.(x, z, y) ?? false\n const cellKind = (x: number, z: number): number => world.cellKind?.(x, z) ?? 0\n const blocked = (x: number, z: number): boolean => (world.blocked ? world.blocked(x, z) : solidAt(x, z, numbers.blockHeight))\n const chanceOf = (kind: string): number => infection?.chances?.[kind] ?? wounds[kind]?.infectionChance ?? 0\n\n const die = (cause: DeathCause): void => {\n if (!P.alive) return\n P.alive = false\n P.cause = cause\n P.deathTime = 0\n P.grabbedBy = -1\n message(cause, 6)\n emit('died', { cause })\n }\n const infect = (source: string): void => {\n if (P.infected || !infection) return\n P.infected = true\n P.infectionTime = 0\n P.infectionSource = source\n emit('infected', { source })\n }\n const release = (how: PlayerEventMap['released']['how'] = 'free'): void => {\n const by = P.grabbedBy\n P.grabbedBy = -1\n if (by >= 0) emit('released', { by, how })\n }\n const hurt = (amount: number): void => {\n if (!P.alive) return\n P.health -= amount\n P.hurtFlash = numbers.hurtFlash\n sound('flesh', numbers.hurtVolume, ['player_hurt'])\n const kind = drawWound(wounds, random)\n P.wounds.push(kind)\n if (wounds[kind]?.bleeds) P.bleeding = 1\n emit('hurt', { amount, wound: kind })\n if (infection && !P.infected && random() < chanceOf(kind)) infect(kind)\n if (P.health <= 0) die(P.infected ? 'infected' : 'killed')\n }\n const bite = (): void => {\n P.health -= numbers.biteDamage\n P.hurtFlash = numbers.biteFlash\n P.bleeding = 1\n P.wounds.push('bite')\n sound('flesh', numbers.biteVolume, ['bite', 'player_hurt'])\n emit('hurt', { amount: numbers.biteDamage, wound: 'bite' })\n infect('bite')\n message('bitten', 5)\n if (P.health <= 0) die('bitten_to_death')\n }\n const grab = (by: number, noJaw = false, drown = false): void => {\n P.grabbedBy = by\n P.grabTimer = numbers.grabSeconds\n P.grabPushes = 0\n P.grabNoJaw = noJaw\n P.grabDrown = drown\n message(drown ? 'grabbed_drown' : 'grabbed', 3)\n sound('flesh', numbers.grabVolume, ['grab'])\n emit('grabbed', { by, noJaw, drown })\n }\n\n const front = (range: number, cosMin: number, yaw: number, crowd: PlayerCrowd | undefined = world.crowd): [number, number][] => {\n const out: [number, number][] = []\n if (!crowd) return out\n const fx = -Math.sin(yaw)\n const fz = -Math.cos(yaw)\n const n = crowd.count()\n for (let i = 0; i < n; i++) {\n if (!crowd.active(i) || crowd.floor(i) !== P.floor) continue\n const ex = crowd.x(i) - P.x\n const ez = crowd.z(i) - P.z\n const d = Math.hypot(ex, ez)\n if (d < range && (ex * fx + ez * fz) / (d || 1) > cosMin) out.push([d, i])\n }\n return out.sort((a, b) => a[0] - b[0])\n }\n\n const shove = (yaw: number): void => {\n sound('step', numbers.shoveVolume, ['shove_two_hands'])\n const crowd = world.crowd\n const targets: number[] = []\n for (const [d, i] of front(numbers.shoveRange, numbers.shoveCone, yaw)) {\n crowd!.stun(i, numbers.shoveStun, ((crowd!.x(i) - P.x) / d) * numbers.shoveSpeed, ((crowd!.z(i) - P.z) / d) * numbers.shoveSpeed)\n targets.push(i)\n }\n emit('shove', { targets })\n }\n\n const melee = (item: MeleeItem, yaw: number): void => {\n const t = front(numbers.meleeRangeBase + (item.reach ?? 0), numbers.meleeCone, yaw)[0]\n const blow = blowOf(item)\n const swing = swingSoundId(blow)\n if (!t) {\n sound('flesh', numbers.meleeVolume, swing ? [swing] : [])\n noise(P.x, P.z, item.noise || 1)\n return\n }\n const crowd = world.crowd!\n const i = t[1]\n // a blow to the head is x3 in melee; on the ground or crawling it is an execution\n const region = crowd.down(i) ? 0 : random() < numbers.meleeHeadChance ? 0 : random() < numbers.meleeArmChance ? 1 : 2 + Math.floor(random() * 2)\n const hit = hitSoundId(blow, region === 0 ? 'head' : 'body')\n if (swing) sound('flesh', numbers.meleeVolume, [swing, hit], undefined, [0, SWING_LEAD_SECONDS[blow]])\n else sound('flesh', numbers.meleeVolume, [hit])\n noise(P.x, P.z, item.noise || 1)\n const damage = item.damage * (1 + (attributes.strength - numbers.meleeStrengthBase) * numbers.meleeStrengthPerPoint)\n const cut = Math.min(1, (item.crit || 0) / numbers.meleeCritToCut)\n crowd.damage(i, { region, amount: damage, distance: t[0], cut })\n emit('melee', { target: i, region, damage, distance: t[0], cut })\n }\n\n const update = (dt: number, input: PlayerInput = {}, frameWorld?: PlayerWorld): void => {\n world = frameWorld ?? defaultWorld\n surfaceHint = input.surface\n if (!P.alive) {\n P.deathTime += dt\n if (P.infected && infection && !P.turned && P.deathTime >= infection.reanimateSeconds) {\n P.turned = true\n emit('turned', { x: P.x, z: P.z, floor: P.floor })\n }\n return\n }\n const pressed: Partial<Record<PlayerAction, boolean>> = { ...input.pressed }\n const wasPressed = (action: PlayerAction): boolean => {\n const v = pressed[action] === true\n pressed[action] = false\n return v\n }\n const viewYaw = input.yaw ?? 0\n const crowd = world.crowd\n P.screamBoost = Math.max(0, P.screamBoost - dt)\n P.blind = Math.max(0, P.blind - dt)\n P.hurtFlash = Math.max(0, P.hurtFlash - dt)\n // infection on its own clock\n if (P.infected && infection) {\n const before = P.infectionTime\n P.infectionTime += dt\n if (before <= infection.feverSeconds && P.infectionTime > infection.feverSeconds) emit('stage', { stage: 'fever' })\n if (before <= infection.deliriumSeconds && P.infectionTime > infection.deliriumSeconds) emit('stage', { stage: 'delirium' })\n const every = 1 / infection.feverNoiseEvery\n if (P.infectionTime > infection.feverSeconds && Math.floor(P.infectionTime * every) !== Math.floor((P.infectionTime - dt) * every) && random() < infection.feverNoiseChance) {\n noise(P.x, P.z, infection.feverNoiseRadius)\n sound('step', infection.feverNoiseVolume, ['cloth_rustle'])\n }\n if (P.infectionTime > infection.deathSeconds) {\n P.health = 0\n die('infection')\n return\n }\n }\n if (P.burnTimer > 0) {\n P.burnTimer -= dt\n P.health -= numbers.burnPerSecond * dt\n if (inWater(P.x, P.z)) P.burnTimer = 0\n }\n P.scentTimer = Math.max(0, P.scentTimer - dt)\n if (P.bleeding) {\n P.health -= dt * numbers.bleedPerSecond\n if (input.bandage && P.bleeding) {\n P.bleeding = 0\n message('bandaged', 2)\n }\n }\n if (needs) P.health -= advanceNeeds(P, dt, { running: P.running, vigor: attributes.vigor }, needs)\n if (P.health <= 0) {\n die(P.infected ? 'infected' : P.bleeding ? 'bled_out' : 'hunger_thirst')\n return\n }\n // grabbed: seconds to react\n if (P.grabbedBy >= 0) {\n const i = P.grabbedBy\n P.grabTimer -= dt\n if (crowd) {\n const k = 1 - Math.exp(-dt * numbers.grabFollow) // glued to the body without a jump\n crowd.hold(i, P.x - Math.sin(P.yaw) * numbers.grabOffset, P.z - Math.cos(P.yaw) * numbers.grabOffset, k, P.x, P.z)\n }\n if (wasPressed('push') && P.stamina > numbers.grabPushMinStamina) {\n P.grabPushes++\n P.stamina -= numbers.grabPushCost\n sound('step', numbers.grabPushVolume, ['shove_two_hands'])\n }\n if (wasPressed('knife')) {\n if (random() < numbers.grabKnifeChance) {\n crowd?.damage(i, { region: numbers.grabKnifeRegion, amount: numbers.grabKnifeDamage, distance: numbers.grabKnifeDistance, cut: numbers.grabKnifeCut })\n message('knife_head', 1.5)\n release('knife')\n return\n } else message('knife_miss', 1)\n }\n if (P.grabPushes >= numbers.grabPushes) {\n crowd?.stun(i, numbers.grabPushStun, -Math.sin(viewYaw) * numbers.grabPushSpeed, -Math.cos(viewYaw) * numbers.grabPushSpeed)\n release('push')\n message('pushed_off', 1.2)\n return\n }\n if (P.grabTimer <= 0) {\n if (P.grabDrown) {\n P.health -= numbers.drownDamage\n P.hurtFlash = numbers.drownFlash\n message('drowning', 2)\n if (P.health <= 0) {\n die('drowned')\n return\n }\n P.grabTimer = numbers.grabSeconds\n P.grabPushes = 0\n return\n }\n if (P.grabNoJaw) {\n hurt(numbers.noJawDamage)\n message('no_jaw', 2)\n } else bite()\n crowd?.chase(i, numbers.grabAttackCooldown)\n release(P.grabNoJaw ? 'scratch' : 'bite')\n }\n return\n }\n // knocked down\n if (P.downTimer > 0) {\n P.downTimer -= dt\n P.vx = P.vz = 0\n if (P.downTimer <= 0) message('stood_up', 0.8)\n return\n }\n if (world.busy?.(dt)) return\n // vaulting a low wall\n if (P.vaultTimer > 0 && P.vault) {\n P.vaultTimer -= dt\n const k = 1 - P.vaultTimer / numbers.vaultSeconds\n P.x = lerp(P.vault[0], P.vault[2], k)\n P.z = lerp(P.vault[1], P.vault[3], k)\n P.y = feet[1] + Math.sin(k * Math.PI) * numbers.vaultHeight\n if (P.vaultTimer <= 0) {\n P.y = feet[1]\n world.controller?.teleport(P.x, P.y, P.z)\n noise(P.x, P.z, numbers.vaultNoise)\n const surface = surfaceHere()\n sound('step', numbers.vaultLandVolume, [landSoundId(surface, 0)], surface)\n }\n return\n }\n if (wasPressed('vault') && P.stamina > numbers.vaultCost && (world.canVault?.() ?? !P.floor)) {\n const fx0 = -Math.sin(viewYaw)\n const fz0 = -Math.cos(viewYaw)\n for (let a = numbers.vaultScanFrom; a <= numbers.vaultScanTo; a += numbers.vaultScanStep) {\n const c = cellKind(P.x + fx0 * a, P.z + fz0 * a)\n if (c === 2) {\n for (let e = a + numbers.vaultLandFrom; e <= a + numbers.vaultLandTo; e += numbers.vaultScanStep) {\n const ex = P.x + fx0 * e\n const ez = P.z + fz0 * e\n if (!solidAt(ex, ez, numbers.vaultCheckHeight) && !solidAt(ex + fx0 * numbers.vaultClearance, ez + fz0 * numbers.vaultClearance, numbers.vaultCheckHeight)) {\n P.vault = [P.x, P.z, ex, ez]\n P.vaultTimer = numbers.vaultSeconds\n P.stamina -= numbers.vaultCost\n sound('step', numbers.vaultStartVolume, ['jump'])\n emit('vault', { from: [P.x, P.z], to: [ex, ez] })\n return\n }\n }\n break\n }\n if (c > 0 && c !== 3) break\n }\n }\n // movement\n const f = input.forward ?? 0\n const s = input.right ?? 0\n if (wasPressed('crouch')) P.crouch = !P.crouch\n const want = f || s\n P.running = !!(input.run && want && P.stamina > numbers.runMinStamina && !input.aim && !P.crouch)\n const fever = P.infected && infection !== null && P.infectionTime > infection.feverSeconds\n let sp = P.running ? derived.runSpeed : P.crouch ? numbers.crouchSpeed : derived.walkSpeed * numbers.walkFactor\n if (fever) sp *= infection!.feverSpeed\n if (input.aim) sp = Math.min(sp, numbers.aimSpeedCap)\n const wet = inWater(P.x, P.z)\n if (wet) sp *= numbers.waterSpeed\n if (P.running) P.stamina = Math.max(0, P.stamina - numbers.runDrain * dt)\n else P.stamina = Math.min(derived.maxStamina, P.stamina + (want ? numbers.regenMoving : numbers.regenStill) * dt)\n const fx = -Math.sin(viewYaw)\n const fz = -Math.cos(viewYaw)\n const mx = fx * f - fz * s\n const mz = fz * f + fx * s\n const ml = Math.hypot(mx, mz) || 1\n const tvx = want ? (mx / ml) * sp : 0\n const tvz = want ? (mz / ml) * sp : 0\n P.vx = lerp(P.vx, tvx, Math.min(1, dt * numbers.acceleration))\n P.vz = lerp(P.vz, tvz, Math.min(1, dt * numbers.acceleration))\n const controller = world.controller\n if (controller) {\n controller.move(P.vx, P.vz, dt)\n controller.read(feet)\n P.x = feet[0] ?? P.x\n P.y = feet[1] ?? P.y\n P.z = feet[2] ?? P.z\n } else {\n const r = numbers.radius * heightScale\n const nx = P.x + P.vx * dt\n const nz = P.z + P.vz * dt\n if (!blocked(nx + Math.sign(P.vx) * r, P.z)) P.x = nx\n if (!blocked(P.x, nz + Math.sign(P.vz) * r)) P.z = nz\n }\n world.afterMove?.(P)\n // the player does not walk through the crowd: agents pressed against the body push it out\n if (crowd) {\n const n = crowd.count()\n const rr = numbers.pushApartRadius\n for (let i = 0; i < n; i++) {\n if (!crowd.active(i) || Math.abs(crowd.y(i) - P.y) > numbers.pushApartHeight) continue\n const ex = P.x - crowd.x(i)\n const ez = P.z - crowd.z(i)\n const e2 = ex * ex + ez * ez\n if (e2 < rr * rr && e2 > 1e-5) {\n const e = Math.sqrt(e2)\n const k = ((rr - e) / e) * 0.5\n if (!solidAt(P.x + ex * k, P.z + ez * k, numbers.blockHeight)) {\n P.x += ex * k\n P.z += ez * k\n }\n }\n }\n }\n const spd = Math.hypot(P.vx, P.vz)\n // the legs follow the move even with the torso on the aim; walking backwards flips the stride\n {\n const cy = Math.cos(P.yaw)\n const sy = Math.sin(P.yaw)\n const lx = P.vx * cy - P.vz * sy\n const lz = P.vx * sy + P.vz * cy\n const back = lz < numbers.backwardsBelow ? -1 : 1\n const hip = spd > numbers.hipMinSpeed ? clamp(Math.atan2(lx * back, lz * back), -numbers.hipLimit, numbers.hipLimit) : 0\n P.hip = P.hip + (hip - P.hip) * Math.min(1, dt * numbers.hipFollow)\n P.phase += dt * (spd < numbers.cadenceMinSpeed ? 0 : numbers.cadenceBase + numbers.cadencePerSpeed * spd) * back\n }\n // the body follows the view (fast, no snap); aiming or firing, at once\n {\n const target = viewYaw + Math.PI\n let dy = target - P.yaw\n dy -= Math.round(dy / TAU_APPROX) * TAU_APPROX\n P.yaw += input.aim || input.firing ? dy : dy * Math.min(1, dt * numbers.turnFollow)\n }\n // footsteps make noise: walk 3 m, run 8 m, crouched 1 m (x the sheet's footstep noise, x2 in water)\n // the host's feet (`input.footfall`) once it sends them, else the stride timer\n if (input.footfall) hostFeet = true\n P.stepTimer -= dt * spd\n const stepNow = hostFeet ? input.footfall === true : P.stepTimer <= 0 && spd > numbers.stepMinSpeed\n if (stepNow) {\n P.stepTimer = numbers.stepEvery\n noise(P.x, P.z, (P.running ? numbers.stepNoiseRun : P.crouch ? numbers.stepNoiseCrouch : numbers.stepNoiseWalk) * derived.footstepNoise * (wet ? numbers.stepNoiseWater : 1))\n const surface = surfaceHere()\n sound('step', P.running ? numbers.stepVolumeRun : numbers.stepVolumeWalk, [footstepSoundId(surface, P.running ? 'run' : 'walk')], surface)\n emit('step', { x: P.x, z: P.z, yaw: P.yaw })\n }\n // shove and melee\n if (wasPressed('push') && P.stamina > numbers.shoveCost) {\n P.stamina -= numbers.shoveCost\n shove(viewYaw)\n }\n if (wasPressed('throw')) emit('throw', {})\n if (wasPressed('knife') && P.stamina > numbers.meleeMinStamina) {\n const item = input.melee ?? fist\n P.stamina -= (item.kg ?? 0) > numbers.meleeHeavyKg ? numbers.meleeCostHeavy : numbers.meleeCostLight\n melee(item, viewYaw)\n }\n // panic: chasing agents in sight nearby\n let near = 0\n if (crowd) {\n const n = crowd.count()\n for (let i = 0; i < n; i++) if (crowd.active(i) && crowd.chasing(i)) near += crowd.panicWeight?.(i) ?? 1\n }\n P.panic = clamp(P.panic + (near * numbers.panicGain - (near ? 0 : numbers.panicDecay)) * dt, 0, numbers.panicMax)\n }\n\n return {\n get state() {\n return P\n },\n heightMetres,\n collider: () => ({\n heightMetres: P.crouch ? heightMetres * numbers.crouchHeightRatio : heightMetres,\n radiusMetres: numbers.radius * heightScale,\n }),\n attributes,\n derived,\n numbers,\n infection,\n needs,\n use: (effect) => (P.alive ? applyItemEffect(P, effect, { maxHealth: derived.maxHealth, ...(needs ? { needs } : {}) }) : { applied: false, health: 0, hunger: 0, thirst: 0, stoppedBleeding: false, calmed: false }),\n update,\n hurt: (amount) => hurt(amount),\n bite: () => bite(),\n grab,\n release: () => release('free'),\n knock(seconds) {\n if (!P.alive) return\n P.downTimer = Math.max(P.downTimer, seconds)\n P.crouch = false\n },\n infect,\n die,\n stage() {\n if (!P.infected || !infection) return 'none'\n return P.infectionTime > infection.deliriumSeconds ? 'delirium' : P.infectionTime > infection.feverSeconds ? 'fever' : 'malaise'\n },\n timeLeft: () => (P.infected && infection ? Math.max(0, infection.deathSeconds - P.infectionTime) : null),\n spreadFactor() {\n const panic = P.panic > derived.composure * numbers.panicSpreadAt ? numbers.panicSpread : 1\n const fever = P.infected && infection && P.infectionTime > infection.feverSeconds ? infection.feverSpread : 1\n return panic * fever * (1 + Math.hypot(P.vx, P.vz) * numbers.moveSpread)\n },\n front,\n on(event, listener) {\n let set = listeners.get(event)\n if (!set) listeners.set(event, (set = new Set()))\n set.add(listener as (event: never) => void)\n return () => void set.delete(listener as (event: never) => void)\n },\n save: () => ({ state: structuredClone(P), attributes }),\n load(save) {\n P = structuredClone(save.state)\n // a save from before the needs: the body starts fed\n P.hunger ??= needs?.start.hunger ?? 0\n P.thirst ??= needs?.start.thirst ?? 0\n world.controller?.teleport(P.x, P.y, P.z)\n },\n setWorld(next) {\n defaultWorld = next\n },\n }\n}\n","import type { CharacterId, PhysicsWorld, Vec3 } from '@adatechnology/game-physics'\n\nimport type { PlayerCollider } from './player'\nimport type { PlayerController } from './types'\n\n/** The part of the physics contract the player's body uses: any `PhysicsWorld` (or the loop's `SeamWorld`) has it. */\nexport type PlayerPhysicsWorld = Pick<PhysicsWorld, 'createCharacter' | 'moveCharacter' | 'pushCharacter' | 'readCharacter' | 'teleportCharacter' | 'removeCharacter' | 'characterSupported'>\n\nexport type PhysicsControllerOptions = {\n /** Where the feet are. */\n readonly position: Vec3\n /** What `player.collider()` says: the capsule is made as tall and as wide as the standing body. */\n readonly collider: PlayerCollider\n /** Kilograms, default 75. */\n readonly mass?: number\n /** Most force (N) it pushes a prop with, default 400: a 30 kg crate over wood, not a wardrobe. */\n readonly strength?: number\n}\n\nexport type PhysicsPlayerController = PlayerController & {\n readonly id: CharacterId\n /** Shoves the body: `impulse` in N s (a blow, a blast, a car's bumper); the controller feels it as impulse / mass, fading in a quarter of a second. */\n push(impulse: Vec3): void\n supported(): boolean\n dispose(): void\n}\n\nexport const PLAYER_MASS_KG = 75\nexport const PLAYER_PUSH_STRENGTH_NEWTONS = 400\n/** The most a person puts into what is in the way just by walking into it, without leaning on it on purpose: about the sustained push force of ISO 11228-2 for a man (100 N), the order of what a walk can keep up. A thing whose floor grip is above it (a 28 kg sofa on wood: 115 N) stops the walk; a lighter one is shoved along. */\nexport const PLAYER_WALK_PUSH_NEWTONS = 100\n\n/**\n * The player's controller in a physics world: a capsule as tall as the standing body (a crouch does not shrink it) that steps up, climbs, pushes props and is\n * pushed. Put it in `PlayerWorld.controller` and call `player.update(h, input)` from a `beforeStep(h)` of the loop's `actors` phase, never with the frame's `dt`.\n */\nexport const createPhysicsController = (world: PlayerPhysicsWorld, options: PhysicsControllerOptions): PhysicsPlayerController => {\n const { radiusMetres, heightMetres } = options.collider\n const id = world.createCharacter({\n position: options.position,\n radius: radiusMetres,\n halfHeight: Math.max(0, (heightMetres - 2 * radiusMetres) / 2),\n mass: options.mass ?? PLAYER_MASS_KG,\n strength: options.strength ?? PLAYER_PUSH_STRENGTH_NEWTONS,\n })\n return {\n id,\n move: (velocityX, velocityZ, dt) => world.moveCharacter(id, velocityX, velocityZ, dt),\n read: (out) => world.readCharacter(id, out, 0),\n teleport: (x, y, z) => world.teleportCharacter(id, [x, y, z]),\n push: (impulse) => world.pushCharacter(id, impulse),\n supported: () => world.characterSupported(id),\n dispose: () => world.removeCharacter(id),\n }\n}\n","/** Samples of the ground across the foot's disc, per radius: the disc is walked in rings of this many steps. */\nconst RINGS = 32\nconst SAMPLES_PER_RING = 48\n\n/**\n * The height a round foot of `radius` comes to rest at over ground `heightAt` (the lower sphere of the capsule): the highest, over the points of the disc under it, of\n * the ground there less how far the sphere's underside rises above its lowest point at that distance. Flat ground gives its own height; a bowl holds the foot above its middle.\n */\nexport const footRestHeight = (heightAt: (x: number, z: number) => number, x: number, z: number, radius: number): number => {\n let rest = heightAt(x, z)\n for (let ring = 1; ring <= RINGS; ring++) {\n const distance = (radius * ring) / RINGS\n const lift = radius - Math.sqrt(radius * radius - distance * distance)\n for (let sample = 0; sample < SAMPLES_PER_RING; sample++) {\n const angle = (2 * Math.PI * sample) / SAMPLES_PER_RING\n rest = Math.max(rest, heightAt(x + distance * Math.cos(angle), z + distance * Math.sin(angle)) - lift)\n }\n }\n return rest\n}\n","import type { BodyId, CharacterId, CharacterShape, Layer, PhysicsServices, Quat, Vec3 } from '@adatechnology/game-physics'\n\nimport { PLAYER_MASS_KG, PLAYER_PUSH_STRENGTH_NEWTONS } from './physics-controller'\nimport type { PlayerCollider } from './player'\n\n/** The vertical speed (m/s) of a jump under the world's 9.81: it rises 0.81 m, as high as the walker's own jump always did. */\nexport const WALKER_JUMP_SPEED = 3.99\n\nexport type WalkerStance = 'standing' | 'crouched' | 'prone'\n\n/** A stance is this fraction of the standing height: 1.80, 1.20 and 0.60 m for a person 1.80 m tall. */\nconst STANCE_HEIGHT_RATIO: Readonly<Record<WalkerStance, number>> = { standing: 1, crouched: 2 / 3, prone: 1 / 3 }\nconst NO_ROTATION: Quat = [0, 0, 0, 1]\n/** The probe sits this much (m) above the feet: the floor it will stand on touches the capsule and is not an overlap. */\nconst PROBE_LIFT = 0.03\nconst SOLID_LAYERS: readonly Layer[] = ['static', 'debris', 'prop', 'vehicle', 'character']\n\nexport type WalkerOptions = {\n /** Where the feet are. */\n readonly position: Vec3\n /** The standing body: `player.collider()` while standing. */\n readonly collider: PlayerCollider\n /** Kilograms, default 75. */\n readonly mass?: number\n /** Most force (N) it pushes a prop with, default 400. */\n readonly strength?: number\n /** Default 0.4 m. */\n readonly stepHeight?: number\n readonly maxSlopeDegrees?: number\n /** Default 9.81. */\n readonly gravity?: number\n /** The layer of the body the world sees of the walker (`agent`: a vehicle does not stop on it). */\n readonly shadow?: Layer\n /** The shadow's `user`. */\n readonly user?: number\n /** What `unpark` may not stand in (default static, debris, prop, vehicle and character). */\n readonly solidLayers?: readonly Layer[]\n}\n\nexport type Walker = {\n /** The character in the world: another one after `unpark`. */\n readonly id: CharacterId\n readonly stance: WalkerStance\n readonly parked: boolean\n /** The wanted horizontal velocity (m/s, world x and z), kept until it is changed: the key of the frame, not of the step. */\n setIntent(velocityX: number, velocityZ: number): void\n /** A jump when the feet stand on something; false in the air or parked. */\n jump(): boolean\n /** Changes the stance; false (the stance stays) when the new capsule would penetrate something. */\n setStance(stance: WalkerStance): boolean\n /** Shoves the body: `impulse` in N s. */\n push(impulse: Vec3): void\n supported(): boolean\n /** The feet of the last fixed step into `out` (x, y, z). */\n read(out: Float32Array | Float64Array): void\n /** The feet between the last two fixed steps, `alpha` (0 to 1) of the way: the scheduler's alpha, not the loop's (`stepFixed` zeroes that one). */\n drawn(alpha: number, out: Float32Array | Float64Array): void\n /** Puts the feet here at once, with no sweep and no speed carried over, and the drawn feet with them (a respawn, a scripted step). Nothing happens while parked. */\n teleport(feet: Vec3): void\n /** Takes the body out of the world (a seat, an aircraft, a vehicle): it no longer moves or blocks. */\n park(): void\n /** Puts the body back at the first of `candidates` (feet) where the capsule overlaps nothing solid, in this order (the door, the far side, the roof); false, still parked, when none fits. */\n unpark(candidates: readonly Vec3[]): boolean\n /** Leaves the loop and the world. */\n dispose(): void\n}\n\nexport type WalkerServices = Pick<PhysicsServices, 'loop' | 'world'>\n\nconst shapeOf = (collider: PlayerCollider, stance: WalkerStance): CharacterShape => {\n const height = collider.heightMetres * STANCE_HEIGHT_RATIO[stance]\n const radius = Math.min(collider.radiusMetres, height / 3)\n return { radius, halfHeight: (height - 2 * radius) / 2 }\n}\n\n/**\n * The player's body in the physics world, walking in the loop's `actors` phase: the intent is set when the key changes, every fixed step walks it with the step's\n * `h`, and the feet of the last two steps are kept for drawing between them. No allocation after the first call.\n */\nexport const createWalker = (services: WalkerServices, options: WalkerOptions): Walker => {\n const { loop, world } = services\n const mass = options.mass ?? PLAYER_MASS_KG\n const shapes: Readonly<Record<WalkerStance, CharacterShape>> = { standing: shapeOf(options.collider, 'standing'), crouched: shapeOf(options.collider, 'crouched'), prone: shapeOf(options.collider, 'prone') }\n const solid = options.solidLayers ?? SOLID_LAYERS\n const found: BodyId[] = []\n const previous = new Float64Array(3)\n const current = new Float64Array(3)\n let intentX = 0\n let intentZ = 0\n let stance: WalkerStance = 'standing'\n let parked = false\n\n const create = (feet: Vec3): CharacterId =>\n world.createCharacter({\n position: feet,\n radius: shapes[stance].radius,\n halfHeight: shapes[stance].halfHeight,\n mass,\n strength: options.strength ?? PLAYER_PUSH_STRENGTH_NEWTONS,\n ...(options.stepHeight !== undefined ? { stepHeight: options.stepHeight } : {}),\n ...(options.maxSlopeDegrees !== undefined ? { maxSlopeDegrees: options.maxSlopeDegrees } : {}),\n ...(options.gravity !== undefined ? { gravity: options.gravity } : {}),\n ...(options.shadow !== undefined ? { shadow: options.shadow } : {}),\n ...(options.user !== undefined ? { user: options.user } : {}),\n })\n\n let id = create(options.position)\n world.readCharacter(id, current, 0)\n previous.set(current)\n\n const stopLoop = loop.add(\n {\n beforeStep: (h) => {\n if (parked) return\n previous.set(current)\n world.moveCharacter(id, intentX, intentZ, h)\n world.readCharacter(id, current, 0)\n },\n },\n 'actors',\n )\n\n const fitsAt = (feet: Vec3): boolean => {\n const shape = shapes[stance]\n const centre: Vec3 = [feet[0], feet[1] + PROBE_LIFT + shape.halfHeight + shape.radius, feet[2]]\n return world.overlapShape({ kind: 'capsule', halfHeight: shape.halfHeight, radius: shape.radius }, centre, NO_ROTATION, found, { layers: solid }) === 0\n }\n\n return {\n get id() {\n return id\n },\n get stance() {\n return stance\n },\n get parked() {\n return parked\n },\n setIntent: (velocityX, velocityZ) => {\n intentX = velocityX\n intentZ = velocityZ\n },\n jump: () => {\n if (parked || !world.characterSupported(id)) return false\n world.pushCharacter(id, [0, mass * WALKER_JUMP_SPEED, 0])\n return true\n },\n setStance: (next) => {\n if (parked) return false\n if (!world.setCharacterShape(id, shapes[next])) return false\n stance = next\n return true\n },\n push: (impulse) => world.pushCharacter(id, impulse),\n supported: () => world.characterSupported(id),\n read: (out) => {\n out[0] = current[0] as number\n out[1] = current[1] as number\n out[2] = current[2] as number\n },\n drawn: (alpha, out) => {\n const t = alpha < 0 ? 0 : alpha > 1 ? 1 : alpha\n for (let axis = 0; axis < 3; axis++) out[axis] = (previous[axis] as number) + ((current[axis] as number) - (previous[axis] as number)) * t\n },\n teleport: (feet) => {\n if (parked) return\n world.teleportCharacter(id, feet)\n world.readCharacter(id, current, 0)\n previous.set(current)\n },\n park: () => {\n if (parked) return\n parked = true\n world.removeCharacter(id)\n },\n unpark: (candidates) => {\n if (!parked) return true\n for (const feet of candidates) {\n if (!fitsAt(feet)) continue\n id = create(feet)\n parked = false\n world.readCharacter(id, current, 0)\n previous.set(current)\n return true\n }\n return false\n },\n dispose: () => {\n stopLoop()\n if (!parked) world.removeCharacter(id)\n parked = true\n },\n }\n}\n","/**\n * Pushing furniture on foot: hold the interaction button against a piece, a timer that grows with its mass fills, and the player then walks with it.\n * Engine-agnostic: the host says where the player wants to go and answers whether the volume of the piece can go there; this says how fast, and when it locks.\n */\n\nimport type { SurfaceId } from '@adatechnology/game-contracts'\n\n/** What dragging a piece leaves on a floor: a strip of this colour and width (metres) under each side of its base. */\nexport type DragMark = { readonly color: number; readonly width: number }\n\nexport type FurniturePushPhase = 'idle' | 'grip' | 'push' | 'strain'\nexport type FurniturePushBlock = 'too_heavy' | 'obstacle' | null\n\n/** Every number of the push; a game overrides what it wants (`createFurniturePush(rules)`). */\nexport interface FurniturePushRules {\n /** The most the player's legs put on the floor, newtons: with the friction it says the heaviest thing that moves. */\n readonly forceN: number\n readonly gravity: number\n /** Static friction of a base on a floor, by the material of the piece. */\n readonly frictionByMaterial: Readonly<Record<string, number>>\n readonly defaultFriction: number\n /** The hold before the push: `base + perKg * mass`, at most `max` seconds. */\n readonly gripSeconds: { readonly base: number; readonly perKg: number; readonly max: number }\n /** Metres per second: `max` with nothing on the hands, `min` at the limit of the force. */\n readonly speed: { readonly max: number; readonly min: number }\n /**\n * How fast the walk with the piece changes, m/s²: `max` the most a person speeds it up (the force left over the friction, over the mass, may give less), `brake` the\n * most it slows it (stopping, turning back). Below what holds a thing on top (friction × g, about 3.4 m/s² for the softest), so a cup on a pushed table rides along.\n */\n readonly accel: { readonly max: number; readonly brake: number; readonly min: number }\n /** A press shorter than this is not a push (the host keeps it for a tap, such as grabbing). */\n readonly tapSeconds: number\n /** How long the effort stays after the last step that was refused, so that it does not flicker. */\n readonly strainHoldSeconds: number\n /**\n * The scratch a dragged piece leaves, by the floor it is dragged on (`SurfaceId` of game-contracts): wood and tile scratch lighter, concrete scuffs darker,\n * dirt and sand take a furrow; a floor left out (carpet, grass, gravel, asphalt, water) keeps no mark.\n */\n readonly dragMarks: Readonly<Partial<Record<SurfaceId, DragMark>>>\n}\n\nexport const FURNITURE_PUSH_DEFAULTS: FurniturePushRules = {\n forceN: 500,\n gravity: 9.81,\n frictionByMaterial: { wood_soft: 0.4, wood_hard: 0.4, mdf: 0.4, plywood: 0.4, steel: 0.35, aluminium: 0.35, cast_iron: 0.4, copper: 0.35, plastic: 0.35, rubber: 0.8, fabric: 0.45, foam: 0.5, ceramic: 0.5, glass: 0.3, tempered_glass: 0.3, brick: 0.6, concrete: 0.65 },\n defaultFriction: 0.45,\n gripSeconds: { base: 0.4, perKg: 0.015, max: 2.5 },\n speed: { max: 1.8, min: 0.35 },\n accel: { max: 1.5, brake: 3, min: 0.2 },\n tapSeconds: 0.2,\n strainHoldSeconds: 0.25,\n dragMarks: {\n wood: { color: 0xd8c4a0, width: 0.012 },\n tile: { color: 0x9a9a96, width: 0.01 },\n concrete: { color: 0x45433f, width: 0.02 },\n metal: { color: 0xd0d4d8, width: 0.008 },\n glass: { color: 0xf2f2f2, width: 0.006 },\n dirt: { color: 0x4a3524, width: 0.04 },\n sand: { color: 0x8d7a5c, width: 0.05 },\n },\n}\n\nexport type FurniturePushTarget = { readonly massKg: number; readonly material?: string }\n\n/** Static friction of a thing of `material` on what it stands on (the floor, a table top). */\nexport const frictionFor = (material: string | undefined, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => (material !== undefined ? rules.frictionByMaterial[material] : undefined) ?? rules.defaultFriction\n\nconst frictionOf = (target: FurniturePushTarget, rules: FurniturePushRules): number => frictionFor(target.material, rules)\n\n/** A piece, or a row of pieces pushed one against the next (a sofa shoving a chair): their frictions on the floor add up against the legs. */\nexport type FurniturePushLoad = FurniturePushTarget | readonly FurniturePushTarget[]\n\nconst piecesOf = (load: FurniturePushLoad): readonly FurniturePushTarget[] => (Array.isArray(load) ? load : [load as FurniturePushTarget])\nconst frictionForceOf = (load: FurniturePushLoad, rules: FurniturePushRules): number => piecesOf(load).reduce((sum, t) => sum + frictionOf(t, rules) * t.massKg * rules.gravity, 0)\nconst massOf = (load: FurniturePushLoad): number => piecesOf(load).reduce((sum, t) => sum + t.massKg, 0)\nconst loadShare = (load: FurniturePushLoad, rules: FurniturePushRules): number => frictionForceOf(load, rules) / rules.forceN\n\nexport const gripSecondsFor = (massKg: number, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => Math.min(rules.gripSeconds.max, rules.gripSeconds.base + rules.gripSeconds.perKg * Math.max(0, massKg))\n\n/** Whether the legs overcome the friction of the piece (or of the row of pieces) on the floor. */\nexport const canPush = (target: FurniturePushLoad, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): boolean => loadShare(target, rules) <= 1\n\n/** Metres per second with the piece on the hands: slower the closer it is to the limit of the force, 0 past it. */\nexport const pushSpeedFor = (target: FurniturePushLoad, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => {\n const share = loadShare(target, rules)\n return share > 1 ? 0 : rules.speed.max + (rules.speed.min - rules.speed.max) * share\n}\n\n/** How fast the walk with the piece speeds up, m/s²: the force left over its friction, over its mass, at most what a person does (`accel.max`). */\nexport const pushAccelerationFor = (target: FurniturePushLoad, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): number => {\n const spare = (rules.forceN - frictionForceOf(target, rules)) / Math.max(1e-3, massOf(target))\n return Math.max(rules.accel.min, Math.min(rules.accel.max, spare))\n}\n\n/** The scratch dragging leaves on `surface`, or null where the floor keeps none (carpet, grass). */\nexport const dragMarkFor = (surface: SurfaceId, rules: FurniturePushRules = FURNITURE_PUSH_DEFAULTS): DragMark | null => rules.dragMarks[surface] ?? null\n\n/** Whether a thing resting on a moving piece slides on it: the piece changes speed faster than the friction under the thing can follow (`accelMps2` > friction × g). */\nexport const slipsOnTop = (accelMps2: number, friction: number, gravity = FURNITURE_PUSH_DEFAULTS.gravity): boolean => accelMps2 > friction * gravity\n\nexport type FurniturePushInput = {\n /** Where the player wants to go on the floor: a unit vector, or `[0, 0]` standing. */\n readonly walk: readonly [number, number]\n /** Whether the volume of the piece (and the player behind it) can move by this offset. */\n readonly isFree: (dx: number, dz: number) => boolean\n}\n\nexport type FurniturePushStep = {\n readonly dx: number\n readonly dz: number\n /** The grip closed on this update. */\n readonly engaged: boolean\n /** A step was refused now and the one before was not: the moment the piece hits something. */\n readonly hitObstacle: boolean\n /** The velocity of the piece after this update, m/s on the floor. */\n readonly velocity: readonly [number, number]\n /** How fast its velocity changed in this update, m/s²: what a thing on top feels. */\n readonly acceleration: number\n /** The velocity it had when it hit something and stopped at once (what rests on it keeps it and slides on), or null. */\n readonly stoppedFrom: readonly [number, number] | null\n}\n\nexport interface FurniturePush {\n readonly phase: FurniturePushPhase\n /** How far the hold timer is, 0 to 1. */\n readonly progress: number\n readonly block: FurniturePushBlock\n readonly heldSeconds: number\n /** Whether the hold is still short enough to be a tap. */\n readonly isTap: boolean\n /** The velocity of the piece now, m/s on the floor. */\n readonly velocity: readonly [number, number]\n begin(target: FurniturePushTarget): void\n /** The load changed while pushing (the piece met another and shoves it along): the speed and the speeding up follow the whole row. */\n setLoad(load: FurniturePushLoad): void\n release(): void\n update(dt: number, input: FurniturePushInput): FurniturePushStep\n}\n\nconst STILL: FurniturePushStep = { dx: 0, dz: 0, engaged: false, hitObstacle: false, velocity: [0, 0], acceleration: 0, stoppedFrom: null }\n\nexport function createFurniturePush(overrides: Partial<FurniturePushRules> = {}): FurniturePush {\n const rules: FurniturePushRules = { ...FURNITURE_PUSH_DEFAULTS, ...overrides }\n let phase: FurniturePushPhase = 'idle'\n let target: FurniturePushTarget = { massKg: 0 }\n let held = 0\n let gripSeconds = 1\n let speed = 0\n let accel = rules.accel.max\n let vx = 0\n let vz = 0\n let block: FurniturePushBlock = null\n let refused = 0\n let wasRefused = false\n\n /** The velocity goes toward the walk, no faster than the push speeds it up (or the legs brake it). Answers the change, m/s². */\n const steer = (dt: number, walk: readonly [number, number]): number => {\n const wantX = walk[0] * speed\n const wantZ = walk[1] * speed\n const braking = wantX * vx + wantZ * vz < vx * vx + vz * vz\n let dvx = wantX - vx\n let dvz = wantZ - vz\n const change = Math.hypot(dvx, dvz)\n const most = (braking ? rules.accel.brake : accel) * dt\n if (change > most) {\n dvx *= most / change\n dvz *= most / change\n }\n vx += dvx\n vz += dvz\n return Math.min(change, most) / dt\n }\n\n const walkWith = (dt: number, input: FurniturePushInput): FurniturePushStep => {\n refused = Math.max(0, refused - dt)\n if (block === 'too_heavy' || dt <= 0) return STILL\n const acceleration = steer(dt, input.walk)\n if (Math.hypot(vx, vz) < 1e-4) {\n vx = vz = 0\n if (refused === 0) {\n phase = 'push'\n block = null\n wasRefused = false\n }\n return { ...STILL, acceleration }\n }\n const dx = vx * dt\n const dz = vz * dt\n if (input.isFree(dx, dz)) {\n if (refused === 0) {\n phase = 'push'\n block = null\n }\n wasRefused = false\n return { dx, dz, engaged: false, hitObstacle: false, velocity: [vx, vz], acceleration, stoppedFrom: null }\n }\n const from: readonly [number, number] = [vx, vz]\n vx = vz = 0\n const hitObstacle = !wasRefused\n wasRefused = true\n refused = rules.strainHoldSeconds\n phase = 'strain'\n block = 'obstacle'\n return { ...STILL, hitObstacle, acceleration: Math.hypot(from[0], from[1]) / dt, stoppedFrom: hitObstacle ? from : null }\n }\n\n return {\n get phase() {\n return phase\n },\n get progress() {\n return phase === 'idle' ? 0 : Math.min(1, held / gripSeconds)\n },\n get block() {\n return block\n },\n get heldSeconds() {\n return held\n },\n get velocity(): readonly [number, number] {\n return [vx, vz]\n },\n get isTap() {\n return phase === 'grip' && held < rules.tapSeconds\n },\n begin(next) {\n target = next\n phase = 'grip'\n held = 0\n block = null\n refused = 0\n wasRefused = false\n gripSeconds = gripSecondsFor(next.massKg, rules)\n speed = pushSpeedFor(next, rules)\n accel = pushAccelerationFor(next, rules)\n vx = vz = 0\n },\n setLoad(load) {\n speed = pushSpeedFor(load, rules)\n accel = pushAccelerationFor(load, rules)\n },\n release() {\n phase = 'idle'\n vx = vz = 0\n held = 0\n block = null\n },\n update(dt, input) {\n if (phase === 'idle') return STILL\n held += dt\n if (phase !== 'grip') return walkWith(dt, input)\n if (held < gripSeconds) return STILL\n if (canPush(target, rules)) phase = 'push'\n else {\n phase = 'strain'\n block = 'too_heavy'\n }\n return { ...STILL, engaged: true }\n },\n }\n}\n","import type { KnownDeathCause, PlayerMessageId } from '../types'\n\nexport type PlayerText = Readonly<Record<PlayerMessageId | KnownDeathCause, string>>\n\n/** The game's own words (G 68434, 68452, 68518, 68525-68541, 68547) and the death causes it shows (G 68448, 68454, 68510, 68519, 68539). */\nconst PT_BR: PlayerText = {\n grabbed: 'AGARRADO! Aperte E várias vezes para empurrar ou F para a faca',\n grabbed_drown: 'O AFOGADO TE PUXA PARA O FUNDO! E várias vezes ou F para a faca',\n bitten: 'Você foi mordido. Não há cura.',\n bandaged: 'Curativo feito',\n knife_head: 'Faca na cabeça!',\n knife_miss: 'Errou a facada',\n pushed_off: 'Empurrou!',\n drowning: 'Afogando! Solte-se!',\n no_jaw: 'Sem mandíbula: só arranhou',\n stood_up: 'De pé!',\n infected: 'Morreu infectado',\n killed: 'Morto pela horda',\n bitten_to_death: 'Mordido',\n infection: 'A infecção venceu',\n bled_out: 'Sangrou até a morte',\n hunger_thirst: 'Fome e sede',\n drowned: 'Afogado',\n burned: 'Queimado',\n}\n\nconst EN: PlayerText = {\n grabbed: 'GRABBED! Press E repeatedly to push or F for the knife',\n grabbed_drown: 'THE DROWNED PULLS YOU UNDER! E repeatedly or F for the knife',\n bitten: 'You were bitten. There is no cure.',\n bandaged: 'Wound dressed',\n knife_head: 'Knife to the head!',\n knife_miss: 'The stab missed',\n pushed_off: 'Pushed off!',\n drowning: 'Drowning! Break free!',\n no_jaw: 'No jaw: only a scratch',\n stood_up: 'Back on your feet!',\n infected: 'Died infected',\n killed: 'Killed by the horde',\n bitten_to_death: 'Bitten',\n infection: 'The infection won',\n bled_out: 'Bled to death',\n hunger_thirst: 'Hunger and thirst',\n drowned: 'Drowned',\n burned: 'Burned',\n}\n\nexport const PLAYER_TEXT: Readonly<Record<'en' | 'pt-BR', PlayerText>> = { en: EN, 'pt-BR': PT_BR }\n\n/** The text of a message or death cause id in a locale (`pt-BR` or `en`, the language part is enough); unknown ids come back as they are. */\nexport const playerTextOf = (id: string, locale = 'pt-BR'): string => {\n const table = locale.toLowerCase().startsWith('en') ? EN : PT_BR\n return (table as Readonly<Record<string, string>>)[id] ?? id\n}\n","export type PlayerBenchText = {\n readonly group: string\n readonly name: string\n readonly controls: Readonly<Record<'infection' | 'agility' | 'vigor' | 'seed' | 'hurt' | 'bite' | 'grab' | 'push' | 'knife' | 'bandage' | 'knock' | 'crouch' | 'reset', string>>\n readonly hints: Readonly<Record<'infection' | 'agility' | 'vigor' | 'seed' | 'grab' | 'push', string>>\n readonly metrics: Readonly<Record<'health' | 'stamina' | 'bleeding' | 'wounds' | 'stage' | 'time_left' | 'panic' | 'spread' | 'grab' | 'noise' | 'steps' | 'message', string>>\n readonly stages: Readonly<Record<'none' | 'malaise' | 'fever' | 'delirium' | 'dead', string>>\n readonly scenarios: Readonly<Record<'stamina' | 'bleed_bandage' | 'normal_world' | 'infection_kills' | 'grab_break_free' | 'determinism', string>>\n readonly yes: string\n readonly no: string\n}\n\nconst EN: PlayerBenchText = {\n group: 'Player',\n name: 'Player area',\n controls: {\n infection: 'Individual infection',\n agility: 'Agility',\n vigor: 'Vigor',\n seed: 'Seed',\n hurt: 'Take a hit (10)',\n bite: 'Bite',\n grab: 'Get grabbed',\n push: 'Push (E)',\n knife: 'Knife (F)',\n bandage: 'Bandage (B)',\n knock: 'Knocked down 1.5 s',\n crouch: 'Crouch (C)',\n reset: 'Start again',\n },\n hints: {\n infection: 'Off: a normal world, wounds never infect. On: the game rule (scratch 6%, laceration 22%, bite 100%; fever at 30 s, death at 120 s).',\n agility: 'The sheet: stamina, run speed and footstep noise come from it.',\n vigor: 'The sheet: health, stamina and composure come from it.',\n seed: 'The same seed gives the same wounds and the same knife rolls.',\n grab: 'Something grabs you from behind: 3 s to push it off (6 pushes) or to land the knife (70%).',\n push: 'Shoves what is in front, or pushes off what holds you.',\n },\n metrics: {\n health: 'Health',\n stamina: 'Stamina',\n bleeding: 'Bleeding',\n wounds: 'Wounds',\n stage: 'Infection',\n time_left: 'Time left',\n panic: 'Panic',\n spread: 'Aim spread x',\n grab: 'Grab timer',\n noise: 'Last noise',\n steps: 'Footsteps',\n message: 'Message',\n },\n stages: { none: 'None', malaise: 'Malaise', fever: 'Fever', delirium: 'Delirium', dead: 'Dead' },\n scenarios: {\n stamina: 'Running drains stamina and resting gives it back',\n bleed_bandage: 'A laceration bleeds until it is dressed',\n normal_world: 'In a normal world a bite hurts and bleeds but never infects',\n infection_kills: 'With the infection on, a bite brings fever and kills at its time',\n grab_break_free: 'Six pushes break a grab before the bite',\n determinism: 'The same seed gives the same wounds',\n },\n yes: 'yes',\n no: 'no',\n}\n\nconst PT_BR: PlayerBenchText = {\n group: 'Jogador',\n name: 'Área do jogador',\n controls: {\n infection: 'Infecção individual',\n agility: 'Agilidade',\n vigor: 'Vigor',\n seed: 'Semente',\n hurt: 'Levar um golpe (10)',\n bite: 'Mordida',\n grab: 'Ser agarrado',\n push: 'Empurrar (E)',\n knife: 'Faca (F)',\n bandage: 'Curativo (B)',\n knock: 'Derrubado 1,5 s',\n crouch: 'Agachar (C)',\n reset: 'Recomeçar',\n },\n hints: {\n infection: 'Desligada: mundo normal, ferida nunca infecta. Ligada: a regra do jogo (arranhão 6%, laceração 22%, mordida 100%; febre aos 30 s, morte aos 120 s).',\n agility: 'A ficha: fôlego, velocidade de corrida e ruído dos passos saem dela.',\n vigor: 'A ficha: vida, fôlego e compostura saem dela.',\n seed: 'A mesma semente dá as mesmas feridas e os mesmos golpes de faca.',\n grab: 'Algo te agarra por trás: 3 s para empurrar (6 empurrões) ou acertar a faca (70%).',\n push: 'Empurra o que está na frente, ou se solta do que te segura.',\n },\n metrics: {\n health: 'Vida',\n stamina: 'Fôlego',\n bleeding: 'Sangrando',\n wounds: 'Feridas',\n stage: 'Infecção',\n time_left: 'Tempo restante',\n panic: 'Pânico',\n spread: 'Dispersão x',\n grab: 'Agarrão',\n noise: 'Último ruído',\n steps: 'Passos',\n message: 'Mensagem',\n },\n stages: { none: 'Nenhuma', malaise: 'Mal-estar', fever: 'Febre', delirium: 'Delírio', dead: 'Morto' },\n scenarios: {\n stamina: 'Correr gasta fôlego e descansar devolve',\n bleed_bandage: 'Uma laceração sangra até o curativo',\n normal_world: 'No mundo normal a mordida machuca e sangra, mas não infecta',\n infection_kills: 'Com a infecção ligada, a mordida dá febre e mata no tempo dela',\n grab_break_free: 'Seis empurrões soltam o agarrão antes da mordida',\n determinism: 'A mesma semente dá as mesmas feridas',\n },\n yes: 'sim',\n no: 'não',\n}\n\nexport const playerBenchTextOf = (locale: string): PlayerBenchText => (locale.toLowerCase().startsWith('en') ? EN : PT_BR)\n","import type { BenchChange, GaitId, ModuleControl, ModuleHost, ModuleMetric, ModuleScenario, SurfaceId, TestableModule } from '@adatechnology/game-contracts'\n\nimport { playerTextOf } from '../locales'\nimport { createPlayer } from '../player'\nimport type { Player, PlayerOptions } from '../player'\nimport type { PlayerAction, PlayerCrowd, PlayerInput } from '../types'\nimport { playerBenchTextOf } from './locale'\n\nexport type PlayerTestModuleOptions = PlayerOptions & { readonly locale?: string }\n\n/** What the scenarios use of the context the test room passes. */\nexport interface PlayerScenarioLike {\n expect(condition: boolean, label: string, data?: Record<string, unknown>): void\n}\n\nexport type PlayerTestModule = TestableModule<PlayerScenarioLike> & {\n /** The player in use (replaced when the bench changes the sheet, the seed or the infection). */\n readonly player: Player\n}\n\ntype CameraLike = { position: { x: number; y: number; z: number }; rotation?: { y: number }; getWorldDirection?(target: unknown): { x: number; z: number } }\ntype ThreeLike = { Vector3?: new () => { x: number; y: number; z: number } }\n\nconst MOVING_SPEED = 0.2\n/** Metres per second above which a move of the view is a jump of the camera, not the body walking. */\nconst TELEPORT_SPEED = 10\nconst SPRINT_SPEED = 3.4\nconst FRAME = 1 / 30\n\n/**\n * One agent standing behind the player for the grab test: the bench has no crowd, so this is the hand that holds. It follows `hold`, takes\n * the shove and the knife, and leaves the count once it lets go.\n */\nconst createGrabber = () => {\n const agent = { x: 0, z: 0, on: false, stunned: 0, hits: 0 }\n const crowd: PlayerCrowd = {\n count: () => (agent.on ? 1 : 0),\n active: () => agent.on,\n x: () => agent.x,\n z: () => agent.z,\n y: () => 0,\n floor: () => 0,\n chasing: () => agent.on,\n down: () => agent.stunned > 0,\n hold(_i, x, z, k) {\n agent.x += (x - agent.x) * k\n agent.z += (z - agent.z) * k\n },\n stun(_i, seconds) {\n agent.stunned = seconds\n agent.on = false\n },\n chase() {\n agent.on = false\n },\n damage() {\n agent.hits += 1\n agent.on = false\n },\n }\n return { agent, crowd }\n}\n\n/**\n * The player area of a test room, against the generic contracts only. The room's camera is the player: where it walks, the player walks; its speed\n * decides walking or running, so stamina, footsteps and their noise follow the viewer. The bench hurts, bites, grabs and knocks the player down,\n * switches the individual infection (off by default: a normal world) and sets the sheet. Footsteps and flesh sounds go to `host.audio`.\n */\nexport function createPlayerTestModule(options: PlayerTestModuleOptions = {}): PlayerTestModule {\n const locale = options.locale ?? 'pt-BR'\n const text = playerBenchTextOf(locale)\n const { locale: _locale, ...playerOptions } = options\n void _locale\n const settings = { infection: options.infection === undefined ? false : options.infection !== false, agility: options.attributes?.agility ?? 5, vigor: options.attributes?.vigor ?? 5, seed: options.seed ?? 1 }\n let host: ModuleHost | null = null\n const grabber = createGrabber()\n let lastNoise = 0\n let steps = 0\n let lastMessage = ''\n let pending: Partial<Record<PlayerAction, boolean>> = {}\n let bandage = false\n let footfall = false\n let surface: SurfaceId | undefined\n let gait: GaitId | undefined\n let last: { x: number; z: number } | null = null\n const offs: (() => void)[] = []\n\n const build = (): Player => {\n for (const off of offs.splice(0)) off()\n const made = createPlayer({ ...playerOptions, seed: settings.seed, infection: settings.infection, attributes: { ...playerOptions.attributes, agility: settings.agility, vigor: settings.vigor } })\n offs.push(made.on('noise', (e) => void (lastNoise = e.radius)))\n offs.push(made.on('step', () => void (steps += 1)))\n offs.push(made.on('message', (e) => void (lastMessage = playerTextOf(e.id, locale))))\n // the body sounds of each event (a footstep on its surface, the swing and then the hit of a blow); the team's class only when it names none\n offs.push(\n made.on('sound', (e) => {\n if (e.ids.length === 0) return\n e.ids.forEach((id, index) => {\n const delay = e.at?.[index] ?? 0\n host?.audio?.play({ sound: id, volume: e.volume, position: e.position, urgent: true, ...(delay > 0 ? { delay } : {}) })\n })\n }),\n )\n offs.push(made.on('died', (e) => host?.log(`player died: ${e.cause}`, { cause: e.cause })))\n lastNoise = 0\n steps = 0\n lastMessage = ''\n return made\n }\n let player = build()\n\n const view = (): { x: number; z: number; yaw: number } | null => {\n const camera = host?.camera as CameraLike | undefined\n if (!camera?.position) return null\n const Vector3 = (host?.THREE as ThreeLike | undefined)?.Vector3\n if (camera.getWorldDirection && Vector3) {\n const look = camera.getWorldDirection(new Vector3())\n return { x: camera.position.x, z: camera.position.z, yaw: Math.atan2(-look.x, -look.z) }\n }\n return { x: camera.position.x, z: camera.position.z, yaw: camera.rotation?.y ?? 0 }\n }\n\n const frame = (dt: number): void => {\n const here = view()\n const raw = here && last && dt > 0 ? Math.hypot(here.x - last.x, here.z - last.z) / dt : 0\n // faster than anyone runs is the view put somewhere else (an area opening, a scripted look), not a walk: no footstep for it\n const speed = raw > TELEPORT_SPEED ? 0 : raw\n if (here) {\n player.state.x = here.x\n player.state.z = here.z\n }\n const input: PlayerInput = { forward: speed > MOVING_SPEED ? 1 : 0, run: gait ? gait === 'run' : speed > SPRINT_SPEED, yaw: here?.yaw ?? 0, bandage, pressed: pending, footfall, ...(surface ? { surface } : {}) }\n pending = {}\n footfall = false\n bandage = false\n player.update(dt, input, { crowd: grabber.crowd })\n if (here) {\n player.state.x = here.x\n player.state.z = here.z\n last = { x: here.x, z: here.z }\n }\n if (grabber.agent.stunned > 0) grabber.agent.stunned = Math.max(0, grabber.agent.stunned - dt)\n }\n\n const grab = (): void => {\n const P = player.state\n grabber.agent.on = true\n grabber.agent.x = P.x - Math.sin(P.yaw) * player.numbers.grabOffset\n grabber.agent.z = P.z - Math.cos(P.yaw) * player.numbers.grabOffset\n player.grab(0)\n }\n\n const onChange = (change: BenchChange): void => {\n if (change.kind === 'action') {\n const id = change.id\n if (id === 'hurt') player.hurt(10)\n else if (id === 'bite') player.bite()\n else if (id === 'grab') grab()\n else if (id === 'knock') player.knock(1.5)\n else if (id === 'bandage') bandage = true\n else if (id === 'push' || id === 'knife' || id === 'crouch') pending = { ...pending, [id]: true }\n else if (id === 'reset') player = build()\n return\n }\n if (change.kind !== 'control') return\n const { id, value } = change\n if (id === 'infection' && typeof value === 'boolean' && value !== settings.infection) settings.infection = value\n else if ((id === 'agility' || id === 'vigor' || id === 'seed') && typeof value === 'number' && value !== settings[id]) settings[id] = value\n else return\n player = build()\n }\n\n const controls = (): ModuleControl[] => [\n { kind: 'boolean', id: 'infection', name: text.controls.infection, hint: text.hints.infection, default: settings.infection },\n { kind: 'number', id: 'agility', name: text.controls.agility, hint: text.hints.agility, min: 1, max: 8, step: 1, default: settings.agility },\n { kind: 'number', id: 'vigor', name: text.controls.vigor, hint: text.hints.vigor, min: 1, max: 8, step: 1, default: settings.vigor },\n { kind: 'number', id: 'seed', name: text.controls.seed, hint: text.hints.seed, min: 1, max: 9999, step: 1, default: settings.seed },\n { kind: 'action', id: 'hurt', name: text.controls.hurt },\n { kind: 'action', id: 'bite', name: text.controls.bite },\n { kind: 'action', id: 'grab', name: text.controls.grab, hint: text.hints.grab },\n { kind: 'action', id: 'push', name: text.controls.push, hint: text.hints.push },\n { kind: 'action', id: 'knife', name: text.controls.knife },\n { kind: 'action', id: 'bandage', name: text.controls.bandage },\n { kind: 'action', id: 'knock', name: text.controls.knock },\n { kind: 'action', id: 'crouch', name: text.controls.crouch },\n { kind: 'action', id: 'reset', name: text.controls.reset },\n ]\n\n const stageName = (): string => (player.state.alive ? text.stages[player.stage()] : text.stages.dead)\n const metrics = (): ModuleMetric[] => [\n { id: 'health', name: text.metrics.health, digits: 1, max: player.derived.maxHealth, read: () => Math.max(0, player.state.health) },\n { id: 'stamina', name: text.metrics.stamina, digits: 1, max: player.derived.maxStamina, read: () => player.state.stamina },\n { id: 'bleeding', name: text.metrics.bleeding, read: () => (player.state.bleeding ? text.yes : text.no) },\n { id: 'wounds', name: text.metrics.wounds, digits: 0, read: () => player.state.wounds.length },\n { id: 'stage', name: text.metrics.stage, read: stageName },\n { id: 'time_left', name: text.metrics.time_left, unit: 's', digits: 0, read: () => player.timeLeft() ?? 0 },\n { id: 'panic', name: text.metrics.panic, digits: 1, read: () => player.state.panic },\n { id: 'spread', name: text.metrics.spread, digits: 2, read: () => player.spreadFactor() },\n { id: 'grab_timer', name: text.metrics.grab, unit: 's', digits: 1, read: () => (player.state.grabbedBy >= 0 ? player.state.grabTimer : 0) },\n { id: 'noise', name: text.metrics.noise, unit: 'm', digits: 1, read: () => lastNoise },\n { id: 'steps', name: text.metrics.steps, digits: 0, read: () => steps },\n { id: 'message', name: text.metrics.message, read: () => lastMessage },\n ]\n\n // each scenario runs its own player, so the bench's live one is not touched\n const fresh = (extra: PlayerOptions = {}): Player => createPlayer({ ...playerOptions, ...extra })\n const run = (made: Player, seconds: number, input: PlayerInput = {}, crowd?: PlayerCrowd): void => {\n for (let t = 0; t < seconds; t += FRAME) made.update(FRAME, input, crowd ? { crowd } : undefined)\n }\n const scenarios = (): Array<ModuleScenario<PlayerScenarioLike>> => [\n {\n id: 'player_stamina',\n name: text.scenarios.stamina,\n run: ({ expect }) => {\n const made = fresh({ seed: 1 })\n const full = made.state.stamina\n run(made, 4, { forward: 1, run: true })\n const tired = made.state.stamina\n expect(tired < full - 40, 'four seconds of running spend 48 of stamina', { full, tired })\n run(made, 3)\n expect(made.state.stamina > tired, 'standing still gives it back', { tired, rested: made.state.stamina })\n },\n },\n {\n id: 'player_bleed_bandage',\n name: text.scenarios.bleed_bandage,\n run: ({ expect }) => {\n const made = fresh({ seed: 1 })\n made.bite()\n const after = made.state.health\n run(made, 2)\n expect(made.state.bleeding === 1 && made.state.health < after, 'the wound bleeds', { health: made.state.health })\n run(made, FRAME, { bandage: true })\n const dressed = made.state.health\n run(made, 2)\n expect(made.state.bleeding === 0 && made.state.health === dressed, 'dressed, it stops', { health: made.state.health })\n },\n },\n {\n id: 'player_normal_world',\n name: text.scenarios.normal_world,\n run: ({ expect }) => {\n const made = fresh({ seed: 1, infection: false })\n made.bite()\n run(made, 10)\n expect(!made.state.infected && made.state.health < made.derived.maxHealth, 'bitten, hurt, not infected', { health: made.state.health })\n },\n },\n {\n id: 'player_infection_kills',\n name: text.scenarios.infection_kills,\n run: ({ expect }) => {\n const made = fresh({ seed: 1, infection: true })\n made.bite()\n run(made, FRAME, { bandage: true })\n run(made, 40)\n expect(made.stage() === 'fever', 'fever after 30 s', { stage: made.stage() })\n run(made, 90)\n expect(!made.state.alive && made.state.cause === 'infection', 'dead at 120 s', { cause: made.state.cause })\n },\n },\n {\n id: 'player_grab_break_free',\n name: text.scenarios.grab_break_free,\n run: ({ expect }) => {\n const made = fresh({ seed: 1 })\n const { agent, crowd } = createGrabber()\n agent.on = true\n made.grab(0)\n for (let push = 0; push < 6; push++) {\n made.update(FRAME, { pressed: { push: true } }, { crowd })\n made.update(FRAME, {}, { crowd })\n }\n expect(made.state.grabbedBy === -1 && made.state.wounds.length === 0, 'free, and no bite', { grabbedBy: made.state.grabbedBy })\n },\n },\n {\n id: 'player_determinism',\n name: text.scenarios.determinism,\n run: ({ expect }) => {\n const wounds = (seed: number): string => {\n const made = fresh({ seed })\n for (let k = 0; k < 12; k++) made.hurt(1)\n return made.state.wounds.join(',')\n }\n expect(wounds(4) === wounds(4), 'the same seed gives the same wounds')\n expect(wounds(4) !== wounds(5), 'another seed gives others')\n },\n },\n ]\n\n const module: PlayerTestModule = {\n id: 'player_area',\n name: text.name,\n ground: { surface: 'dirt' },\n group: text.group,\n get player() {\n return player\n },\n items: () => [],\n controls: () => controls(),\n metrics: () => metrics(),\n scenarios: () => scenarios(),\n attach(lent) {\n host = lent\n last = null\n const off = lent.bench?.onChange(onChange)\n const offFrame = lent.onFrame(frame)\n // the host's body puts its feet down: the footsteps follow it (and what it says is under them)\n const offFeet = lent.on((event) => {\n if (event.type !== 'footfall') return\n footfall = true\n surface = event.surface\n gait = event.gait\n })\n return () => {\n off?.()\n offFrame()\n offFeet()\n host = null\n }\n },\n }\n return module\n}\n","/**\n * Opening and closing a hinged or sliding leaf by hand (a house door, a wardrobe or fridge door, a drawer, a car door, a hood): the hand reaches the handle, the leaf\n * follows the hand at a speed set by its mass, stops where something is in its way, and a locked leaf only rattles.\n * The player does not follow the leaf: when the handle leaves arm reach a leaf that goes away is shoved on (`push`) and one that comes toward the body is let go (`release`),\n * and either one finishes its swing on its own.\n * Engine-agnostic: the host says how open the leaf is (0 closed, 1 open) and answers whether it can go to a new opening; this says how far it goes each step.\n */\n\nexport type DoorUsePhase = 'idle' | 'reach' | 'swing' | 'push' | 'release' | 'rattle'\nexport type DoorUseBlock = 'locked' | 'obstacle' | null\n\n/** Every number of the use; a game overrides what it wants (`createDoorUse(rules)`). */\nexport interface DoorUseRules {\n /** The hand going to the handle before the leaf moves, seconds. */\n readonly reachSeconds: number\n /** A full swing: `base + perKg * mass` of the leaf, between `min` and `max` seconds (a fridge door is quick, a car door slower, a steel door slower still). */\n readonly swingSeconds: { readonly base: number; readonly perKg: number; readonly min: number; readonly max: number }\n /** The shove of a leaf that goes away once the handle is out of reach, seconds. */\n readonly pushSeconds: number\n /** The hand letting go and coming back, seconds. */\n readonly releaseSeconds: number\n /** How long a locked leaf is shaken before the hand gives up, seconds. */\n readonly rattleSeconds: number\n /** The part of the swing tested at a time against what is around (smaller is finer and costs more). */\n readonly stepFraction: number\n /** Within this of closed or open a leaf counts as there: the last use's way no longer turns it round. */\n readonly endTolerance: number\n}\n\nexport const DOOR_USE_DEFAULTS: DoorUseRules = {\n reachSeconds: 0.3,\n swingSeconds: { base: 0.45, perKg: 0.02, min: 0.45, max: 1.6 },\n pushSeconds: 0.18,\n releaseSeconds: 0.22,\n // the length of the recorded handle shaken (game-audio door_locked_rattle, 0.6 to 0.83 s): the hand lets go as the sound ends\n rattleSeconds: 0.75,\n stepFraction: 0.04,\n endTolerance: 0.02,\n}\n\n/** The body's shoulder, metres over the feet (the avatar's door pose is drawn for it). */\nexport const DOOR_SHOULDER_HEIGHT = 1.42\n/** The farthest a handle is from the shoulder joint for the palm to stay on it (measured on the body in both views: the palm is 0.06 m off up to 0.5, 0.11 at 0.55, 0.24 at 0.65). */\nexport const DOOR_ARM_REACH = 0.55\n\nexport type DoorUseTarget = {\n /** How open the leaf is now, 0 closed to 1 open. */\n readonly opening: number\n readonly massKg: number\n readonly locked?: boolean\n /** Where the last use sent this leaf: a leaf stopped between closed and open goes the other way (a door blocked half open closes). */\n readonly lastGoal?: 0 | 1\n}\n\nexport type DoorUseStep = {\n readonly phase: DoorUsePhase\n /** How open the leaf is after the step. */\n readonly opening: number\n /** The phase's own progress, 0 to 1 (how far the hand is to the handle, how far the swing went, how much of the rattle is left). */\n readonly progress: number\n /** Set on the step the leaf stopped short or would not move. */\n readonly block: DoorUseBlock\n /** The leaf got where it was going on this step (fully open or fully closed). */\n readonly arrived: boolean\n}\n\n/** Seconds of a full swing for a leaf of this mass. */\nexport const swingSecondsFor = (massKg: number, rules: DoorUseRules = DOOR_USE_DEFAULTS): number =>\n Math.min(rules.swingSeconds.max, Math.max(rules.swingSeconds.min, rules.swingSeconds.base + rules.swingSeconds.perKg * Math.max(0, massKg)))\n\nexport type DoorUseHand = { readonly reaches: () => boolean; readonly pull: boolean }\n\nexport interface DoorUse {\n readonly phase: DoorUsePhase\n /** Where the leaf is going: 1 opening, 0 closing. */\n readonly goal: 0 | 1\n readonly opening: number\n /**\n * Starts using a leaf: the other way from where the last use sent it (`lastGoal`), else a closed or half-open leaf opens and an open\n * one closes. A use in the middle of a swing turns it round.\n * Answers the goal (1 open, 0 closed), or null when the leaf is locked (it rattles instead).\n */\n begin(target: DoorUseTarget): 0 | 1 | null\n /**\n * Advances the use; `isFree(from, to)` answers whether the leaf can go from one opening to the other (nothing in the way of its sweep). `hand` says whether the handle is still\n * within arm reach after the step and whether the leaf comes toward the body (`pull`): once the handle is out of reach the swing hands over to `push` (a leaf going away is shoved\n * on) or `release` (a leaf coming toward the body is let go) and the leaf finishes on its own. Without `hand` the hand never lets go.\n */\n step(dt: number, isFree: (from: number, to: number) => boolean, hand?: DoorUseHand): DoorUseStep\n /** Lets go at once. */\n cancel(): void\n}\n\nexport function createDoorUse(rules: Partial<DoorUseRules> = {}): DoorUse {\n const r: DoorUseRules = { ...DOOR_USE_DEFAULTS, ...rules, swingSeconds: { ...DOOR_USE_DEFAULTS.swingSeconds, ...rules.swingSeconds } }\n let phase: DoorUsePhase = 'idle'\n let goal: 0 | 1 = 1\n let opening = 0\n let time = 0\n let swing = 1\n let start = 0\n /** The hand let go and the leaf is still going to its goal on its own. */\n let coasting = false\n\n const out = (progress: number, arrived = false, b: DoorUseBlock = null): DoorUseStep => ({ phase, opening, progress: Math.max(0, Math.min(1, progress)), block: b, arrived })\n\n /** Moves the leaf toward its goal for `dt` seconds, a little at a time so it stops at the first thing in its way and not past it. */\n const advance = (dt: number, isFree: (from: number, to: number) => boolean): 'moving' | 'stopped' | 'arrived' => {\n const want = goal - opening\n const reach = Math.min(Math.abs(want), dt / swing)\n let moved = 0\n while (moved < reach - 1e-9) {\n const inc = Math.min(r.stepFraction, reach - moved)\n const next = opening + Math.sign(want) * inc\n if (!isFree(opening, next)) return 'stopped'\n opening = next\n moved += inc\n }\n return Math.abs(goal - opening) < 1e-6 ? 'arrived' : 'moving'\n }\n\n /** The hand coming back to rest; it waits there (progress 1) while the leaf still goes on its own. */\n const releaseOut = (arrived: boolean, b: DoorUseBlock = null): DoorUseStep => {\n const p = time / r.releaseSeconds\n if (p >= 1 && !coasting) phase = 'idle'\n return out(p, arrived, b)\n }\n\n return {\n get phase() {\n return phase\n },\n get goal() {\n return goal\n },\n get opening() {\n return opening\n },\n begin(target) {\n opening = Math.max(0, Math.min(1, target.opening))\n time = 0\n coasting = false\n if (target.locked) {\n phase = 'rattle'\n return null\n }\n // in the middle of a swing the hand is already on the handle: the leaf turns round at once\n if (phase === 'swing' || phase === 'reach') goal = goal === 1 ? 0 : 1\n else if (target.lastGoal !== undefined && opening > r.endTolerance && opening < 1 - r.endTolerance) goal = target.lastGoal === 1 ? 0 : 1\n else goal = opening > 0.5 ? 0 : 1\n swing = swingSecondsFor(target.massKg, r)\n start = opening\n phase = phase === 'swing' ? 'swing' : 'reach'\n return goal\n },\n step(dt, isFree, hand) {\n if (phase === 'idle') return out(0)\n time += dt\n if (phase === 'rattle') {\n const p = time / r.rattleSeconds\n if (p >= 1) {\n phase = 'idle'\n return out(1, false, 'locked')\n }\n return out(p, false, time === dt ? 'locked' : null)\n }\n if (phase === 'reach') {\n const p = time / r.reachSeconds\n if (p < 1) return out(p)\n phase = 'swing'\n time = 0\n start = opening\n }\n if (phase === 'swing' || phase === 'push' || coasting) {\n const result = advance(dt, isFree)\n const travel = Math.abs(goal - start) || 1\n const progress = 1 - Math.abs(goal - opening) / travel\n const inHand = phase !== 'release'\n if (result === 'stopped' || result === 'arrived') {\n if (result === 'arrived') opening = goal\n coasting = false\n if (inHand) {\n phase = 'release'\n time = 0\n }\n if (result === 'arrived') return inHand ? out(1, true) : releaseOut(true)\n return inHand ? out(progress, false, 'obstacle') : releaseOut(false, 'obstacle')\n }\n if (inHand && hand && !hand.reaches()) {\n time = 0\n if (hand.pull) {\n phase = 'release'\n coasting = true\n } else phase = 'push'\n return out(0)\n }\n if (phase === 'push') {\n if (time >= r.pushSeconds) {\n phase = 'release'\n time = 0\n coasting = true\n return out(0)\n }\n return out(time / r.pushSeconds)\n }\n if (phase === 'swing') return out(progress)\n }\n return releaseOut(false)\n },\n cancel() {\n phase = 'idle'\n time = 0\n },\n }\n}\n","/**\n * The hands and the weapon (decision of the owner, 2026-11-24): an interaction of one hand (a small thing picked up, a door, a switch) takes the free hand, the one that does not\n * hold the weapon, and the weapon stays in its hand; one of both hands (a big thing carried, a push, a climb) first puts the weapon away in a slot of the body that takes it\n * (a holster at the hip, a sling or back slot for a long gun) and, with none, lets it fall to the ground. A two-handed weapon (a rifle, a shotgun) leaves no hand free, so any\n * interaction puts it away or drops it. When the interaction ends, what was put away comes back to its hand; what fell stays on the ground.\n * A long gun on its sling (decision of the owner, 2026-11-25) is not put away: it swings onto the sling and hangs on the body (`sling`), and stays there after the interaction until\n * the player brings it back to the hands; with no sling worn it goes to the next slot that takes it (`SLOT_FALLBACKS`: the back).\n * A second weapon of the belt (a pistol or a knife in the other hand, decision of the owner 2026-11-27) is not thrown away when the holster is taken: it is tucked in the\n * belt (`SLOT_FALLBACKS`: hip, then belt) and comes back after, as the holstered one does. Picking something up never drops a weapon the body has a place for.\n * Engine-agnostic: the host says what is in each hand and which slots the body wears; this says which hand acts and what happens to each weapon.\n */\n\n/** `R` the weapon hand, `L` the other one. */\nexport type BodyHand = 'R' | 'L'\n\n/** A weapon in a hand: `hands` it takes (0 the bare hand, 1, 2) and the slot of the body that takes it (`hip`, `back`...), null when none does. */\nexport interface HandWeapon {\n readonly id: string\n readonly hands: 0 | 1 | 2\n readonly slot: string | null\n}\n\nexport interface HandsRules {\n /** A thing up to `maxKg` whose longest side is up to `maxLength` metres goes in one hand; anything bigger or heavier takes both. */\n readonly oneHand: { readonly maxKg: number; readonly maxLength: number }\n}\n\nexport const HANDS_DEFAULTS: HandsRules = { oneHand: { maxKg: 4, maxLength: 0.7 } }\n\n/** The slot a weapon goes to when the body wears none of its own (or it is taken): a long gun with no sling goes across the back, a second handgun or knife into the belt. */\nexport const SLOT_FALLBACKS: Readonly<Record<string, readonly string[]>> = { sling: ['back'], hip: ['belt'] }\n\n/** The belt: where a one-handed weapon is tucked when its own place on the body is taken. */\nexport const BELT_SLOT = 'belt'\n\n/** The slot of a long gun that hangs on its sling. */\nexport const SLING_SLOT = 'sling'\n\n/**\n * What a weapon does when the hands are wanted: `holster` goes to `slot` and comes back after; `sling` hangs on the body by its sling and stays there until it is brought back;\n * `drop` falls to the ground and stays there.\n */\nexport type HandsMoveKind = 'holster' | 'sling' | 'drop'\n\nexport interface HandsMove {\n readonly hand: BodyHand\n readonly weapon: string\n readonly move: HandsMoveKind\n readonly slot?: string\n}\n\nexport interface HandsPlan {\n /** The hand the interaction takes, or `both`. */\n readonly hand: BodyHand | 'both'\n /** What happens to each weapon that is in the way, the weapon hand first. */\n readonly moves: readonly HandsMove[]\n}\n\nexport interface PlanHandsParams {\n /** The hands the interaction takes (`interactionHandsFor` for a thing picked up). */\n readonly hands: 1 | 2\n /** What each hand holds; absent or null is an empty hand. */\n readonly weapons: { readonly R?: HandWeapon | null; readonly L?: HandWeapon | null }\n /** The slots the body wears and that are empty (a holster, a sling); one weapon each. */\n readonly slots: readonly string[]\n /** The slots tried when a weapon's own is not worn; default `SLOT_FALLBACKS`. */\n readonly fallbacks?: Readonly<Record<string, readonly string[]>>\n}\n\n/** How many hands it takes to carry a thing of `massKg` and `size` (metres, any order). */\nexport function interactionHandsFor(thing: { readonly massKg: number; readonly size?: readonly number[] }, rules: HandsRules = HANDS_DEFAULTS): 1 | 2 {\n const longest = Math.max(0, ...(thing.size ?? []))\n return thing.massKg > rules.oneHand.maxKg || longest > rules.oneHand.maxLength ? 2 : 1\n}\n\nconst holds = (weapon: HandWeapon | null | undefined): weapon is HandWeapon => !!weapon && weapon.hands > 0\n\n/** Which hand acts and what happens to each weapon in the way. */\nexport function planHands(params: PlanHandsParams): HandsPlan {\n const { R, L } = params.weapons\n const free = [...params.slots]\n const fallbacks = params.fallbacks ?? SLOT_FALLBACKS\n const stow = (hand: BodyHand, weapon: HandWeapon): HandsMove => {\n const own = weapon.slot === null ? [] : [weapon.slot, ...(fallbacks[weapon.slot] ?? [])]\n // a one-handed weapon (a second handgun, a compact SMG, a hatchet) is tucked in the belt when its own places are taken, never thrown away\n const tried = weapon.hands === 1 && !own.includes(BELT_SLOT) ? [...own, BELT_SLOT] : own\n const slot = tried.find((name) => free.includes(name))\n if (slot === undefined) return { hand, weapon: weapon.id, move: 'drop' }\n free.splice(free.indexOf(slot), 1)\n return { hand, weapon: weapon.id, move: slot === SLING_SLOT ? 'sling' : 'holster', slot }\n }\n if (params.hands === 2) {\n const moves = [...(holds(R) ? [stow('R', R)] : []), ...(holds(L) ? [stow('L', L)] : [])]\n return { hand: 'both', moves }\n }\n if (holds(L)) return { hand: 'L', moves: [stow('L', L)] }\n if (!holds(R)) return { hand: 'R', moves: [] }\n return { hand: 'L', moves: R.hands === 2 ? [stow('R', R)] : [] }\n}\n\n/** What comes back to the hands once the interaction ends: the weapons that were put away, each to its hand; the slung ones stay on the sling and the dropped ones on the ground. */\nexport function drawBackOf(plan: HandsPlan): readonly { readonly hand: BodyHand; readonly weapon: string }[] {\n return plan.moves.filter((move) => move.move === 'holster').map((move) => ({ hand: move.hand, weapon: move.weapon }))\n}\n","/**\n * Whether one person lifts a thing off the floor with the hands, from its mass and its size (the mass comes from the material of the SDK: density times volume, or\n * the real mass of the catalogue). The strength is the most a person lifts held against the body; a bulky thing is held away from it, and the back takes the load\n * times its lever (the horizontal multiplier of the NIOSH lifting equation: what is held at `H` metres from the spine is `closeReach / H` of what is held against\n * it). The thing is held the easiest way: its thinnest side away from the body, the hands around the middle one. A sofa (45 kg, 2 x 0.9 x 0.85 m) is held at\n * 0.58 m and weighs more than the 26 kg a person lifts that far out: it is pushed or dragged, not picked up. A gas bottle (16 kg, 0.36 m across) goes up.\n * Engine-agnostic: the host passes the mass and the box of the thing.\n */\n\nexport interface LiftRules {\n /** The most a person lifts held against the body, kg. */\n readonly maxKg: number\n /** Distance (m) from the spine to a load held against the body: NIOSH's 25 cm, where the lever costs nothing. */\n readonly closeReach: number\n /** Distance (m) from the spine to the near face of what is held: the front of the trunk. */\n readonly bodyDepth: number\n /** The widest a person holds between the hands around a thing, metres: the arms hugging it. */\n readonly maxSpan: number\n}\n\nexport const LIFT_DEFAULTS: LiftRules = { maxKg: 60, closeReach: 0.25, bodyDepth: 0.15, maxSpan: 1.3 }\n\n/** `ok` it goes up; `too_heavy` heavier than the strength even against the body; `too_bulky` too wide for the arms or too far out for its weight. */\nexport type LiftVerdict = 'ok' | 'too_heavy' | 'too_bulky'\n\nexport interface LiftCheck {\n readonly verdict: LiftVerdict\n /** The most this thing could weigh and still go up, held its easiest way, kg. */\n readonly liftableKg: number\n}\n\n/** Whether a thing of `massKg` and `size` (metres, any order; without it, a thing held against the body) goes up in one person's hands. */\nexport function liftCheckFor(thing: { readonly massKg: number; readonly size?: readonly number[] }, rules: Partial<LiftRules> = {}): LiftCheck {\n const r = { ...LIFT_DEFAULTS, ...rules }\n const [, middle = 0, thinnest = 0] = [...(thing.size ?? [])].sort((a, b) => b - a)\n const reach = r.bodyDepth + Math.max(0, thinnest) / 2\n const liftableKg = r.maxKg * Math.min(1, r.closeReach / Math.max(reach, 1e-6))\n if (thing.massKg > r.maxKg) return { verdict: 'too_heavy', liftableKg }\n if (middle > r.maxSpan || thing.massKg > liftableKg) return { verdict: 'too_bulky', liftableKg }\n return { verdict: 'ok', liftableKg }\n}\n","/**\n * The little pose algebra the hands need, engine-agnostic: a pose is a position and a unit quaternion `[x, y, z, w]` (local to world), as `HandPose` of game-contracts.\n */\n\nexport type Vec3Tuple = readonly [number, number, number]\nexport type QuatTuple = readonly [number, number, number, number]\n\nexport interface Pose {\n readonly position: Vec3Tuple\n readonly quaternion: QuatTuple\n}\n\n/** The rotation whose local x, y and z go to `x`, `y` and `z` (an orthonormal, right-handed basis). */\nexport function quaternionOfBasis(x: readonly number[], y: readonly number[], z: readonly number[]): [number, number, number, number] {\n const [m00, m10, m20] = [x[0] ?? 0, x[1] ?? 0, x[2] ?? 0]\n const [m01, m11, m21] = [y[0] ?? 0, y[1] ?? 0, y[2] ?? 0]\n const [m02, m12, m22] = [z[0] ?? 0, z[1] ?? 0, z[2] ?? 0]\n const trace = m00 + m11 + m22\n if (trace > 0) {\n const s = 0.5 / Math.sqrt(trace + 1)\n return [(m21 - m12) * s, (m02 - m20) * s, (m10 - m01) * s, 0.25 / s]\n }\n if (m00 > m11 && m00 > m22) {\n const s = 2 * Math.sqrt(1 + m00 - m11 - m22)\n return [0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s]\n }\n if (m11 > m22) {\n const s = 2 * Math.sqrt(1 + m11 - m00 - m22)\n return [(m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s]\n }\n const s = 2 * Math.sqrt(1 + m22 - m00 - m11)\n return [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s]\n}\n\nexport function multiplyQuaternions(a: QuatTuple, b: QuatTuple): [number, number, number, number] {\n const [ax, ay, az, aw] = a\n const [bx, by, bz, bw] = b\n return [ax * bw + aw * bx + ay * bz - az * by, ay * bw + aw * by + az * bx - ax * bz, az * bw + aw * bz + ax * by - ay * bx, aw * bw - ax * bx - ay * by - az * bz]\n}\n\nexport function conjugateQuaternion(q: QuatTuple): [number, number, number, number] {\n return [-q[0], -q[1], -q[2], q[3]]\n}\n\nexport function rotateVector(q: QuatTuple, v: Vec3Tuple): [number, number, number] {\n const [x, y, z, w] = q\n const tx = 2 * (y * v[2] - z * v[1])\n const ty = 2 * (z * v[0] - x * v[2])\n const tz = 2 * (x * v[1] - y * v[0])\n return [v[0] + w * tx + (y * tz - z * ty), v[1] + w * ty + (z * tx - x * tz), v[2] + w * tz + (x * ty - y * tx)]\n}\n\n/** `parent` then `local`: the pose of a thing given in the frame of `parent`. */\nexport function composePose(parent: Pose, local: Pose): Pose {\n const offset = rotateVector(parent.quaternion, local.position)\n return {\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\n quaternion: multiplyQuaternions(parent.quaternion, local.quaternion),\n }\n}\n\n/** The pose whose frame puts `local` at `world`: `composePose(result, local)` is `world`. */\nexport function poseHolding(world: Pose, local: Pose): Pose {\n const quaternion = multiplyQuaternions(world.quaternion, conjugateQuaternion(local.quaternion))\n const offset = rotateVector(quaternion, local.position)\n return { position: [world.position[0] - offset[0], world.position[1] - offset[1], world.position[2] - offset[2]], quaternion }\n}\n\n/** Between `a` (k 0) and `b` (k 1): the position on the line, the turn the short way round. */\nexport function blendPoses(a: Pose, b: Pose, k: number): Pose {\n const lerp = (i: 0 | 1 | 2): number => a.position[i] + (b.position[i] - a.position[i]) * k\n const dot = a.quaternion[0] * b.quaternion[0] + a.quaternion[1] * b.quaternion[1] + a.quaternion[2] * b.quaternion[2] + a.quaternion[3] * b.quaternion[3]\n const sign = dot < 0 ? -1 : 1\n const mixed = [0, 1, 2, 3].map((i) => (a.quaternion[i] ?? 0) * (1 - k) + (b.quaternion[i] ?? 0) * sign * k)\n const length = Math.hypot(...mixed) || 1\n return { position: [lerp(0), lerp(1), lerp(2)], quaternion: [(mixed[0] ?? 0) / length, (mixed[1] ?? 0) / length, (mixed[2] ?? 0) / length, (mixed[3] ?? 1) / length] }\n}\n\n/** Slow in, slow out: a hand speeds up off its start and settles on its target. */\nexport function easeInOut(t: number): number {\n const k = Math.min(1, Math.max(0, t))\n return k * k * (3 - 2 * k)\n}\n","/**\n * How a hand closes on a thing it picks up (decision of the owner, 2026-11-25: the hand on the thing's real grip, the fingers closed around it, the thing in the palm, aligned with\n * the hand in both views). Engine-agnostic: the thing is its box (`size`, metres, in its own frame), the hand frame is the one of `HandTargets`: +x along the fingers, +y the back\n * of the hand, the thumb at -z for a right hand and +z for a left one. The thing's longest side runs through the fist along the thumb (a bottle stands up in a hand held thumb up),\n * its thinnest side across the palm (the palm lies on its broad face), and its middle sits a palm's thickness plus half that side under the middle of the palm.\n */\nimport type { BodyHand } from './hands'\nimport { composePose, poseHolding, quaternionOfBasis } from './hand-math'\nimport type { Pose, Vec3Tuple } from './hand-math'\n\nexport const ITEM_GRIP = {\n /** Half the thickness of a palm (m): what lies between the middle of the palm and the thing. */\n palm: 0.011,\n /** The closure of the fingers (0 open, 1 a fist) on a thing this thick (m) or thinner. */\n fistAt: 0.03,\n closed: 0.95,\n /** How much the closure opens per metre the thing is thicker than `fistAt`, and the most it opens to. */\n openPerMetre: 4,\n open: 0.35,\n /** The fingers before they close on it, as the hand comes to the thing. */\n reaching: 0.15,\n} as const\n\nexport interface ItemGrip {\n /** The thing's middle and turn in the frame of the hand. */\n readonly local: Pose\n /** How closed the fingers are on it (`HandTargets.grip`). */\n readonly grip: number\n}\n\nconst AXES: readonly Vec3Tuple[] = [\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n]\n\nconst cross = (a: Vec3Tuple, b: Vec3Tuple): Vec3Tuple => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]\nconst scaled = (v: Vec3Tuple, k: number): Vec3Tuple => [v[0] * k, v[1] * k, v[2] * k]\n\n/** The grip of a hand on a thing of box `size` (its own frame, metres). */\nexport function gripOfItem(size: readonly number[], hand: BodyHand): ItemGrip {\n const sides = [0, 1, 2].map((axis) => ({ axis, length: Math.max(0, size[axis] ?? 0) })).sort((a, b) => b.length - a.length)\n const [long, mid, thin] = sides as [(typeof sides)[0], (typeof sides)[0], (typeof sides)[0]]\n const thumb: Vec3Tuple = hand === 'R' ? [0, 0, -1] : [0, 0, 1]\n // where each of the thing's own axes goes in the hand: the long one along the thumb, the thin one across the palm, the last one keeps the frame right-handed\n const columns: Vec3Tuple[] = [AXES[0] as Vec3Tuple, AXES[1] as Vec3Tuple, AXES[2] as Vec3Tuple]\n columns[long.axis] = thumb\n columns[thin.axis] = [0, 1, 0]\n const next = (axis: number): number => (axis + 1) % 3\n // x × y = z for the thing's frame: the column after `mid` crossed with the one after that names it\n const before = columns[next(next(mid.axis))] as Vec3Tuple\n const after = columns[next(mid.axis)] as Vec3Tuple\n columns[mid.axis] = cross(after, before)\n const quaternion = quaternionOfBasis(columns[0] as Vec3Tuple, columns[1] as Vec3Tuple, columns[2] as Vec3Tuple)\n const depth = ITEM_GRIP.palm + thin.length / 2\n const across = (mid.length + thin.length) / 2\n const grip = Math.max(ITEM_GRIP.open, Math.min(ITEM_GRIP.closed, ITEM_GRIP.closed - ITEM_GRIP.openPerMetre * Math.max(0, across - ITEM_GRIP.fistAt)))\n return { local: { position: scaled([0, -1, 0], depth), quaternion }, grip }\n}\n\n/** Where the thing is with the hand at `hand` holding it by `grip`. */\nexport function itemPoseInHand(hand: Pose, grip: ItemGrip): Pose {\n return composePose(hand, grip.local)\n}\n\n/** Where the hand goes to take the thing where it lies (`item`, its middle and turn) by `grip`. */\nexport function handPoseOnItem(item: Pose, grip: ItemGrip): Pose {\n return poseHolding(item, grip.local)\n}\n","/**\n * The hands take a thing in steps one can see (decision of the owner, 2026-11-25): first each weapon in the way goes off the hands (`stow` to its holster, `sling` onto its sling, or\n * `drop`: tossed to the ground), then the hand `reach`es the thing's grip, the fingers `close` on it, and it is `lift`ed to where it is carried. A weapon comes back to the hands the\n * same way round (`draw`). Engine-agnostic and clock-free: the host advances it by its own frame's `dt` and does what each step says.\n */\nimport type { HandsMove, HandsPlan } from './hands'\nimport { easeInOut } from './hand-math'\n\n/** Seconds each step takes. */\nexport interface HandsTiming {\n readonly stow: number\n readonly sling: number\n readonly drop: number\n readonly reach: number\n readonly close: number\n readonly lift: number\n readonly draw: number\n}\n\nexport const HANDS_TIMING: HandsTiming = { stow: 0.5, sling: 0.45, drop: 0.4, reach: 0.38, close: 0.16, lift: 0.3, draw: 0.5 }\n\nexport type TakeStepKind = 'stow' | 'sling' | 'drop' | 'reach' | 'close' | 'lift' | 'draw'\n\nexport interface TakeStep {\n readonly kind: TakeStepKind\n /** The weapon the step moves (`stow`, `sling`, `drop`, `draw`). */\n readonly move?: HandsMove\n readonly start: number\n readonly end: number\n}\n\nexport interface TakeSequence {\n readonly steps: readonly TakeStep[]\n readonly duration: number\n}\n\nconst KIND_OF_MOVE: Readonly<Record<HandsMove['move'], 'stow' | 'sling' | 'drop'>> = { holster: 'stow', sling: 'sling', drop: 'drop' }\n\nconst lay = (parts: readonly { readonly kind: TakeStepKind; readonly seconds: number; readonly move?: HandsMove }[]): TakeSequence => {\n let at = 0\n const steps = parts.map((part) => {\n const step: TakeStep = { kind: part.kind, start: at, end: at + part.seconds, ...(part.move ? { move: part.move } : {}) }\n at = step.end\n return step\n })\n return { steps, duration: at }\n}\n\n/** The steps of taking a thing with `plan`: the weapons off the hands (the off hand first), then reach, close and lift. `take` false leaves the thing out (a push). */\nexport function planTakeSequence(plan: HandsPlan, options: { readonly timing?: HandsTiming; readonly take?: boolean } = {}): TakeSequence {\n const timing = options.timing ?? HANDS_TIMING\n const moves = [...plan.moves].reverse().map((move) => ({ kind: KIND_OF_MOVE[move.move], seconds: timing[KIND_OF_MOVE[move.move]], move }))\n const take = options.take === false ? [] : [\n { kind: 'reach' as const, seconds: timing.reach },\n { kind: 'close' as const, seconds: timing.close },\n { kind: 'lift' as const, seconds: timing.lift },\n ]\n return lay([...moves, ...take])\n}\n\n/** The steps of bringing weapons back to the hands, one after the other. */\nexport function planDrawSequence(moves: readonly HandsMove[], timing: HandsTiming = HANDS_TIMING): TakeSequence {\n return lay(moves.map((move) => ({ kind: 'draw' as const, seconds: timing.draw, move })))\n}\n\nexport interface TakeProgress {\n /** The step going on now, null once the sequence is over. */\n readonly step: TakeStep | null\n /** How far into it, 0..1, eased (slow in, slow out). */\n readonly progress: number\n /** The steps that began during this advance, in order. */\n readonly started: readonly TakeStep[]\n /** The steps that ended during this advance, in order. */\n readonly ended: readonly TakeStep[]\n readonly done: boolean\n}\n\nexport interface TakeTimeline {\n readonly sequence: TakeSequence\n /** Seconds since it began. */\n readonly time: number\n /** Moves the timeline on by `dt` seconds (the host's frame). The first call with 0 starts the first step. */\n advance(dt: number): TakeProgress\n}\n\nexport function createTakeTimeline(sequence: TakeSequence): TakeTimeline {\n let time = 0\n // the steps already begun and already over: each is reported once\n let begun = 0\n let over = 0\n const steps = sequence.steps\n return {\n sequence,\n get time() {\n return time\n },\n advance(dt) {\n time = Math.min(sequence.duration, time + Math.max(0, dt))\n const startedFrom = begun\n while (begun < steps.length && (steps[begun] as TakeStep).start <= time) begun++\n const endedFrom = over\n while (over < begun && (steps[over] as TakeStep).end <= time) over++\n const started = steps.slice(startedFrom, begun)\n const ended = steps.slice(endedFrom, over)\n const step = steps.find((entry) => time < entry.end) ?? null\n const progress = step ? easeInOut((time - step.start) / Math.max(1e-6, step.end - step.start)) : 1\n return { step, progress, started, ended, done: time >= sequence.duration }\n },\n }\n}\n","/**\n * Draws a body that moves in fixed steps between two of them: remember the last two step poses, blend by the scheduler's `alpha` (CLAUDE.md §15).\n * Drawn at the step pose, a body moves 0, 1 or 2 steps per frame at a display that is not the step's rate: it stutters.\n */\n\nexport type StepPosition = { readonly x: number; readonly y: number; readonly z: number }\n\nexport type StepPoseOptions = {\n /** A step longer than this (metres) is a teleport (a respawn, a placed body): drawn at the new pose at once, never swept across. Default 3. */\n readonly teleportDistance?: number\n}\n\nexport type StepPose = {\n /** The body's pose after a fixed step. */\n record(position: StepPosition): void\n /** Puts both poses on `position`: nothing is blended from where the body was. */\n reset(position: StepPosition): void\n /** The pose to draw: `alpha` in [0, 1] is how far the frame is into the next step. */\n blend(alpha: number): StepPosition\n}\n\nexport const STEP_POSE_DEFAULTS = { teleportDistance: 3 } as const\n\nexport function createStepPose(start: StepPosition, options: StepPoseOptions = {}): StepPose {\n const teleportDistance = options.teleportDistance ?? STEP_POSE_DEFAULTS.teleportDistance\n let previous = { x: start.x, y: start.y, z: start.z }\n let current = { x: start.x, y: start.y, z: start.z }\n return {\n record(position) {\n previous = current\n current = { x: position.x, y: position.y, z: position.z }\n if (Math.hypot(current.x - previous.x, current.y - previous.y, current.z - previous.z) > teleportDistance) previous = current\n },\n reset(position) {\n previous = { x: position.x, y: position.y, z: position.z }\n current = previous\n },\n blend(alpha) {\n const k = Math.min(1, Math.max(0, alpha))\n return { x: previous.x + (current.x - previous.x) * k, y: previous.y + (current.y - previous.y) * k, z: previous.z + (current.z - previous.z) * k }\n },\n }\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;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,KA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