@adatechnology/game-characters 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/dist/index.d.ts +1103 -0
- package/dist/index.global.js +2448 -0
- package/dist/index.global.js.map +1 -0
- package/dist/index.js +2421 -0
- package/dist/index.js.map +1 -0
- package/package.json +52 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/data/body.json","../src/body/body-spec.ts","../src/corpses.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../src/presets/team-game.json","../src/body/regions.ts","../src/data/segments.json","../src/body/segment-tree.ts","../src/body/body-state.ts","../src/body/describe.ts","../src/body/object-state.ts","../src/body/rig.ts","../src/character.ts","../src/body/transform.ts","../src/damage/bleeding.ts","../src/damage/body-ops.ts","../src/presets/physical.json","../src/damage/defaults.ts","../src/damage/penetration.ts","../src/damage/rules/blow.ts","../src/damage/points.ts","../src/damage/rules/regions.ts","../src/damage/blast.ts","../src/damage/protection.ts","../src/damage/resolve-part.ts","../src/damage/rules/arsenal.ts","../src/damage/rules/elenco.ts","../src/damage/rules/kit.ts","../src/damage/pipeline.ts","../src/damage/damage-character.ts","../src/damage/line.ts","../src/registry.ts","../src/kit.ts","../src/data/gait.json","../src/gait/stride.ts","../src/gait/profile.ts","../src/gait/animate.ts","../src/gait/cascade.ts","../src/gait/moves.ts","../src/gait/lying.ts","../src/condition/timeline.ts","../src/data/appearance.json","../src/appearance/variance.ts","../src/appearance/palette.ts","../src/appearance/traits.ts"],"sourcesContent":["/**\n * @adatechnology/game-characters: living bodies without an engine. Proportions and rig, the 17-segment tree with the 6 crowd regions, the\n * registries of presets, and the damage model (protection, penetration, severity, dismemberment, death, bleeding) as a `DestructibleImpl`.\n * Knows nothing about any game: content packs (people, uniformed forces, undead) add presets. Engine units: joules, metres, seconds.\n */\nexport { createCharacters, applyPreset, resolveDamageRules, DEFAULT_CORPSES, PERSON_PRESET } from './kit'\nexport type { CharacterKit } from './kit'\nexport type { Character, ResolvedCharacterSpec } from './character'\nexport { GUIDE, TEAM_GAME, JOINT_IDS, createBodySpec } from './body/body-spec'\nexport type { BodySpec, JointId } from './body/body-spec'\nexport { createRig, GAME_BONES, JOINT_PARENTS } from './body/rig'\nexport type { CreateRigParams, Rig } from './body/rig'\nexport { SEGMENT_TREE, SEGMENT_IDS, SEGMENT_NUMBERS, segmentNode, segmentsBelow, isSegmentId } from './body/segment-tree'\nexport type { SegmentId, SegmentNode, SegmentNumbers, SegmentSide } from './body/segment-tree'\nexport { BODY_REGIONS, LIMB_REGIONS, REGION_HIT_POINTS, REGION_SEGMENTS, isBodyRegion } from './body/regions'\nexport type { LimbRegion } from './body/regions'\nexport { BODY_MATERIAL, describeBody } from './body/describe'\nexport { mergeById, applyPatches, removeIds } from './registry'\nexport * from './gait'\nexport { createConditionTimeline } from './condition/timeline'\nexport type { ConditionOptions, ConditionPhase, ConditionSample, ConditionTimeline } from './condition/timeline'\nexport { createCorpseLedger } from './corpses'\nexport type { CorpseEntry, CorpseLedger } from './corpses'\nexport * from './appearance'\nexport type { DamageCharacter } from './damage/damage-character'\nexport {\n ARSENAL_RULES,\n DAMAGE_PRESETS,\n DEFAULT_DAMAGE_RULES,\n ELENCO_RULES,\n PROTECTION_PRESETS,\n TEAM_GAME_CALIBERS,\n TEAM_GAME_CALIBER_KEYS,\n} from './damage/defaults'\nexport {\n PENETRATION_MODELS,\n PHYSICAL_PENETRATION,\n TEAM_GAME_PENETRATION,\n TORSO_RESISTANCE,\n energyKept,\n segmentResistance,\n teamGameCost,\n teamGameFalloff,\n} from './damage/penetration'\nexport { createRng, cutOf, penetrationForce, pointsFromEnergy, projectileOf, resolvePoints, spreadPoints } from './damage/points'\nexport { LAYERED_PROTECTION_CAP, layeredProtection, layersOn, protect } from './damage/protection'\nexport type { ProtectionOutcome } from './damage/protection'\nexport { penetrateLine } from './damage/line'\nexport type { LineHit, LineResult, LineShot, LineTarget, PenetrateLineParams } from './damage/line'\nexport { BLOOD_LITERS_PER_DROP, bleedRateAt } from './damage/bleeding'\nexport type { Bleeder } from './damage/bleeding'\nexport type {\n BallisticClass,\n BlastRules,\n BodyHit,\n CaliberEntry,\n DamageRules,\n DeathRule,\n HitReport,\n PenetrationModel,\n ProjectileInfo,\n ProtectionLayer,\n SegmentRuleId,\n SeverityRules,\n} from './damage/types'\nexport type {\n AgeGroup,\n BodyMultipliers,\n CharacterPack,\n CharacterPreset,\n CharacterSpec,\n CharactersOptions,\n CorpseOptions,\n DamageOptions,\n Detail,\n SegmentState,\n SegmentStatus,\n} from './types'\n","{\n \"guide\": {\n \"heightMetres\": 1.8,\n \"shoulderWidthMetres\": 0.61,\n \"shoulderWidthWomanMetres\": 0.57,\n \"shoulderHeightMetres\": 1.475,\n \"headToHeight\": 0.1667\n },\n \"teamGame\": {\n \"source\": \"G 65336 J (shoulders +-0.24 m)\",\n \"joints\": {\n \"quadril\": [\n 0,\n 0.95,\n 0\n ],\n \"pescoco\": [\n 0,\n 1.52,\n 0\n ],\n \"ombroE\": [\n -0.24,\n 1.44,\n 0\n ],\n \"ombroD\": [\n 0.24,\n 1.44,\n 0\n ],\n \"cotoveloE\": [\n -0.27,\n 1.13,\n 0\n ],\n \"cotoveloD\": [\n 0.27,\n 1.13,\n 0\n ],\n \"coxaE\": [\n -0.1,\n 0.92,\n 0\n ],\n \"coxaD\": [\n 0.1,\n 0.92,\n 0\n ],\n \"joelhoE\": [\n -0.1,\n 0.5,\n 0\n ],\n \"joelhoD\": [\n 0.1,\n 0.5,\n 0\n ]\n },\n \"heightMetres\": 1.8\n },\n \"lodDistancesMetres\": [\n 18,\n 55\n ],\n \"triangleBudget\": {\n \"lod0\": 2500,\n \"lod1\": 800,\n \"lod2\": 250\n }\n}\n","import type { SegmentKind, Vec3 } from '@adatechnology/game-contracts'\n\nimport body from '../data/body.json'\n\n/** The 17 joints of a body: one per segment, the point the segment hangs from. */\nexport type JointId =\n | 'hip'\n | 'spine'\n | 'neck'\n | 'head'\n | 'jaw'\n | 'shoulderL'\n | 'shoulderR'\n | 'elbowL'\n | 'elbowR'\n | 'wristL'\n | 'wristR'\n | 'hipL'\n | 'hipR'\n | 'kneeL'\n | 'kneeR'\n | 'ankleL'\n | 'ankleR'\n\nexport const JOINT_IDS: readonly JointId[] = ['hip', 'spine', 'neck', 'head', 'jaw', 'shoulderL', 'shoulderR', 'elbowL', 'elbowR', 'wristL', 'wristR', 'hipL', 'hipR', 'kneeL', 'kneeR', 'ankleL', 'ankleR']\n\n/**\n * Proportions of a body: joint positions in metres for a body of `heightMetres`, standing, feet on y = 0, facing +z, left side on +x.\n * `segmentRadius` is the radius of the capsule a segment is hit through.\n */\nexport type BodySpec = {\n readonly id: string\n readonly heightMetres: number\n readonly joints: Readonly<Record<JointId, Vec3>>\n readonly segmentRadius: Readonly<Record<SegmentKind, number>>\n}\n\nconst SEGMENT_RADIUS: Readonly<Record<SegmentKind, number>> = {\n head: 0.1,\n jaw: 0.05,\n neck: 0.06,\n torso: 0.17,\n pelvis: 0.16,\n upperArm: 0.085,\n forearm: 0.065,\n hand: 0.05,\n thigh: 0.1,\n shin: 0.08,\n foot: 0.05,\n}\n\nconst { guide } = body\nconst shoulderX = guide.shoulderWidthMetres / 2\nconst shoulderY = guide.shoulderHeightMetres\n\n/** The Elenco style guide body (1.80 m, shoulders 0.61 m at 1.475 m, head about 1/6 of the height): the default. */\nexport const GUIDE: BodySpec = {\n id: 'guide',\n heightMetres: guide.heightMetres,\n joints: {\n hip: [0, 0.92, 0],\n spine: [0, 1.05, 0],\n neck: [0, 1.56, 0],\n head: [0, 1.64, 0],\n jaw: [0, 1.66, 0.06],\n shoulderL: [shoulderX, shoulderY, 0],\n shoulderR: [-shoulderX, shoulderY, 0],\n elbowL: [shoulderX, shoulderY - 0.31, 0],\n elbowR: [-shoulderX, shoulderY - 0.31, 0],\n wristL: [shoulderX, shoulderY - 0.61, 0],\n wristR: [-shoulderX, shoulderY - 0.61, 0],\n hipL: [0.105, 0.9, 0],\n hipR: [-0.105, 0.9, 0],\n kneeL: [0.105, 0.48, 0],\n kneeR: [-0.105, 0.48, 0],\n ankleL: [0.105, 0.1, 0],\n ankleR: [-0.105, 0.1, 0],\n },\n segmentRadius: SEGMENT_RADIUS,\n}\n\nconst J = body.teamGame.joints\nconst below = (point: readonly number[], drop: number): Vec3 => [point[0], point[1] - drop, point[2]]\n\n/**\n * The game's crowd body (G 65336 `J`, shoulders ±0.24 m), kept for the goldens of the instanced path. `J` has no spine, head, jaw, wrist or\n * ankle: spine and head sit on the hip and neck bones (bones 0 and 1 of the game), the wrist and ankle one forearm and one shin below.\n */\nexport const TEAM_GAME: BodySpec = {\n id: 'team-game',\n heightMetres: body.teamGame.heightMetres,\n joints: {\n hip: J.quadril as Vec3,\n spine: J.quadril as Vec3,\n neck: J.pescoco as Vec3,\n head: J.pescoco as Vec3,\n jaw: [0, J.pescoco[1] + 0.08, 0.06],\n shoulderL: J.ombroE as Vec3,\n shoulderR: J.ombroD as Vec3,\n elbowL: J.cotoveloE as Vec3,\n elbowR: J.cotoveloD as Vec3,\n wristL: below(J.cotoveloE, 0.3),\n wristR: below(J.cotoveloD, 0.3),\n hipL: J.coxaE as Vec3,\n hipR: J.coxaD as Vec3,\n kneeL: J.joelhoE as Vec3,\n kneeR: J.joelhoD as Vec3,\n ankleL: below(J.joelhoE, 0.42),\n ankleR: below(J.joelhoD, 0.42),\n },\n segmentRadius: SEGMENT_RADIUS,\n}\n\n/** A body spec from `base` (default `GUIDE`) with the given fields replaced; `joints` and `segmentRadius` merge key by key. */\nexport const createBodySpec = (patch: Partial<BodySpec> = {}, base: BodySpec = GUIDE): BodySpec => ({\n id: patch.id ?? base.id,\n heightMetres: patch.heightMetres ?? base.heightMetres,\n joints: { ...base.joints, ...patch.joints },\n segmentRadius: { ...base.segmentRadius, ...patch.segmentRadius },\n})\n","import type { CorpseOptions } from './types'\n\nexport type CorpseEntry<TData> = {\n /** Seconds since it fell. */\n age: number\n readonly data: TData\n}\n\nexport type CorpseLedger<TData> = {\n readonly entries: readonly CorpseEntry<TData>[]\n readonly count: number\n /** Adds a corpse; when the ledger is full the oldest one is replaced. Returns the replaced data, if any. */\n add(data: TData): TData | undefined\n /** Ages every corpse by `dt` seconds and removes the ones past their life (swap with the last, like the game). Returns the removed data. */\n update(dt: number): TData[]\n clear(): void\n}\n\n/** The bodies left on the ground: capped (400) and gone after a lifetime (900 s); generic over what each one carries. */\nexport const createCorpseLedger = <TData>(options: CorpseOptions): CorpseLedger<TData> => {\n const entries: CorpseEntry<TData>[] = []\n return {\n entries,\n get count() {\n return entries.length\n },\n add(data) {\n if (entries.length < options.max) {\n entries.push({ age: 0, data })\n return undefined\n }\n let oldest = 0\n for (let index = 1; index < entries.length; index++) if ((entries[index] as CorpseEntry<TData>).age > (entries[oldest] as CorpseEntry<TData>).age) oldest = index\n const replaced = (entries[oldest] as CorpseEntry<TData>).data\n entries[oldest] = { age: 0, data }\n return replaced\n },\n update(dt) {\n const removed: TData[] = []\n for (let index = 0; index < entries.length; index++) {\n const entry = entries[index] as CorpseEntry<TData>\n entry.age += dt\n if (entry.age <= options.seconds) continue\n removed.push(entry.data)\n entries[index] = entries[entries.length - 1] as CorpseEntry<TData>\n entries.pop()\n index--\n }\n return removed\n },\n clear() {\n entries.length = 0\n },\n }\n}\n","import 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 */\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /** Parts, joints and structure in the impl's local space, for raycast, inspector and log. Called often: keep it cheap. */\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 /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n state(): ObjectState\n reset?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n}\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).\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 return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { Hit, 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}\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 source: shot.source ?? shot.weapon,\n }\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\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n}\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 = 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 }\n}\n","type 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. */\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 }\n}\n\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) entries.delete(id)\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}\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\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}\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 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 }\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; 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","{\n \"id\": \"team-game\",\n \"segments\": {\n \"head\": 40,\n \"arm\": 60,\n \"leg\": 80\n },\n \"calibers\": {\n \"7_62x51\": {\n \"gameKey\": \"308\",\n \"name\": \"7,62×51 (.308)\",\n \"points\": 75,\n \"penetration\": 4,\n \"effectiveRangeMetres\": 600,\n \"noiseMetres\": 130,\n \"skullRange\": 1,\n \"class\": \"rifle\"\n },\n \"9x19\": {\n \"gameKey\": \"9x19\",\n \"name\": \"9×19 mm\",\n \"points\": 35,\n \"penetration\": 1.2,\n \"effectiveRangeMetres\": 35,\n \"noiseMetres\": 60,\n \"skullRange\": 1,\n \"class\": \"pistol\"\n },\n \"12ga_00buck\": {\n \"gameKey\": \"12ga\",\n \"name\": \"12 ga 00\",\n \"points\": 12,\n \"pellets\": 9,\n \"penetration\": 0.5,\n \"effectiveRangeMetres\": 15,\n \"noiseMetres\": 90,\n \"skullRange\": 8,\n \"class\": \"pistol\"\n },\n \"7_62x39\": {\n \"gameKey\": \"762x39\",\n \"name\": \"7,62×39 mm\",\n \"points\": 55,\n \"penetration\": 3,\n \"effectiveRangeMetres\": 250,\n \"noiseMetres\": 110,\n \"skullRange\": 1,\n \"class\": \"rifle\"\n }\n },\n \"regionCost\": {\n \"head\": 0.7,\n \"torso\": 1,\n \"bruteTorso\": 2,\n \"limb\": 0.5\n },\n \"damageKeptPerBody\": 0.75,\n \"falloff\": {\n \"fullAtRange\": 1,\n \"atTwiceRange\": 0.5\n },\n \"helmetAbsorbs\": \"pistol\",\n \"regions\": [\n \"head\",\n \"torso\",\n \"armL\",\n \"armR\",\n \"legL\",\n \"legR\"\n ]\n}\n","import type { BodyRegion } from '@adatechnology/game-contracts'\n\nimport teamGame from '../presets/team-game.json'\nimport type { SegmentId } from './segment-tree'\n\n/** The regions that keep their own hit points in the crowd model (the torso has none: torso hits go to vitality). */\nexport type LimbRegion = Exclude<BodyRegion, 'torso'>\n\nexport const LIMB_REGIONS: readonly LimbRegion[] = ['head', 'armL', 'armR', 'legL', 'legR']\n\n/** The game's region numbers (`SEG`): hit points of the head, of an arm and of a leg. */\nexport const REGION_HIT_POINTS: Readonly<Record<LimbRegion, number>> = {\n head: teamGame.segments.head,\n armL: teamGame.segments.arm,\n armR: teamGame.segments.arm,\n legL: teamGame.segments.leg,\n legR: teamGame.segments.leg,\n}\n\n/** The segments that make up each region, and the one that names it in events (the first). */\nexport const REGION_SEGMENTS: Readonly<Record<BodyRegion, readonly SegmentId[]>> = {\n head: ['head', 'jaw', 'neck'],\n torso: ['torso', 'pelvis'],\n armL: ['upperArmL', 'forearmL', 'handL'],\n armR: ['upperArmR', 'forearmR', 'handR'],\n legL: ['thighL', 'shinL', 'footL'],\n legR: ['thighR', 'shinR', 'footR'],\n}\n\nexport const BODY_REGIONS: readonly BodyRegion[] = ['head', 'torso', 'armL', 'armR', 'legL', 'legR']\n\nexport const isBodyRegion = (value: string): value is BodyRegion => (BODY_REGIONS as readonly string[]).includes(value)\n","{\n \"segments\": [\n {\n \"id\": \"head\",\n \"region\": \"head\",\n \"hitPoints\": 40,\n \"multiplier\": 3,\n \"bleed\": 40\n },\n {\n \"id\": \"jaw\",\n \"region\": \"head\",\n \"hitPoints\": 12,\n \"multiplier\": 2,\n \"bleed\": 8\n },\n {\n \"id\": \"neck\",\n \"region\": \"head\",\n \"hitPoints\": 25,\n \"multiplier\": 2,\n \"bleed\": 46\n },\n {\n \"id\": \"torso\",\n \"region\": \"torso\",\n \"hitPoints\": 150,\n \"multiplier\": 1,\n \"bleed\": 10\n },\n {\n \"id\": \"pelvis\",\n \"region\": \"torso\",\n \"hitPoints\": 90,\n \"multiplier\": 1,\n \"bleed\": 12\n },\n {\n \"id\": \"upperArm\",\n \"region\": \"arm\",\n \"hitPoints\": 45,\n \"multiplier\": 0.6,\n \"bleed\": 15\n },\n {\n \"id\": \"forearm\",\n \"region\": \"arm\",\n \"hitPoints\": 30,\n \"multiplier\": 0.6,\n \"bleed\": 8\n },\n {\n \"id\": \"hand\",\n \"region\": \"arm\",\n \"hitPoints\": 12,\n \"multiplier\": 0.6,\n \"bleed\": 3\n },\n {\n \"id\": \"thigh\",\n \"region\": \"leg\",\n \"hitPoints\": 55,\n \"multiplier\": 0.7,\n \"bleed\": 19\n },\n {\n \"id\": \"shin\",\n \"region\": \"leg\",\n \"hitPoints\": 40,\n \"multiplier\": 0.7,\n \"bleed\": 9\n },\n {\n \"id\": \"foot\",\n \"region\": \"leg\",\n \"hitPoints\": 15,\n \"multiplier\": 0.7,\n \"bleed\": 3\n }\n ],\n \"regions\": {\n \"head\": {\n \"hitPoints\": 40,\n \"segmentSum\": 77,\n \"scale\": 0.5195\n },\n \"arm\": {\n \"hitPoints\": 60,\n \"segmentSum\": 87,\n \"scale\": 0.6897\n },\n \"leg\": {\n \"hitPoints\": 80,\n \"segmentSum\": 110,\n \"scale\": 0.7273\n }\n },\n \"arsenalWeapons\": {\n \"pistola\": {\n \"n\": \"Pistola 9×19\",\n \"dmg\": 35,\n \"pel\": 1\n },\n \"fuzil\": {\n \"n\": \"Fuzil 7,62×39\",\n \"dmg\": 55,\n \"pel\": 1\n },\n \"escopeta\": {\n \"n\": \"Escopeta 12 ga\",\n \"dmg\": 12,\n \"pel\": 9\n },\n \"cinquenta\": {\n \"n\": \".50 BMG\",\n \"dmg\": 180,\n \"pel\": 1\n },\n \"granada\": {\n \"n\": \"Granada\",\n \"dmg\": 300,\n \"pel\": 0\n }\n },\n \"elenco\": {\n \"segments\": {\n \"head\": {\n \"hp\": 40,\n \"radius\": 0.07\n },\n \"torso\": {\n \"hp\": 120\n },\n \"pelvis\": {\n \"hp\": 90\n },\n \"upperArm\": {\n \"hp\": 60,\n \"radius\": 0.085\n },\n \"forearm\": {\n \"hp\": 45,\n \"radius\": 0.065\n },\n \"hand\": {\n \"hp\": 25,\n \"radius\": 0.05\n },\n \"thigh\": {\n \"hp\": 80,\n \"radius\": 0.1\n },\n \"shin\": {\n \"hp\": 55,\n \"radius\": 0.08\n }\n },\n \"below\": {\n \"upperArm\": [\n \"forearm\",\n \"hand\"\n ],\n \"forearm\": [\n \"hand\"\n ],\n \"thigh\": [\n \"shin\"\n ]\n },\n \"falls\": {\n \"upperArm\": \"o braço inteiro\",\n \"forearm\": \"o antebraço com a mão\",\n \"hand\": \"a mão\",\n \"thigh\": \"a perna inteira\",\n \"shin\": \"a canela com o pé\",\n \"head\": \"a cabeça\"\n },\n \"cutWeapons\": [\n {\n \"id\": \"faca\",\n \"n\": \"Faca\",\n \"dmg\": 22,\n \"cut\": 0.7\n },\n {\n \"id\": \"facao\",\n \"n\": \"Facão\",\n \"dmg\": 55,\n \"cut\": 1\n },\n {\n \"id\": \"machado\",\n \"n\": \"Machado\",\n \"dmg\": 85,\n \"cut\": 1\n },\n {\n \"id\": \"p9\",\n \"n\": \"Pistola 9 mm\",\n \"dmg\": 30,\n \"cut\": 0.15\n },\n {\n \"id\": \"e12\",\n \"n\": \"Espingarda 12\",\n \"dmg\": 95,\n \"cut\": 0.75\n },\n {\n \"id\": \"f762\",\n \"n\": \"Fuzil 7,62\",\n \"dmg\": 65,\n \"cut\": 0.45\n }\n ]\n },\n \"severity\": {\n \"severAtCut\": 0.5,\n \"severAtDamageFraction\": 0.9,\n \"destroyAtDamageMultiple\": 2,\n \"limpAtHpFraction\": 0.5,\n \"splitAtDamage\": 150,\n \"headKillDamage\": 20,\n \"jawChance\": 0.3,\n \"jawDamage\": 25,\n \"headBitDamage\": 60,\n \"headBitShotgunMetres\": 5\n },\n \"defaultCut\": {\n \"slash\": 0.85,\n \"blunt\": 0,\n \"explosive\": 1,\n \"ballistic\": {\n \"pistol\": 0.15,\n \"buckshot\": 0.75,\n \"rifle\": 0.45\n }\n },\n \"deathRule\": {\n \"default\": \"vitality-or-head\",\n \"options\": [\n \"vitality-or-head\",\n \"head-only\"\n ]\n }\n}\n","import type { BodyRegion, BodySlot, SegmentKind } from '@adatechnology/game-contracts'\n\nimport segments from '../data/segments.json'\nimport type { JointId } from './body-spec'\n\nexport type SegmentSide = 'L' | 'R'\ntype LimbKind = 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\nexport type SegmentId = 'pelvis' | 'torso' | 'neck' | 'head' | 'jaw' | `${LimbKind}${SegmentSide}`\n\n/** One segment of the tree: the joint it hangs from, its parent, the crowd region it belongs to and the item slots that cover it. */\nexport type SegmentNode = {\n readonly id: SegmentId\n readonly kind: SegmentKind\n readonly side?: SegmentSide\n readonly joint: JointId\n readonly parent?: SegmentId\n readonly region: BodyRegion\n readonly slots: readonly BodySlot[]\n}\n\n/** Numbers of a segment kind (the Arsenal table, A4): hit points, damage multiplier and bleed rate. */\nexport type SegmentNumbers = { readonly hitPoints: number; readonly multiplier: number; readonly bleed: number }\n\nconst limb = (kind: LimbKind, side: SegmentSide, joint: JointId, parent: SegmentId | undefined, slots: readonly BodySlot[]): SegmentNode => {\n const isArm = kind === 'upperArm' || kind === 'forearm' || kind === 'hand'\n const region: BodyRegion = isArm ? (side === 'L' ? 'armL' : 'armR') : side === 'L' ? 'legL' : 'legR'\n return { id: `${kind}${side}`, kind, side, joint, region, slots, ...(parent ? { parent } : {}) }\n}\n\nconst sideOf = (side: SegmentSide): SegmentNode[] => [\n limb('upperArm', side, `shoulder${side}`, 'torso', ['arms']),\n limb('forearm', side, `elbow${side}`, `upperArm${side}`, ['arms']),\n limb('hand', side, `wrist${side}`, `forearm${side}`, ['hands']),\n limb('thigh', side, `hip${side}`, 'pelvis', ['legs']),\n limb('shin', side, `knee${side}`, `thigh${side}`, ['legs']),\n limb('foot', side, `ankle${side}`, `shin${side}`, ['feet']),\n]\n\n/** The 17 segments (11 kinds, limbs on both sides), parents before children. Neck and jaw have no item slot: a helmet does not cover them. */\nexport const SEGMENT_TREE: readonly SegmentNode[] = [\n { id: 'pelvis', kind: 'pelvis', joint: 'hip', region: 'torso', slots: ['torso'] },\n { id: 'torso', kind: 'torso', joint: 'spine', parent: 'pelvis', region: 'torso', slots: ['torso'] },\n { id: 'neck', kind: 'neck', joint: 'neck', parent: 'torso', region: 'head', slots: [] },\n { id: 'head', kind: 'head', joint: 'head', parent: 'neck', region: 'head', slots: ['head', 'eyes'] },\n { id: 'jaw', kind: 'jaw', joint: 'jaw', parent: 'head', region: 'head', slots: [] },\n ...sideOf('L'),\n ...sideOf('R'),\n]\n\nexport const SEGMENT_IDS: readonly SegmentId[] = SEGMENT_TREE.map((node) => node.id)\n\nconst NODES = new Map(SEGMENT_TREE.map((node) => [node.id, node]))\n\nexport const segmentNode = (id: SegmentId): SegmentNode => {\n const node = NODES.get(id)\n if (!node) throw new Error(`game-characters: unknown segment \"${id}\"`)\n return node\n}\n\nexport const isSegmentId = (value: string): value is SegmentId => NODES.has(value as SegmentId)\n\n/** Every segment that hangs below `id` (children, grandchildren...), in tree order: what falls with it when it is severed. */\nexport const segmentsBelow = (id: SegmentId): SegmentId[] => {\n const out: SegmentId[] = []\n const visit = (parent: SegmentId): void => {\n for (const node of SEGMENT_TREE) {\n if (node.parent !== parent) continue\n out.push(node.id)\n visit(node.id)\n }\n }\n visit(id)\n return out\n}\n\n/** The Arsenal numbers per segment kind (hit points, `MULT`, `BLEED`). */\nexport const SEGMENT_NUMBERS: Readonly<Record<SegmentKind, SegmentNumbers>> = Object.fromEntries(\n segments.segments.map((entry) => [entry.id, { hitPoints: entry.hitPoints, multiplier: entry.multiplier, bleed: entry.bleed }]),\n) as Record<SegmentKind, SegmentNumbers>\n","import { MISSING_BITS } from '@adatechnology/game-contracts'\nimport type { SegmentKind } from '@adatechnology/game-contracts'\n\nimport type { Detail, SegmentState } from '../types'\nimport { LIMB_REGIONS, REGION_HIT_POINTS, REGION_SEGMENTS } from './regions'\nimport type { LimbRegion } from './regions'\nimport { SEGMENT_TREE } from './segment-tree'\nimport type { SegmentId, SegmentSide } from './segment-tree'\n\n/** The mutable state of one body. Both detail levels live here: the 17 segments and the hit points of the 5 crowd regions. */\nexport type BodyState = {\n readonly segments: SegmentState[]\n readonly regions: Record<LimbRegion, number>\n vitality: number\n readonly maxVitality: number\n alive: boolean\n /** The game's `MISSING_BITS` mask. */\n missing: number\n /** Sides that limp, in the order they started. */\n readonly limping: SegmentSide[]\n crawl: boolean\n stunSeconds: number\n /** Loose pieces: each severed segment with what fell with it. */\n readonly pieces: SegmentId[][]\n /** Protection layers used up (a helmet that took its one shot). */\n readonly consumed: Set<string>\n detail: Detail\n}\n\nexport type CreateBodyStateParams = { readonly vitality: number; readonly detail: Detail; readonly crawling?: boolean; readonly hitPointsOf: (kind: SegmentKind) => number }\n\nexport const createBodyState = ({ vitality, detail, crawling, hitPointsOf }: CreateBodyStateParams): BodyState => ({\n segments: SEGMENT_TREE.map((node) => {\n const max = hitPointsOf(node.kind)\n return { id: node.id, kind: node.kind, region: node.region, hp: max, max, status: 'ok', attached: true, ...(node.side ? { side: node.side } : {}) }\n }),\n regions: { ...REGION_HIT_POINTS },\n vitality,\n maxVitality: vitality,\n alive: true,\n missing: 0,\n limping: [],\n crawl: crawling ?? false,\n stunSeconds: 0,\n pieces: [],\n consumed: new Set(),\n detail,\n})\n\nexport const segmentOf = (body: BodyState, id: SegmentId): SegmentState => {\n const segment = body.segments.find((candidate) => candidate.id === id)\n if (!segment) throw new Error(`game-characters: unknown segment \"${id}\"`)\n return segment\n}\n\nconst LIMB_MASK: readonly { readonly ids: readonly SegmentId[]; readonly lost: number; readonly broken: number }[] = [\n { ids: ['upperArmL', 'forearmL'], lost: MISSING_BITS.armL, broken: MISSING_BITS.armLBroken },\n { ids: ['upperArmR', 'forearmR'], lost: MISSING_BITS.armR, broken: MISSING_BITS.armRBroken },\n { ids: ['thighL', 'shinL'], lost: MISSING_BITS.legL, broken: MISSING_BITS.legLBroken },\n { ids: ['thighR', 'shinR'], lost: MISSING_BITS.legR, broken: MISSING_BITS.legRBroken },\n]\n\n/** The crowd mask the segments amount to: a lost head, jaw, arm or leg (upper or lower part), and a broken one still attached. */\nexport const missingFromSegments = (body: BodyState): number => {\n let mask = 0\n if (!segmentOf(body, 'head').attached) mask |= MISSING_BITS.head\n else if (!segmentOf(body, 'jaw').attached) mask |= MISSING_BITS.jaw\n for (const limb of LIMB_MASK) {\n const parts = limb.ids.map((id) => segmentOf(body, id))\n if (parts.some((part) => !part.attached)) mask |= limb.lost\n else if (parts.some((part) => part.status === 'broken')) mask |= limb.broken\n }\n return mask\n}\n\n/** Region hit points from the segments: the share of the region's segment hit points left, scaled to the region's own hit points. */\nexport const regionsFromSegments = (body: BodyState): void => {\n for (const region of LIMB_REGIONS) {\n const parts = REGION_SEGMENTS[region].map((id) => segmentOf(body, id))\n const left = parts.reduce((sum, part) => sum + (part.attached ? Math.max(0, part.hp) : 0), 0)\n const total = parts.reduce((sum, part) => sum + part.max, 0)\n body.regions[region] = (REGION_HIT_POINTS[region] * left) / total\n }\n body.missing |= missingFromSegments(body)\n}\n\n/** Segment hit points from the regions (the reverse is lossy: every segment of a region keeps the region's share). */\nexport const segmentsFromRegions = (body: BodyState): void => {\n for (const region of LIMB_REGIONS) {\n const share = Math.max(0, body.regions[region]) / REGION_HIT_POINTS[region]\n for (const id of REGION_SEGMENTS[region]) {\n const part = segmentOf(body, id)\n if (part.attached) part.hp = Math.min(part.hp, part.max * share)\n }\n }\n}\n","import type { DestructibleSpec, JointSpec, PartShape, PartSpec, SegmentKind, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { BodySpec } from './body-spec'\nimport type { Rig } from './rig'\nimport { SEGMENT_TREE } from './segment-tree'\nimport type { SegmentNode } from './segment-tree'\n\n/** The material id the parts of a body carry (a destruction world without it skips its own material rules: the body is a `DestructibleImpl`). */\nexport const BODY_MATERIAL = 'flesh'\n\n/** Share of the body mass per segment kind (sums to 1 over the 17 segments). */\nconst MASS_SHARE: Readonly<Record<SegmentKind, number>> = {\n head: 0.07,\n jaw: 0.01,\n neck: 0.02,\n torso: 0.34,\n pelvis: 0.14,\n upperArm: 0.028,\n forearm: 0.016,\n hand: 0.006,\n thigh: 0.1,\n shin: 0.045,\n foot: 0.015,\n}\nconst ADULT_MASS_KG = 70\nconst LEAF_KINDS: ReadonlySet<SegmentKind> = new Set(['head', 'jaw', 'hand', 'foot'])\n\nconst firstChild = (node: SegmentNode): SegmentNode | undefined => SEGMENT_TREE.find((candidate) => candidate.parent === node.id)\n\n/** A cylinder from `from` to `to`: centred between them, its local +Y turned onto the segment (Euler XYZ). */\nconst cylinderBetween = (from: Vec3, to: Vec3, radius: number): { shape: PartShape; position: Vec3; rotation: Vec3 } => {\n const axis: Vec3 = [to[0] - from[0], to[1] - from[1], to[2] - from[2]]\n const length = Math.max(1e-3, Math.hypot(axis[0], axis[1], axis[2]))\n const [x, y, z] = [axis[0] / length, axis[1] / length, axis[2] / length]\n return {\n shape: { kind: 'cylinder', radius, height: length },\n position: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2, (from[2] + to[2]) / 2],\n rotation: [Math.atan2(z, y), 0, -Math.asin(Math.max(-1, Math.min(1, x)))],\n }\n}\n\nconst partOf = (node: SegmentNode, rig: Rig, body: BodySpec, massKg: number): PartSpec => {\n const joint = rig.joints[node.joint]\n const radius = body.segmentRadius[node.kind] * (rig.height / body.heightMetres)\n const mass = massKg * MASS_SHARE[node.kind]\n const child = firstChild(node)\n if (LEAF_KINDS.has(node.kind) || !child) {\n const lift = node.kind === 'head' ? radius : node.kind === 'jaw' ? 0 : -radius\n return { id: node.id, material: BODY_MATERIAL, shape: { kind: 'sphere', radius }, position: [joint[0], joint[1] + lift, joint[2]], mass, tags: ['body', node.kind] }\n }\n const placed = cylinderBetween(joint, rig.joints[child.joint], radius)\n return { id: node.id, material: BODY_MATERIAL, ...placed, mass, tags: ['body', node.kind] }\n}\n\nexport type DescribeBodyParams = { readonly rig: Rig; readonly body: BodySpec; readonly build: number; readonly name?: string }\n\n/** The body as destruction parts (one per segment, in the body's local space) and the joints between them. */\nexport const describeBody = ({ rig, body, build, name }: DescribeBodyParams): DestructibleSpec => {\n const massKg = ADULT_MASS_KG * (rig.height / body.heightMetres) ** 3 * build\n const parts = SEGMENT_TREE.map((node) => partOf(node, rig, body, massKg))\n const joints: JointSpec[] = SEGMENT_TREE.filter((node) => node.parent).map((node) => ({ id: `${node.parent}~${node.id}`, a: node.parent as string, b: node.id, kind: 'fused', tools: [] }))\n return { ...(name ? { name } : {}), parts, joints, tags: ['character'] }\n}\n","import type { DestructibleSpec, JointState, ObjectState, PartState, PartStatus, Quat, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { SegmentStatus } from '../types'\nimport { missingFromSegments } from './body-state'\nimport type { BodyState } from './body-state'\n\nconst PART_STATUS: Readonly<Record<SegmentStatus, PartStatus>> = { ok: 'intact', wounded: 'damaged', broken: 'damaged', severed: 'collapsed', destroyed: 'broken' }\nconst BODY_TEMPERATURE_C = 37\n\nexport type ToObjectStateParams = {\n readonly id: string\n readonly name?: string\n readonly position: Vec3\n readonly rotation: Quat\n readonly body: BodyState\n readonly spec: DestructibleSpec\n}\n\n/** The body in the destruction contract: one part per segment, the joints between them, the pieces and the `body` summary. */\nexport const toObjectState = ({ id, name, position, rotation, body, spec }: ToObjectStateParams): ObjectState => {\n const groups: string[][] = [body.segments.filter((segment) => segment.attached).map((segment) => segment.id)]\n for (const piece of body.pieces) {\n const left = piece.filter((part) => body.segments.find((segment) => segment.id === part)?.status !== 'destroyed')\n if (left.length > 0) groups.push(left)\n }\n const groupOf = (part: string): number => groups.findIndex((group) => group.includes(part))\n const parts: PartState[] = body.segments.map((segment) => {\n const mass = spec.parts.find((part) => part.id === segment.id)?.mass ?? 0\n return {\n id: segment.id,\n material: 'flesh',\n status: PART_STATUS[segment.status],\n hp: Math.max(0, segment.hp),\n maxHp: segment.max,\n mass,\n temperature: BODY_TEMPERATURE_C,\n burning: false,\n fuel: 0,\n char: 0,\n melt: 0,\n dents: [],\n holes: [],\n cracks: [],\n group: groupOf(segment.id),\n }\n })\n const joints: JointState[] = (spec.joints ?? []).map((joint) => {\n const child = body.segments.find((segment) => segment.id === joint.b)\n const parent = body.segments.find((segment) => segment.id === joint.a)\n const open = child !== undefined && parent !== undefined && parent.attached !== child.attached\n return { id: joint.id ?? `${joint.a}~${joint.b}`, a: joint.a, b: joint.b, kind: joint.kind, hp: open ? 0 : 1, maxHp: 1, progress: 0, open, ...(open ? { openedBy: 'break' as const } : {}) }\n })\n return {\n id,\n ...(name ? { name } : {}),\n position: [...position],\n rotation: [...rotation],\n parts,\n joints,\n groups,\n destroyed: false,\n body: { alive: body.alive, vitality: body.vitality, missing: body.detail === 'segments' ? body.missing | missingFromSegments(body) : body.missing, limp: body.limping.length > 0, crawl: body.crawl },\n }\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { JOINT_IDS } from './body-spec'\nimport type { BodySpec, JointId } from './body-spec'\n\n/** The bones of the game's instanced body (G 65336): 0 torso and hip, 1 head, 2/3 arms, 4/5 thighs, 6 eyes, 7/8 forearms, 9/10 shins, 11 jaw. */\nexport const GAME_BONES = {\n torso: 0,\n head: 1,\n upperArmL: 2,\n upperArmR: 3,\n thighL: 4,\n thighR: 5,\n eyes: 6,\n forearmL: 7,\n forearmR: 8,\n shinL: 9,\n shinR: 10,\n jaw: 11,\n} as const\n\nexport const JOINT_PARENTS: Readonly<Record<JointId, JointId | undefined>> = {\n hip: undefined,\n spine: 'hip',\n neck: 'spine',\n head: 'neck',\n jaw: 'head',\n shoulderL: 'spine',\n shoulderR: 'spine',\n elbowL: 'shoulderL',\n elbowR: 'shoulderR',\n wristL: 'elbowL',\n wristR: 'elbowR',\n hipL: 'hip',\n hipR: 'hip',\n kneeL: 'hipL',\n kneeR: 'hipR',\n ankleL: 'kneeL',\n ankleR: 'kneeR',\n}\n\n/** The joints of one body, scaled to its height and build. */\nexport type Rig = {\n readonly joints: Readonly<Record<JointId, Vec3>>\n readonly parents: Readonly<Record<JointId, JointId | undefined>>\n readonly gameBones: typeof GAME_BONES\n /** Height in metres of this body. */\n readonly height: number\n}\n\nexport type CreateRigParams = { readonly body: BodySpec; readonly height: number; readonly build: number }\n\n/** Joints of `body` scaled to `height` metres (vertical and depth) and to `build` (width). */\nexport const createRig = ({ body, height, build }: CreateRigParams): Rig => {\n const scale = height / body.heightMetres\n const joints = Object.fromEntries(\n JOINT_IDS.map((id) => {\n const [x, y, z] = body.joints[id]\n return [id, [x * scale * build, y * scale, z * scale] as Vec3]\n }),\n ) as Record<JointId, Vec3>\n return { joints, parents: JOINT_PARENTS, gameBones: GAME_BONES, height }\n}\n","import type { DestructibleSpec, ObjectState, Quat, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { BodySpec } from './body/body-spec'\nimport { createBodyState, regionsFromSegments, segmentsFromRegions } from './body/body-state'\nimport type { BodyState } from './body/body-state'\nimport { describeBody } from './body/describe'\nimport { toObjectState } from './body/object-state'\nimport type { LimbRegion } from './body/regions'\nimport { createRig } from './body/rig'\nimport type { Rig } from './body/rig'\nimport { SEGMENT_NUMBERS } from './body/segment-tree'\nimport type { BodyMultipliers, CharacterSpec, Detail, SegmentState } from './types'\n\n/** A spec with every default filled in. */\nexport type ResolvedCharacterSpec = CharacterSpec & {\n readonly id: string\n readonly height: number\n readonly build: number\n readonly vitality: number\n readonly multipliers: BodyMultipliers\n readonly limbFactor: number\n readonly bloodFactor: number\n readonly bodyCount: number\n readonly stunSeconds: number\n readonly protection: readonly string[]\n readonly detail: Detail\n}\n\nexport type Character = {\n readonly id: string\n readonly spec: ResolvedCharacterSpec\n readonly rig: Rig\n /** Live view of the 17 segments. */\n readonly segments: readonly SegmentState[]\n readonly detail: Detail\n /** Hit points of the 5 crowd regions (head, arms, legs). */\n regionHitPoints(): Readonly<Record<LimbRegion, number>>\n /** Swaps the detail level: segments to regions sums each region (lossless); regions to segments spreads the region's share (lossy). */\n setDetail(detail: Detail): void\n setTransform(position: Vec3, rotation?: Quat): void\n describe(): DestructibleSpec\n state(): ObjectState\n reset(): void\n}\n\nexport const DEFAULT_VITALITY = 100\nexport const DEFAULT_STUN_SECONDS = 0.45\nconst NO_MULTIPLIERS: BodyMultipliers = { head: 1, torso: 1, arms: 1, legs: 1 }\n\nexport const resolveSpec = (spec: CharacterSpec, body: BodySpec, counter: number): ResolvedCharacterSpec => ({\n ...spec,\n id: spec.id ?? `${spec.kind}_${counter}`,\n height: spec.height ?? body.heightMetres,\n build: spec.build ?? 1,\n vitality: spec.vitality ?? DEFAULT_VITALITY,\n multipliers: { ...NO_MULTIPLIERS, ...spec.multipliers },\n limbFactor: spec.limbFactor ?? 1,\n bloodFactor: spec.bloodFactor ?? 1,\n bodyCount: spec.bodyCount ?? 1,\n stunSeconds: spec.stunSeconds ?? DEFAULT_STUN_SECONDS,\n protection: spec.protection ?? [],\n detail: spec.detail ?? 'segments',\n})\n\nexport type CharacterCore = {\n readonly spec: ResolvedCharacterSpec\n readonly rig: Rig\n readonly body: BodyState\n position: Vec3\n rotation: Quat\n readonly describe: () => DestructibleSpec\n /** Back to the state at creation (full health, every segment attached). */\n readonly resetBody: () => void\n}\n\nexport type CreateCharacterCoreParams = { readonly spec: ResolvedCharacterSpec; readonly bodySpec: BodySpec; readonly hitPointsOf?: (kind: SegmentState['kind']) => number }\n\n/** The state every character shares: rig, body state, transform and the cached part list. */\nexport const createCharacterCore = ({ spec, bodySpec, hitPointsOf }: CreateCharacterCoreParams): CharacterCore => {\n const rig = createRig({ body: bodySpec, height: spec.height, build: spec.build })\n const parts = describeBody({ rig, body: bodySpec, build: spec.build, name: spec.kind })\n const fresh = (): BodyState => createBodyState({ vitality: spec.vitality, detail: spec.detail, crawling: spec.crawling ?? false, hitPointsOf: hitPointsOf ?? ((kind) => SEGMENT_NUMBERS[kind].hitPoints) })\n const body = fresh()\n return { spec, rig, body, position: [0, 0, 0], rotation: [0, 0, 0, 1], describe: () => parts, resetBody: () => void Object.assign(body, fresh()) }\n}\n\n/** The plain-data part of a character (state, detail and transform); the damage model is added on top of it. */\nexport const characterView = (core: CharacterCore): Character => ({\n id: core.spec.id,\n spec: core.spec,\n rig: core.rig,\n get segments() {\n return core.body.segments\n },\n get detail() {\n return core.body.detail\n },\n regionHitPoints: () => ({ ...core.body.regions }),\n setDetail(detail) {\n if (detail === core.body.detail) return\n if (detail === 'regions') regionsFromSegments(core.body)\n else segmentsFromRegions(core.body)\n core.body.detail = detail\n },\n setTransform(position, rotation) {\n core.position = [...position]\n if (rotation) core.rotation = [...rotation]\n },\n describe: core.describe,\n state: () => toObjectState({ id: core.spec.id, name: core.spec.kind, position: core.position, rotation: core.rotation, body: core.body, spec: core.describe() }),\n reset: core.resetBody,\n})\n","import type { Quat, Vec3 } from '@adatechnology/game-contracts'\n\n/** `v` rotated by the unit quaternion `q`. */\nexport const rotate = (q: Quat, v: Vec3): Vec3 => {\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\nconst conjugate = (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]]\n\nexport type Transform = { readonly position: Vec3; readonly rotation: Quat }\n\nexport const toWorld = ({ position, rotation }: Transform, local: Vec3): Vec3 => {\n const turned = rotate(rotation, local)\n return [turned[0] + position[0], turned[1] + position[1], turned[2] + position[2]]\n}\n\nexport const toLocal = ({ position, rotation }: Transform, world: Vec3): Vec3 => rotate(conjugate(rotation), [world[0] - position[0], world[1] - position[1], world[2] - position[2]])\n\nexport const distance = (a: Vec3, b: Vec3): number => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2])\n","import type { DestructionEvent, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { SegmentId } from '../body/segment-tree'\n\n/** A bleeding wound: `rate` in drops per second (the Arsenal's unit) fading to 0 over `duration` seconds; `spurt` pulses like an artery. */\nexport type Bleeder = {\n readonly part: SegmentId\n readonly rate: number\n readonly duration: number\n readonly spurt: boolean\n age: number\n /** Whole seconds of this bleeder already reported as `leak` events. */\n reported: number\n}\n\n/** Volume of one drop (a 4 mm drop of the Arsenal's blood): `leak` events carry litres per second. */\nexport const BLOOD_LITERS_PER_DROP = 0.00027\n\nexport const bleedRateAt = (bleeder: Bleeder): number => (bleeder.age >= bleeder.duration ? 0 : bleeder.rate * (1 - bleeder.age / bleeder.duration))\n\nexport type StepBleedingParams = {\n readonly bleeders: Bleeder[]\n readonly dt: number\n readonly emit: (event: Omit<Extract<DestructionEvent, { type: 'leak' }>, 'object' | 'time'>) => void\n readonly pointOf: (id: SegmentId) => Vec3\n}\n\n/** Ages the bleeders; each one still running reports a `leak` with its current rate once per second of its life. */\nexport const stepBleeding = ({ bleeders, dt, emit, pointOf }: StepBleedingParams): void => {\n for (const bleeder of bleeders) {\n if (bleeder.age >= bleeder.duration) continue\n bleeder.age += dt\n const second = Math.floor(bleeder.age)\n if (second <= bleeder.reported) continue\n bleeder.reported = second\n const rate = bleedRateAt(bleeder)\n if (rate > 0) emit({ type: 'leak', part: bleeder.part, fluid: 'blood', point: pointOf(bleeder.part), direction: [0, -1, 0], rate: rate * BLOOD_LITERS_PER_DROP, pressurized: bleeder.spurt })\n }\n}\n","import type { DamageType, DestructionEvent, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { BodyState } from '../body/body-state'\nimport { segmentOf } from '../body/body-state'\nimport { segmentNode, segmentsBelow } from '../body/segment-tree'\nimport type { SegmentId, SegmentSide } from '../body/segment-tree'\nimport type { ResolvedCharacterSpec } from '../character'\nimport type { SegmentState } from '../types'\nimport { BLOOD_LITERS_PER_DROP } from './bleeding'\nimport type { Bleeder } from './bleeding'\nimport type { DamageRules, DeathRule } from './types'\n\ntype BodyChange = Extract<DestructionEvent, { type: 'body' }>['change']\ntype KillCause = 'head' | 'vitality' | 'bleed' | 'explosion'\ntype EventDraft = DestructionEvent extends infer E ? (E extends DestructionEvent ? Omit<E, 'object' | 'time'> : never) : never\n\nexport type BleedParams = { readonly segment: SegmentState; readonly rate: number; readonly duration: number; readonly spurt: boolean; readonly point?: Vec3; readonly direction?: Vec3 }\n\n/** How severing treats what hangs below: the Arsenal only detaches it, the Elenco also zeroes it and marks it cut. */\nexport type SeverBelow = 'detach' | 'zero'\n\n/** Every change a damage rule can make to a body, each emitting its events. The rules (kit, arsenal, elenco, regions) only decide. */\nexport type BodyOps = {\n readonly body: BodyState\n readonly spec: ResolvedCharacterSpec\n readonly rules: DamageRules\n readonly random: () => number\n readonly events: DestructionEvent[]\n emit(event: EventDraft): void\n pointOf(id: SegmentId): Vec3\n change(change: BodyChange, part?: SegmentId, extra?: { cause?: KillCause; below?: string[] }): void\n damage(segment: SegmentState, amount: number, damageType: DamageType): void\n wound(segment: SegmentState): void\n breakBone(segment: SegmentState): void\n sever(segment: SegmentState, below?: SeverBelow): void\n destroy(segment: SegmentState): void\n kill(cause: KillCause): void\n limp(side: SegmentSide): void\n crawl(): void\n /** A heavy hit staggers the body for the spec's `stunSeconds`. */\n stun(): void\n bleed(params: BleedParams): void\n}\n\nexport type CreateBodyOpsParams = {\n readonly body: BodyState\n readonly spec: ResolvedCharacterSpec\n readonly rules: DamageRules\n readonly random: () => number\n readonly time: number\n readonly source?: string\n readonly pointOf: (id: SegmentId) => Vec3\n readonly bleeders: Bleeder[]\n}\n\nconst killAllowed = (rule: DeathRule, cause: KillCause): boolean => rule === 'vitality-or-head' || cause === 'head' || cause === 'explosion'\n\nexport const createBodyOps = ({ body, spec, rules, random, time, source, pointOf, bleeders }: CreateBodyOpsParams): BodyOps => {\n const events: DestructionEvent[] = []\n const emit = (event: EventDraft): void => void events.push({ ...event, object: spec.id, time, ...(source !== undefined ? { source } : {}) } as DestructionEvent)\n const change: BodyOps['change'] = (kind, part, extra) => emit({ type: 'body', change: kind, ...(part ? { part } : {}), ...extra })\n const detachBelow = (segment: SegmentState, below: SeverBelow): SegmentId[] => {\n const fallen = segmentsBelow(segment.id).filter((id) => segmentOf(body, id).attached)\n segment.attached = false\n for (const id of fallen) {\n const part = segmentOf(body, id)\n part.attached = false\n if (below === 'zero') Object.assign(part, { hp: 0, status: 'severed' })\n }\n return fallen\n }\n const ops: BodyOps = {\n body,\n spec,\n rules,\n random,\n events,\n emit,\n pointOf,\n change,\n damage: (segment, amount, damageType) => emit({ type: 'damage', part: segment.id, amount, hp: Math.max(0, segment.hp), damageType }),\n wound(segment) {\n if (segment.status === 'ok') segment.status = 'wounded'\n change('wound', segment.id)\n },\n breakBone(segment) {\n segment.status = 'broken'\n change('broken', segment.id)\n },\n sever(segment, below = 'detach') {\n if (!segment.attached) return\n const fallen = detachBelow(segment, below)\n segment.status = 'severed'\n body.pieces.push([segment.id, ...fallen])\n const parent = segmentNode(segment.id).parent\n change('severed', segment.id, { below: fallen })\n if (parent) emit({ type: 'detach', joint: `${parent}~${segment.id}`, parts: [parent, segment.id], by: 'break', groups: [[segment.id, ...fallen]] })\n },\n destroy(segment) {\n if (!segment.attached) return\n const fallen = detachBelow(segment, 'detach')\n segment.status = 'destroyed'\n if (fallen.length > 0) body.pieces.push(fallen)\n change('destroyed', segment.id, { below: fallen })\n emit({ type: 'fracture', part: segment.id, style: 'tear', fragments: [], point: pointOf(segment.id) })\n },\n kill(cause) {\n if (!body.alive || !killAllowed(rules.deathRule, cause)) return\n body.alive = false\n change('killed', undefined, { cause })\n },\n limp(side) {\n if (body.limping.includes(side)) return\n body.limping.push(side)\n change('limp')\n },\n crawl() {\n if (body.crawl) return\n body.crawl = true\n change('crawl')\n },\n stun() {\n body.stunSeconds = spec.stunSeconds\n change('stunned')\n },\n bleed({ segment, rate, duration, spurt, point, direction }) {\n const scaled = rate * spec.bloodFactor\n bleeders.push({ part: segment.id, rate: scaled, duration, spurt, age: 0, reported: 0 })\n emit({ type: 'leak', part: segment.id, fluid: 'blood', point: point ?? pointOf(segment.id), direction: direction ?? [0, -1, 0], rate: scaled * BLOOD_LITERS_PER_DROP, pressurized: spurt })\n },\n }\n return ops\n}\n","{\n \"id\": \"physical\",\n \"tissuePerCentimetre\": {\n \"flesh\": 0.25,\n \"bone\": 1\n },\n \"torsoPath\": {\n \"fleshCentimetres\": 22,\n \"boneCentimetres\": 2\n },\n \"regionFactor\": {\n \"head\": 0.7,\n \"limb\": 0.5,\n \"torso\": 1\n },\n \"bruteTorsoFactor\": 2,\n \"energyKept\": \"P / (P + R)\",\n \"points\": {\n \"coefficient\": 3.5,\n \"exponent\": 0.37\n },\n \"tolerance\": {\n \"bodies\": 0,\n \"energyKept\": 0.05\n },\n \"calibration\": [\n {\n \"caliber\": \"9x19\",\n \"force\": 7.67,\n \"bodies\": 2,\n \"energyKeptFirstBody\": 0.51,\n \"expectedBodies\": 2,\n \"bestiaryEnergyKept\": 0.5\n },\n {\n \"caliber\": \"5_56x45\",\n \"force\": 16.56,\n \"bodies\": 3,\n \"energyKeptFirstBody\": 0.69,\n \"expectedBodies\": 3,\n \"bestiaryEnergyKept\": 0.65\n },\n {\n \"caliber\": \"7_62x51\",\n \"force\": 26.67,\n \"bodies\": 4,\n \"energyKeptFirstBody\": 0.78,\n \"expectedBodies\": 4,\n \"bestiaryEnergyKept\": 0.75\n },\n {\n \"caliber\": \"7_62x39\",\n \"force\": 18.52,\n \"bodies\": 3,\n \"energyKeptFirstBody\": 0.71,\n \"expectedBodies\": 3\n },\n {\n \"caliber\": \"12ga_00buck\",\n \"force\": 4.35,\n \"bodies\": 1,\n \"energyKeptFirstBody\": 0.37,\n \"expectedBodies\": 1\n }\n ],\n \"torsoResistance\": 7.5\n}\n","import type { SegmentKind } from '@adatechnology/game-contracts'\n\nimport { SEGMENT_NUMBERS } from '../body/segment-tree'\nimport segments from '../data/segments.json'\nimport physical from '../presets/physical.json'\nimport teamGame from '../presets/team-game.json'\nimport type { BallisticClass, CaliberEntry, DamageRules, ProtectionLayer } from './types'\n\nconst { severity } = segments\n\n/** The kit's rules: Arsenal numbers per segment (A4), the design's severity, the game's head rule, death by vitality or head. */\nexport const DEFAULT_DAMAGE_RULES: DamageRules = {\n deathRule: 'vitality-or-head',\n segmentRule: 'kit',\n severity: { ...severity, stunAtPoints: 35, limbVitalityShare: 0.3, regionLimbVitalityShare: 0.5 },\n blast: { minimumPoints: 8, headDestroyPoints: 40, bigPoints: 120 },\n defaultCut: segments.defaultCut,\n points: physical.points,\n spread: 0,\n segments: SEGMENT_NUMBERS,\n burnPointsPerSecond: 3,\n}\n\n/** The Galeria 3D do Arsenal, replayed: its `damage`, `sever`, `explodeSeg`, `splitTorso`, `legLost` and `grenadeAt`. */\nexport const ARSENAL_RULES: DamageRules = { ...DEFAULT_DAMAGE_RULES, segmentRule: 'arsenal' }\n\nconst ELENCO_HIT_POINTS = segments.elenco.segments as Partial<Record<SegmentKind, { readonly hp: number }>>\n\n/** The Elenco, replayed: its own hit points, no multiplier, ±15 % per blow and its cut rule (`hit`, `sever`, `breakBone`); a torso at 0 kills (a human). */\nexport const ELENCO_RULES: DamageRules = {\n ...DEFAULT_DAMAGE_RULES,\n segmentRule: 'elenco',\n spread: 0.15,\n segments: Object.fromEntries(\n Object.entries(SEGMENT_NUMBERS).map(([kind, numbers]) => [kind, { ...numbers, multiplier: 1, hitPoints: ELENCO_HIT_POINTS[kind as SegmentKind]?.hp ?? numbers.hitPoints }]),\n ) as DamageRules['segments'],\n}\n\nexport const DAMAGE_PRESETS = { kit: DEFAULT_DAMAGE_RULES, arsenal: ARSENAL_RULES, elenco: ELENCO_RULES } as const\n\n/** The protection presets that reproduce the game's `ROUPAS` (tools/characters-catalog/decisions.json `protectionPresets`). */\nexport const PROTECTION_PRESETS: readonly ProtectionLayer[] = [\n { id: 'vest_police', slots: ['torso'], ballistic: { resistance: 14, blunt: 0.3, pass: 0.8 } },\n { id: 'vest_military', slots: ['torso'], ballistic: { resistance: 28, blunt: 0.5 } },\n { id: 'helmet_combat', slots: ['head'], ballistic: { resistance: 9, blunt: 0, pass: 1, consumable: true } },\n { id: 'turnout_gear', slots: ['torso', 'arms', 'legs'], fire: 0.25, limbs: 0.8 },\n]\n\nconst CLASS_OF: Readonly<Record<string, BallisticClass>> = { pistol: 'pistol', rifle: 'rifle' }\n\n/** The game's calibre table (`CALIBRES`) under the kit's calibre ids, for the `team-game` model. */\nexport const TEAM_GAME_CALIBERS: readonly CaliberEntry[] = Object.entries(teamGame.calibers).map(([id, entry]) => ({\n id,\n points: entry.points,\n penetration: entry.penetration,\n class: CLASS_OF[entry.class] ?? 'pistol',\n skullRange: entry.skullRange,\n pellets: 'pellets' in entry ? entry.pellets : 1,\n effectiveRangeMetres: entry.effectiveRangeMetres,\n}))\n\n/** The game's calibre keys (`9x19`, `12ga`, `762x39`, `308`) to the kit's calibre ids. */\nexport const TEAM_GAME_CALIBER_KEYS: Readonly<Record<string, string>> = Object.fromEntries(Object.entries(teamGame.calibers).map(([id, entry]) => [entry.gameKey, id]))\n\nexport const TEAM_GAME_RULES = { regionCost: teamGame.regionCost, damageKeptPerBody: teamGame.damageKeptPerBody, falloff: teamGame.falloff } as const\n\nexport const PHYSICAL_RULES = physical\n","import type { BodyRegion, SegmentKind } from '@adatechnology/game-contracts'\n\nimport { PHYSICAL_RULES, TEAM_GAME_RULES } from './defaults'\nimport type { PenetrationModel } from './types'\n\n/** P = √(E·m/A) against the resistance of the path; a protection layer stops a projectile whose force is not above its resistance. */\nexport const PHYSICAL_PENETRATION: PenetrationModel = {\n id: 'physical',\n stops: (layer, projectile) => projectile.force <= (layer.ballistic?.resistance ?? 0),\n piercesSkull: (projectile, headResistance) => projectile.force > headResistance,\n}\n\n/** The game's rule: pistol-class rounds are stopped by a vest or a helmet; the skull is pierced within the calibre's `cranio` range. */\nexport const TEAM_GAME_PENETRATION: PenetrationModel = {\n id: 'team-game',\n stops: (_layer, projectile) => projectile.class === 'pistol',\n piercesSkull: (projectile) => projectile.skullRange === 1 || projectile.distance <= projectile.skullRange,\n}\n\nexport const PENETRATION_MODELS = { physical: PHYSICAL_PENETRATION, 'team-game': TEAM_GAME_PENETRATION } as const\n\nconst { tissuePerCentimetre, torsoPath, regionFactor } = PHYSICAL_RULES\n\n/** Resistance of a torso path: flesh 22 cm × 0.25 + bone 2 cm × 1.0 = 7.5. */\nexport const TORSO_RESISTANCE = torsoPath.fleshCentimetres * tissuePerCentimetre.flesh + torsoPath.boneCentimetres * tissuePerCentimetre.bone\n\nconst HEAD_KINDS: ReadonlySet<SegmentKind> = new Set(['head', 'jaw', 'neck'])\nconst TORSO_KINDS: ReadonlySet<SegmentKind> = new Set(['torso', 'pelvis'])\n\nexport type ResistanceParams = { readonly kind: SegmentKind; readonly bodyCount: number; readonly protection: number }\n\n/** R of the path through a segment: torso 7.5 (× the body count of a brute), head 0.7×, limbs 0.5×, plus the protection worn over it. */\nexport const segmentResistance = ({ kind, bodyCount, protection }: ResistanceParams): number => {\n if (TORSO_KINDS.has(kind)) return TORSO_RESISTANCE * regionFactor.torso * bodyCount + protection\n if (HEAD_KINDS.has(kind)) return TORSO_RESISTANCE * regionFactor.head + protection\n return TORSO_RESISTANCE * regionFactor.limb + protection\n}\n\n/** Share of the energy a projectile of force `force` keeps after a path of resistance `resistance`: P/(P+R). */\nexport const energyKept = (force: number, resistance: number): number => (force > 0 ? force / (force + resistance) : 0)\n\n/** Penetration points a region costs in the game (`custo`): head 0.7, torso 1 (a brute 2), limb 0.5. */\nexport const teamGameCost = (region: BodyRegion, bodyCount: number): number => {\n const cost = TEAM_GAME_RULES.regionCost\n if (region === 'head') return cost.head\n if (region === 'torso') return bodyCount > 1 ? cost.bruteTorso : cost.torso\n return cost.limb\n}\n\n/** The game's falloff: full damage up to the effective range, then linear down to half at twice the range, never below half. */\nexport const teamGameFalloff = (distance: number, range: number): number => {\n const floor = TEAM_GAME_RULES.falloff.atTwiceRange\n return distance <= range * TEAM_GAME_RULES.falloff.fullAtRange ? 1 : Math.max(floor, 1 - ((distance - range) / range) * (1 - floor))\n}\n","import type { DamageType, SegmentKind, Vec3 } from '@adatechnology/game-contracts'\n\nimport { segmentNode } from '../../body/segment-tree'\nimport type { ResolvedCharacterSpec } from '../../character'\nimport type { SegmentState } from '../../types'\nimport type { BodyOps } from '../body-ops'\nimport type { PenetrationModel, ProjectileInfo } from '../types'\n\n/** One blow on one segment, after protection: what every segment rule receives. */\nexport type SegmentBlow = {\n readonly segment: SegmentState\n /** Points after protection, before the rule's multipliers and spread. */\n readonly points: number\n readonly cut: number\n readonly damageType: DamageType\n readonly projectile?: ProjectileInfo\n readonly explosive: boolean\n /** A blast strong enough to destroy what it takes to 0 (Arsenal `big`). */\n readonly big: boolean\n /** Where it landed (world): a bullet wound bleeds there; a blast share has none. */\n readonly point?: Vec3\n /** Extra factor on arms and legs (age × protection). */\n readonly limbFactor: number\n readonly model: PenetrationModel\n /** Resistance of the head path (the skull rule of the `physical` model). */\n readonly headResistance: number\n}\n\nexport type RuleResult = { readonly headshot: boolean }\n\nexport type SegmentRule = (ops: BodyOps, blow: SegmentBlow) => RuleResult\n\nexport const NO_HEADSHOT: RuleResult = { headshot: false }\nexport const HEADSHOT: RuleResult = { headshot: true }\n\nconst ARM_KINDS: ReadonlySet<SegmentKind> = new Set(['upperArm', 'forearm', 'hand'])\nconst LEG_KINDS: ReadonlySet<SegmentKind> = new Set(['thigh', 'shin', 'foot'])\n\nexport const isArm = (kind: SegmentKind): boolean => ARM_KINDS.has(kind)\nexport const isLeg = (kind: SegmentKind): boolean => LEG_KINDS.has(kind)\nexport const isLimb = (kind: SegmentKind): boolean => isArm(kind) || isLeg(kind)\n\n/** The body type's multiplier for the group the segment is in (head, torso, arms, legs). */\nexport const typeMultiplier = (spec: ResolvedCharacterSpec, kind: SegmentKind): number => {\n if (isArm(kind)) return spec.multipliers.arms\n if (isLeg(kind)) return spec.multipliers.legs\n if (kind === 'torso' || kind === 'pelvis') return spec.multipliers.torso\n return spec.multipliers.head\n}\n\n/** Points the segment takes: the blow × segment multiplier × body type × (on a limb) age and protection. */\nexport const segmentDamage = (ops: BodyOps, blow: SegmentBlow, points: number): number => {\n const { kind } = blow.segment\n return points * ops.rules.segments[kind].multiplier * typeMultiplier(ops.spec, kind) * (isLimb(kind) ? blow.limbFactor : 1)\n}\n\n/** The stump a lost segment leaves bleeds hard (×1.5 at the neck and head) for 45 s, spurting (Arsenal `stumpAt`). */\nexport const bleedStump = (ops: BodyOps, segment: SegmentState): void => {\n const bleed = ops.rules.segments[segment.kind].bleed\n const parent = segmentNode(segment.id).parent\n const stump = parent ? (ops.body.segments.find((candidate) => candidate.id === parent) ?? segment) : segment\n ops.bleed({ segment: stump, rate: bleed * (segment.kind === 'neck' || segment.kind === 'head' ? 1.5 : 1), duration: 45, spurt: true })\n}\n\n/** The piece that flies off bleeds 35 % of the rate for 15 s (Arsenal `sever`). */\nexport const bleedPiece = (ops: BodyOps, segment: SegmentState): void => ops.bleed({ segment, rate: ops.rules.segments[segment.kind].bleed * 0.35, duration: 15, spurt: true })\n\n/** A bullet wound bleeds 30 % of the segment's rate for 10 s, without spurting (Arsenal `damage` with a point). */\nexport const bleedWound = (ops: BodyOps, segment: SegmentState, point: Vec3): void =>\n ops.bleed({ segment, rate: ops.rules.segments[segment.kind].bleed * 0.3, duration: 10, spurt: false, point })\n\n/** Cut off at the joint, with its two bleeders. */\nexport const severWithBleeding = (ops: BodyOps, segment: SegmentState): void => {\n if (!segment.attached) return\n bleedStump(ops, segment)\n ops.sever(segment)\n bleedPiece(ops, segment)\n}\n\n/** Blown to pieces: only the stump bleeds. */\nexport const destroyWithBleeding = (ops: BodyOps, segment: SegmentState): void => {\n if (!segment.attached) return\n bleedStump(ops, segment)\n ops.destroy(segment)\n}\n","import type { DamageType } from '@adatechnology/game-contracts'\n\nimport type { BallisticClass, BodyHit, CaliberEntry, DamageRules, ProjectileInfo } from './types'\n\n/** Deterministic mulberry32 stream in [0, 1). */\nexport const 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/** Damage points of a blow from its energy in joules: `coefficient · E^exponent` (9×19 → 35, 7.62×39 → 59, .308 → 71.7). */\nexport const pointsFromEnergy = (energy: number, rules: Pick<DamageRules, 'points'>): number => (energy > 0 ? rules.points.coefficient * energy ** rules.points.exponent : 0)\n\n/** The caller's points, else the calibre table's, else the energy formula. */\nexport const resolvePoints = (hit: BodyHit, caliber: CaliberEntry | undefined, rules: Pick<DamageRules, 'points'>): number => hit.points ?? caliber?.points ?? pointsFromEnergy(hit.energy ?? 0, rules)\n\n/** One draw of ±`spread` on the points (none when the spread is 0, so the stream is not touched). */\nexport const spreadPoints = (points: number, spread: number, random: () => number): number => (spread > 0 ? points * (1 - spread + random() * 2 * spread) : points)\n\nconst DEFAULT_PROJECTILE_GRAMS = 8\nconst RIFLE_JOULES = 1000\n\n/** P = √(E·m/A): E in joules, m in grams, A the cross-section in mm². */\nexport const penetrationForce = (energy: number, grams: number, diameterMm: number): number => {\n const area = (Math.PI * diameterMm ** 2) / 4\n return area > 0 && energy > 0 ? Math.sqrt((energy * grams) / area) : 0\n}\n\n/** What a ballistic hit is (force, class, skull range, pellets, distance), from the hit and the calibre table. */\nexport const projectileOf = (hit: BodyHit, caliber: CaliberEntry | undefined): ProjectileInfo => {\n const pellets = hit.pellets ?? caliber?.pellets ?? 1\n const energy = hit.energy ?? 0\n const fallback: BallisticClass = energy > RIFLE_JOULES ? 'rifle' : 'pistol'\n return {\n force: penetrationForce(energy, hit.mass ?? DEFAULT_PROJECTILE_GRAMS, hit.caliber ?? 9),\n class: caliber?.class ?? fallback,\n skullRange: caliber?.skullRange ?? 1,\n pellets,\n distance: hit.distance ?? 0,\n }\n}\n\n/** `hit.cut`, else the default of its damage type (a bullet by class: pistol 0.15, buckshot 0.75, rifle 0.45). */\nexport const cutOf = (hit: BodyHit, projectile: ProjectileInfo | undefined, rules: Pick<DamageRules, 'defaultCut'>): number => {\n if (hit.cut !== undefined) return hit.cut\n const type: DamageType = hit.type\n if (type === 'ballistic' && projectile) return rules.defaultCut.ballistic[projectile.pellets > 1 ? 'buckshot' : projectile.class]\n if (type === 'slash' || type === 'blunt' || type === 'explosive') return rules.defaultCut[type]\n return 0\n}\n","import { MISSING_BITS } from '@adatechnology/game-contracts'\nimport type { BodyRegion, DamageType } from '@adatechnology/game-contracts'\n\nimport { segmentOf } from '../../body/body-state'\nimport { REGION_HIT_POINTS, REGION_SEGMENTS } from '../../body/regions'\nimport type { LimbRegion } from '../../body/regions'\nimport type { BodyOps } from '../body-ops'\nimport { spreadPoints } from '../points'\nimport type { ProtectionOutcome } from '../protection'\nimport type { PenetrationModel, ProjectileInfo } from '../types'\nimport { HEADSHOT, NO_HEADSHOT } from './blow'\nimport type { RuleResult } from './blow'\n\n/** One blow on one crowd region. `points` are the blow's own (the game stuns on them); the torso applies the vest share itself. */\nexport type RegionBlow = {\n readonly region: BodyRegion\n readonly points: number\n readonly cut: number\n readonly damageType: DamageType\n readonly projectile?: ProjectileInfo\n readonly protection: ProtectionOutcome\n readonly model: PenetrationModel\n readonly headResistance: number\n}\n\nconst LIMB_BITS: Readonly<Record<Exclude<LimbRegion, 'head'>, { readonly severed: number; readonly broken: number }>> = {\n armL: { severed: MISSING_BITS.armL, broken: MISSING_BITS.armLBroken },\n armR: { severed: MISSING_BITS.armR, broken: MISSING_BITS.armRBroken },\n legL: { severed: MISSING_BITS.legL, broken: MISSING_BITS.legLBroken },\n legR: { severed: MISSING_BITS.legR, broken: MISSING_BITS.legRBroken },\n}\n\nconst rootOf = (ops: BodyOps, region: BodyRegion) => segmentOf(ops.body, REGION_SEGMENTS[region][0] as Parameters<typeof segmentOf>[1])\n\nconst hitHead = (ops: BodyOps, blow: RegionBlow, points: number): RuleResult => {\n const { body, rules } = ops\n const rule = rules.severity\n const multiplier = rules.segments.head.multiplier\n const { projectile } = blow\n const lethal = projectile ? blow.model.piercesSkull(projectile, blow.headResistance) && points >= rule.headKillDamage : points * multiplier >= body.regions.head\n if (lethal) {\n const shotgunClose = projectile !== undefined && projectile.pellets > 1 && projectile.distance < rule.headBitShotgunMetres\n if (points > rule.headBitDamage || shotgunClose) {\n body.missing |= MISSING_BITS.head\n ops.destroy(segmentOf(body, 'head'))\n }\n return HEADSHOT\n }\n body.vitality -= points * multiplier\n body.regions.head -= points\n ops.damage(segmentOf(body, 'head'), points * multiplier, blow.damageType)\n if (points > rule.jawDamage && ops.random() < rule.jawChance && (body.missing & MISSING_BITS.jaw) === 0) {\n body.missing |= MISSING_BITS.jaw\n ops.sever(segmentOf(body, 'jaw'))\n }\n return NO_HEADSHOT\n}\n\nconst hitLimb = (ops: BodyOps, blow: RegionBlow, region: Exclude<LimbRegion, 'head'>, points: number): void => {\n const { body, spec, rules } = ops\n const leg = region === 'legL' || region === 'legR'\n const factor = (leg ? spec.multipliers.legs : spec.multipliers.arms) * spec.limbFactor * blow.protection.limbs\n const amount = points * factor\n body.regions[region] -= amount\n body.vitality -= amount * rules.severity.regionLimbVitalityShare\n const root = rootOf(ops, region)\n ops.damage(root, amount, blow.damageType)\n const max = REGION_HIT_POINTS[region]\n if (leg && body.regions[region] <= max * rules.severity.limpAtHpFraction) ops.limp(region === 'legL' ? 'L' : 'R')\n if (body.regions[region] > 0) return\n const severs = blow.cut >= rules.severity.severAtCut || amount > max * rules.severity.severAtDamageFraction\n const bit = severs ? LIMB_BITS[region].severed : LIMB_BITS[region].broken\n const isNew = (body.missing & bit) === 0\n body.missing |= bit\n if (leg) ops.crawl()\n if (!isNew) return\n if (severs) ops.sever(root)\n else ops.breakBone(root)\n}\n\n/** The game's `zDamage` (G 67011–67045): the crowd model of 6 regions, the bitmask, the helmet, the vest, limp, crawl and the jaw. */\nexport const regionRule = (ops: BodyOps, blow: RegionBlow): RuleResult => {\n const { body, rules } = ops\n const points = spreadPoints(blow.points, rules.spread, ops.random)\n let result = NO_HEADSHOT\n if (blow.region === 'head') result = hitHead(ops, blow, points)\n else if (blow.region === 'torso') {\n const amount = points * ops.spec.multipliers.torso * blow.protection.ballistic\n body.vitality -= amount\n ops.damage(segmentOf(body, 'torso'), amount, blow.damageType)\n } else hitLimb(ops, blow, blow.region, points)\n if (result.headshot) ops.kill('head')\n else if (body.vitality <= 0) ops.kill('vitality')\n if (!body.alive || result.headshot || body.vitality <= 0) return result\n if (points >= rules.severity.stunAtPoints) ops.stun()\n return result\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { REGION_SEGMENTS, BODY_REGIONS } from '../body/regions'\nimport { segmentNode } from '../body/segment-tree'\nimport type { SegmentId } from '../body/segment-tree'\nimport { distance } from '../body/transform'\nimport type { BodyOps } from './body-ops'\nimport { HEADSHOT, NO_HEADSHOT, destroyWithBleeding } from './rules/blow'\nimport type { RuleResult, SegmentBlow, SegmentRule } from './rules/blow'\nimport { regionRule } from './rules/regions'\nimport type { RegionBlow } from './rules/regions'\n\nexport type BlastParams = {\n readonly ops: BodyOps\n /** Centre of the blast in the body's local space. */\n readonly center: Vec3\n readonly points: number\n readonly radius: number\n /** A joint position in local space. */\n readonly jointOf: (id: SegmentId) => Vec3\n}\n\n/** The share of a blast each target takes: points × (1 − distance/radius), kept above the minimum, strongest first (Arsenal `grenadeAt`). */\nconst shares = <TTarget>(params: BlastParams, targets: readonly TTarget[], pivot: (target: TTarget) => SegmentId): { target: TTarget; points: number }[] =>\n targets\n .map((target) => ({ target, points: params.points * Math.max(0, 1 - distance(params.jointOf(pivot(target)), params.center) / params.radius) }))\n .filter((share) => share.points > params.ops.rules.blast.minimumPoints)\n .sort((a, b) => b.points - a.points)\n\nexport type SegmentBlastParams = BlastParams & { readonly rule: SegmentRule; readonly blow: Omit<SegmentBlow, 'segment' | 'points' | 'big' | 'explosive' | 'point'> }\n\n/** A blast on the 17 segments: a strong share on the head blows it off; every other share goes through the segment rule as an explosive blow. */\nexport const segmentBlast = (params: SegmentBlastParams): RuleResult => {\n const { ops, rule, blow } = params\n const { blast, segments } = ops.rules\n let result = NO_HEADSHOT\n for (const { target, points } of shares(params, ops.body.segments.filter((segment) => segment.attached), (segment) => segment.id)) {\n if (!target.attached) continue\n if (target.kind === 'head' && points > blast.headDestroyPoints) {\n destroyWithBleeding(ops, target)\n ops.kill('explosion')\n result = HEADSHOT\n continue\n }\n rule(ops, { ...blow, segment: target, points: points / segments[target.kind].multiplier, big: points > blast.bigPoints, explosive: true })\n }\n return result\n}\n\nexport type RegionBlastParams = BlastParams & { readonly blow: Omit<RegionBlow, 'region' | 'points'> }\n\n/** A blast on the 6 crowd regions, each measured at the joint of the segment that names it. */\nexport const regionBlast = (params: RegionBlastParams): RuleResult => {\n let result = NO_HEADSHOT\n const pivot = (region: (typeof BODY_REGIONS)[number]): SegmentId => segmentNode(REGION_SEGMENTS[region][0] as SegmentId).id\n for (const { target, points } of shares(params, BODY_REGIONS, pivot)) {\n if (regionRule(params.ops, { ...params.blow, region: target, points }).headshot) result = HEADSHOT\n }\n return result\n}\n","import type { BodySlot } from '@adatechnology/game-contracts'\n\nimport type { PenetrationModel, ProjectileInfo, ProtectionLayer } from './types'\n\n/** The layered protection of T3: `1 − Π(1 − value·condition)`, at most `cap`. */\nexport const LAYERED_PROTECTION_CAP = 0.9\n\nexport type LayeredProtectionParams = {\n readonly layers: readonly ProtectionLayer[]\n readonly attack: 'bite' | 'scratch'\n /** 0..1 condition per layer id (worn, torn); 1 by default. */\n readonly conditions?: Readonly<Record<string, number>>\n}\n\nexport const layeredProtection = ({ layers, attack, conditions }: LayeredProtectionParams): number => {\n const through = layers.reduce((left, layer) => left * (1 - (layer[attack] ?? 0) * (conditions?.[layer.id] ?? 1)), 1)\n return Math.min(LAYERED_PROTECTION_CAP, 1 - through)\n}\n\n/** The layers worn that cover any of `slots` and are not used up. */\nexport const layersOn = (worn: readonly ProtectionLayer[], slots: readonly BodySlot[], consumed: ReadonlySet<string>): ProtectionLayer[] =>\n worn.filter((layer) => !consumed.has(layer.id) && layer.slots.some((slot) => slots.includes(slot)))\n\n/** What the layers over a segment do to one blow. */\nexport type ProtectionOutcome = {\n /** A consumable layer took the whole projectile (a helmet): no damage, and the layer is used up. */\n readonly absorbedBy?: string\n /** Share of the points that gets through the ballistic layers. */\n readonly ballistic: number\n /** Penetration resistance the layers add (the `physical` model). */\n readonly resistance: number\n /** Factor on limb damage (a turnout coat). */\n readonly limbs: number\n /** Factor on fire damage. */\n readonly fire: number\n}\n\nexport type ProtectParams = {\n readonly layers: readonly ProtectionLayer[]\n readonly projectile?: ProjectileInfo\n readonly model: PenetrationModel\n}\n\n/** A stopped projectile does the layer's `blunt` share; one that goes through, `pass` (default `blunt`). Non-projectiles ignore ballistic layers. */\nexport const protect = ({ layers, projectile, model }: ProtectParams): ProtectionOutcome => {\n let ballistic = 1\n let resistance = 0\n for (const layer of layers) {\n const armour = layer.ballistic\n if (!armour || !projectile) continue\n const stops = model.stops(layer, projectile)\n if (stops && armour.consumable) return { absorbedBy: layer.id, ballistic: 0, resistance: armour.resistance, limbs: 1, fire: 1 }\n ballistic *= stops ? armour.blunt : (armour.pass ?? armour.blunt)\n resistance += armour.resistance\n }\n const limbs = layers.reduce((factor, layer) => factor * (layer.limbs ?? 1), 1)\n const fire = layers.reduce((factor, layer) => factor * (layer.fire ?? 1), 1)\n return { ballistic, resistance, limbs, fire }\n}\n","import type { BodyRegion, DestructibleSpec, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { BodyState } from '../body/body-state'\nimport { isBodyRegion, REGION_SEGMENTS } from '../body/regions'\nimport { isSegmentId } from '../body/segment-tree'\nimport type { SegmentId } from '../body/segment-tree'\nimport { distance } from '../body/transform'\n\nconst radiusOf = (part: DestructibleSpec['parts'][number]): number => (part.shape.kind === 'box' ? Math.min(...part.shape.size) / 2 : part.shape.radius)\n\n/**\n * The segment a hit lands on: `hit.part` when the caller resolved it (a segment id, or a region id for its first segment), else the attached\n * part whose surface is nearest to the local point.\n */\nexport const resolveSegment = (body: BodyState, spec: DestructibleSpec, part: string | undefined, localPoint: Vec3): SegmentId => {\n if (part !== undefined && isSegmentId(part)) return part\n if (part !== undefined && isBodyRegion(part)) return REGION_SEGMENTS[part][0] as SegmentId\n let best: SegmentId = 'torso'\n let bestGap = Infinity\n for (const candidate of spec.parts) {\n const segment = body.segments.find((entry) => entry.id === candidate.id)\n if (!segment?.attached) continue\n const gap = distance(candidate.position, localPoint) - radiusOf(candidate)\n if (gap < bestGap) [best, bestGap] = [segment.id, gap]\n }\n return best\n}\n\nexport const regionOfSegment = (body: BodyState, id: SegmentId): BodyRegion => body.segments.find((segment) => segment.id === id)?.region ?? 'torso'\n","import { segmentOf } from '../../body/body-state'\nimport type { SegmentState } from '../../types'\nimport type { BodyOps } from '../body-ops'\nimport { HEADSHOT, NO_HEADSHOT, bleedWound, destroyWithBleeding, segmentDamage, severWithBleeding } from './blow'\nimport type { SegmentBlow, SegmentRule } from './blow'\n\n/** A blow of at least this many points blows the head off (Arsenal `damage`: `dmg >= 30`). */\nconst HEAD_BLOW_POINTS = 30\nconst LIMB_VITALITY_SHARE = 0.3\n\nconst split = (ops: BodyOps): void => {\n const torso = segmentOf(ops.body, 'torso')\n if (!torso.attached) return\n severWithBleeding(ops, torso)\n ops.change('split', 'torso')\n ops.kill('vitality')\n}\n\nconst loseLimb = (ops: BodyOps, segment: SegmentState, blow: SegmentBlow): void => {\n if (blow.big || -segment.hp > segment.max) destroyWithBleeding(ops, segment)\n else severWithBleeding(ops, segment)\n const { body } = ops\n if (segment.kind === 'thigh' || segment.kind === 'shin') {\n if (body.alive) ops.crawl()\n } else if (segment.kind === 'foot' && body.alive && !body.crawl && body.limping.length === 0 && segment.side) ops.limp(segment.side)\n}\n\n/** The Galeria 3D do Arsenal's `damage`: every number and branch of the page, in its order. */\nexport const arsenalRule: SegmentRule = (ops, blow) => {\n const { segment } = blow\n if (!segment.attached) return NO_HEADSHOT\n const amount = segmentDamage(ops, blow, blow.points)\n if (blow.point) bleedWound(ops, segment, blow.point)\n segment.hp -= amount\n ops.damage(segment, amount, blow.damageType)\n let result = NO_HEADSHOT\n if (segment.kind === 'head') {\n if (blow.points >= HEAD_BLOW_POINTS || segment.hp <= 0) {\n destroyWithBleeding(ops, segment)\n ops.kill('head')\n result = HEADSHOT\n } else ops.wound(segment)\n } else if (segment.kind === 'jaw') {\n if (segment.hp <= 0) severWithBleeding(ops, segment)\n } else if (segment.kind === 'neck') {\n if (segment.hp <= 0) {\n severWithBleeding(ops, segment)\n ops.kill('head')\n }\n } else if (segment.kind === 'torso' || segment.kind === 'pelvis') {\n ops.body.vitality -= amount\n if (blow.points >= ops.rules.severity.splitAtDamage || segment.hp <= 0) split(ops)\n } else {\n ops.body.vitality -= amount * LIMB_VITALITY_SHARE\n if (segment.hp <= 0) loseLimb(ops, segment, blow)\n }\n if (ops.body.alive && ops.body.vitality <= 0) ops.kill('vitality')\n return result\n}\n","import type { SegmentKind } from '@adatechnology/game-contracts'\n\nimport { spreadPoints } from '../points'\nimport { HEADSHOT, NO_HEADSHOT, isLeg, segmentDamage } from './blow'\nimport type { SegmentRule } from './blow'\n\n/** A head at 0 is cut off by an edge of at least this `cut` or a blow of at least this many points (Elenco `hit`). */\nconst HEAD_SEVER_CUT = 0.7\nconst HEAD_SEVER_POINTS = 90\n/** The segments that hang from a joint of their own in the Elenco (`s.node`): they are cut or break at it. */\nconst JOINTED: ReadonlySet<SegmentKind> = new Set(['head', 'upperArm', 'forearm', 'hand', 'thigh', 'shin', 'foot'])\n\n/** The Elenco's `hit`, `sever` and `breakBone`: one ±15 % draw per blow, cut at the joint above, broken bones dangle or make the leg limp. */\nexport const elencoRule: SegmentRule = (ops, blow) => {\n const { segment } = blow\n const { body, rules } = ops\n if (!segment.attached || (!body.alive && segment.kind !== 'head')) return NO_HEADSHOT\n const amount = segmentDamage(ops, blow, spreadPoints(blow.points, rules.spread, ops.random))\n segment.hp = Math.max(0, segment.hp - amount)\n ops.damage(segment, amount, blow.damageType)\n if (segment.hp > 0) {\n ops.wound(segment)\n return NO_HEADSHOT\n }\n if (segment.kind === 'head') {\n if (blow.cut >= HEAD_SEVER_CUT || blow.points >= HEAD_SEVER_POINTS) ops.sever(segment, 'zero')\n else ops.breakBone(segment)\n ops.kill('head')\n return HEADSHOT\n }\n if (JOINTED.has(segment.kind)) {\n if (blow.cut >= rules.severity.severAtCut || amount >= segment.max * rules.severity.severAtDamageFraction) {\n ops.sever(segment, 'zero')\n if (isLeg(segment.kind)) ops.crawl()\n return NO_HEADSHOT\n }\n ops.breakBone(segment)\n if (isLeg(segment.kind) && segment.side) {\n ops.limp(segment.side)\n if (body.limping.length === 2) ops.crawl()\n }\n return NO_HEADSHOT\n }\n ops.breakBone(segment)\n if (segment.kind === 'torso') ops.kill('vitality')\n else if (segment.kind === 'pelvis') ops.crawl()\n else if (segment.kind === 'neck') ops.kill('head')\n return NO_HEADSHOT\n}\n","import { segmentOf } from '../../body/body-state'\nimport type { SegmentState } from '../../types'\nimport type { BodyOps } from '../body-ops'\nimport { spreadPoints } from '../points'\nimport { HEADSHOT, NO_HEADSHOT, bleedWound, destroyWithBleeding, isLeg, segmentDamage, severWithBleeding } from './blow'\nimport type { RuleResult, SegmentBlow, SegmentRule } from './blow'\n\ntype Outcome = 'destroyed' | 'severed' | 'broken'\n\n/** At 0: destroyed by a blast or a blow of twice the segment; severed by an edge (`cut` ≥ 0.5) or a blow above 90 % of it; else broken. */\nexport const severityOf = (ops: BodyOps, blow: SegmentBlow, amount: number, max: number): Outcome => {\n const rule = ops.rules.severity\n if (blow.explosive || amount >= max * rule.destroyAtDamageMultiple) return 'destroyed'\n if (blow.cut >= rule.severAtCut || amount > max * rule.severAtDamageFraction) return 'severed'\n return 'broken'\n}\n\nconst lose = (ops: BodyOps, segment: SegmentState, outcome: Outcome): void => {\n if (outcome === 'destroyed') destroyWithBleeding(ops, segment)\n else if (outcome === 'severed') severWithBleeding(ops, segment)\n else ops.breakBone(segment)\n}\n\n/** The game's head rule: a projectile kills when it pierces the skull with enough points, a blow when it takes the head's hit points. */\nconst hitHead = (ops: BodyOps, blow: SegmentBlow, points: number, amount: number, hpBefore: number): RuleResult => {\n const { segment, projectile } = blow\n const rule = ops.rules.severity\n const lethal = projectile ? blow.model.piercesSkull(projectile, blow.headResistance) && points >= rule.headKillDamage : amount >= hpBefore\n if (lethal) {\n const shotgunClose = projectile !== undefined && projectile.pellets > 1 && projectile.distance < rule.headBitShotgunMetres\n if (blow.explosive || points > rule.headBitDamage || shotgunClose) destroyWithBleeding(ops, segment)\n else ops.breakBone(segment)\n ops.kill('head')\n return HEADSHOT\n }\n ops.body.vitality -= amount\n ops.wound(segment)\n if (points > rule.jawDamage && ops.random() < rule.jawChance) severWithBleeding(ops, segmentOf(ops.body, 'jaw'))\n return NO_HEADSHOT\n}\n\nconst hitTorso = (ops: BodyOps, points: number, amount: number, segment: SegmentState): void => {\n ops.body.vitality -= amount\n if (points < ops.rules.severity.splitAtDamage && segment.hp > 0) return ops.wound(segment)\n const torso = segmentOf(ops.body, 'torso')\n if (!torso.attached) return\n severWithBleeding(ops, torso)\n ops.change('split', 'torso')\n if (ops.rules.deathRule === 'head-only') ops.crawl()\n else ops.kill('vitality')\n}\n\nconst hitLimb = (ops: BodyOps, blow: SegmentBlow, amount: number, hpBefore: number): void => {\n const { segment } = blow\n const rule = ops.rules.severity\n ops.body.vitality -= amount * rule.limbVitalityShare\n if (isLeg(segment.kind) && segment.side && segment.hp <= segment.max * rule.limpAtHpFraction) ops.limp(segment.side)\n if (segment.hp > 0 || hpBefore <= 0) return ops.wound(segment)\n const outcome = severityOf(ops, blow, amount, segment.max)\n lose(ops, segment, outcome)\n if (segment.kind === 'thigh' || segment.kind === 'shin') ops.crawl()\n}\n\n/** The kit's rule: Arsenal numbers, the design's severity, the game's head rule, the death rule of the kit. */\nexport const kitRule: SegmentRule = (ops, blow) => {\n const { segment } = blow\n if (!segment.attached) return NO_HEADSHOT\n const points = spreadPoints(blow.points, ops.rules.spread, ops.random)\n const amount = segmentDamage(ops, blow, points)\n if (blow.point && !blow.explosive) bleedWound(ops, segment, blow.point)\n const hpBefore = segment.hp\n segment.hp -= amount\n ops.damage(segment, amount, blow.damageType)\n let result = NO_HEADSHOT\n if (segment.kind === 'head') result = hitHead(ops, blow, points, amount, hpBefore)\n else if (segment.kind === 'torso' || segment.kind === 'pelvis') hitTorso(ops, points, amount, segment)\n else if (segment.kind === 'jaw' || segment.kind === 'neck') {\n if (segment.hp <= 0 && hpBefore > 0) {\n lose(ops, segment, severityOf(ops, blow, amount, segment.max))\n if (segment.kind === 'neck' && !segment.attached) ops.kill('head')\n } else ops.wound(segment)\n } else hitLimb(ops, blow, amount, hpBefore)\n if (ops.body.vitality <= 0) ops.kill('vitality')\n if (ops.body.alive && points >= ops.rules.severity.stunAtPoints) ops.stun()\n return result\n}\n","import type { DestructibleSpec, Vec3 } from '@adatechnology/game-contracts'\n\nimport { segmentOf } from '../body/body-state'\nimport { REGION_SEGMENTS } from '../body/regions'\nimport { segmentNode } from '../body/segment-tree'\nimport type { SegmentId } from '../body/segment-tree'\nimport { regionBlast, segmentBlast } from './blast'\nimport type { BodyOps } from './body-ops'\nimport type { DamageSetup } from './damage-character'\nimport { energyKept, segmentResistance } from './penetration'\nimport { cutOf, pointsFromEnergy, projectileOf, resolvePoints } from './points'\nimport { layersOn, protect } from './protection'\nimport type { ProtectionOutcome } from './protection'\nimport { resolveSegment, regionOfSegment } from './resolve-part'\nimport { arsenalRule } from './rules/arsenal'\nimport type { RuleResult, SegmentRule } from './rules/blow'\nimport { elencoRule } from './rules/elenco'\nimport { kitRule } from './rules/kit'\nimport { regionRule } from './rules/regions'\nimport type { BodyHit, HitReport, ProtectionLayer } from './types'\n\nconst SEGMENT_RULES: Readonly<Record<string, SegmentRule>> = { kit: kitRule, arsenal: arsenalRule, elenco: elencoRule }\nconst HEAD_RESISTANCE = segmentResistance({ kind: 'head', bodyCount: 1, protection: 0 })\nconst NO_PROTECTION: ProtectionOutcome = { ballistic: 1, resistance: 0, limbs: 1, fire: 1 }\nconst ABSORBED_SPARKS = 8\nconst METRES_PER_MM = 0.001\n\nexport type ApplyBlowParams = {\n readonly ops: BodyOps\n readonly hit: BodyHit\n readonly setup: DamageSetup\n readonly worn: readonly ProtectionLayer[]\n readonly localPoint: Vec3\n readonly jointOf: (id: SegmentId) => Vec3\n readonly describe: () => DestructibleSpec\n}\n\nconst report = (ops: BodyOps, fields: Partial<HitReport> & { points: number }, result: RuleResult = { headshot: false }): HitReport => ({\n through: false,\n exitEnergy: 0,\n ...fields,\n killed: !ops.body.alive,\n headshot: result.headshot,\n})\n\n/** Fire and heat: the exposure burns the torso (`burnPointsPerSecond` × seconds), less what the clothing keeps off. */\nconst burn = ({ ops, hit, setup, worn }: ApplyBlowParams): HitReport => {\n const torso = segmentOf(ops.body, 'torso')\n const fire = protect({ layers: layersOn(worn, segmentNode('torso').slots, ops.body.consumed), model: setup.model }).fire\n const points = setup.rules.burnPointsPerSecond * (hit.duration ?? 0) * fire\n ops.body.vitality -= points\n ops.damage(torso, points, hit.type)\n if (ops.body.vitality <= 0) ops.kill('vitality')\n return report(ops, { part: 'torso', points })\n}\n\nconst blast = ({ ops, hit, setup, localPoint, jointOf }: ApplyBlowParams): HitReport => {\n const points = hit.points ?? pointsFromEnergy(hit.energy ?? 0, setup.rules)\n const base = { ops, center: localPoint, points, radius: hit.radius ?? 1, jointOf }\n const common = { cut: hit.cut ?? setup.rules.defaultCut.explosive, damageType: hit.type, model: setup.model, headResistance: HEAD_RESISTANCE }\n const rule = SEGMENT_RULES[setup.rules.segmentRule] ?? kitRule\n const result =\n ops.body.detail === 'regions'\n ? regionBlast({ ...base, blow: { ...common, protection: NO_PROTECTION } })\n : segmentBlast({ ...base, rule, blow: { ...common, limbFactor: ops.spec.limbFactor } })\n return report(ops, { points }, result)\n}\n\nconst DEFAULT_PATH_METRES = 0.2\n\n/** Length of the path through a part (its diameter), for the exit point of a projectile that goes through. */\nconst pathThrough = (spec: DestructibleSpec, id: SegmentId): number => {\n const shape = spec.parts.find((part) => part.id === id)?.shape\n return shape && shape.kind !== 'box' ? 2 * shape.radius : DEFAULT_PATH_METRES\n}\n\nconst exitOf = (hit: BodyHit, depth: number): Vec3 => {\n const [x, y, z] = hit.direction ?? [0, 0, -1]\n return [hit.point[0] + x * depth, hit.point[1] + y * depth, hit.point[2] + z * depth]\n}\n\n/** Bullets, blades and blunt blows: resolve the segment, the protection, the penetration, the points; then the detail's rule decides. */\nconst direct = ({ ops, hit, setup, worn, localPoint, describe }: ApplyBlowParams): HitReport => {\n const { body, spec, rules } = ops\n const caliber = hit.caliberId === undefined ? undefined : setup.calibers.get(hit.caliberId)\n const projectile = hit.type === 'ballistic' ? projectileOf(hit, caliber) : undefined\n const id = resolveSegment(body, describe(), hit.part, localPoint)\n const region = regionOfSegment(body, id)\n const slots = segmentNode(body.detail === 'regions' ? (REGION_SEGMENTS[region][0] as SegmentId) : id).slots\n const protection = protect({ layers: layersOn(worn, slots, body.consumed), model: setup.model, ...(projectile ? { projectile } : {}) })\n if (protection.absorbedBy) {\n body.consumed.add(protection.absorbedBy)\n ops.emit({ type: 'debris', part: id, kind: 'sparks', point: hit.point, normal: [0, 1, 0], count: ABSORBED_SPARKS, speed: 3 })\n return report(ops, { part: id, points: 0, absorbedBy: protection.absorbedBy })\n }\n const rawPoints = resolvePoints(hit, caliber, rules)\n const points = rawPoints * protection.ballistic\n const cut = cutOf(hit, projectile, rules)\n const segment = segmentOf(body, id)\n const resistance = segmentResistance({ kind: segment.kind, bodyCount: spec.bodyCount, protection: protection.resistance })\n const through = setup.model.id === 'physical' && projectile !== undefined && projectile.force > resistance\n const exitEnergy = through && projectile ? (hit.energy ?? 0) * energyKept(projectile.force, resistance) : 0\n if (projectile) {\n const depth = pathThrough(describe(), id)\n ops.emit({ type: 'hole', part: id, hole: { point: localPoint, normal: [0, 0, 1], diameter: (hit.caliber ?? 9) * METRES_PER_MM, through }, worldPoint: hit.point, ...(through ? { exitPoint: exitOf(hit, depth) } : {}) })\n }\n const common = { points, cut, damageType: hit.type, model: setup.model, headResistance: HEAD_RESISTANCE, ...(projectile ? { projectile } : {}) }\n const result =\n body.detail === 'regions'\n ? regionRule(ops, { ...common, points: rawPoints, region, protection })\n : (SEGMENT_RULES[rules.segmentRule] ?? kitRule)(ops, {\n ...common,\n segment,\n explosive: false,\n big: points > rules.blast.bigPoints,\n limbFactor: spec.limbFactor * protection.limbs,\n ...(hit.woundAtPoint === false ? {} : { point: hit.point }),\n })\n return report(ops, { part: id, points, through, exitEnergy }, result)\n}\n\nexport const applyBlow = (params: ApplyBlowParams): HitReport => {\n if (params.hit.type === 'fire' || params.hit.type === 'heat') return burn(params)\n if (params.hit.type === 'explosive') return blast(params)\n return direct(params)\n}\n","import type { DestructibleImpl, DestructionEvent, Hit, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { BodyState } from '../body/body-state'\nimport { segmentNode } from '../body/segment-tree'\nimport type { SegmentId, SegmentSide } from '../body/segment-tree'\nimport { toLocal, toWorld } from '../body/transform'\nimport { characterView } from '../character'\nimport type { Character, CharacterCore } from '../character'\nimport { stepBleeding } from './bleeding'\nimport type { Bleeder } from './bleeding'\nimport { createBodyOps } from './body-ops'\nimport type { BodyOps } from './body-ops'\nimport { segmentResistance } from './penetration'\nimport { applyBlow } from './pipeline'\nimport { createRng } from './points'\nimport { layeredProtection, layersOn } from './protection'\nimport { resolveSegment } from './resolve-part'\nimport type { BodyHit, CaliberEntry, DamageRules, HitReport, PenetrationModel, ProtectionLayer } from './types'\n\n/** A character with the damage model: a `DestructibleImpl` a destruction world can host next to its own objects. */\nexport type DamageCharacter = Character &\n DestructibleImpl & {\n readonly alive: boolean\n /** The sides that limp, in the order they started. */\n readonly limping: readonly SegmentSide[]\n /** Seconds of stagger left from a heavy hit. */\n readonly stunSeconds: number\n /** What the last `hit` did (points, kill, headshot, through). */\n readonly lastHit?: HitReport\n /** The bleeding wounds, oldest first. */\n bleeders(): readonly Readonly<Bleeder>[]\n /** 0..1 protection of the layers over a segment against a bite or a scratch (the layered T3 formula, capped at 90 %). */\n protectionAgainst(attack: 'bite' | 'scratch', part: SegmentId): number\n /** Ids of the protection layers worn and not used up (a helmet that took its shot is gone). */\n intactProtection(): readonly string[]\n /** Penetration resistance R of the path through a part (a segment or a region id), with the protection worn over it. */\n resistanceOf(part: string): number\n hit(hit: Hit | BodyHit): DestructionEvent[]\n /** Ages bleeders (a `leak` per second each) and the stun. */\n update(dt: number): DestructionEvent[]\n serialize(): unknown\n load(data: unknown): void\n }\n\nexport type DamageSetup = {\n readonly rules: DamageRules\n readonly model: PenetrationModel\n readonly protection: ReadonlyMap<string, ProtectionLayer>\n readonly calibers: ReadonlyMap<string, CaliberEntry>\n}\n\ntype Saved = { body: Omit<BodyState, 'consumed'> & { consumed: string[] }; bleeders: Bleeder[]; hitCounter: number; clock: number }\n\nexport const createDamageCharacter = (core: CharacterCore, setup: DamageSetup): DamageCharacter => {\n const view = characterView(core)\n const worn = core.spec.protection.map((id) => setup.protection.get(id)).filter((layer): layer is ProtectionLayer => layer !== undefined)\n let bleeders: Bleeder[] = []\n let hitCounter = 0\n let clock = 0\n let lastHit: HitReport | undefined\n const transform = () => ({ position: core.position, rotation: core.rotation })\n const jointOf = (id: SegmentId): Vec3 => core.rig.joints[segmentNode(id).joint]\n const pointOf = (id: SegmentId): Vec3 => toWorld(transform(), jointOf(id))\n const opsFor = (random: () => number, source?: string): BodyOps =>\n createBodyOps({ body: core.body, spec: core.spec, rules: setup.rules, random, time: clock, pointOf, bleeders, ...(source !== undefined ? { source } : {}) })\n\n const character: DamageCharacter = {\n ...view,\n get segments() {\n return core.body.segments\n },\n get detail() {\n return core.body.detail\n },\n get alive() {\n return core.body.alive\n },\n get limping() {\n return [...core.body.limping]\n },\n get stunSeconds() {\n return core.body.stunSeconds\n },\n get lastHit() {\n return lastHit\n },\n name: core.spec.kind,\n hit(raw) {\n const hit = raw as BodyHit\n hitCounter += 1\n const random = core.spec.random ?? createRng((core.spec.seed ^ hitCounter) >>> 0)\n const ops = opsFor(random, hit.source)\n lastHit = applyBlow({ ops, hit, setup, worn, localPoint: toLocal(transform(), hit.point), jointOf, describe: core.describe })\n return ops.events\n },\n update(dt) {\n clock += dt\n core.body.stunSeconds = Math.max(0, core.body.stunSeconds - dt)\n const ops = opsFor(() => 0)\n stepBleeding({ bleeders, dt, emit: ops.emit, pointOf })\n return ops.events\n },\n bleeders: () => bleeders.map((bleeder) => ({ ...bleeder })),\n intactProtection: () => core.spec.protection.filter((id) => !core.body.consumed.has(id)),\n resistanceOf(part) {\n const id = resolveSegment(core.body, core.describe(), part, [0, 0, 0])\n const layers = layersOn(worn, segmentNode(id).slots, core.body.consumed)\n const protection = layers.reduce((sum, layer) => sum + (layer.ballistic?.resistance ?? 0), 0)\n return segmentResistance({ kind: segmentNode(id).kind, bodyCount: core.spec.bodyCount, protection })\n },\n protectionAgainst: (attack, part) => layeredProtection({ layers: layersOn(worn, segmentNode(part).slots, core.body.consumed), attack }),\n reset() {\n core.resetBody()\n bleeders = []\n hitCounter = 0\n lastHit = undefined\n },\n serialize(): Saved {\n const { consumed, ...rest } = core.body\n return { body: { ...structuredClone(rest), consumed: [...consumed] }, bleeders: structuredClone(bleeders), hitCounter, clock }\n },\n load(data) {\n const saved = data as Saved\n Object.assign(core.body, structuredClone(saved.body), { consumed: new Set(saved.body.consumed) })\n bleeders = structuredClone(saved.bleeders)\n hitCounter = saved.hitCounter\n clock = saved.clock\n },\n }\n return character\n}\n","import type { DestructionEvent, Vec3 } from '@adatechnology/game-contracts'\n\nimport { isBodyRegion } from '../body/regions'\nimport { isSegmentId, segmentNode } from '../body/segment-tree'\nimport type { DamageCharacter } from './damage-character'\nimport { TEAM_GAME_RULES } from './defaults'\nimport { energyKept, teamGameCost, teamGameFalloff } from './penetration'\nimport { penetrationForce } from './points'\nimport type { CaliberEntry } from './types'\n\n/** One body in the line of fire, `distance` metres from the muzzle. */\nexport type LineTarget = { readonly character: DamageCharacter; readonly part: string; readonly distance: number; readonly point?: Vec3 }\n\n/** What the line needs from a shot (a `Shot` of game-weapons fits). */\nexport type LineShot = {\n readonly energyAt: (distance: number) => number\n /** Projectile grams. */\n readonly mass: number\n /** Diameter in mm. */\n readonly caliber: number\n readonly caliberId?: string\n readonly source?: string\n}\n\nexport type LineHit = { readonly index: number; readonly points: number; readonly energy: number; readonly killed: boolean; readonly headshot: boolean; readonly events: DestructionEvent[] }\nexport type LineResult = { readonly hits: LineHit[]; /** 1-based index of the last body hit (0: none). */ readonly stoppedAt: number }\n\nexport type PenetrateLineParams = {\n readonly model: 'physical' | 'team-game'\n readonly shot: LineShot\n readonly targets: readonly LineTarget[]\n readonly calibers: ReadonlyMap<string, CaliberEntry>\n}\n\n/** After a kill the game restarts the ray 0.3 m past the body and measures the next distances from there (`shootRay`). */\nconst RESTART_METRES = 0.3\n\nconst regionOfPart = (part: string) => (isSegmentId(part) ? segmentNode(part).region : isBodyRegion(part) ? part : 'torso')\n\nconst lineHit = (index: number, target: LineTarget, fields: { points: number; energy: number; events: DestructionEvent[] }): LineHit => ({\n index,\n ...fields,\n killed: !target.character.alive,\n headshot: target.character.lastHit?.headshot ?? false,\n})\n\n/** The game's `shootRay`: penetration points spent per body (head 0.7, torso 1, a brute 2, limb 0.5), 75 % of the damage carried on. */\nconst teamGameLine = ({ shot, targets, calibers }: PenetrateLineParams): LineResult => {\n const caliber = shot.caliberId === undefined ? undefined : calibers.get(shot.caliberId)\n if (caliber?.penetration === undefined || caliber.points === undefined) throw new Error(`game-characters: the team-game line needs a calibre with points and penetration (\"${shot.caliberId}\")`)\n let penetration = caliber.penetration\n let points = caliber.points\n let origin = 0\n const hits: LineHit[] = []\n for (const [index, target] of targets.entries()) {\n if (!target.character.alive || target.distance - origin <= 0) continue\n const distance = target.distance - origin\n const dealt = points * teamGameFalloff(distance, caliber.effectiveRangeMetres ?? Infinity)\n const events = target.character.hit({ type: 'ballistic', point: target.point ?? [0, 0, 0], part: target.part, points: dealt, caliberId: caliber.id, distance, ...(shot.source ? { source: shot.source } : {}) })\n hits.push(lineHit(index, target, { points: dealt, energy: shot.energyAt(target.distance), events }))\n penetration -= teamGameCost(regionOfPart(target.part), target.character.spec.bodyCount)\n points *= TEAM_GAME_RULES.damageKeptPerBody\n if (penetration <= 0) break\n if (!target.character.alive) origin = target.distance + RESTART_METRES\n }\n return { hits, stoppedAt: hits.length === 0 ? 0 : (hits[hits.length - 1]?.index ?? -1) + 1 }\n}\n\n/** P7: the force P = √(E·m/A) hits a body while it is above 0, loses the body's resistance R and keeps P/(P+R) of the energy. */\nconst physicalLine = ({ shot, targets }: PenetrateLineParams): LineResult => {\n const first = targets[0]\n let force = first ? penetrationForce(shot.energyAt(first.distance), shot.mass, shot.caliber) : 0\n let kept = 1\n const hits: LineHit[] = []\n for (const [index, target] of targets.entries()) {\n if (force <= 0) break\n if (!target.character.alive) continue\n const energy = shot.energyAt(target.distance) * kept\n const events = target.character.hit({ type: 'ballistic', point: target.point ?? [0, 0, 0], part: target.part, energy, mass: shot.mass, caliber: shot.caliber, distance: target.distance, ...(shot.caliberId ? { caliberId: shot.caliberId } : {}) })\n hits.push(lineHit(index, target, { points: target.character.lastHit?.points ?? 0, energy, events }))\n const resistance = target.character.resistanceOf(target.part)\n kept *= energyKept(force, resistance)\n force -= resistance\n }\n return { hits, stoppedAt: hits.length === 0 ? 0 : (hits[hits.length - 1]?.index ?? -1) + 1 }\n}\n\n/** A shot through a line of bodies, nearest first. Each body takes the hit through its own damage model. */\nexport const penetrateLine = (params: PenetrateLineParams): LineResult => (params.model === 'team-game' ? teamGameLine(params) : physicalLine(params))\n","type Entry = { readonly id: string }\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 shallow merge); a patch for an id that does not exist is ignored. */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, 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, { ...entry, ...patch, id })\n }\n}\n\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) entries.delete(id)\n}\n","import { createBodySpec } from './body/body-spec'\nimport { createCorpseLedger } from './corpses'\nimport type { CorpseLedger } from './corpses'\nimport type { BodySpec } from './body/body-spec'\nimport { createCharacterCore, resolveSpec } from './character'\nimport { createDamageCharacter } from './damage/damage-character'\nimport type { DamageCharacter } from './damage/damage-character'\nimport { DAMAGE_PRESETS, PROTECTION_PRESETS, TEAM_GAME_CALIBERS } from './damage/defaults'\nimport { penetrateLine } from './damage/line'\nimport type { LineResult, LineShot, LineTarget } from './damage/line'\nimport { PENETRATION_MODELS } from './damage/penetration'\nimport type { CaliberEntry, DamageRules, PenetrationModel, ProtectionLayer } from './damage/types'\nimport { applyPatches, mergeById, removeIds } from './registry'\nimport type { CharacterPreset, CharacterSpec, CharactersOptions, CorpseOptions, DamageOptions } from './types'\n\nexport const DEFAULT_CORPSES: CorpseOptions = { max: 400, seconds: 900 }\n\n/** The base preset every spec can start from: an unnamed adult person. */\nexport const PERSON_PRESET: CharacterPreset = { id: 'person', kind: 'person', age: 'adult' }\n\nexport type CharacterKit = {\n readonly body: BodySpec\n readonly presets: ReadonlyMap<string, CharacterPreset>\n readonly corpses: CorpseOptions\n readonly damage: DamageRules\n readonly penetration: PenetrationModel\n readonly protection: ReadonlyMap<string, ProtectionLayer>\n readonly calibers: ReadonlyMap<string, CaliberEntry>\n /** A new character: the preset (`spec.preset`, else the one named `spec.kind`) under the spec. */\n create(spec: CharacterSpec): DamageCharacter\n /** The bodies left on the ground, capped and timed by the kit's `corpses` option. */\n createCorpses<TData>(): CorpseLedger<TData>\n /** A shot through a line of bodies with the kit's penetration model and calibre table. */\n penetrateLine(shot: LineShot, targets: readonly LineTarget[]): LineResult\n}\n\n/** Fills a spec from its preset: what the spec says wins; `multipliers` merge field by field. */\nexport const applyPreset = (spec: CharacterSpec, presets: ReadonlyMap<string, CharacterPreset>): CharacterSpec => {\n const preset = presets.get(spec.preset ?? spec.kind)\n if (!preset) return spec\n const { id: _presetId, ...defaults } = preset\n const multipliers = { ...defaults.multipliers, ...spec.multipliers }\n return { ...defaults, ...spec, multipliers }\n}\n\n/** The rules of a preset (`kit` by default) with the given fields replaced; `severity`, `blast` and `segments` merge key by key. */\nexport const resolveDamageRules = (options: DamageOptions = {}): DamageRules => {\n const { preset, severity, blast, segments, ...rest } = options\n const base = DAMAGE_PRESETS[preset ?? 'kit']\n return { ...base, ...rest, severity: { ...base.severity, ...severity }, blast: { ...base.blast, ...blast }, segments: { ...base.segments, ...segments } }\n}\n\nconst modelOf = (option: CharactersOptions['penetration']): PenetrationModel => (typeof option === 'object' ? option : PENETRATION_MODELS[option ?? 'physical'])\n\nexport const createCharacters = (options: CharactersOptions = {}): CharacterKit => {\n const body = createBodySpec(options.body)\n const packs = options.packs ?? []\n const presets = mergeById([PERSON_PRESET], packs.flatMap((pack) => pack.presets ?? []))\n applyPatches(presets, options.patch)\n removeIds(presets, options.remove)\n const damage = resolveDamageRules(options.damage)\n const penetration = modelOf(options.penetration)\n const protection = mergeById(PROTECTION_PRESETS, [...packs.flatMap((pack) => pack.protection ?? []), ...(options.protection ?? [])])\n const shippedCalibers = penetration.id === 'team-game' ? TEAM_GAME_CALIBERS : []\n const calibers = mergeById(shippedCalibers, [...packs.flatMap((pack) => pack.calibers ?? []), ...(options.calibers ?? [])])\n const setup = { rules: damage, model: penetration, protection, calibers }\n let counter = 0\n return {\n body,\n presets,\n corpses: { ...DEFAULT_CORPSES, ...options.corpses },\n damage,\n penetration,\n protection,\n calibers,\n create(spec) {\n counter += 1\n const resolved = resolveSpec(applyPreset(spec, presets), body, counter)\n const core = createCharacterCore({ spec: resolved, bodySpec: body, hitPointsOf: (kind) => damage.segments[kind].hitPoints })\n return createDamageCharacter(core, setup)\n },\n createCorpses: () => createCorpseLedger({ ...DEFAULT_CORPSES, ...options.corpses }),\n penetrateLine: (shot, targets) => penetrateLine({ model: penetration.id === 'team-game' ? 'team-game' : 'physical', shot, targets, calibers }),\n }\n}\n","{\n \"cascade\": {\n \"hip\": 16,\n \"spine\": 11,\n \"shoulder\": 9,\n \"elbow\": 7,\n \"leg\": 14,\n \"knee\": 11,\n \"head\": 6\n },\n \"moves\": {\n \"idle\": {\n \"gait\": 0,\n \"freq\": 0,\n \"amp\": 0,\n \"knee\": 0,\n \"bob\": 0,\n \"lean\": 0,\n \"arm\": 0,\n \"elb\": 0.12,\n \"crouch\": 0,\n \"aim\": 0,\n \"turn\": 0,\n \"grip\": 0.35\n },\n \"walk\": {\n \"gait\": 1,\n \"freq\": 5.6,\n \"amp\": 0.42,\n \"knee\": 0.85,\n \"bob\": 0.035,\n \"lean\": 0.05,\n \"arm\": 0.42,\n \"elb\": 0.3,\n \"crouch\": 0,\n \"aim\": 0,\n \"turn\": 0,\n \"grip\": 0.4\n },\n \"run\": {\n \"gait\": 1,\n \"freq\": 9.2,\n \"amp\": 0.72,\n \"knee\": 1.5,\n \"bob\": 0.06,\n \"lean\": 0.3,\n \"arm\": 0.85,\n \"elb\": 1.35,\n \"crouch\": 0,\n \"aim\": 0,\n \"turn\": 0,\n \"grip\": 1.1\n },\n \"crouch\": {\n \"gait\": 1,\n \"freq\": 3.8,\n \"amp\": 0.3,\n \"knee\": 0.6,\n \"bob\": 0.02,\n \"lean\": 0.42,\n \"arm\": 0.15,\n \"elb\": 0.7,\n \"crouch\": 1,\n \"aim\": 0,\n \"turn\": 0,\n \"grip\": 0.8\n },\n \"aim\": {\n \"gait\": 0,\n \"freq\": 0,\n \"amp\": 0,\n \"knee\": 0,\n \"bob\": 0,\n \"lean\": 0.06,\n \"arm\": 0,\n \"elb\": 0.2,\n \"crouch\": 0.25,\n \"aim\": 1,\n \"turn\": 0,\n \"grip\": 1.2\n },\n \"turn\": {\n \"gait\": 0.5,\n \"freq\": 4.2,\n \"amp\": 0.14,\n \"knee\": 0.7,\n \"bob\": 0.012,\n \"lean\": 0.03,\n \"arm\": 0.12,\n \"elb\": 0.25,\n \"crouch\": 0,\n \"aim\": 0,\n \"turn\": 1,\n \"grip\": 0.4\n }\n },\n \"poses\": [\n {\n \"index\": 0,\n \"id\": \"walk\",\n \"name\": {\n \"pt-BR\": \"anda\"\n }\n },\n {\n \"index\": 1,\n \"id\": \"crawl\",\n \"name\": {\n \"pt-BR\": \"rasteja\"\n }\n },\n {\n \"index\": 2,\n \"id\": \"fallen\",\n \"name\": {\n \"pt-BR\": \"caído\"\n }\n },\n {\n \"index\": 3,\n \"id\": \"attack\",\n \"name\": {\n \"pt-BR\": \"ataca\"\n }\n },\n {\n \"index\": 4,\n \"id\": \"scream\",\n \"name\": {\n \"pt-BR\": \"grito\"\n }\n },\n {\n \"index\": 5,\n \"id\": \"crouch\",\n \"name\": {\n \"pt-BR\": \"agachado\"\n }\n },\n {\n \"index\": 6,\n \"id\": \"leap\",\n \"name\": {\n \"pt-BR\": \"salto\"\n }\n },\n {\n \"index\": 7,\n \"id\": \"eat\",\n \"name\": {\n \"pt-BR\": \"comendo\"\n }\n }\n ],\n \"walk\": {\n \"cadenceBase\": 0.5,\n \"cadencePerSpeed\": 0.3,\n \"stopBelowSpeed\": 0.05,\n \"maxSine\": 0.9,\n \"strideFactor\": 4,\n \"legLengthFactor\": 0.9\n }\n}\n","import gait from '../data/gait.json'\n\nconst WALK = gait.walk\n\n/** Cycles per second at `speed` m/s (the game's `walkCad`). */\nexport const walkCadence = (speed: number): number => WALK.cadenceBase + WALK.cadencePerSpeed * speed\n\n/** Hip swing in radians at `speed` m/s for a body `height` times the base height: the stride that makes the foot meet the ground (the game's `walkGait`). */\nexport const walkGait = (speed: number, height = 1): number =>\n speed < WALK.stopBelowSpeed ? 0 : 2 * Math.asin(Math.min(WALK.maxSine, speed / (WALK.strideFactor * WALK.legLengthFactor * height * walkCadence(speed))))\n\nexport type StrideParams = {\n readonly speed: number\n readonly height?: number\n /** Default true: cadence and swing come from the speed, so the feet do not slide. False keeps the profile's own numbers (the Bestiário preset). */\n readonly strideFromSpeed?: boolean\n}\n\nexport type Stride = {\n /** Cycles per second. */\n readonly frequency: number\n /** Thigh swing, radians. */\n readonly swing: number\n /** Knee bend, radians. */\n readonly kneeBend: number\n}\n\nconst SWING_SHARE = 0.5\nconst KNEE_PER_GAIT = 0.85\n\n/** The gait numbers for a speed: from the ground-matching stride, or `fallback` (the profile) when `strideFromSpeed` is false. */\nexport const strideFor = ({ speed, height = 1, strideFromSpeed = true }: StrideParams, fallback: Stride): Stride => {\n if (!strideFromSpeed) return fallback\n const amplitude = walkGait(speed, height)\n return { frequency: walkCadence(speed), swing: amplitude * SWING_SHARE, kneeBend: amplitude * KNEE_PER_GAIT }\n}\n","import gait from '../data/gait.json'\n\n/** How a body type walks: offsets over its rest pose (the Bestiário's `GAIT`). `f` cycles per second, `a` thigh swing, `k` knee bend, `arm` arm swing. */\nexport type GaitProfile = {\n readonly f: number\n readonly a?: number\n readonly k?: number\n readonly arm?: number\n readonly bob?: number\n readonly sway?: number\n readonly drag?: boolean\n readonly crawl?: boolean\n readonly idle?: boolean\n readonly eat?: boolean\n readonly leap?: boolean\n readonly listen?: boolean\n readonly stalk?: boolean\n readonly sniff?: boolean\n}\n\nexport type JointAngles = { readonly shoulder: number; readonly elbow: number }\nexport type LegAngles = { readonly hip: number; readonly knee: number; readonly lost?: boolean }\n\n/**\n * The pose the gait swings around. `arms[0]` is the right arm and `arms[1]` the left; `legs[0]` is the left leg and `legs[1]` the right\n * (the order the Bestiário builds them in). `hipY` is the rest height of the hips.\n */\nexport type RestPose = {\n readonly hipY: number\n readonly lean: number\n readonly headX: number\n readonly arms: readonly [JointAngles, JointAngles]\n readonly legs: readonly [LegAngles, LegAngles]\n}\n\n/** What a gait sets this frame; a field the gait does not write stays `undefined` and the joint keeps what it had. */\nexport type GaitSample = {\n hipY?: number\n upper: { x?: number; y?: number; z?: number }\n head: { x?: number; y?: number }\n arms: { shoulder?: number; elbow?: number }[]\n legs: { hip?: number; knee?: number }[]\n}\n\nexport const emptySample = (): GaitSample => ({ upper: {}, head: {}, arms: [{}, {}], legs: [{}, {}] })\n\nexport type CascadeJoint = keyof typeof gait.cascade\n\n/** Cascade rates per joint (1/s): each joint reaches its target with a delay, from the hips to the head (Bestiário 12.3). */\nexport const CASCADE: Readonly<Record<CascadeJoint, number>> = gait.cascade\n\n/** The 8 poses of the instanced body, in the order of the game's `iB.w`. */\nexport const INSTANCE_POSES = ['walk', 'crawl', 'fallen', 'attack', 'scream', 'crouch', 'leap', 'eat'] as const\nexport type InstancePose = (typeof INSTANCE_POSES)[number]\n\nconst MIN_HEIGHT = -2\nconst MAX_HEIGHT = 8\nconst HEIGHT_STEPS = 1000\nconst POSE_SLOTS = 16\n\n/** `iB.w` of the instanced body: the pose plus 16 times the ground height in millimetres (a pile of bodies, a jump). */\nexport const encodePoseHeight = (pose: InstancePose, height = 0): number =>\n INSTANCE_POSES.indexOf(pose) + POSE_SLOTS * Math.round((Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, height)) - MIN_HEIGHT) * HEIGHT_STEPS)\n\nexport const decodePoseHeight = (encoded: number): { readonly pose: InstancePose; readonly height: number } => {\n const height = Math.floor(encoded / POSE_SLOTS) / HEIGHT_STEPS + MIN_HEIGHT\n return { pose: INSTANCE_POSES[encoded - Math.floor(encoded / POSE_SLOTS) * POSE_SLOTS] as InstancePose, height }\n}\n","import { emptySample } from './profile'\nimport type { GaitProfile, GaitSample, RestPose } from './profile'\nimport { strideFor } from './stride'\nimport type { StrideParams } from './stride'\n\nconst TWO_PI = Math.PI * 2\nconst LEAP_AIR_SHARE = 0.38\nconst LEAP_PHASE_DIVISOR = 6.3\nconst DEFAULT_PROFILE: GaitProfile = { f: 1.1, a: 0.28, k: 0.35, drag: true, arm: 0.08 }\n\nexport type AnimateProfileParams = {\n readonly profile?: GaitProfile\n readonly rest: RestPose\n /** Seconds. */\n readonly time: number\n /** Per-body phase offset, radians (the page's `rig.ph`). */\n readonly phase: number\n /** With `strideFromSpeed`, the speed and height that set cadence and swing. Without it the profile's own numbers are used. */\n readonly stride?: StrideParams\n}\n\n/** The leap, as a cycle: crouched, then airborne for 38% of it. */\nconst leap = ({ rest, time, phase, profile }: Required<Pick<AnimateProfileParams, 'rest' | 'time' | 'phase'>> & { profile: GaitProfile }): GaitSample => {\n const sample = emptySample()\n const cycle = (time * profile.f + phase / LEAP_PHASE_DIVISOR) % 1\n const air = cycle < LEAP_AIR_SHARE ? Math.sin((cycle / LEAP_AIR_SHARE) * Math.PI) : 0\n sample.hipY = rest.hipY + air * 0.95\n sample.upper.x = rest.lean - air * 0.45\n rest.legs.forEach((leg, index) => (sample.legs[index] = { hip: leg.hip * (1 - air * 0.7), knee: leg.knee * (1 - air * 0.75) }))\n rest.arms.forEach((arm, index) => (sample.arms[index] = { shoulder: arm.shoulder - air * 2.3, elbow: arm.elbow * (1 - air) }))\n return sample\n}\n\n/** Joint targets of one gait at `time` (the Bestiário's `animate0`), as numbers; the rig applies the ones that are set. */\nexport const animateProfile = ({ profile = DEFAULT_PROFILE, rest, time, phase, stride }: AnimateProfileParams): GaitSample => {\n const own = { frequency: profile.f, swing: profile.a ?? 0, kneeBend: profile.k ?? 0 }\n const { frequency, swing, kneeBend } = stride ? strideFor(stride, own) : own\n const angle = time * frequency * TWO_PI + phase\n const sine = Math.sin(angle)\n const cosine = Math.cos(angle)\n const sample = emptySample()\n if (profile.leap) return leap({ rest, time, phase, profile })\n if (profile.listen) {\n sample.head.y = Math.sin(time * 0.7 + phase) * 0.6\n rest.arms.forEach((arm, index) => (sample.arms[index] = { shoulder: arm.shoulder + Math.sin(time * 0.9 + index) * 0.08 }))\n return sample\n }\n if (profile.eat) {\n const wave = Math.sin(time * profile.f * TWO_PI + phase)\n sample.head.x = rest.headX + Math.max(0, wave) * 0.35\n sample.upper.x = rest.lean + Math.max(0, wave) * 0.08\n rest.arms.forEach((arm, index) => (sample.arms[index] = { elbow: arm.elbow + wave * 0.2 }))\n return sample\n }\n if (profile.crawl) {\n rest.arms.forEach((arm, index) => {\n const wave = index ? sine : -sine\n sample.arms[index] = { shoulder: arm.shoulder + wave * 0.35, elbow: arm.elbow - Math.max(0, wave) * 0.6 }\n })\n sample.upper.z = sine * 0.06\n return sample\n }\n if (profile.idle) {\n const scare = Math.max(0, Math.sin(time * 0.9 + phase))\n sample.upper.x = rest.lean - scare * 0.18\n sample.head.x = rest.headX - scare * 0.25\n rest.arms.forEach((arm, index) => (sample.arms[index] = { shoulder: arm.shoulder + scare * 0.25 }))\n return sample\n }\n rest.legs.forEach((leg, index) => {\n if (leg.lost) return\n const wave = index ? -sine : sine\n if (profile.drag && index === 1) return void (sample.legs[index] = { hip: leg.hip + wave * swing * 0.35, knee: leg.knee })\n sample.legs[index] = { hip: leg.hip + wave * swing, knee: leg.knee + Math.max(0, index ? cosine : -cosine) * kneeBend }\n })\n rest.arms.forEach((arm, index) => (sample.arms[index] = { shoulder: arm.shoulder + (index ? sine : -sine) * (profile.arm || 0.1) }))\n sample.hipY = rest.hipY - Math.abs(cosine) * (profile.bob || 0.02)\n sample.upper.y = sine * 0.06\n sample.upper.z = (profile.sway || 0) * sine + (profile.drag ? 0.04 : 0)\n if (profile.stalk) sample.upper.x = rest.lean + sine * 0.04\n if (profile.sniff) sample.head.y = Math.sin(time * 3.1 + phase) * 0.35\n return sample\n}\n","import { CASCADE } from './profile'\nimport type { CascadeJoint } from './profile'\n\n/** One joint moving toward its target: it covers `dt · rate` of the distance each step (never more than all of it). */\nexport const stepCascade = (current: number, target: number, dt: number, joint: CascadeJoint, rates: Readonly<Record<CascadeJoint, number>> = CASCADE): number =>\n current + (target - current) * Math.min(1, dt * rates[joint])\n\n/** Between two poses by joint name: a joint `from` does not name starts at the target (the Bestiário's `lerpPose`). */\nexport const lerpPose = <TPose extends Readonly<Record<string, number>>>(from: Partial<TPose>, to: TPose, amount: number): TPose => {\n const result: Record<string, number> = {}\n for (const name of Object.keys(to)) {\n const start = from[name]\n const end = to[name] as number\n result[name] = start === undefined ? end : (start as number) + (end - (start as number)) * amount\n }\n return result as TPose\n}\n","import gait from '../data/gait.json'\n\nexport type MoveId = keyof typeof gait.moves\nexport type MoveBlend = { gait: number; freq: number; amp: number; knee: number; bob: number; lean: number; arm: number; elb: number; crouch: number; aim: number; turn: number; grip: number }\n\n/** The human movement states the Elenco blends every frame. */\nexport const MOVES: Readonly<Record<MoveId, Readonly<MoveBlend>>> = gait.moves\n\nexport const MOVE_BLEND_RATE = 4\n\nexport const moveBlendOf = (move: MoveId): MoveBlend => ({ ...MOVES[move] })\n\n/** Moves `current` toward the target move: each number covers `dt · 4` of the distance (never past it). Mutates and returns `current`. */\nexport const blendMoves = (current: MoveBlend, target: MoveId | Readonly<MoveBlend>, dt: number): MoveBlend => {\n const goal = typeof target === 'string' ? MOVES[target] : target\n const amount = Math.min(1, dt * MOVE_BLEND_RATE)\n for (const key of Object.keys(goal) as (keyof MoveBlend)[]) current[key] += (goal[key] - current[key]) * amount\n return current\n}\n\nexport type HumanArm = { readonly side: 1 | -1; readonly hold?: boolean }\n\nexport type HumanPoseParams = {\n readonly moves: Readonly<MoveBlend>\n /** Seconds since the start. */\n readonly time: number\n /** The character's own phase offset. */\n readonly phase: number\n /** `phase + offset`: the walking cycle's angle, advanced by `dt · freq`. */\n readonly cycle: number\n /** The character's resting hunch plus the stage's. */\n readonly hunch: number\n /** The infection stage's arm raise (0 healthy .. 1 reanimated). */\n readonly armRaise: number\n /** Stage index: 3 and up adds a spine tremor, 4 is the reanimated body. */\n readonly stage: number\n /** The `prefers-reduced-motion` mode: no idle motion, no gait. */\n readonly reduced?: boolean\n readonly skirt?: boolean\n /** [right, left] as built: side and whether the hand holds an item. */\n readonly arms: readonly [HumanArm, HumanArm]\n /** [left, right] leg sides. */\n readonly legSides: readonly [1 | -1, 1 | -1]\n}\n\nexport type HumanPose = {\n readonly chestScaleY: number\n readonly hip: { readonly x: number; readonly y: number; readonly zRotation: number }\n readonly upper: { readonly x: number; readonly y: number; readonly z: number }\n readonly head: { readonly x: number; readonly y: number; readonly z: number }\n readonly legs: readonly { readonly hip: number; readonly knee: number; readonly hipZ: number }[]\n readonly arms: readonly { readonly shoulder: number; readonly shoulderZ: number; readonly elbow: number; readonly wrist: number; readonly grip: number }[]\n}\n\nconst REANIMATED_STAGE = 4\nconst TREMOR_STAGE = 3\n\n/** The blended walk of the Elenco for one frame (hips, spine, head, legs, arms), as joint targets. Pure: the caller keeps the phase and the blend. */\nexport const humanPose = (params: HumanPoseParams): HumanPose => {\n const { moves, time, phase, cycle, hunch, armRaise, stage, reduced = false, skirt = false } = params\n const zombie = stage === REANIMATED_STAGE\n const walking = reduced ? 0 : moves.gait\n const phased = phase + time\n const shift = reduced ? 0 : Math.sin(time * 0.45 + phase) * (1 - walking) * (1 - moves.aim)\n const upperX = hunch + moves.crouch * 0.15 + (stage >= TREMOR_STAGE && !reduced ? Math.sin(phased * 2.3) * 0.03 : 0)\n const upperY = walking * Math.sin(cycle - 0.35) * (0.08 + moves.arm * 0.12) - moves.aim * 0.35 + moves.turn * 0.25\n const upperZ = -shift * 0.025 + walking * Math.sin(cycle - 0.35) * 0.02 + (zombie ? 0.05 + Math.sin(cycle * 0.5) * 0.06 * walking : 0)\n const legs = params.legSides.map((side, index) => {\n const legCycle = cycle + (index ? Math.PI : 0)\n const amplitude = moves.amp * (zombie && index === 0 ? 0.45 : 1) * (skirt ? 0.75 : 1)\n return {\n hip: -walking * Math.sin(legCycle) * amplitude - moves.crouch * 0.95 + (zombie && !walking ? (index ? -0.1 : 0.08) : 0),\n knee:\n walking * (Math.max(0, Math.cos(legCycle)) * moves.knee * (zombie && index === 0 ? 0.3 : 1) + 0.06) +\n moves.crouch * 1.55 +\n (1 - walking) * (0.03 + Math.max(0, shift * (index ? 1 : -1)) * 0.18),\n hipZ: side * (0.02 + moves.aim * 0.1 + moves.crouch * 0.06),\n }\n })\n const arms = params.arms.map(({ side, hold = false }, index) => {\n const raise = armRaise * (hold && !zombie ? 0.2 : 1)\n const swing = cycle - 0.25\n const shoulderX =\n (hold ? -0.2 : 0) -\n raise * (zombie ? 1.12 : 1.3) -\n side * Math.sin(swing) * moves.arm * walking * (zombie ? 0.3 : 1) +\n (reduced || walking ? 0 : Math.sin(phased * 1.6 + side) * 0.04) +\n (zombie && !reduced ? Math.sin(phased * 3 + side * 2) * 0.08 : 0)\n const aimX = index === 0 ? -1.45 : -1.32\n return {\n shoulder: shoulderX * (1 - moves.aim) + aimX * moves.aim,\n shoulderZ: side * (0.07 + (zombie ? 0.1 : 0)) * (1 - moves.aim) - side * 0.32 * moves.aim,\n elbow: zombie ? -0.18 : -((moves.elb + (hold ? 0.25 : 0) + walking * Math.max(0, side * Math.sin(swing - 0.3)) * 0.3) * (1 - moves.aim) + (index === 0 ? 0.15 : 0.55) * moves.aim),\n wrist: reduced ? 0 : -walking * Math.sin(swing - 0.6) * 0.15 * side * (1 - moves.aim),\n grip: (hold ? 1.25 : moves.grip) * (zombie ? 0.5 : 1),\n }\n })\n const headY = (reduced ? 0 : Math.sin(phased * 0.5) * 0.25 * (1 - walking) * (1 - moves.aim) * (zombie ? 0.3 : 1)) - upperY * 0.75 * (1 - moves.turn) + moves.turn * 0.45 + moves.aim * 0.3\n return {\n chestScaleY: 1 + (reduced ? 0 : Math.sin(phased * (1.6 + moves.freq * 0.12)) * (0.012 + moves.freq * 0.0012)),\n hip: { x: shift * 0.025 + walking * Math.sin(cycle) * 0.018, y: -walking * moves.bob * Math.abs(Math.sin(cycle)) - moves.crouch * 0.26, zRotation: shift * 0.02 - walking * Math.sin(cycle) * 0.022 },\n upper: { x: upperX, y: upperY, z: upperZ },\n head: { x: -hunch * 0.6 - moves.crouch * 0.12 + (zombie ? 0.15 : 0) + walking * Math.sin(cycle * 2 - 0.6) * 0.02, y: headY, z: (zombie ? 0.22 : 0) - upperZ * 0.6 },\n legs,\n arms,\n }\n}\n\n/** A leg that cannot carry weight (limp): the swing shrinks to 30%, the knee straightens, the spine leans toward the good leg. */\nexport const LIMP = { swing: 0.3, knee: 0.05, lean: 0.07 } as const\n","/** Prone crawl on the arms (the Elenco's leg-less body): joint targets at `time`; `figTilt` is the body's tilt target, which the caller approaches at `dt · 4`. */\nexport type CrawlPose = {\n readonly figTilt: number\n readonly hipY: number\n readonly hipZRotation: number\n readonly upper: { readonly x: number; readonly y: number }\n readonly headX: number\n readonly arms: readonly { readonly shoulder: number; readonly shoulderZ: number; readonly elbow: number }[]\n readonly legs: readonly { readonly hip: number; readonly knee: number }[]\n}\n\nexport const CRAWL_TILT_RATE = 4\nexport const DEAD_TILT_RATE = 3\n\nexport const crawlPose = (time: number, phase: number, sides: readonly [1 | -1, 1 | -1]): CrawlPose => {\n const cycle = time * 2.2 + phase\n const wave = Math.sin(cycle)\n return {\n figTilt: 1.38,\n hipY: 0.2 + Math.abs(wave) * 0.02,\n hipZRotation: wave * 0.05,\n upper: { x: 0, y: wave * 0.12 },\n headX: -0.95,\n arms: sides.map((side) => ({ shoulder: -2.55 + side * wave * 0.45, shoulderZ: side * 0.25, elbow: -0.35 - Math.max(0, -side * wave) * 0.6 })),\n legs: [\n { hip: 0.1, knee: 0 },\n { hip: 0.12 + wave * 0.08, knee: 0.25 },\n ],\n }\n}\n\nexport type DeadPose = {\n readonly figTilt: number\n readonly hipY: number\n readonly headY: number\n readonly arms: readonly { readonly shoulder: number; readonly shoulderZ: number; readonly elbow: number }[]\n readonly legs: readonly { readonly hip: number; readonly hipZ: number; readonly knee: number }[]\n}\n\n/** A body on the ground (the Elenco's death pose); the caller approaches `figTilt` at `dt · 3`. */\nexport const deadPose = (armSides: readonly [1 | -1, 1 | -1]): DeadPose => ({\n figTilt: -1.45,\n hipY: 0.22,\n headY: 0.5,\n arms: armSides.map((side) => ({ shoulder: -0.2, shoulderZ: side * 1.1, elbow: -0.3 })),\n legs: [-0.15, 0.15].map((hipZ) => ({ hip: 0, hipZ, knee: 0.1 })),\n})\n","export type ConditionPhase = {\n readonly id: string\n /** When the phase starts, in the timeline's units (hours, or seconds on an accelerated clock). The first phase starts at 0. */\n readonly startsAt: number\n /** Numbers the phase drives (skin tint, hunch, arm raise, ...), by name. */\n readonly effects?: Readonly<Record<string, number>>\n}\n\nexport type ConditionOptions = {\n readonly phases: readonly ConditionPhase[]\n /** Timeline units per real second: 1 on a clock already in seconds (the accelerated preset), 1/3600 for hours. Default 1. */\n readonly unitsPerSecond?: number\n /** Interpolate effects toward the next phase instead of stepping. Default false. */\n readonly blend?: boolean\n}\n\nexport type ConditionSample = {\n readonly index: number\n readonly phase: ConditionPhase\n /** 0..1 inside the current phase (1 on the last one). */\n readonly progress: number\n readonly effects: Readonly<Record<string, number>>\n readonly isFinal: boolean\n}\n\nexport type ConditionTimeline = {\n readonly elapsed: number\n /** Advances the clock by `seconds` of real time. */\n advance(seconds: number): ConditionSample\n /** Jumps the clock to `units` of the timeline. */\n seek(units: number): ConditionSample\n sample(): ConditionSample\n reset(): void\n}\n\nconst phaseIndexAt = (phases: readonly ConditionPhase[], units: number): number => {\n let found = 0\n phases.forEach((phase, index) => {\n if (units >= phase.startsAt) found = index\n })\n return found\n}\n\nconst mixEffects = (from: ConditionPhase['effects'], to: ConditionPhase['effects'], amount: number): Record<string, number> => {\n const result: Record<string, number> = {}\n for (const name of new Set([...Object.keys(from ?? {}), ...Object.keys(to ?? {})])) {\n const start = from?.[name] ?? 0\n result[name] = start + ((to?.[name] ?? 0) - start) * amount\n }\n return result\n}\n\n/** A condition that moves through ordered phases over time (an infection: well, fever, delirium, reanimated). Generic: phases and effects are data. */\nexport const createConditionTimeline = (options: ConditionOptions): ConditionTimeline => {\n const { phases, unitsPerSecond = 1, blend = false } = options\n if (phases.length === 0) throw new Error('createConditionTimeline: at least one phase is required')\n let units = 0\n const sample = (): ConditionSample => {\n const index = phaseIndexAt(phases, units)\n const phase = phases[index] as ConditionPhase\n const next = phases[index + 1]\n const progress = next ? Math.min(1, (units - phase.startsAt) / (next.startsAt - phase.startsAt)) : 1\n const effects = blend && next ? mixEffects(phase.effects, next.effects, progress) : { ...phase.effects }\n return { index, phase, progress, effects, isFinal: !next }\n }\n return {\n get elapsed() {\n return units\n },\n advance(seconds) {\n units += seconds * unitsPerSecond\n return sample()\n },\n seek(target) {\n units = Math.max(0, target)\n return sample()\n },\n sample,\n reset() {\n units = 0\n },\n }\n}\n","{\n \"variance\": {\n \"height\": {\n \"gaussianSpread\": 0.09,\n \"min\": 0.9,\n \"max\": 1.1\n },\n \"buildBands\": [\n {\n \"below\": 0.3,\n \"base\": 0.85,\n \"range\": 0.1\n },\n {\n \"below\": 0.8,\n \"base\": 0.95,\n \"range\": 0.13\n },\n {\n \"base\": 1.08,\n \"range\": 0.17\n }\n ],\n \"buildSpeed\": {\n \"lean\": 1.05,\n \"heavy\": 0.9\n },\n \"buildHealth\": {\n \"lean\": 0.9,\n \"heavy\": 1.15\n },\n \"speedJitter\": {\n \"base\": 0.92,\n \"range\": 0.16\n },\n \"wanderJitter\": {\n \"base\": 0.8,\n \"range\": 0.4\n },\n \"runnerAgeClamp\": 1,\n \"variantCount\": {\n \"walker\": 4,\n \"runner\": 3,\n \"crawler\": 2,\n \"brute\": 2\n },\n \"variantSeedBase\": 7000\n },\n \"civilianColors\": [\n \"6D5A4A\",\n \"4D5D6B\",\n \"7A3B33\",\n \"5B6B4A\",\n \"8A7A5A\",\n \"3E4A5C\",\n \"6A4A6A\",\n \"9A8A70\",\n \"40403A\"\n ],\n \"corpses\": {\n \"max\": 400,\n \"lifeSeconds\": 900\n }\n}\n","import appearance from '../data/appearance.json'\n\nconst { variance } = appearance\n\nexport type BuildClass = 'lean' | 'average' | 'heavy'\n\n/** What `zSpawn` draws for a body: height, width, how it builds up and the speed jitters. Every field comes from the stream, in the game's order. */\nexport type BodyVariance = {\n readonly height: number\n readonly build: number\n readonly buildClass: BuildClass\n /** Multiplies the chase speed: the build factor times a 0.92 .. 1.08 jitter. */\n readonly speedFactor: number\n /** Multiplies the wander speed: 0.8 .. 1.2. */\n readonly wanderFactor: number\n /** Multiplies the health: 0.9 lean, 1.15 heavy. */\n readonly healthFactor: number\n}\n\nexport type VarianceScale = { readonly height?: number; readonly build?: number }\n\nconst clamp = (value: number, low: number, high: number): number => Math.min(high, Math.max(low, value))\n\n/**\n * One body's variance from `random`, drawing exactly what the game's `zSpawn` draws after the type, age and outfit picks:\n * three draws for the height (a gaussian), one for the build band plus one inside it, one for the speed and one for the wander speed.\n * `scale` is the type's own scale (a brute's 1.42) and `build` its width factor.\n */\nexport const drawBodyVariance = (random: () => number, scale: VarianceScale = {}): BodyVariance => {\n const spread = (random() + random() + random() - 1.5) * variance.height.gaussianSpread\n const height = clamp(1 + spread, variance.height.min, variance.height.max) * (scale.height ?? 1)\n const band = random()\n const bands = variance.buildBands as readonly { below?: number; base: number; range: number }[]\n const found = bands.find((candidate) => candidate.below !== undefined && band < candidate.below) ?? (bands[bands.length - 1] as { base: number; range: number })\n const { base, range } = found\n const build = (base + random() * range) * (scale.build ?? 1)\n const buildClass: BuildClass = band < 0.3 ? 'lean' : band >= 0.8 ? 'heavy' : 'average'\n const speedBuild = buildClass === 'lean' ? variance.buildSpeed.lean : buildClass === 'heavy' ? variance.buildSpeed.heavy : 1\n const healthBuild = buildClass === 'lean' ? variance.buildHealth.lean : buildClass === 'heavy' ? variance.buildHealth.heavy : 1\n return {\n height,\n build,\n buildClass,\n speedFactor: speedBuild * (variance.speedJitter.base + random() * variance.speedJitter.range),\n wanderFactor: variance.wanderJitter.base + random() * variance.wanderJitter.range,\n healthFactor: healthBuild,\n }\n}\n\n/** Variants baked per type (the game's `nv`): 4 walkers, 3 runners, 2 crawlers and brutes, 1 for the rest. */\nexport const variantCountFor = (typeId: string): number => (variance.variantCount as Readonly<Record<string, number>>)[typeId] ?? 1\n\n/** The seed of variant `variant` of the type at `typeIndex` (the game's ZVAR rule: `7000 + c·101 + v·13`). */\nexport const variantSeed = (typeIndex: number, variant: number): number => variance.variantSeedBase + typeIndex * 101 + variant * 13\n\n/** The decay each variant is baked at: 1, 2, 1, 2. */\nexport const variantDecay = (variant: number): number => (variant % 2 === 0 ? 1 : 2)\n","/** The colour and style pools of the Bestiário v17 builder, in the order its random stream picks from them. */\nexport const SKIN_TONES = [0xf1c9a5, 0xe0ac80, 0xc68c62, 0xa8714a, 0x8a5a3a, 0x5e3b26] as const\nexport const TOP_COLORS = [0x4a6f96, 0x8e3b3b, 0x5d4a3a, 0x4f7a43, 0x6b6f78, 0x3f5f3a, 0x5a4a6e, 0x8a6a3a, 0xb8b2a2, 0x2c2c30, 0x9a4a2a, 0x2f5d63, 0xc9a94a, 0x7a2e4a, 0xd8d4c8, 0x3a4a6a] as const\nexport const PANTS_COLORS = [0x2c3340, 0x1f2228, 0x4a4030, 0x5a5f66, 0x3a4a6a, 0x6a5a40, 0x2a3a2a] as const\nexport const SLEEVES = ['short', 'short', 'long', 'tank'] as const\nexport const HAIR_STYLES_FEMALE = ['long', 'long', 'bun', 'short', 'afro', 'bald'] as const\nexport const HAIR_STYLES_MALE = ['short', 'short', 'buzz', 'bald', 'afro', 'long'] as const\nexport const CAP_COLORS = [0x8e3b3b, 0x2c2c30, 0x3a4a6a, 0xc9a94a] as const\nexport const BAG_COLORS = [0x3a4a3a, 0x5a2a24, 0x2c3340] as const\nexport const HAIR_COLORS = [0x1a1410, 0x2a1e16, 0x3b2c20, 0x6a4a2a, 0xb08a50, 0x7a2a1a] as const\nexport const SHOE_COLORS = [0x1d1f22, 0x3a2a1a, 0xb8b4a8, 0x4a1a1a] as const\n/** Uniform bodies (the crowd's baked variants): skin by decay, shirt by type index. */\nexport const DECAY_SKIN = [0xcdbba8, 0x94a084, 0x7b744a, 0x8c7c5e] as const\nexport const UNIFORM_SHIRTS = [0x4a6f96, 0x8e3b3b, 0x5d4a3a, 0x4f7a43, 0x6b6f78, 0x3f5f3a, 0x5a4a6e, 0x8a6a3a] as const\nexport const UNIFORM_PANTS = 0x2c3340\nexport const UNIFORM_SHOES = 0x1d1f22\nexport const SKIN_DECAY_BLEND = [0.45, 0.65, 0.8, 0.88] as const\nexport const GRAY = 0x4a4a46\nexport const RED = 0x7a120c\nexport const BLOOD_COLORS = [0x9e1b12, 0x6e1410, 0x4a2a18, 0x1c1612] as const\nexport const OLD_HAIR = 0x8a8780\n","import { createRng } from '../damage/points'\n\nimport {\n BAG_COLORS,\n CAP_COLORS,\n DECAY_SKIN,\n HAIR_COLORS,\n HAIR_STYLES_FEMALE,\n HAIR_STYLES_MALE,\n OLD_HAIR,\n PANTS_COLORS,\n SHOE_COLORS,\n SKIN_TONES,\n SLEEVES,\n TOP_COLORS,\n UNIFORM_PANTS,\n UNIFORM_SHIRTS,\n UNIFORM_SHOES,\n} from './palette'\n\nexport type HairStyle = (typeof HAIR_STYLES_FEMALE)[number] | (typeof HAIR_STYLES_MALE)[number]\n\nexport type OutfitLook = { readonly cloth?: number; readonly pants?: number; readonly hat?: string }\n\nexport type AppearanceParams = {\n readonly seed: number\n /** The look of an outfit (police, military ...): its colours replace the draws, so the stream does not spend them. */\n readonly outfit?: OutfitLook\n /** A baked crowd variant: no random look, fixed skin, shirt by `typeIndex`, short hair. */\n readonly uniform?: boolean\n readonly typeIndex?: number\n readonly clothIndex?: number\n /** Forces the sex; unset draws it (42% female). */\n readonly female?: boolean\n /** False for bodies that are never female (a brute): the draw is skipped. */\n readonly allowFemale?: boolean\n readonly tone?: number\n readonly hairStyle?: HairStyle\n readonly hairColor?: number\n /** The type's own look: wet bodies have long hair, charred ones are bald. */\n readonly wet?: boolean\n readonly charred?: boolean\n /** A living person: no bag, no tear. */\n readonly human?: boolean\n /** 0 fresh-dead, 1 normal, 2 old (grey hair). */\n readonly life?: number\n}\n\nexport type AppearanceTraits = {\n readonly female: boolean\n readonly tone: number\n readonly topColor: number\n readonly pantsColor: number\n readonly sleeve: string\n readonly hair: string\n readonly headWidth: number\n readonly headHeight: number\n readonly jaw: number\n readonly nose: number\n readonly beard: boolean\n readonly glasses: boolean\n readonly cap: boolean\n readonly capColor: number\n readonly bag: boolean\n readonly bagColor: number\n readonly torn: boolean\n readonly apron: boolean\n readonly hairColor: number\n readonly shoeColor: number\n}\n\nexport type DrawnAppearance = {\n readonly traits: AppearanceTraits\n /** The stream, positioned after the look: the body builder keeps drawing from it (the hair of a decrepit body). */\n readonly random: () => number\n}\n\n/** The seed of the blood stream (the same drips on every level of detail). */\nexport const BLOOD_SEED_OFFSET = 99\n\nexport const createBloodStream = (seed: number): (() => number) => createRng(seed + BLOOD_SEED_OFFSET)\n\nconst FEMALE_SHARE = 0.42\nconst BEARD_SHARE = 0.25\nconst GLASSES_SHARE = 0.12\nconst CAP_SHARE = 0.12\nconst BAG_SHARE = 0.15\nconst TORN_SHARE = 0.35\nconst APRON_SHARE = 0.05\n\n/**\n * A person's look from a seed, drawing in exactly the order the Bestiário v17 builder draws from its `VR` stream, including the draws a\n * short-circuit skips (no beard roll for a woman, no cap roll under a hat). Returns the stream so the builder can continue from it.\n */\nexport const drawAppearance = (params: AppearanceParams): DrawnAppearance => {\n const { seed, outfit = {}, uniform = false, typeIndex = 0, human = false, life = 1 } = params\n const random = createRng(seed)\n const pick = <T>(options: readonly T[]): T => options[Math.floor(random() * options.length)] as T\n const female = !uniform && (params.allowFemale ?? true) && (params.female ?? random() < FEMALE_SHARE)\n const tone = params.tone ?? (uniform ? (DECAY_SKIN[0] as number) : pick(SKIN_TONES))\n const topColor = outfit.cloth ?? (uniform ? (UNIFORM_SHIRTS[(params.clothIndex ?? typeIndex) % UNIFORM_SHIRTS.length] as number) : pick(TOP_COLORS))\n const pantsColor = outfit.pants ?? (uniform ? UNIFORM_PANTS : pick(PANTS_COLORS))\n const look = uniform ? uniformLook() : drawLook({ random, pick, female, outfit, human, params })\n const hairColor = params.hairColor ?? (life === 2 ? OLD_HAIR : pick(HAIR_COLORS))\n const shoeColor = uniform ? UNIFORM_SHOES : pick(SHOE_COLORS)\n return { traits: { female, tone, topColor, pantsColor, ...look, hairColor, shoeColor }, random }\n}\n\ntype Look = Omit<AppearanceTraits, 'female' | 'tone' | 'topColor' | 'pantsColor' | 'hairColor' | 'shoeColor'>\n\nconst uniformLook = (): Look => ({\n sleeve: 'short',\n hair: 'short',\n headWidth: 1,\n headHeight: 1,\n jaw: 1,\n nose: 1,\n beard: false,\n glasses: false,\n cap: false,\n capColor: 0,\n bag: false,\n bagColor: 0,\n torn: false,\n apron: false,\n})\n\ntype DrawLookParams = {\n readonly random: () => number\n readonly pick: <T>(options: readonly T[]) => T\n readonly female: boolean\n readonly outfit: OutfitLook\n readonly human: boolean\n readonly params: AppearanceParams\n}\n\nconst drawLook = ({ random, pick, female, outfit, human, params }: DrawLookParams): Look => {\n const sleeve = outfit.cloth ? 'long' : pick(SLEEVES)\n const hair = params.hairStyle ?? (params.wet ? 'long' : params.charred ? 'bald' : pick(female ? HAIR_STYLES_FEMALE : HAIR_STYLES_MALE))\n const headWidth = 1 + (random() - 0.5) * 0.16\n const headHeight = 1 + (random() - 0.5) * 0.14\n const jaw = 1 + (random() - 0.5) * 0.3\n const nose = 1 + (random() - 0.5) * 0.5\n const beard = !female && random() < BEARD_SHARE\n const glasses = random() < GLASSES_SHARE\n const cap = !outfit.hat && random() < CAP_SHARE\n const capColor = pick(CAP_COLORS)\n const bag = random() < BAG_SHARE && !human\n const bagColor = pick(BAG_COLORS)\n const torn = random() < TORN_SHARE && !human\n const apron = random() < APRON_SHARE\n return { sleeve, hair, headWidth, headHeight, jaw, nose, beard, glasses, cap, capColor, bag, bagColor, torn, apron }\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,IACE,OAAS;AAAA,MACP,cAAgB;AAAA,MAChB,qBAAuB;AAAA,MACvB,0BAA4B;AAAA,MAC5B,sBAAwB;AAAA,MACxB,cAAgB;AAAA,IAClB;AAAA,IACA,UAAY;AAAA,MACV,QAAU;AAAA,MACV,QAAU;AAAA,QACR,SAAW;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,QACA,SAAW;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,QAC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