@adatechnology/game-interactables 0.11.0 → 0.13.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/README.md +17 -0
- package/dist/index.d.ts +263 -10
- package/dist/index.global.js +783 -43
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +691 -43
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.global.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/fixture-emitters.ts","../src/colliders.ts","../src/rng.ts","../src/loot.ts","../src/locale.ts","../src/math.ts","../src/world.ts","../src/engine-chain.ts","../src/engine-soft.ts","../src/engine-leaf.ts","../src/engine-parts.ts","../src/span.ts","../src/wire-runs.ts","../src/cast-with-member.ts","../src/fits-volume.ts","../src/sink-uses.ts","../src/object-uses.ts","../src/object-controls.ts"],"sourcesContent":["export type * from './types'\nexport type { PartDriver, PartPhysics, SoftDriver } from './part-physics'\nexport { createWorld } from './world'\nexport { rng, hashString } from './rng'\nexport { generateLoot, fitsSize, fitsSlot } from './loot'\nexport { poseOf, localToWorld, worldToLocal, rotY, rotateAxis } from './math'\nexport type { Pose } from './math'\nexport { resolveStrings, locales, format, pickLocale } from './locale'\nexport { mergeColliders } from './colliders'\nexport { FLUSH_RUN_SECONDS, createFixtureEmitters } from './fixture-emitters'\nexport type { FixtureEmitters, RunningEmitter } from './fixture-emitters'\nexport { createEnginePartPhysics } from './engine-parts'\nexport type { EnginePartDriver } from './engine-leaf'\nexport type { EnginePartOptions, EnginePartPhysics } from './engine-parts'\nexport { alignY, buildChain, chainPoints, disposeChain } from './engine-chain'\nexport { hangTail, polylineLength, solveSpan, spanStrength } from './span'\nexport { wireRuns } from './wire-runs'\nexport { COLLAR_REACH, END_GAP, castWithMember, endsMember, wrapsMember } from './cast-with-member'\nexport type { CastBox } from './cast-with-member'\nexport type { WireRun, WireRunsParams } from './wire-runs'\nexport type { HangTailParams, SolveSpanParams, Span, SpanMaterial, SpanShape } from './span'\nexport type { Chain, ChainSpec } from './engine-chain'\nexport { CONTROLLED_OBJECT, createObjectControls } from './object-controls'\nexport type { ObjectControls, ObjectControlsOptions, ObjectControlsState } from './object-controls'\nexport type { Soil, UsesState } from './object-uses'\nexport { fitsInVolume } from './fits-volume'\nexport { DRINK_LITRES, DRINK_LPS, DRY_SECONDS, FILL_SHARE, REACH_SECONDS, WASH_SCRUB_SECONDS, createSinkRoutines, dirtyDishes, findNeeds, fixtureFlowLps, sinkVerdict } from './sink-uses'\nexport type { RoutineEnd, SinkRoutine, SinkRoutines, SinkUseSpec, SinkUsesOptions, SinkVerdict } from './sink-uses'\nexport { FLOW_DEFAULTS } from './world'\n","// The water a piece runs while its handle is worked, for a host that moves the parts itself (a test room plays the part's clip, a game its own animation) and has\n// no interactables world: from the piece's spec and how open each part is now, which of its water emitters run and how hard. A tap runs as far as its handle\n// is turned; a flush runs for its seconds once its button goes down, whatever the button does next. Pure: no three.js, object-local, no allocation per call once\n// warmed up but the answer list.\nimport type { EmitterSpec, FixtureSpec, ObjectSpec } from './types'\n\n/** Seconds a flush runs once its button goes down (the interactables world's own flush time). */\nexport const FLUSH_RUN_SECONDS = 2\n/** How open a handle has to be before the water starts, 0..1: a tap barely touched drips nothing. */\nconst START_OPENING = 0.05\n/** A flush button counts as pressed past this far down. */\nconst PRESSED = 0.5\n/** Seconds the end of a flush takes to die down. */\nconst FLUSH_FADE = 0.4\n\n/** One emitter running now, object-local, with its strength 0..1. */\nexport interface RunningEmitter {\n readonly emitter: EmitterSpec\n readonly intensity: number\n}\n\nexport interface FixtureEmitters {\n /** The water emitters of the piece that run now: `opening(part)` is how open that part is, 0 closed to 1 open. Advances the flushes by `dt` seconds. */\n update(dt: number, opening: (part: string) => number): RunningEmitter[]\n /** Whether the piece has any emitter a handle runs (a sink, a shower, a toilet): a host can skip the others. */\n readonly runs: boolean\n}\n\ninterface Driven {\n readonly emitter: EmitterSpec\n readonly fixture: FixtureSpec & { part: string }\n /** Flush only: seconds of run left, and whether the button was down the last time. */\n left: number\n down: boolean\n}\n\n/** The driver of one piece's water emitters by its handles. */\nexport function createFixtureEmitters(spec: Pick<ObjectSpec, 'emitters' | 'fixtures'>): FixtureEmitters {\n const fixtures = new Map((spec.fixtures ?? []).map((fixture) => [fixture.id, fixture]))\n const driven: Driven[] = []\n for (const emitter of spec.emitters ?? []) {\n if (emitter.kind !== 'water') continue\n const fixture = fixtures.get(emitter.source)\n if (!fixture?.part) continue\n driven.push({ emitter, fixture: { ...fixture, part: fixture.part }, left: 0, down: false })\n }\n return {\n runs: driven.length > 0,\n update(dt, opening) {\n const out: RunningEmitter[] = []\n for (const d of driven) {\n const open = Math.min(1, Math.max(0, opening(d.fixture.part)))\n if (d.fixture.kind === 'flush') {\n const down = open >= PRESSED\n if (down && !d.down) d.left = FLUSH_RUN_SECONDS\n d.down = down\n if (d.left <= 0) continue\n d.left = Math.max(0, d.left - dt)\n out.push({ emitter: d.emitter, intensity: Math.min(1, (d.left + 1e-6) / FLUSH_FADE) })\n continue\n }\n if (open > START_OPENING) out.push({ emitter: d.emitter, intensity: open })\n }\n return out\n },\n }\n}\n","import type { ColliderOptions, WorldCollider } from './types'\n\ninterface Box {\n ids: string[]\n object: string\n u0: number\n u1: number\n v0: number\n v1: number\n y0: number\n y1: number\n}\n\nconst volume = (b: Box): number => (b.u1 - b.u0) * (b.v1 - b.v0) * (b.y1 - b.y0)\nconst overlap = (a0: number, a1: number, b0: number, b1: number): number => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0))\n\nfunction tryMerge(a: Box, b: Box, gap: number, slack: number): Box | null {\n if (a.u0 - gap > b.u1 || b.u0 - gap > a.u1) return null\n if (a.v0 - gap > b.v1 || b.v0 - gap > a.v1) return null\n if (a.y0 - gap > b.y1 || b.y0 - gap > a.y1) return null\n const u0 = Math.min(a.u0, b.u0)\n const u1 = Math.max(a.u1, b.u1)\n const v0 = Math.min(a.v0, b.v0)\n const v1 = Math.max(a.v1, b.v1)\n const y0 = Math.min(a.y0, b.y0)\n const y1 = Math.max(a.y1, b.y1)\n const hull = (u1 - u0) * (v1 - v0) * (y1 - y0)\n const common = overlap(a.u0, a.u1, b.u0, b.u1) * overlap(a.v0, a.v1, b.v0, b.v1) * overlap(a.y0, a.y1, b.y0, b.y1)\n const real = volume(a) + volume(b) - common\n if (hull > real * (1 + slack) + 1e-9) return null\n return { ids: [...a.ids, ...b.ids], object: a.object, u0, u1, v0, v1, y0, y1 }\n}\n\n/**\n * Union overlapping or adjacent colliders of the same object (same rotation) into fewer OBBs.\n * A merge happens only when the merged box adds at most `slack` extra volume over the real union, so coverage is never lost\n * and never grows noticeably. Colliders of different objects or rotations are left alone.\n */\nexport function mergeColliders(list: WorldCollider[], options: Pick<ColliderOptions, 'gap' | 'slack'> = {}): WorldCollider[] {\n const gap = options.gap ?? 0.02\n const slack = options.slack ?? 0.1\n const groups = new Map<string, WorldCollider[]>()\n for (const c of list) {\n const key = `${c.object}|${Math.round(c.ry * 1000)}`\n const g = groups.get(key)\n if (g) g.push(c)\n else groups.set(key, [c])\n }\n const out: WorldCollider[] = []\n for (const g of groups.values()) {\n const ry = g[0]?.ry ?? 0\n const cs = Math.cos(ry)\n const sn = Math.sin(ry)\n let boxes: Box[] = g.map((c) => {\n const u = c.cx * cs - c.cz * sn\n const v = c.cx * sn + c.cz * cs\n return { ids: [c.id], object: c.object, u0: u - c.hw, u1: u + c.hw, v0: v - c.hd, v1: v + c.hd, y0: c.y0, y1: c.y1 }\n })\n let changed = boxes.length > 1\n while (changed) {\n changed = false\n outer: for (let i = 0; i < boxes.length; i++) {\n for (let j = i + 1; j < boxes.length; j++) {\n const m = tryMerge(boxes[i] as Box, boxes[j] as Box, gap, slack)\n if (!m) continue\n boxes = boxes.filter((_, k) => k !== i && k !== j)\n boxes.push(m)\n changed = true\n break outer\n }\n }\n }\n for (const b of boxes) {\n const u = (b.u0 + b.u1) / 2\n const v = (b.v0 + b.v1) / 2\n out.push({\n id: b.ids.length === 1 ? (b.ids[0] as string) : `${b.ids[0]}+${b.ids.length - 1}`,\n object: b.object,\n cx: u * cs + v * sn,\n cz: -u * sn + v * cs,\n hw: (b.u1 - b.u0) / 2,\n hd: (b.v1 - b.v0) / 2,\n ry,\n y0: b.y0,\n y1: b.y1,\n })\n }\n }\n return out\n}\n","/** FNV-1a hash of a string to a 32-bit unsigned integer. */\nexport function hashString(text: string): number {\n let h = 2166136261\n for (let i = 0; i < text.length; i++) {\n h ^= text.charCodeAt(i)\n h = Math.imul(h, 16777619)\n }\n return h >>> 0\n}\n\n/** Deterministic random generator (mulberry32). Returns a function producing floats in [0, 1). Numbers and strings are accepted as seeds. */\nexport function rng(seed: number | string = 1): () => number {\n let a = (typeof seed === 'number' ? Math.floor(seed) >>> 0 : hashString(seed)) || 0x9e3779b9\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n","import { rng } from './rng'\nimport type { ItemCatalog, ItemStack, LootTables, SlotSpec, Vec3 } from './types'\n\n/** True when an item of `size` [w, h, d] fits in a slot of `max`; width and depth may be swapped (the item is turned). */\nexport function fitsSize(size: Vec3, max: Vec3): boolean {\n const eps = 1e-9\n if (size[1] > max[1] + eps) return false\n return (size[0] <= max[0] + eps && size[2] <= max[2] + eps) || (size[2] <= max[0] + eps && size[0] <= max[2] + eps)\n}\n\n/** Does the item type fit the slot. Types missing from the catalog are accepted (the host owns unknown items). */\nexport function fitsSlot(type: string, slot: SlotSpec, items?: ItemCatalog): boolean {\n const def = items?.[type]\n return def ? fitsSize(def.size, slot.max) : true\n}\n\n/**\n * Deterministic contents for a container: one entry per slot. A slot is filled with probability `fill`; the entry is a weighted pick\n * among the table entries whose item fits the slot. Same seed, same table and same slots always give the same result.\n */\nexport function generateLoot(\n tables: LootTables | undefined,\n tableId: string,\n slots: SlotSpec[],\n seed: number | string,\n items?: ItemCatalog,\n): Array<ItemStack | null> {\n const table = tables?.[tableId]\n const out: Array<ItemStack | null> = slots.map(() => null)\n if (!table) return out\n const rand = rng(seed)\n slots.forEach((slot, i) => {\n // Always draw the same number of random values per slot so a change in one slot does not shift the others.\n const roll = rand()\n const pick = rand()\n const q = rand()\n if (roll >= table.fill) return\n const candidates = table.entries.filter((e) => e.weight > 0 && fitsSlot(e.type, slot, items))\n const total = candidates.reduce((s, e) => s + e.weight, 0)\n if (total <= 0) return\n let r = pick * total\n let chosen = candidates[candidates.length - 1]\n for (const e of candidates) {\n r -= e.weight\n if (r < 0) {\n chosen = e\n break\n }\n }\n const [lo, hi] = chosen.qty ?? [1, 1]\n const def = items?.[chosen.type]\n const stackMax = def ? (def.stack ?? 1) : Number.POSITIVE_INFINITY\n const qty = Math.max(1, Math.min(stackMax, lo + Math.floor(q * (hi - lo + 1))))\n out[i] = { type: chosen.type, qty }\n })\n return out\n}\n","import type { InteractablesLocale, Strings } from './types'\n\n/** Engine-level prompts and messages. Content packs add their own keys through `WorldOptions.strings`. */\nexport const locales: Record<InteractablesLocale, Strings> = {\n en: {\n 'prompt.open': 'Open {name}',\n 'prompt.close': 'Close {name}',\n 'prompt.turn_on': 'Turn on {name}',\n 'prompt.turn_off': 'Turn off {name}',\n 'prompt.take': 'Take',\n 'prompt.sit': 'Sit',\n 'prompt.lie_down': 'Lie down',\n 'prompt.get_up': 'Get up',\n 'prompt.light': 'Light',\n 'prompt.change_channel': 'Change channel',\n 'prompt.read': 'Read',\n 'prompt.breaker_on': 'Switch on {circuit}',\n 'prompt.breaker_off': 'Switch off {circuit}',\n 'prompt.main_on': 'Switch on the main breaker',\n 'prompt.main_off': 'Switch off the main breaker',\n 'prompt.open_valve': 'Open valve',\n 'prompt.close_valve': 'Close valve',\n no_power: 'No power',\n no_gas: 'No gas',\n no_water: 'No water',\n locked: 'Locked',\n requires_open: 'Open it first',\n already_lit: 'Already lit',\n needs_ignition: 'Light it first',\n turn_on_first: 'Turn it on first',\n empty: 'Empty',\n full: 'Full',\n 'use.put_in': 'Put {item} in {name}',\n 'use.put_in.none': 'Put what you hold in {name}',\n 'use.empty': 'Empty {name}',\n 'use.fill': 'Fill the {bowl} bowl',\n 'use.program.stop': 'Stop {name} ({left} left)',\n 'use.relieve.urine': 'Pee',\n 'use.relieve.feces': 'Poo',\n 'bowl.food': 'food',\n 'bowl.water': 'water',\n hand_empty: 'Your hand is empty',\n not_fit: '{item} does not fit in {name}',\n not_accepted: '{item} does not go in the {bowl} bowl',\n bowl_full: 'The {bowl} bowl is already full',\n needs_closed: 'Close it first',\n already_soiled: 'Flush first',\n done_put_in: '{item} went into {name}',\n done_empty: '{name} emptied ({n} things)',\n done_fill: 'The {bowl} bowl is full',\n done_program: '{name}: {program} started ({time})',\n done_program_end: '{name}: {program} finished',\n done_program_stop: '{name} stopped',\n done_relieve_urine: 'You peed in {name}',\n done_relieve_feces: 'You pooed in {name}',\n done_clean: '{name} flushed clean',\n 'use.wash_dishes': 'Wash the dishes',\n 'use.drink_water': 'Drink water',\n busy: 'Already in use',\n needs_running: 'Turn the water on first',\n needs_item: 'You need {need}',\n item_spent: '{item} is empty',\n no_dirty_dishes: 'No dirty dishes in the sink',\n started_wash: '{label}…',\n started_drink: '{label}…',\n done_wash: 'Washed and rinsed',\n done_wash_dishes: 'Dishes washed: {n} on the rack',\n done_drink: 'You drank {litres} l of water',\n },\n 'pt-BR': {\n 'prompt.open': 'Abrir {name}',\n 'prompt.close': 'Fechar {name}',\n 'prompt.turn_on': 'Ligar {name}',\n 'prompt.turn_off': 'Desligar {name}',\n 'prompt.take': 'Pegar',\n 'prompt.sit': 'Sentar',\n 'prompt.lie_down': 'Deitar',\n 'prompt.get_up': 'Levantar',\n 'prompt.light': 'Acender',\n 'prompt.change_channel': 'Trocar de canal',\n 'prompt.read': 'Ler',\n 'prompt.breaker_on': 'Ligar {circuit}',\n 'prompt.breaker_off': 'Desligar {circuit}',\n 'prompt.main_on': 'Ligar o disjuntor geral',\n 'prompt.main_off': 'Desligar o disjuntor geral',\n 'prompt.open_valve': 'Abrir registro',\n 'prompt.close_valve': 'Fechar registro',\n no_power: 'Sem energia',\n no_gas: 'Sem gás',\n no_water: 'Sem água',\n locked: 'Trancado',\n requires_open: 'Abra primeiro',\n already_lit: 'Já está aceso',\n needs_ignition: 'Acenda primeiro',\n turn_on_first: 'Ligue primeiro',\n empty: 'Vazio',\n full: 'Cheio',\n 'use.put_in': 'Pôr {item} em {name}',\n 'use.put_in.none': 'Pôr o que está na mão em {name}',\n 'use.empty': 'Esvaziar {name}',\n 'use.fill': 'Encher o pote de {bowl}',\n 'use.program.stop': 'Parar {name} (faltam {left})',\n 'use.relieve.urine': 'Fazer xixi (1)',\n 'use.relieve.feces': 'Fazer cocô (2)',\n 'bowl.food': 'ração',\n 'bowl.water': 'água',\n hand_empty: 'A mão está vazia',\n not_fit: '{item} não cabe em {name}',\n not_accepted: '{item} não vai no pote de {bowl}',\n bowl_full: 'O pote de {bowl} já está cheio',\n needs_closed: 'Feche primeiro',\n already_soiled: 'Dê a descarga primeiro',\n done_put_in: '{item} foi para dentro de {name}',\n done_empty: '{name} esvaziado ({n} coisas)',\n done_fill: 'O pote de {bowl} está cheio',\n done_program: '{name}: {program} começou ({time})',\n done_program_end: '{name}: {program} terminou',\n done_program_stop: '{name} parou',\n done_relieve_urine: 'Você fez xixi em {name}',\n done_relieve_feces: 'Você fez cocô em {name}',\n done_clean: 'Descarga dada: {name} limpo',\n 'use.wash_dishes': 'Lavar a louça',\n 'use.drink_water': 'Beber água',\n busy: 'Já está em uso',\n needs_running: 'Abra a água primeiro',\n needs_item: 'Precisa de {need}',\n item_spent: '{item} acabou',\n no_dirty_dishes: 'Não há louça suja na pia',\n started_wash: '{label}…',\n started_drink: '{label}…',\n done_wash: 'Lavado e enxaguado',\n done_wash_dishes: 'Louça lavada: {n} no escorredor',\n done_drink: 'Você bebeu {litres} l de água',\n },\n}\n\n/** Pick a built-in locale for an arbitrary tag (`pt`, `pt-br`, `en-GB`...). Unknown tags give `en`. */\nexport function pickLocale(locale: string | undefined): InteractablesLocale {\n if (!locale) return 'en'\n const l = locale.toLowerCase()\n if (l === 'pt-br' || l === 'pt') return 'pt-BR'\n return 'en'\n}\n\n/**\n * Merged table for a locale: built-in `en`, then the built-in table of `locale`, then the extra strings for `en` and for `locale`.\n * Lookup therefore falls back to English, and the caller never gets undefined for engine keys.\n */\nexport function resolveStrings(locale?: string, extra?: Partial<Record<InteractablesLocale, Strings>>): Strings {\n const loc = pickLocale(locale)\n return { ...locales.en, ...locales[loc], ...(extra?.en ?? {}), ...(loc === 'en' ? {} : (extra?.[loc] ?? {})) }\n}\n\n/** Replace `{name}` placeholders. Unknown placeholders are left untouched. */\nexport function format(text: string, vars?: Record<string, string | number>): string {\n if (!vars) return text\n return text.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m))\n}\n","import type { Motion, Transform, Vec3 } from './types'\n\nexport interface Pose {\n /** Translation relative to the pivot. */\n position: Vec3\n /** Rotation around `axis` (in the part frame) by `angle` radians. */\n rotation: { axis: Vec3; angle: number }\n scale: Vec3\n}\n\nconst DEFAULT_AXIS: Vec3 = [0, 1, 0]\n\n/**\n * Pose of a part at animation value `t` (0..1), relative to its pivot, so any renderer can apply it:\n * `position`, then `rotation` around the pivot, then `scale` along the axis.\n */\nexport function poseOf(motion: Motion, t: number): Pose {\n const tt = Math.max(0, Math.min(1, t))\n const axis = motion.axis ?? DEFAULT_AXIS\n const pose: Pose = { position: [0, 0, 0], rotation: { axis: [axis[0], axis[1], axis[2]], angle: 0 }, scale: [1, 1, 1] }\n switch (motion.kind) {\n case 'hinge':\n case 'rocker':\n case 'knob':\n pose.rotation.angle = (motion.angle ?? Math.PI / 2) * tt\n break\n case 'slide': {\n const d = (motion.distance ?? 0.4) * tt\n pose.position = [axis[0] * d, axis[1] * d, axis[2] * d]\n break\n }\n case 'scale': {\n const k = 1 + ((motion.scale ?? 0.2) - 1) * tt\n pose.scale = [axis[0] !== 0 ? k : 1, axis[1] !== 0 ? k : 1, axis[2] !== 0 ? k : 1]\n break\n }\n }\n return pose\n}\n\n/** Rotate a vector around +y by `ry` radians (same convention as three.js `rotation.y`). */\nexport function rotY(v: Vec3, ry: number): Vec3 {\n const c = Math.cos(ry)\n const s = Math.sin(ry)\n return [c * v[0] + s * v[2], v[1], -s * v[0] + c * v[2]]\n}\n\n/** Object-local point to world space. */\nexport function localToWorld(transform: Transform, v: Vec3): Vec3 {\n const r = rotY(v, transform.ry)\n return [transform.x + r[0], transform.y + r[1], transform.z + r[2]]\n}\n\n/** World point to object-local space. */\nexport function worldToLocal(transform: Transform, v: Vec3): Vec3 {\n return rotY([v[0] - transform.x, v[1] - transform.y, v[2] - transform.z], -transform.ry)\n}\n\n/** Rodrigues rotation of `v` around a unit-length-normalised `axis` by `angle`. */\nexport function rotateAxis(v: Vec3, axis: Vec3, angle: number): Vec3 {\n const len = Math.hypot(axis[0], axis[1], axis[2]) || 1\n const k: Vec3 = [axis[0] / len, axis[1] / len, axis[2] / len]\n const c = Math.cos(angle)\n const s = Math.sin(angle)\n const dot = k[0] * v[0] + k[1] * v[1] + k[2] * v[2]\n const cross: Vec3 = [k[1] * v[2] - k[2] * v[1], k[2] * v[0] - k[0] * v[2], k[0] * v[1] - k[1] * v[0]]\n return [v[0] * c + cross[0] * s + k[0] * dot * (1 - c), v[1] * c + cross[1] * s + k[1] * dot * (1 - c), v[2] * c + cross[2] * s + k[2] * dot * (1 - c)]\n}\n\nexport function clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v\n}\n\nexport function dist3(a: Vec3, b: Vec3): number {\n return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2])\n}\n","import { FLUSH_RUN_SECONDS } from './fixture-emitters'\nimport { mergeColliders } from './colliders'\nimport { fitsSlot, generateLoot } from './loot'\nimport { format, resolveStrings } from './locale'\nimport type { PartDriver, SoftDriver } from './part-physics'\nimport { clamp, dist3, localToWorld, rotateAxis, rotY, worldToLocal } from './math'\nimport type {\n ActiveEmitter,\n BurnerSpec,\n ColliderOptions,\n DeviceSpec,\n FixtureSpec,\n FuelSourceSpec,\n Interactable,\n InteractionSpec,\n ItemStack,\n ObjectSpec,\n PartSpec,\n SeatResult,\n SoftSpec,\n TankSpec,\n TargetOptions,\n Transform,\n Vec3,\n World,\n WorldCollider,\n WorldEvent,\n WorldObject,\n WorldOptions,\n WorldState,\n} from './types'\n\n// ---------------------------------------------------------------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------------------------------------------------------------\n\nconst DEFAULT_ACTOR = 'player'\nconst DEFAULT_RADIUS = 1.2\n/** Local id prefix of the `take` a stack in an open container offers (`<object>:take.<container>.<slot>`). */\nconst TAKE_PREFIX = 'take.'\n/** Reach radius of one contained item, metres. */\nconst TAKE_RADIUS = 0.6\nconst AUTO_RANGE = 2\n/** How far behind a socket's face (m) a plug may be and still take it: a plug on the wall's other side is a wall's thickness (10 cm or more) behind it. */\nconst SOCKET_BEHIND = 0.05\nconst SMOKE_TAIL = 20\nconst FLUSH_SECONDS = FLUSH_RUN_SECONDS\nconst ACTOR_HEIGHT = 1.7\nconst PUSH_GAIN = 1.2\nconst SWEEP_STEPS = 24\nexport const FLOW_DEFAULTS: Readonly<Record<string, number>> = { tap: 6, shower: 8, utility_sink: 6, flush: 0, hose: 10, filter: 1 }\n\n// ---------------------------------------------------------------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------------------------------------------------------------\n\ninterface PartState {\n spec: PartSpec\n t: number\n target: number\n maxT: number\n /** With `WorldOptions.partPhysics`: the engine moves the part, and `t` is read from it. */\n driver?: PartDriver\n /** The target the driver was last told (`aim`). */\n commanded?: number\n /** The driver is going to a target: arriving reports the part event. */\n moving?: boolean\n broken?: boolean\n}\n\ninterface DeviceState {\n spec: DeviceSpec\n on: boolean\n channel: number\n}\n\ninterface FuelState {\n spec: FuelSourceSpec\n level: number\n}\n\ninterface BurnerState {\n spec: BurnerSpec\n on: boolean\n lit: boolean\n /** Seconds of smoke left after a solid-fuel fire went out. */\n smoke: number\n}\n\ninterface TankState {\n spec: TankSpec\n level: number\n}\n\ninterface FixtureState {\n spec: FixtureSpec\n on: boolean\n flowing: boolean\n /** Delivered / wanted in the last step, 0..1. */\n frac: number\n /** Seconds left of a flush. */\n timer: number\n}\n\ninterface SoftState {\n spec: SoftSpec\n ax: number\n az: number\n vax: number\n vaz: number\n phase: number\n /** With `WorldOptions.partPhysics`: the engine swings the volume (the spring is not used). */\n driver?: SoftDriver\n}\n\ninterface DamageState {\n max: number\n hp: number\n}\n\ninterface ObjState {\n id: string\n public: WorldObject\n spec: ObjectSpec\n parts: Map<string, PartState>\n contents: Map<string, Array<ItemStack | null>>\n devices: Map<string, DeviceState>\n fuels: Map<string, FuelState>\n burners: Map<string, BurnerState>\n tanks: Map<string, TankState>\n fixtures: Map<string, FixtureState>\n soft: Map<string, SoftState>\n hp: Map<string, DamageState>\n interactions: InteractionSpec[]\n}\n\nfunction cloneStack(s: ItemStack | null): ItemStack | null {\n return s ? { type: s.type, qty: s.qty, ...(s.data ? { data: JSON.parse(JSON.stringify(s.data)) as Record<string, unknown> } : {}) } : null\n}\n\nfunction humanize(id: string): string {\n const s = id.replace(/[_-]+/g, ' ').trim()\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\n// ---------------------------------------------------------------------------------------------------------------------------------\n// World\n// ---------------------------------------------------------------------------------------------------------------------------------\n\nexport function createWorld(options: WorldOptions = {}): World {\n const seed = options.seed ?? 1\n const objs = new Map<string, ObjState>()\n const breakers = new Map<string, boolean>()\n const seats = new Map<string, { object: string; seat: string }>()\n const plugs = new Map<string, string | null>()\n let locale = options.locale ?? 'en'\n let table = resolveStrings(locale, options.strings)\n let grid = options.grid ?? true\n // the main breaker of the service entrance, after the meter: off, nothing of the building has power whatever the grid and its circuits say\n let main = true\n let rain = options.rain ?? 0\n let wind: [number, number] = options.wind ? [options.wind[0], options.wind[1]] : [0, 0]\n let defaultTank: string | null = null\n let defaultTankExplicit = false\n let time = 0\n\n // ------------------------------------------------------------------ text & events\n function t(key: string, vars?: Record<string, string | number>): string {\n return format(table[key] ?? key, vars)\n }\n\n function emit(e: WorldEvent): void {\n options.onEvent?.(e)\n }\n\n function message(key: string): void {\n emit({ type: 'message', key, text: t(key) })\n }\n\n // ------------------------------------------------------------------ lookup helpers\n function gid(o: ObjState, local: string): string {\n return `${o.id}:${local}`\n }\n\n /** Find the first entity matching a world-wide id `objectId:localId`. */\n function findGlobal<T>(id: string, pick: (o: ObjState, local: string) => T | undefined): { o: ObjState; value: T; local: string } | null {\n for (const o of objs.values()) {\n if (!id.startsWith(o.id + ':')) continue\n const local = id.slice(o.id.length + 1)\n const value = pick(o, local)\n if (value !== undefined) return { o, value, local }\n }\n return null\n }\n\n function objectOrThrow(id: string): ObjState {\n const o = objs.get(id)\n if (!o) throw new Error(`Unknown object \"${id}\"`)\n return o\n }\n\n function originOf(o: ObjState): Vec3 {\n const tr = o.public.transform\n return [tr.x, tr.y, tr.z]\n }\n\n function toWorld(o: ObjState, v: Vec3): Vec3 {\n return localToWorld(o.public.transform, v)\n }\n\n // ------------------------------------------------------------------ parts\n function openThreshold(p: PartState): number {\n return Math.min(0.5, p.maxT * 0.9)\n }\n\n function isOpen(o: ObjState, partId: string | undefined): boolean {\n if (!partId) return true\n const p = o.parts.get(partId)\n if (!p) return true\n return p.maxT >= 0.1 && p.t >= openThreshold(p)\n }\n\n function targetIsOpen(p: PartState): boolean {\n return p.maxT >= 0.1 && p.target >= openThreshold(p)\n }\n\n function writeT(o: ObjState, p: PartState, v: number): void {\n p.t = v\n o.public.parts[p.spec.id] = v\n }\n\n function gated(o: ObjState, p: PartState): boolean {\n return !!p.spec.requires && o.parts.has(p.spec.requires) && !isOpen(o, p.spec.requires)\n }\n\n function setOnePart(o: ObjState, p: PartState, target: number, instant: boolean): void {\n const next = clamp(target, 0, p.maxT)\n const changed = next !== p.target\n p.target = next\n if (instant) {\n p.driver?.snap(next)\n p.commanded = next\n writeT(o, p, next)\n }\n if (changed || instant) emit({ type: 'part', object: o.id, part: p.spec.id, t: p.t, target: p.target })\n }\n\n function setPartTarget(o: ObjState, partId: string, target: number, instant = false): void {\n const p = o.parts.get(partId)\n if (!p) return\n const group = p.spec.group\n const members = group ? [...o.parts.values()].filter((q) => q.spec.group === group) : [p]\n for (const q of members) {\n setOne(o, q, target, instant)\n }\n }\n\n function setOne(o: ObjState, p: PartState, target: number, instant: boolean): void {\n setOnePart(o, p, target, instant)\n // a part that other parts require closes them with it (the drawer behind a door closes with the door)\n if (!targetIsOpen(p)) {\n for (const q of o.parts.values()) {\n if (q.spec.requires === p.spec.id && q.target > 0) setPartTarget(o, q.spec.id, 0, instant)\n }\n }\n }\n\n /** Frame of a part right now: rotation (axis in object-local, angle) and translation, both about its pivot. */\n function partFrame(o: ObjState, partId: string | undefined): { pivot: Vec3; axis: Vec3; angle: number; offset: Vec3 } | null {\n if (!partId) return null\n const p = o.parts.get(partId)\n if (!p) return null\n const m = p.spec.motion\n const axis = rotY(m.axis ?? [0, 1, 0], p.spec.ry ?? 0)\n const frame = { pivot: p.spec.pivot, axis, angle: 0, offset: [0, 0, 0] as Vec3 }\n if (m.kind === 'slide') {\n const d = (m.distance ?? 0.4) * p.t\n frame.offset = [axis[0] * d, axis[1] * d, axis[2] * d]\n } else if (m.kind !== 'scale') {\n frame.angle = (m.angle ?? Math.PI / 2) * p.t\n }\n return frame\n }\n\n function applyPart(o: ObjState, partId: string | undefined, local: Vec3): Vec3 {\n const f = partFrame(o, partId)\n if (!f) return local\n const rel: Vec3 = [local[0] - f.pivot[0], local[1] - f.pivot[1], local[2] - f.pivot[2]]\n const r = f.angle !== 0 ? rotateAxis(rel, f.axis, f.angle) : rel\n return [f.pivot[0] + r[0] + f.offset[0], f.pivot[1] + r[1] + f.offset[1], f.pivot[2] + r[2] + f.offset[2]]\n }\n\n /** Moves the full closed-pose slab of a part and returns the largest t whose pose keeps every sampled point clear. */\n function fitBounds(o: ObjState, p: PartState, b: NonNullable<PartSpec['bounds']>, blockedAt: (x: number, z: number) => boolean): number {\n const STEP = 0.05\n const ANGLES = 48\n const m = p.spec.motion\n const axis = rotY(m.axis ?? [0, 1, 0], p.spec.ry ?? 0)\n const lo: Vec3 = [Math.min(b[0], b[3]), Math.min(b[1], b[4]), Math.min(b[2], b[5])]\n const hi: Vec3 = [Math.max(b[0], b[3]), Math.max(b[1], b[4]), Math.max(b[2], b[5])]\n const axisPoints = (i: number): number[] => {\n const n = Math.max(1, Math.ceil((hi[i] - lo[i]) / STEP))\n return Array.from({ length: n + 1 }, (_, k) => lo[i] + ((hi[i] - lo[i]) * k) / n)\n }\n const xs = axisPoints(0)\n const ys = axisPoints(1)\n const zs = axisPoints(2)\n // `blocked` only sees x/z, so only the floor footprint matters. About a vertical axis (and for slides) y never changes\n // the footprint, so the x/z outline is enough; otherwise the footprint boundary is the projection of the box edges.\n const flat = m.kind === 'slide' || Math.abs(axis[1]) > 0.999\n const seen = new Set<string>()\n const pts: Vec3[] = []\n const add = (x: number, y: number, z: number): void => {\n const key = `${x.toFixed(5)},${y.toFixed(5)},${z.toFixed(5)}`\n if (seen.has(key)) return\n seen.add(key)\n pts.push([x, y, z])\n }\n if (flat) {\n for (const x of xs) for (const z of [lo[2], hi[2]]) add(x, lo[1], z)\n for (const z of zs) for (const x of [lo[0], hi[0]]) add(x, lo[1], z)\n } else {\n for (const x of xs) for (const y of [lo[1], hi[1]]) for (const z of [lo[2], hi[2]]) add(x, y, z)\n for (const y of ys) for (const x of [lo[0], hi[0]]) for (const z of [lo[2], hi[2]]) add(x, y, z)\n for (const z of zs) for (const x of [lo[0], hi[0]]) for (const y of [lo[1], hi[1]]) add(x, y, z)\n }\n const tr = o.public.transform\n const pivot = p.spec.pivot\n for (let i = 1; i <= ANGLES; i++) {\n const tt = i / ANGLES\n const angle = m.kind === 'slide' ? 0 : (m.angle ?? Math.PI / 2) * tt\n const d = m.kind === 'slide' ? (m.distance ?? 0.4) * tt : 0\n for (const [x, y, z] of pts) {\n let q: Vec3 = [x, y, z]\n if (angle !== 0) {\n const r = rotateAxis([x - pivot[0], y - pivot[1], z - pivot[2]], axis, angle)\n q = [pivot[0] + r[0], pivot[1] + r[1], pivot[2] + r[2]]\n }\n const w = localToWorld(tr, [q[0] + axis[0] * d, 0, q[2] + axis[2] * d])\n if (blockedAt(w[0], w[2])) return (i - 1) / ANGLES\n }\n }\n return 1\n }\n\n function fitSweep(objectId: string, partId: string, blocked: (x: number, z: number) => boolean): number {\n const o = objectOrThrow(objectId)\n const p = o.parts.get(partId)\n if (!p) throw new Error(`Unknown part \"${partId}\" on \"${objectId}\"`)\n const sweep = p.spec.sweep\n let result = 1\n const bounds = p.spec.bounds\n const mk = p.spec.motion.kind\n if (bounds && (mk === 'hinge' || mk === 'rocker' || mk === 'knob' || mk === 'slide')) {\n result = fitBounds(o, p, bounds, blocked)\n } else if (sweep) {\n const x0 = Math.min(sweep[0], sweep[2])\n const x1 = Math.max(sweep[0], sweep[2])\n const z0 = Math.min(sweep[1], sweep[3])\n const z1 = Math.max(sweep[1], sweep[3])\n const tr = o.public.transform\n const hit = (lx: number, lz: number): boolean => {\n const w = localToWorld(tr, [lx, 0, lz])\n return blocked(w[0], w[2])\n }\n const m = p.spec.motion\n const axis = rotY(m.axis ?? [0, 1, 0], p.spec.ry ?? 0)\n if (m.kind === 'hinge' || m.kind === 'rocker' || m.kind === 'knob') {\n if (Math.abs(axis[1]) >= 0.5) {\n const angle = m.angle ?? Math.PI / 2\n const total = -angle * Math.sign(axis[1])\n const [px, , pz] = p.spec.pivot\n const cx = (x0 + x1) / 2\n const cz = (z0 + z1) / 2\n const w = x1 - x0\n const d = z1 - z0\n const radius = Math.abs(angle) > 1.7 ? Math.min(w, d) : Math.max(w, d)\n const tol = 0.05\n const inRect = (x: number, z: number) => x >= x0 - tol && x <= x1 + tol && z >= z0 - tol && z <= z1 + tol\n const centered = Math.hypot(cx - px, cz - pz) < 1e-6\n const mid = Math.atan2(cz - pz, cx - px)\n for (let i = 1; i <= SWEEP_STEPS && result === 1; i++) {\n const tt = i / SWEEP_STEPS\n let isHit = false\n if (centered) {\n for (let x = x0; x <= x1 + 1e-9 && !isHit; x += 0.1) for (let z = z0; z <= z1 + 1e-9 && !isHit; z += 0.1) isHit = hit(x, z)\n } else {\n const phi = mid - total / 2 + total * tt\n const steps = Math.max(2, Math.ceil(radius / 0.1))\n for (let k = 1; k <= steps && !isHit; k++) {\n const r = (radius * k) / steps\n const x = px + Math.cos(phi) * r\n const z = pz + Math.sin(phi) * r\n if (inRect(x, z)) isHit = hit(x, z)\n }\n }\n if (isHit) result = (i - 1) / SWEEP_STEPS\n }\n }\n } else if (m.kind === 'slide') {\n const len = Math.hypot(axis[0], axis[2])\n if (len > 1e-6) {\n const dx = axis[0] / len\n const dz = axis[2] / len\n const proj = [x0 * dx + z0 * dz, x1 * dx + z0 * dz, x0 * dx + z1 * dz, x1 * dx + z1 * dz]\n const pmin = Math.min(...proj)\n const pmax = Math.max(...proj)\n const nx = Math.max(1, Math.ceil((x1 - x0) / 0.1))\n const nz = Math.max(1, Math.ceil((z1 - z0) / 0.1))\n for (let i = 1; i <= SWEEP_STEPS && result === 1; i++) {\n const limit = pmin + (pmax - pmin) * (i / SWEEP_STEPS)\n let isHit = false\n for (let a = 0; a <= nx && !isHit; a++) {\n for (let b = 0; b <= nz && !isHit; b++) {\n const x = x0 + ((x1 - x0) * a) / nx\n const z = z0 + ((z1 - z0) * b) / nz\n if (x * dx + z * dz <= limit + 1e-9 && hit(x, z)) isHit = true\n }\n }\n if (isHit) result = (i - 1) / SWEEP_STEPS\n }\n }\n }\n }\n p.maxT = result\n if (p.target > result) p.target = result\n if (p.t > result) writeT(o, p, result)\n return result\n }\n\n // ------------------------------------------------------------------ containers\n function containerOf(o: ObjState, id: string) {\n return o.spec.containers?.find((c) => c.id === id)\n }\n\n function accessible(objectId: string, containerId: string): boolean {\n const o = objs.get(objectId)\n if (!o) return false\n const c = containerOf(o, containerId)\n if (!c) return false\n return isOpen(o, c.access)\n }\n\n function contents(objectId: string, containerId: string): Array<ItemStack | null> {\n return (objs.get(objectId)?.contents.get(containerId) ?? []).map(cloneStack)\n }\n\n function take(objectId: string, containerId: string, slot: number, actor: string = DEFAULT_ACTOR): ItemStack | null {\n const o = objs.get(objectId)\n if (!o) return null\n const list = o.contents.get(containerId)\n if (!list || !accessible(objectId, containerId)) return null\n const stack = list[slot]\n if (!stack) return null\n const def = options.items?.[stack.type]\n if (def && def.pickable === false) return null\n list[slot] = null\n emit({ type: 'pickup', object: objectId, container: containerId, slot, stack: cloneStack(stack) as ItemStack, actor })\n return stack\n }\n\n function put(objectId: string, containerId: string, stack: ItemStack): number | null {\n const o = objs.get(objectId)\n if (!o) return null\n const c = containerOf(o, containerId)\n const list = o.contents.get(containerId)\n if (!c || !list || !accessible(objectId, containerId)) return null\n const maxStack = options.items?.[stack.type]?.stack ?? 1\n for (let i = 0; i < list.length; i++) {\n const cur = list[i]\n if (cur && cur.type === stack.type && !cur.data && !stack.data && cur.qty + stack.qty <= maxStack) {\n cur.qty += stack.qty\n return i\n }\n }\n for (let i = 0; i < list.length; i++) {\n if (!list[i] && fitsSlot(stack.type, c.slots[i], options.items)) {\n list[i] = cloneStack(stack)\n return i\n }\n }\n message('full')\n return null\n }\n\n function slotPosition(objectId: string, containerId: string, slot: number): Vec3 {\n const o = objectOrThrow(objectId)\n const c = containerOf(o, containerId)\n const s = c?.slots[slot]\n if (!c || !s) throw new Error(`Unknown slot ${slot} of \"${containerId}\" on \"${objectId}\"`)\n return toWorld(o, applyPart(o, s.part, s.pos))\n }\n\n // ------------------------------------------------------------------ power\n function rebuildPlugs(): void {\n plugs.clear()\n const sockets: Array<{ id: string; pos: Vec3; circuit?: string; local: string; facing: Vec3 }> = []\n for (const o of objs.values()) {\n for (const s of o.spec.sockets ?? []) {\n const pos = toWorld(o, s.pos)\n const ahead = toWorld(o, [s.pos[0], s.pos[1], s.pos[2] + 1])\n sockets.push({ id: gid(o, s.id), local: s.id, pos, circuit: s.circuit, facing: [ahead[0] - pos[0], ahead[1] - pos[1], ahead[2] - pos[2]] })\n }\n }\n const used = new Set<string>()\n const autos: Array<{ o: ObjState; d: DeviceState }> = []\n for (const o of objs.values()) {\n for (const d of o.devices.values()) {\n const key = gid(o, d.spec.id)\n const want = d.spec.socket\n if (want === undefined || d.spec.circuit) {\n plugs.set(key, null)\n } else if (want === 'auto') {\n plugs.set(key, null)\n autos.push({ o, d })\n } else {\n const s = sockets.find((x) => x.id === want) ?? sockets.find((x) => x.id === gid(o, want)) ?? sockets.find((x) => x.local === want)\n plugs.set(key, s ? s.id : null)\n if (s) used.add(s.id)\n }\n }\n }\n for (const { o, d } of autos) {\n const from = d.spec.plug ? toWorld(o, d.spec.plug) : originOf(o)\n let best: (typeof sockets)[number] | null = null\n let bestD = AUTO_RANGE\n for (const s of sockets) {\n if (used.has(s.id)) continue\n // a socket faces out of its wall (+z): a plug behind its face is on the wall's other side, in the next room, and its cord would cross the wall\n if ((from[0] - s.pos[0]) * s.facing[0] + (from[1] - s.pos[1]) * s.facing[1] + (from[2] - s.pos[2]) * s.facing[2] < -SOCKET_BEHIND) continue\n const dd = dist3(from, s.pos)\n if (dd <= bestD) {\n best = s\n bestD = dd\n }\n }\n if (best) {\n used.add(best.id)\n plugs.set(gid(o, d.spec.id), best.id)\n }\n }\n }\n\n function breaker(circuit: string): boolean {\n return breakers.get(circuit) ?? true\n }\n\n function devicePowered(o: ObjState, d: DeviceState): boolean {\n if (d.spec.electric === false) return true\n if (!grid || !main) return false\n if (d.spec.circuit) return breaker(d.spec.circuit)\n if (d.spec.socket === undefined) return false\n const sid = plugs.get(gid(o, d.spec.id))\n if (!sid) return false\n const found = findGlobal(sid, (oo, local) => oo.spec.sockets?.find((s) => s.id === local))\n if (!found) return false\n return found.value.circuit ? breaker(found.value.circuit) : true\n }\n\n function getDevice(objectId: string, deviceId: string): { o: ObjState; d: DeviceState } | null {\n const o = objs.get(objectId)\n const d = o?.devices.get(deviceId)\n return o && d ? { o, d } : null\n }\n\n function powerSnapshot(): Map<string, boolean> {\n const m = new Map<string, boolean>()\n for (const o of objs.values()) for (const d of o.devices.values()) m.set(gid(o, d.spec.id), d.on && devicePowered(o, d))\n return m\n }\n\n function emitPowerChanges(before: Map<string, boolean>): void {\n for (const o of objs.values()) {\n for (const d of o.devices.values()) {\n const key = gid(o, d.spec.id)\n const now = d.on && devicePowered(o, d)\n if (before.get(key) !== now && d.on) emit({ type: 'device', object: o.id, device: d.spec.id, on: d.on, powered: devicePowered(o, d), channel: d.spec.kind === 'screen' ? d.channel : undefined })\n }\n }\n }\n\n function setDeviceOn(o: ObjState, d: DeviceState, on: boolean): void {\n d.on = on\n if (d.spec.part) setPartTarget(o, d.spec.part, on ? 1 : 0)\n const powered = devicePowered(o, d)\n emit({ type: 'device', object: o.id, device: d.spec.id, on, powered, channel: d.spec.kind === 'screen' ? d.channel : undefined })\n if (on && !powered) message('no_power')\n }\n\n function setDevice(objectId: string, deviceId: string, on: boolean): boolean {\n const f = getDevice(objectId, deviceId)\n if (!f) return false\n if (f.d.on !== on) setDeviceOn(f.o, f.d, on)\n return true\n }\n\n function setFixture(objectId: string, fixtureId: string, on: boolean): boolean {\n const fx = objs.get(objectId)?.fixtures.get(fixtureId)\n if (!fx) return false\n if (fx.on !== on) toggleFixture(objs.get(objectId) as ObjState, fixtureId)\n return fx.on === on\n }\n\n function setBurner(objectId: string, burnerId: string, on: boolean): boolean {\n const o = objs.get(objectId)\n const b = o?.burners.get(burnerId)\n if (!o || !b) return false\n const isOn = b.on || b.lit\n if (on === isOn) return true\n if (!on) return toggleBurner(o, burnerId)\n return b.spec.needsIgnition ? ignite(o, burnerId) : toggleBurner(o, burnerId)\n }\n\n function resolveDevice(o: ObjState, id: string): { o: ObjState; d: DeviceState } | null {\n if (id.includes(':')) {\n const f = findGlobal(id, (oo, local) => oo.devices.get(local))\n return f ? { o: f.o, d: f.value } : null\n }\n const local = o.devices.get(id)\n if (local) return { o, d: local }\n for (const oo of objs.values()) {\n const d = oo.devices.get(id)\n if (d) return { o: oo, d }\n }\n return null\n }\n\n function switchIsOn(o: ObjState, spec: { part?: string; controls: string[] }): boolean {\n if (spec.part && o.parts.has(spec.part)) return targetIsOpen(o.parts.get(spec.part) as PartState)\n return spec.controls.some((id) => resolveDevice(o, id)?.d.on)\n }\n\n function toggleSwitch(o: ObjState, id: string): boolean {\n const sw = o.spec.switches?.find((s) => s.id === id)\n if (!sw) return false\n const on = !switchIsOn(o, sw)\n if (sw.part) setPartTarget(o, sw.part, on ? 1 : 0)\n let unpowered = false\n for (const ref of sw.controls) {\n const r = resolveDevice(o, ref)\n if (!r) continue\n r.d.on = on\n if (r.d.spec.part) setPartTarget(r.o, r.d.spec.part, on ? 1 : 0)\n const powered = devicePowered(r.o, r.d)\n if (on && !powered) unpowered = true\n emit({ type: 'device', object: r.o.id, device: r.d.spec.id, on, powered })\n }\n emit({ type: 'switch', object: o.id, switch: sw.id, on })\n if (unpowered) message('no_power')\n return true\n }\n\n // ------------------------------------------------------------------ fuel\n function resolveFuel(o: ObjState, b: BurnerState): { o: ObjState; f: FuelState } | null {\n const want = b.spec.fuel\n if (want === 'auto') {\n const from = toWorld(o, b.spec.pos)\n let best: { o: ObjState; f: FuelState } | null = null\n let bestD = AUTO_RANGE\n for (const oo of objs.values()) {\n for (const f of oo.fuels.values()) {\n if (f.spec.kind !== 'gas') continue\n const d = dist3(from, originOf(oo))\n if (d <= bestD) {\n best = { o: oo, f }\n bestD = d\n }\n }\n }\n return best\n }\n if (want.includes(':')) {\n const f = findGlobal(want, (oo, local) => oo.fuels.get(local))\n return f ? { o: f.o, f: f.value } : null\n }\n const local = o.fuels.get(want)\n return local ? { o, f: local } : null\n }\n\n function valveOpen(o: ObjState, f: FuelState): boolean {\n const v = f.spec.valve\n if (!v || !o.parts.has(v)) return true\n return targetIsOpen(o.parts.get(v) as PartState)\n }\n\n function canBurn(b: BurnerState, ref: { o: ObjState; f: FuelState } | null): boolean {\n return !!ref && ref.f.level > 0 && valveOpen(ref.o, ref.f)\n }\n\n function isSolid(ref: { f: FuelState } | null): boolean {\n return !!ref && ref.f.spec.kind !== 'gas'\n }\n\n function emitBurner(o: ObjState, b: BurnerState): void {\n emit({ type: 'burner', object: o.id, burner: b.spec.id, on: b.on, lit: b.lit })\n }\n\n function extinguish(o: ObjState, b: BurnerState, turnOff: boolean): void {\n const ref = resolveFuel(o, b)\n const wasLit = b.lit\n b.lit = false\n if (turnOff) b.on = false\n if (b.spec.part) setPartTarget(o, b.spec.part, b.on ? 1 : 0)\n if (wasLit && isSolid(ref)) b.smoke = SMOKE_TAIL\n emitBurner(o, b)\n }\n\n function toggleBurner(o: ObjState, id: string): boolean {\n const b = o.burners.get(id)\n if (!b) return false\n if (b.on || b.lit) {\n extinguish(o, b, true)\n return true\n }\n if (b.spec.needsIgnition) return false\n const ref = resolveFuel(o, b)\n b.on = true\n b.lit = canBurn(b, ref)\n if (b.lit) b.smoke = 0\n if (b.spec.part) setPartTarget(o, b.spec.part, 1)\n emitBurner(o, b)\n if (!b.lit) message(ref && ref.f.level <= 0 ? 'empty' : 'no_gas')\n return true\n }\n\n function ignite(o: ObjState, id: string): boolean {\n const b = o.burners.get(id)\n if (!b || b.lit) return false\n const ref = resolveFuel(o, b)\n if (!canBurn(b, ref)) {\n message(ref && ref.f.level <= 0 ? 'empty' : 'no_gas')\n return false\n }\n b.on = true\n b.lit = true\n b.smoke = 0\n if (b.spec.part) setPartTarget(o, b.spec.part, 1)\n emitBurner(o, b)\n return true\n }\n\n function toggleFuel(o: ObjState, id: string): boolean {\n const f = o.fuels.get(id)\n if (!f || !f.spec.valve || !o.parts.has(f.spec.valve)) return false\n const p = o.parts.get(f.spec.valve) as PartState\n setPartTarget(o, f.spec.valve, targetIsOpen(p) ? 0 : 1)\n return true\n }\n\n // ------------------------------------------------------------------ water\n function resolveTank(o: ObjState, id: string | undefined): { o: ObjState; t: TankState } | null {\n const want = id === undefined || id === 'auto' ? defaultTank : id\n if (!want) return null\n const f = findGlobal(want, (oo, local) => oo.tanks.get(local))\n if (f) return { o: f.o, t: f.value }\n const local = o.tanks.get(want)\n return local ? { o, t: local } : null\n }\n\n function drawWater(o: ObjState, fx: FixtureState, liters: number): number {\n if (liters <= 0) return 0\n if (options.waterSupply) return Math.max(0, Math.min(liters, options.waterSupply.draw(gid(o, fx.spec.id), liters)))\n const tank = resolveTank(o, fx.spec.tank)\n if (!tank) return 0\n const got = Math.min(liters, tank.t.level)\n tank.t.level -= got\n return got\n }\n\n function emitFixture(o: ObjState, fx: FixtureState): void {\n emit({ type: 'fixture', object: o.id, fixture: fx.spec.id, on: fx.on, flowing: fx.flowing })\n }\n\n function flowOf(fx: FixtureState): number {\n return fx.spec.flow ?? FLOW_DEFAULTS[fx.spec.kind] ?? 6\n }\n\n function stepFixture(o: ObjState, fx: FixtureState, dt: number): void {\n if (!fx.on) return\n if (fx.spec.kind === 'flush') {\n fx.timer -= dt\n if (fx.timer <= 0) {\n fx.on = false\n fx.flowing = false\n fx.frac = 0\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 0)\n emitFixture(o, fx)\n }\n return\n }\n if (dt <= 0) return\n const wanted = (flowOf(fx) / 60) * dt\n const got = drawWater(o, fx, wanted)\n const flowing = got > 1e-9\n fx.frac = wanted > 0 ? Math.min(1, got / wanted) : 0\n if (flowing !== fx.flowing) {\n fx.flowing = flowing\n emitFixture(o, fx)\n }\n }\n\n function toggleFixture(o: ObjState, id: string): boolean {\n const fx = o.fixtures.get(id)\n if (!fx) return false\n if (fx.on) {\n fx.on = false\n fx.flowing = false\n fx.frac = 0\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 0)\n emitFixture(o, fx)\n return true\n }\n fx.on = true\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 1)\n if (fx.spec.kind === 'flush') {\n const volume = fx.spec.volume ?? 6\n const got = drawWater(o, fx, volume)\n fx.flowing = got > 1e-9\n fx.frac = fx.flowing ? 1 : 0\n fx.timer = FLUSH_SECONDS\n if (!fx.flowing) {\n fx.on = false\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 0)\n }\n } else {\n fx.flowing = false\n fx.frac = 0\n stepFixture(o, fx, 1 / 60)\n }\n emitFixture(o, fx)\n if (!fx.flowing) message('no_water')\n return true\n }\n\n // ------------------------------------------------------------------ seats\n function seatTaken(objectId: string, seatId: string): string | null {\n for (const [actor, s] of seats) if (s.object === objectId && s.seat === seatId) return actor\n return null\n }\n\n function stand(actor: string = DEFAULT_ACTOR): Vec3 | null {\n const s = seats.get(actor)\n if (!s) return null\n seats.delete(actor)\n const o = objs.get(s.object)\n const spec = o?.spec.seats?.find((x) => x.id === s.seat)\n emit({ type: 'seat', object: s.object, seat: s.seat, actor, seated: false })\n if (!o || !spec) return null\n return toWorld(o, spec.exit)\n }\n\n function sit(objectId: string, seatId: string, actor: string = DEFAULT_ACTOR): SeatResult | null {\n const o = objs.get(objectId)\n const seat = o?.spec.seats?.find((s) => s.id === seatId)\n if (!o || !seat) return null\n const holder = seatTaken(objectId, seatId)\n if (holder && holder !== actor) return null\n if (seats.has(actor) && !holder) stand(actor)\n seats.set(actor, { object: objectId, seat: seatId })\n const eye = seat.eye ?? (seat.pose === 'lie' ? 0.18 : 0.62)\n emit({ type: 'seat', object: objectId, seat: seatId, actor, seated: true })\n return { eye: toWorld(o, [seat.pos[0], seat.pos[1] + eye, seat.pos[2]]), yaw: o.public.transform.ry + seat.ry + Math.PI, pose: seat.pose }\n }\n\n // ------------------------------------------------------------------ soft volumes\n function push(pos: Vec3, radius: number, vel: Vec3): void {\n for (const o of objs.values()) {\n if (!o.soft.size) continue\n const tr = o.public.transform\n const lp = worldToLocal(tr, pos)\n const lv = rotY(vel, -tr.ry)\n for (const s of o.soft.values()) {\n const [w, h, d] = s.spec.size\n const hx = w / 2\n const hz = Math.max(d, 0.1) / 2\n const dx = Math.max(Math.abs(lp[0] - s.spec.anchor[0]) - hx, 0)\n const dz = Math.max(Math.abs(lp[2] - s.spec.anchor[2]) - hz, 0)\n if (Math.hypot(dx, dz) > radius) continue\n const top = tr.y + s.spec.anchor[1]\n if (pos[1] + ACTOR_HEIGHT < top - h || pos[1] > top) continue\n if (s.driver) {\n s.driver.push(lv)\n if (s.spec.kind === 'panel' && s.spec.part && lv[2] < -0.05 && lp[2] > s.spec.anchor[2]) setPartTarget(o, s.spec.part, 1)\n continue\n }\n const cap = 8\n s.vax = clamp(s.vax - lv[2] * PUSH_GAIN, -cap, cap)\n s.vaz = clamp(s.vaz + lv[0] * PUSH_GAIN, -cap, cap)\n if (s.spec.kind === 'panel' && s.spec.part && lv[2] < -0.05 && lp[2] > s.spec.anchor[2]) setPartTarget(o, s.spec.part, 1)\n }\n }\n }\n\n const swingOut: [number, number] = [0, 0]\n function stepSoft(dt: number): void {\n const sub = Math.max(1, Math.ceil(dt / (1 / 120)))\n const h = dt / sub\n for (const o of objs.values()) {\n if (!o.soft.size) continue\n const wl = rotY([wind[0], 0, wind[1]], -o.public.transform.ry)\n for (const s of o.soft.values()) {\n const k = s.spec.stiffness ?? 30\n const c = s.spec.damping ?? 4\n const max = s.spec.maxAngle ?? 0.7\n if (s.driver) {\n s.driver.swing(swingOut)\n s.ax = swingOut[0]\n s.az = swingOut[1]\n continue\n }\n const gain = s.spec.wind ?? (s.spec.kind === 'panel' ? 0 : 1)\n const gust = gain * (0.6 + 0.4 * Math.sin(time * 1.7 + s.phase)) * 0.1\n const fx = -wl[2] * gust\n const fz = wl[0] * gust\n for (let i = 0; i < sub; i++) {\n s.vax += (-k * s.ax - c * s.vax + fx) * h\n s.vaz += (-k * s.az - c * s.vaz + fz) * h\n s.ax += s.vax * h\n s.az += s.vaz * h\n }\n if (Math.abs(s.ax) > max) {\n s.ax = Math.sign(s.ax) * max\n s.vax = 0\n }\n if (Math.abs(s.az) > max) {\n s.az = Math.sign(s.az) * max\n s.vaz = 0\n }\n }\n }\n }\n\n // ------------------------------------------------------------------ damage\n function damage(objectId: string, target: string, amount: number, _kind?: string): { hp: number; destroyed: boolean } | null {\n const o = objs.get(objectId)\n if (o && options.destruction) {\n const pos = toWorld(o, [0, 0.5, 0])\n const type = _kind === 'gas' ? 'explosive' : _kind === 'fabric' ? 'slash' : 'blunt'\n const result = options.destruction.hitPart(objectId, target, { type, point: pos, energy: Math.max(0, amount), source: 'interactables' }) as { events?: Array<{ type?: string; part?: string }> } | null | undefined\n const destroyed = !!result?.events?.some((e) => e.type === 'fracture' && e.part === target)\n emit({ type: 'damage', object: objectId, target, hp: -1, destroyed })\n return { hp: -1, destroyed }\n }\n const st = o?.hp.get(target)\n if (!o || !st) return null\n if (st.hp <= 0) return { hp: 0, destroyed: true }\n const before = st.hp\n st.hp = Math.max(0, st.hp - Math.max(0, amount))\n const destroyed = st.hp <= 0\n emit({ type: 'damage', object: objectId, target, hp: st.hp, destroyed })\n const pos = toWorld(o, [0, 0.5, 0])\n const fuel = o.fuels.get(target)\n if (fuel && destroyed && fuel.spec.kind === 'gas' && fuel.level > 0) {\n emit({ type: 'explosion', object: objectId, pos, radius: 2 + fuel.level / 5 })\n fuel.level = 0\n }\n const tank = o.tanks.get(target)\n if (tank && before === st.max && st.hp < before) emit({ type: 'leak', object: objectId, target, pos })\n return { hp: st.hp, destroyed }\n }\n\n // ------------------------------------------------------------------ interactions\n function deriveInteractions(spec: ObjectSpec): InteractionSpec[] {\n const out: InteractionSpec[] = []\n const used = new Set<string>()\n const partPos = (id: string | undefined, fallback: Vec3): Vec3 => spec.parts?.find((p) => p.id === id)?.pivot ?? fallback\n const partLabel = (id: string | undefined): string => spec.parts?.find((p) => p.id === id)?.label ?? ''\n const claim = (id: string | undefined) => {\n if (id) used.add(id)\n }\n for (const d of spec.devices ?? []) {\n claim(d.part)\n const pos = d.part ? partPos(d.part, [0, 1, 0]) : (d.plug ?? [0, 1, 0])\n // a hard-wired lamp (circuit, no plug, no part to press) is driven by switches and `setDevice`: it never steals the interact key\n if (d.kind === 'lamp' && !d.part && !d.plug && d.electric !== false) continue\n out.push({ id: `device.${d.id}`, pos, action: { do: 'toggle_device', device: d.id }, label: partLabel(d.part) })\n if (d.kind === 'screen' && (d.channels ?? 1) > 1) out.push({ id: `channel.${d.id}`, pos, action: { do: 'cycle_device', device: d.id }, label: '' })\n }\n for (const s of spec.switches ?? []) {\n claim(s.part)\n out.push({ id: `switch.${s.id}`, pos: partPos(s.part, [0, 1.2, 0]), action: { do: 'toggle_switch', switch: s.id }, label: partLabel(s.part) })\n }\n const driven = new Set((spec.devices ?? []).map((d) => d.fixture))\n for (const f of spec.fixtures ?? []) {\n claim(f.part)\n if (driven.has(f.id)) continue\n out.push({ id: `fixture.${f.id}`, pos: f.part ? partPos(f.part, f.outlet) : f.outlet, action: { do: 'toggle_fixture', fixture: f.id }, label: partLabel(f.part) })\n }\n for (const b of spec.burners ?? []) {\n claim(b.part)\n const pos = b.part ? partPos(b.part, b.pos) : b.pos\n if (b.needsIgnition) out.push({ id: `ignite.${b.id}`, pos, action: { do: 'ignite', burner: b.id }, label: '' })\n out.push({ id: `burner.${b.id}`, pos, action: { do: 'toggle_burner', burner: b.id }, label: partLabel(b.part) })\n }\n for (const f of spec.fuels ?? []) {\n if (!f.valve) continue\n claim(f.valve)\n out.push({ id: `fuel.${f.id}`, pos: partPos(f.valve, [0, 0.5, 0]), action: { do: 'toggle_fuel', fuel: f.id }, label: partLabel(f.valve) })\n }\n for (const c of spec.containers ?? []) {\n if (!c.access) out.push({ id: `open.${c.id}`, pos: c.volume.center, action: { do: 'open_container', container: c.id }, label: '' })\n }\n for (const p of spec.parts ?? []) {\n if (used.has(p.id)) continue\n if (p.label) out.push({ id: `part.${p.id}`, pos: p.pivot, action: { do: 'toggle_part', part: p.id }, label: p.label })\n }\n for (const c of spec.containers ?? []) {\n if (c.access && !spec.parts?.find((p) => p.id === c.access)?.label) {\n out.push({ id: `open.${c.id}`, pos: partPos(c.access, c.volume.center), action: { do: 'open_container', container: c.id }, label: '' })\n }\n }\n for (const s of spec.seats ?? []) out.push({ id: `seat.${s.id}`, pos: s.pos, action: { do: 'sit', seat: s.id }, label: '' })\n return out\n }\n\n function typeName(o: ObjState): string {\n return table[`type.${o.spec.type}`] ?? humanize(o.spec.type)\n }\n\n function promptOf(o: ObjState, i: InteractionSpec): { label: string; verb: string; object: string } {\n const a = i.action\n let state: string | null = null\n let def = ''\n switch (a.do) {\n case 'toggle_part': {\n const p = o.parts.get(a.part)\n const open = !!p && targetIsOpen(p)\n state = open ? 'open' : 'closed'\n def = open ? 'prompt.close' : 'prompt.open'\n break\n }\n case 'open_container': {\n const c = containerOf(o, a.container)\n const p = c?.access ? o.parts.get(c.access) : undefined\n const open = p ? targetIsOpen(p) : false\n state = p ? (open ? 'open' : 'closed') : null\n def = open ? 'prompt.close' : 'prompt.open'\n break\n }\n case 'toggle_device': {\n const on = !!o.devices.get(a.device)?.on\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_switch': {\n const sw = o.spec.switches?.find((s) => s.id === a.switch)\n const on = !!sw && switchIsOn(o, sw)\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_breaker': {\n const on = breaker(a.circuit)\n state = on ? 'on' : 'off'\n def = on ? 'prompt.breaker_off' : 'prompt.breaker_on'\n break\n }\n case 'toggle_main': {\n state = main ? 'on' : 'off'\n def = main ? 'prompt.main_off' : 'prompt.main_on'\n break\n }\n case 'toggle_fixture': {\n const on = !!o.fixtures.get(a.fixture)?.on\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_burner': {\n const b = o.burners.get(a.burner)\n const on = !!b && (b.on || b.lit)\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_fuel': {\n const f = o.fuels.get(a.fuel)\n const open = !!f && valveOpen(o, f)\n state = open ? 'open' : 'closed'\n def = open ? 'prompt.close_valve' : 'prompt.open_valve'\n break\n }\n case 'take':\n def = 'prompt.take'\n break\n case 'read':\n def = 'prompt.read'\n break\n case 'ignite':\n def = 'prompt.light'\n break\n case 'cycle_device':\n def = 'prompt.change_channel'\n break\n case 'sit': {\n const seat = o.spec.seats?.find((s) => s.id === a.seat)\n const mine = seats.get(DEFAULT_ACTOR)\n def = mine && mine.object === o.id && mine.seat === a.seat ? 'prompt.get_up' : seat?.pose === 'lie' ? 'prompt.lie_down' : 'prompt.sit'\n break\n }\n }\n let key = def\n if (i.label) {\n if (state && table[`${i.label}.${state}`] !== undefined) key = `${i.label}.${state}`\n else if (table[i.label] !== undefined) key = i.label\n }\n const vars = { name: typeName(o), circuit: a.do === 'toggle_breaker' ? (a.name ?? a.circuit) : '' }\n const label = t(key, vars)\n // structured prompt: explicit `<key>.verb` / `<key>.object` entries win; otherwise the first word is the verb and the rest the object\n let verb: string\n let object: string\n if (table[`${key}.verb`] !== undefined) {\n verb = t(`${key}.verb`, vars)\n object = table[`${key}.object`] ? t(`${key}.object`, vars) : vars.name\n } else {\n const sp = label.indexOf(' ')\n verb = sp < 0 ? label : label.slice(0, sp)\n object = sp < 0 ? vars.name : label.slice(sp + 1)\n }\n return { label, verb, object }\n }\n\n /** Locale key of the reason an interaction cannot be used right now, or null when it can. */\n function unavailableReason(o: ObjState, i: InteractionSpec): string | null {\n const a = i.action\n if (!requirementMet(i)) return 'requires_open'\n switch (a.do) {\n case 'toggle_part': {\n const p = o.parts.get(a.part)\n return p && gated(o, p) ? 'requires_open' : null\n }\n case 'open_container': {\n const c = containerOf(o, a.container)\n const p = c?.access ? o.parts.get(c.access) : undefined\n return p && gated(o, p) ? 'requires_open' : null\n }\n case 'toggle_breaker':\n case 'toggle_main': {\n const rocker = a.part ? o.parts.get(a.part) : undefined\n return rocker && gated(o, rocker) ? 'requires_open' : null\n }\n case 'take':\n case 'read':\n return accessible(o.id, a.container) ? null : 'requires_open'\n case 'ignite':\n return o.burners.get(a.burner)?.lit ? 'already_lit' : null\n case 'toggle_burner': {\n const b = o.burners.get(a.burner)\n return !b?.spec.needsIgnition || b.lit ? null : 'needs_ignition'\n }\n case 'cycle_device': {\n const d = o.devices.get(a.device)\n if (!d || !d.on) return 'turn_on_first'\n return devicePowered(o, d) ? null : 'no_power'\n }\n default:\n return null\n }\n }\n\n function requirementMet(i: InteractionSpec): boolean {\n if (!i.requires) return true\n const p = objs.get(i.requires.object)?.parts.get(i.requires.part)\n return !!p && targetIsOpen(p)\n }\n\n function interactablesOf(o: ObjState): Array<{ item: Interactable; spec: InteractionSpec; o: ObjState }> {\n return o.interactions.map((i) => {\n const id = gid(o, i.id)\n const p = promptOf(o, i)\n const item: Interactable = {\n id,\n object: o.id,\n kind: i.action.do,\n pos: toWorld(o, i.pos),\n radius: i.radius ?? DEFAULT_RADIUS,\n label: p.label,\n verb: p.verb,\n noun: p.object,\n available: true,\n act: (actor) => act(id, actor),\n }\n const reason = unavailableReason(o, i) ?? (options.canInteract?.(item, DEFAULT_ACTOR) === false ? 'locked' : null)\n if (reason) {\n item.available = false\n item.reason = reason\n }\n return { item, spec: i, o }\n })\n }\n\n /**\n * One `take` per stack an open container shows, at its slot (it rides the drawer or door shelf with it): each item inside a piece of furniture is picked up\n * on its own, with one hand. Items the catalogue marks `pickable: false`, and stacks whose data says so, are left out.\n */\n function contentTakes(o: ObjState): Interactable[] {\n if (options.takeContents === false) return []\n const out: Interactable[] = []\n for (const c of o.spec.containers ?? []) {\n const list = o.contents.get(c.id)\n if (!list || !list.some((st) => st !== null) || !accessible(o.id, c.id)) continue\n list.forEach((stack, slot) => {\n if (!stack || options.items?.[stack.type]?.pickable === false || stack.data?.pickable === false) return\n const verb = t('prompt.take')\n const noun = table[`item.${stack.type}`] ?? humanize(stack.type)\n const item: Interactable = {\n id: `${o.id}:${TAKE_PREFIX}${c.id}.${slot}`,\n object: o.id,\n kind: 'take',\n pos: slotPosition(o.id, c.id, slot),\n radius: TAKE_RADIUS,\n label: `${verb} ${noun}`,\n verb,\n noun,\n hands: 1,\n itemType: stack.type,\n available: true,\n act: (actor) => takeAt(o.id, c.id, slot, actor ?? DEFAULT_ACTOR),\n }\n if (options.canInteract?.(item, DEFAULT_ACTOR) === false) {\n item.available = false\n item.reason = 'locked'\n }\n out.push(item)\n })\n }\n return out\n }\n\n function takeAt(objectId: string, containerId: string, slot: number, actor: string): boolean {\n const o = objs.get(objectId)\n if (!o) return false\n const probe = contentTakes(o).find((k) => k.id === `${objectId}:${TAKE_PREFIX}${containerId}.${slot}`)\n if (!probe || options.canInteract?.(probe, actor) === false) return false\n return take(objectId, containerId, slot, actor) !== null\n }\n\n function interactables(): Interactable[] {\n const out: Interactable[] = []\n for (const o of objs.values()) {\n for (const e of interactablesOf(o)) out.push(e.item)\n out.push(...contentTakes(o))\n }\n return out\n }\n\n function target(eye: { x: number; y: number; z: number; yaw: number; pitch: number }, opts: TargetOptions = {}): Interactable | null {\n const reach = opts.reach ?? 1.8\n const cone = opts.cone ?? 0.45\n const dir: Vec3 = [-Math.sin(eye.yaw) * Math.cos(eye.pitch), Math.sin(eye.pitch), -Math.cos(eye.yaw) * Math.cos(eye.pitch)]\n let best: Interactable | null = null\n let bestScore = Infinity\n for (const o of objs.values()) {\n for (const item of [...interactablesOf(o).map((e) => e.item), ...contentTakes(o)]) {\n if (!item.available && !opts.includeUnavailable) continue\n if (opts.kinds && !opts.kinds.includes(item.kind)) continue\n if (opts.filter && !opts.filter(item)) continue\n const v: Vec3 = [item.pos[0] - eye.x, item.pos[1] - eye.y, item.pos[2] - eye.z]\n const d = Math.hypot(v[0], v[1], v[2])\n if (d > reach) continue\n const cos = d < 1e-6 ? 1 : clamp((v[0] * dir[0] + v[1] * dir[1] + v[2] * dir[2]) / d, -1, 1)\n const angle = Math.acos(cos)\n if (angle > cone) continue\n const score = (angle / cone) * 0.6 + (d / reach) * 0.4\n if (score < bestScore) {\n bestScore = score\n best = item\n }\n }\n }\n return best\n }\n\n function act(interactableId: string, actor: string = DEFAULT_ACTOR): boolean {\n let found: { item: Interactable; spec: InteractionSpec; o: ObjState } | null = null\n for (const o of objs.values()) {\n if (!interactableId.startsWith(o.id + ':')) continue\n const local = interactableId.slice(o.id.length + 1)\n if (local.startsWith(TAKE_PREFIX)) {\n const at = contentTakes(o).find((k) => k.id === interactableId)\n if (at) return at.act(actor)\n }\n if (!o.interactions.some((i) => i.id === local)) continue\n found = interactablesOf(o).find((e) => e.spec.id === local) ?? null\n if (found) break\n }\n if (!found) return false\n if (!requirementMet(found.spec)) return false\n if (options.canInteract?.(found.item, actor) === false) return false\n return execute(found.o, found.spec.action, actor)\n }\n\n function execute(o: ObjState, a: InteractionSpec['action'], actor: string): boolean {\n switch (a.do) {\n case 'toggle_part': {\n const p = o.parts.get(a.part)\n if (!p || gated(o, p)) return false\n setPartTarget(o, a.part, targetIsOpen(p) ? 0 : 1)\n return true\n }\n case 'open_container': {\n const c = containerOf(o, a.container)\n if (!c) return false\n if (c.access) return execute(o, { do: 'toggle_part', part: c.access }, actor)\n emit({ type: 'container', object: o.id, container: c.id, open: true })\n return true\n }\n case 'take': {\n if (!accessible(o.id, a.container)) return false\n const list = o.contents.get(a.container)\n if (!list) return false\n const slot = a.slot ?? list.findIndex((s) => s !== null)\n if (slot < 0 || !list[slot]) {\n message('empty')\n return false\n }\n return take(o.id, a.container, slot, actor) !== null\n }\n case 'read': {\n if (!accessible(o.id, a.container)) return false\n const stack = o.contents.get(a.container)?.[a.slot]\n if (!stack) {\n message('empty')\n return false\n }\n const key = typeof stack.data?.text === 'string' ? stack.data.text : null\n if (!key) return false\n message(key)\n return true\n }\n case 'toggle_device': {\n const d = o.devices.get(a.device)\n if (!d) return false\n setDeviceOn(o, d, !d.on)\n return true\n }\n case 'cycle_device': {\n const d = o.devices.get(a.device)\n if (!d || !d.on) return false\n if (!devicePowered(o, d)) {\n message('no_power')\n return false\n }\n d.channel = (d.channel + 1) % Math.max(1, d.spec.channels ?? 1)\n emit({ type: 'device', object: o.id, device: d.spec.id, on: true, powered: true, channel: d.channel })\n return true\n }\n case 'toggle_switch':\n return toggleSwitch(o, a.switch)\n case 'toggle_breaker': {\n const rocker = a.part ? o.parts.get(a.part) : undefined\n if (rocker && gated(o, rocker)) return false\n const on = !breaker(a.circuit)\n if (a.part) setPartTarget(o, a.part, on ? 1 : 0)\n world.power.setBreaker(a.circuit, on)\n return true\n }\n case 'toggle_main': {\n const rocker = a.part ? o.parts.get(a.part) : undefined\n if (rocker && gated(o, rocker)) return false\n const on = !main\n if (a.part) setPartTarget(o, a.part, on ? 1 : 0)\n world.power.setMain(on)\n return true\n }\n case 'toggle_fixture':\n return toggleFixture(o, a.fixture)\n case 'toggle_burner':\n return toggleBurner(o, a.burner)\n case 'ignite':\n return ignite(o, a.burner)\n case 'toggle_fuel':\n return toggleFuel(o, a.fuel)\n case 'sit': {\n const mine = seats.get(actor)\n if (mine && mine.object === o.id && mine.seat === a.seat) {\n stand(actor)\n return true\n }\n return sit(o.id, a.seat, actor) !== null\n }\n }\n }\n\n // ------------------------------------------------------------------ emitters, mirrors, colliders\n function emitters(): ActiveEmitter[] {\n const out: ActiveEmitter[] = []\n for (const o of objs.values()) {\n for (const e of o.spec.emitters ?? []) {\n let intensity = 0\n const b = o.burners.get(e.source)\n const fx = o.fixtures.get(e.source)\n const dev = o.devices.get(e.source)\n const fuel = o.fuels.get(e.source)\n if (b) {\n const ref = resolveFuel(o, b)\n const frac = ref ? clamp(ref.f.level / ref.f.spec.capacity, 0, 1) : 0\n if (b.lit) intensity = 0.35 + 0.65 * frac\n else if (e.kind === 'smoke' && b.smoke > 0) intensity = 0.6 * (b.smoke / SMOKE_TAIL)\n } else if (fx) {\n if (fx.on && fx.flowing) intensity = fx.frac\n } else if (dev) {\n if (dev.on && devicePowered(o, dev)) intensity = 1\n } else if (fuel) {\n const lit = [...o.burners.values()].some((bb) => bb.lit && resolveFuel(o, bb)?.f === fuel)\n if (lit) intensity = 0.35 + 0.65 * clamp(fuel.level / fuel.spec.capacity, 0, 1)\n }\n if (intensity <= 0) continue\n const dir = rotY(e.dir ?? [0, 1, 0], o.public.transform.ry)\n out.push({ id: gid(o, e.id), object: o.id, kind: e.kind, pos: toWorld(o, e.pos), dir, size: e.size ?? 0.3, ...(e.reach !== undefined ? { reach: e.reach } : {}), ...(e.bowl ? { bowl: e.bowl } : {}), intensity: clamp(intensity, 0, 1) })\n }\n }\n return out\n }\n\n function mirrors(eye: Vec3, maxDistance = 10, count = 4) {\n const out: Array<{ id: string; center: Vec3; normal: Vec3; w: number; h: number; distance: number }> = []\n for (const o of objs.values()) {\n for (const m of o.spec.mirrors ?? []) {\n const center = toWorld(o, applyPart(o, m.part, m.center))\n const f = partFrame(o, m.part)\n const ln = f && f.angle !== 0 ? rotateAxis(m.normal, f.axis, f.angle) : m.normal\n const normal = rotY(ln, o.public.transform.ry)\n const len = Math.hypot(normal[0], normal[1], normal[2]) || 1\n const n: Vec3 = [normal[0] / len, normal[1] / len, normal[2] / len]\n const to: Vec3 = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]]\n if (n[0] * to[0] + n[1] * to[1] + n[2] * to[2] <= 0) continue\n const distance = Math.hypot(to[0], to[1], to[2])\n if (distance > maxDistance) continue\n out.push({ id: gid(o, m.id), center, normal: n, w: m.w, h: m.h, distance })\n }\n }\n return out.sort((a, b) => a.distance - b.distance).slice(0, count)\n }\n\n function colliders(opts: ColliderOptions = {}): WorldCollider[] {\n const out: WorldCollider[] = []\n const fixed: WorldCollider[] = []\n for (const o of objs.values()) {\n const tr = o.public.transform\n for (const c of o.spec.colliders ?? []) {\n if (c.part && c.offWhenOpen && (o.parts.get(c.part)?.t ?? 0) > 0.5) continue\n let extra = 0\n if (c.part) {\n const f = partFrame(o, c.part)\n if (f && f.angle !== 0 && Math.abs(f.axis[1]) >= 0.5) extra = f.angle * Math.sign(f.axis[1])\n }\n const center = toWorld(o, applyPart(o, c.part, c.center))\n ;(c.part ? out : fixed).push({\n id: gid(o, c.id),\n object: o.id,\n cx: center[0],\n cz: center[2],\n hw: c.half[0],\n hd: c.half[2],\n ry: tr.ry + (c.ry ?? 0) + extra,\n y0: center[1] - c.half[1],\n y1: center[1] + c.half[1],\n })\n }\n }\n if (opts.merge) return [...mergeColliders(fixed, { gap: opts.gap, slack: opts.slack }), ...out]\n return [...fixed, ...out]\n }\n\n // ------------------------------------------------------------------ update\n /** A part the engine moves: it aims at the target when that changed, then `t` is what the joint says; a broken one stays where it broke. */\n function updateDriven(o: ObjState, p: PartState, dt: number): void {\n const driver = p.driver as PartDriver\n if (p.broken) return\n if (p.commanded !== p.target && !(gated(o, p) && p.target > p.t)) {\n driver.aim(p.target)\n p.commanded = p.target\n p.moving = true\n }\n driver.update(dt)\n if (driver.broken) {\n p.broken = true\n emit({ type: 'broke', object: o.id, part: p.spec.id })\n return\n }\n const next = clamp(driver.read(), 0, p.maxT)\n if (next !== p.t) writeT(o, p, next)\n if (!driver.settled) return\n // let go (or pushed by hand): what the joint holds is the target, so the next interaction toggles from there\n p.target = next\n p.commanded = next\n if (p.moving) emit({ type: 'part', object: o.id, part: p.spec.id, t: next, target: next })\n p.moving = false\n }\n\n function update(dt: number): void {\n if (!(dt > 0)) return\n time += dt\n for (const o of objs.values()) {\n for (const p of o.parts.values()) {\n if (p.driver) {\n updateDriven(o, p, dt)\n continue\n }\n if (p.t === p.target) continue\n if (gated(o, p) && p.target > p.t) continue // a gated part may still close\n const step = (p.spec.motion.speed ?? 2.5) * dt\n const next = p.t < p.target ? Math.min(p.target, p.t + step) : Math.max(p.target, p.t - step)\n writeT(o, p, next)\n if (next === p.target) emit({ type: 'part', object: o.id, part: p.spec.id, t: next, target: p.target })\n }\n }\n stepSoft(dt)\n for (const o of objs.values()) {\n for (const b of o.burners.values()) {\n if (b.lit) {\n const ref = resolveFuel(o, b)\n if (!ref || !valveOpen(ref.o, ref.f)) {\n extinguish(o, b, !!b.spec.needsIgnition)\n } else {\n ref.f.level = Math.max(0, ref.f.level - b.spec.rate * dt)\n if (ref.f.level <= 0) extinguish(o, b, !!b.spec.needsIgnition)\n }\n } else if (b.on && !b.spec.needsIgnition && canBurn(b, resolveFuel(o, b))) {\n // a gas knob left open without gas lights as soon as the bottle valve opens\n b.lit = true\n b.smoke = 0\n emitBurner(o, b)\n } else if (b.smoke > 0) {\n b.smoke = Math.max(0, b.smoke - dt)\n }\n }\n if (rain > 0) {\n for (const tk of o.tanks.values()) {\n if (tk.spec.rainArea) tk.level = Math.min(tk.spec.capacity, tk.level + ((rain * tk.spec.rainArea) / 3600) * dt)\n }\n }\n for (const tk of o.tanks.values()) {\n const st = o.hp.get(tk.spec.id)\n if (st && st.hp < st.max && tk.level > 0) {\n const rate = 0.5 + 2.5 * (1 - st.hp / st.max)\n tk.level = Math.max(0, tk.level - rate * dt)\n }\n }\n }\n for (const o of objs.values()) {\n for (const d of o.devices.values()) {\n const fx = d.spec.fixture ? o.fixtures.get(d.spec.fixture) : undefined\n if (!fx) continue\n const run = d.on && devicePowered(o, d)\n if (fx.on === run) continue\n fx.on = run\n if (!run) {\n fx.flowing = false\n fx.frac = 0\n emitFixture(o, fx)\n }\n }\n for (const fx of o.fixtures.values()) stepFixture(o, fx, dt)\n }\n }\n\n // ------------------------------------------------------------------ add / remove\n function add(id: string, spec: ObjectSpec, transform: Transform): WorldObject {\n if (objs.has(id)) throw new Error(`Object \"${id}\" already exists`)\n const pub: WorldObject = { id, spec, transform: { ...transform }, parts: {} }\n const o: ObjState = {\n id,\n public: pub,\n spec,\n parts: new Map(),\n contents: new Map(),\n devices: new Map(),\n fuels: new Map(),\n burners: new Map(),\n tanks: new Map(),\n fixtures: new Map(),\n soft: new Map(),\n hp: new Map(),\n interactions: spec.interactions ?? deriveInteractions(spec),\n }\n for (const p of spec.parts ?? []) {\n const t0 = clamp(p.t0 ?? 0, 0, 1)\n const driver = options.partPhysics?.attachPart(id, p, pub.transform)\n o.parts.set(p.id, { spec: p, t: t0, target: t0, maxT: 1, ...(driver ? { driver, commanded: t0 } : {}) })\n driver?.snap(t0)\n pub.parts[p.id] = t0\n }\n for (const c of spec.containers ?? []) {\n let list: Array<ItemStack | null>\n if (c.contents) list = c.slots.map((_, i) => cloneStack(c.contents?.[i] ?? null))\n else if (c.loot) list = generateLoot(options.loot, c.loot, c.slots, `${seed}|${id}|${c.id}`, options.items)\n else list = c.slots.map(() => null)\n o.contents.set(c.id, list)\n }\n for (const d of spec.devices ?? []) {\n o.devices.set(d.id, { spec: d, on: !!d.on, channel: 0 })\n if (d.on && d.part) {\n const p = o.parts.get(d.part)\n if (p) {\n p.target = p.maxT\n writeT(o, p, p.maxT)\n }\n }\n }\n for (const f of spec.fuels ?? []) o.fuels.set(f.id, { spec: f, level: clamp(f.level ?? f.capacity, 0, f.capacity) })\n for (const b of spec.burners ?? []) o.burners.set(b.id, { spec: b, on: false, lit: false, smoke: 0 })\n for (const tk of spec.tanks ?? []) o.tanks.set(tk.id, { spec: tk, level: clamp(tk.level ?? tk.capacity, 0, tk.capacity) })\n for (const f of spec.fixtures ?? []) o.fixtures.set(f.id, { spec: f, on: false, flowing: false, frac: 0, timer: 0 })\n let n = 0\n for (const s of spec.soft ?? []) {\n const driver = options.partPhysics?.attachSoft?.(id, s, pub.transform)\n o.soft.set(s.id, { spec: s, ax: 0, az: 0, vax: 0, vaz: 0, phase: (n++ * 2.399963) % (Math.PI * 2), ...(driver ? { driver } : {}) })\n }\n for (const d of spec.damage ?? []) o.hp.set(d.target, { max: d.hp, hp: d.hp })\n objs.set(id, o)\n if (!defaultTankExplicit && defaultTank === null && o.tanks.size) defaultTank = gid(o, [...o.tanks.keys()][0])\n rebuildPlugs()\n return pub\n }\n\n function remove(id: string): void {\n const o = objs.get(id)\n if (!o) return\n for (const [actor, s] of [...seats]) if (s.object === id) seats.delete(actor)\n for (const p of o.parts.values()) p.driver?.dispose()\n for (const s of o.soft.values()) s.driver?.dispose()\n objs.delete(id)\n if (defaultTank && defaultTank.startsWith(id + ':')) defaultTank = null\n rebuildPlugs()\n }\n\n // ------------------------------------------------------------------ save / load\n function serialize(): WorldState {\n const objects: WorldState['objects'] = {}\n for (const o of objs.values()) {\n objects[o.id] = {\n parts: Object.fromEntries([...o.parts].map(([k, p]) => [k, p.t])),\n contents: Object.fromEntries([...o.contents].map(([k, v]) => [k, v.map(cloneStack)])),\n devices: Object.fromEntries([...o.devices].map(([k, d]) => [k, { on: d.on, channel: d.channel }])),\n fuels: Object.fromEntries([...o.fuels].map(([k, f]) => [k, { level: f.level, open: valveOpen(o, f) }])),\n burners: Object.fromEntries([...o.burners].map(([k, b]) => [k, { on: b.on, lit: b.lit }])),\n tanks: Object.fromEntries([...o.tanks].map(([k, tk]) => [k, tk.level])),\n fixtures: Object.fromEntries([...o.fixtures].map(([k, f]) => [k, f.on])),\n hp: Object.fromEntries([...o.hp].map(([k, h]) => [k, h.hp])),\n }\n }\n return {\n version: 1,\n objects,\n grid,\n main,\n breakers: Object.fromEntries(breakers),\n seats: Object.fromEntries([...seats].map(([a, s]) => [a, { object: s.object, seat: s.seat }])),\n defaultTank,\n }\n }\n\n function load(state: WorldState): void {\n for (const [id, st] of Object.entries(state.objects)) {\n const o = objs.get(id)\n if (!o) continue\n for (const [k, v] of Object.entries(st.parts)) {\n const p = o.parts.get(k)\n if (p) {\n // keep the limit found by fitSweep: a loaded save must not let a door open through a wall again\n p.target = clamp(v, 0, p.maxT)\n p.driver?.snap(p.target)\n p.commanded = p.target\n writeT(o, p, p.target)\n }\n }\n for (const [k, v] of Object.entries(st.contents)) {\n const c = containerOf(o, k)\n if (c) o.contents.set(k, c.slots.map((_, i) => cloneStack(v[i] ?? null)))\n }\n for (const [k, v] of Object.entries(st.devices)) {\n const d = o.devices.get(k)\n if (d) {\n d.on = v.on\n d.channel = v.channel\n }\n }\n for (const [k, v] of Object.entries(st.fuels)) {\n const f = o.fuels.get(k)\n if (f) f.level = v.level\n }\n for (const [k, v] of Object.entries(st.burners)) {\n const b = o.burners.get(k)\n if (b) {\n b.on = v.on\n b.lit = v.lit\n b.smoke = 0\n }\n }\n for (const [k, v] of Object.entries(st.tanks)) {\n const tk = o.tanks.get(k)\n if (tk) tk.level = v\n }\n for (const [k, v] of Object.entries(st.fixtures)) {\n const f = o.fixtures.get(k)\n if (f) {\n f.on = v\n f.flowing = false\n f.frac = 0\n f.timer = v && f.spec.kind === 'flush' ? FLUSH_SECONDS : 0\n }\n }\n for (const [k, v] of Object.entries(st.hp)) {\n const h = o.hp.get(k)\n if (h) h.hp = v\n }\n }\n grid = state.grid\n main = state.main ?? true\n breakers.clear()\n for (const [k, v] of Object.entries(state.breakers)) breakers.set(k, v)\n seats.clear()\n for (const [a, s] of Object.entries(state.seats)) if (objs.has(s.object)) seats.set(a, { object: s.object, seat: s.seat })\n defaultTank = state.defaultTank\n defaultTankExplicit = true\n }\n\n // ------------------------------------------------------------------ public surface\n const world: World = {\n add,\n remove,\n get: (id) => objs.get(id)?.public,\n objects: () => [...objs.values()].map((o) => o.public),\n update,\n interactables,\n target,\n act,\n partT: (objectId, partId) => objs.get(objectId)?.parts.get(partId)?.t ?? 0,\n setDevice,\n setFixture,\n setBurner,\n setPart: (objectId, partId, targetT, instant) => {\n const o = objs.get(objectId)\n if (o) setPartTarget(o, partId, targetT, instant)\n },\n fitSweep,\n contents,\n accessible,\n take,\n put,\n slotPosition,\n power: {\n get grid() {\n return grid\n },\n set grid(on: boolean) {\n world.power.setGrid(on)\n },\n setGrid(on) {\n if (on === grid) return\n const before = powerSnapshot()\n grid = on\n emit({ type: 'power', grid, main })\n emitPowerChanges(before)\n },\n get main() {\n return main\n },\n setMain(on) {\n if (on === main) return\n const before = powerSnapshot()\n main = on\n emit({ type: 'power', grid, main })\n emitPowerChanges(before)\n },\n setBreaker(circuit, on) {\n if (breaker(circuit) === on) {\n breakers.set(circuit, on)\n return\n }\n const before = powerSnapshot()\n breakers.set(circuit, on)\n emitPowerChanges(before)\n },\n breaker,\n isPowered: (objectId, deviceId) => {\n const r = getDevice(objectId, deviceId)\n return r ? devicePowered(r.o, r.d) : false\n },\n isOn: (objectId, deviceId) => getDevice(objectId, deviceId)?.d.on ?? false,\n pluggedInto: (objectId, deviceId) => plugs.get(`${objectId}:${deviceId}`) ?? null,\n channel: (objectId, deviceId) => getDevice(objectId, deviceId)?.d.channel ?? 0,\n },\n fuelLevel: (objectId, fuelId) => objs.get(objectId)?.fuels.get(fuelId)?.level ?? 0,\n isLit: (objectId, burnerId) => objs.get(objectId)?.burners.get(burnerId)?.lit ?? false,\n water: {\n setDefaultTank(tankId) {\n defaultTank = tankId\n defaultTankExplicit = true\n },\n level(tankId) {\n return findGlobal(tankId, (oo, local) => oo.tanks.get(local))?.value.level ?? 0\n },\n refill(tankId, liters) {\n const f = findGlobal(tankId, (oo, local) => oo.tanks.get(local))\n if (!f) return 0\n const added = Math.max(0, Math.min(liters, f.value.spec.capacity - f.value.level))\n f.value.level += added\n return added\n },\n setRain(mm) {\n rain = Math.max(0, mm)\n },\n isFlowing: (objectId, fixtureId) => {\n const fx = objs.get(objectId)?.fixtures.get(fixtureId)\n return !!fx && fx.on && fx.flowing\n },\n },\n sit,\n stand,\n seatOf: (actor = DEFAULT_ACTOR) => {\n const s = seats.get(actor)\n return s ? { object: s.object, seat: s.seat } : null\n },\n push,\n sway: (objectId, softId) => {\n const s = objs.get(objectId)?.soft.get(softId)\n return s ? { ax: s.ax, az: s.az } : { ax: 0, az: 0 }\n },\n setWind: (x, z) => {\n wind = [x, z]\n },\n emitters,\n mirrors,\n colliders,\n damage,\n hp: (objectId, target) => (options.destruction ? null : (objs.get(objectId)?.hp.get(target)?.hp ?? null)),\n t,\n setLocale: (l) => {\n locale = l\n table = resolveStrings(locale, options.strings)\n },\n serialize,\n load,\n }\n return world\n}\n","import type { BodyId, JointId, Quat, SeamWorld, Vec3 } from '@adatechnology/game-physics'\n\n/** A chain of boxes along a polyline, each joined to the one before by a swing-twist joint: a cord, a cable, a strip of a curtain. */\nexport interface ChainSpec {\n /** From the start to the end of the chain; one link between each two points. */\n readonly points: readonly Vec3[]\n /** Half the width and the depth of a link (m); its length is the segment's. */\n readonly halfWidth: number\n readonly halfDepth: number\n readonly totalMass: number\n /** What the first link hangs from (a static body, or a kinematic one a host moves). */\n readonly startBody: BodyId\n /** What the last link is tied to; undefined: it hangs free. */\n readonly endBody?: BodyId\n /** Half cone of every joint (radians) and the most it twists either way. */\n readonly halfCone: number\n readonly twist: number\n /** Torque (N m) that holds a joint still against the swing: the chain's stiffness at rest. */\n readonly jointFriction: number\n /** Share of velocity lost per second by every link (the air, the cloth). */\n readonly damping: number\n}\n\nexport interface Chain {\n readonly bodies: readonly BodyId[]\n readonly joints: readonly JointId[]\n /** Half the length of each link, for reading its ends. */\n readonly halfLengths: readonly number[]\n /** The collision group the links share (released with the chain). */\n readonly group: number\n}\n\nconst UP: Vec3 = [0, 1, 0]\n\nconst sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]\nconst length = (v: Vec3): number => Math.hypot(v[0], v[1], v[2])\nconst cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]\n\n/** The turn that takes +y (a link's length) onto `direction` (unit). */\nexport function alignY(direction: Vec3): Quat {\n const axis = cross(UP, direction)\n const sine = length(axis)\n if (sine < 1e-9) return direction[1] >= 0 ? [0, 0, 0, 1] : [1, 0, 0, 0]\n const angle = Math.atan2(sine, direction[1])\n const half = Math.sin(angle / 2) / sine\n return [axis[0] * half, axis[1] * half, axis[2] * half, Math.cos(angle / 2)]\n}\n\n/** A vector turned by a unit quaternion. */\nexport function rotateByQuat(v: Vec3, q: Quat): 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 perpendicular = (direction: Vec3): Vec3 => {\n const side = Math.abs(direction[0]) < 0.9 ? cross(direction, [1, 0, 0]) : cross(direction, [0, 0, 1])\n const size = length(side)\n return [side[0] / size, side[1] / size, side[2] / size]\n}\n\n/** Builds the links and joints of a chain in the world, in the pose its points give (so a cord starts already sagging). */\nexport function buildChain(world: SeamWorld, spec: ChainSpec): Chain {\n const count = spec.points.length - 1\n const lengths = Array.from({ length: count }, (_, i) => length(sub(spec.points[i + 1] as Vec3, spec.points[i] as Vec3)))\n const total = lengths.reduce((sum, each) => sum + each, 0)\n const pairs: Array<readonly [number, number]> = []\n for (let a = 0; a < count; a++) for (let b = a + 1; b < count; b++) pairs.push([a, b])\n const group = world.createGroup(count, pairs)\n const bodies: BodyId[] = []\n const joints: JointId[] = []\n for (let i = 0; i < count; i++) {\n const from = spec.points[i] as Vec3\n const to = spec.points[i + 1] as Vec3\n const span = lengths[i] as number\n const direction: Vec3 = [(to[0] - from[0]) / span, (to[1] - from[1]) / span, (to[2] - from[2]) / span]\n const link = world.createBody({\n shape: { kind: 'box', half: [spec.halfWidth, span / 2, spec.halfDepth] },\n motion: 'dynamic',\n mass: spec.totalMass * (span / total),\n position: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2, (from[2] + to[2]) / 2],\n rotation: alignY(direction),\n layer: 'debris',\n group: { id: group, sub: i },\n linearDamping: spec.damping,\n angularDamping: spec.damping,\n user: -4,\n })\n const previous = i === 0 ? spec.startBody : (bodies[i - 1] as BodyId)\n if (i === 0) world.ignorePair(spec.startBody, link, true)\n joints.push(world.createJoint(swingTwist(spec, previous, link, from, direction)))\n bodies.push(link)\n }\n if (spec.endBody !== undefined) {\n const last = spec.points[count] as Vec3\n const direction = sub(last, spec.points[count - 1] as Vec3)\n const size = length(direction)\n world.ignorePair(spec.endBody, bodies[count - 1] as BodyId, true)\n joints.push(world.createJoint(swingTwist(spec, bodies[count - 1] as BodyId, spec.endBody, last, [direction[0] / size, direction[1] / size, direction[2] / size])))\n }\n return { bodies, joints, halfLengths: lengths.map((each) => each / 2), group }\n}\n\n/** Takes a chain out of the world: its joints, its links, then the group the links shared. */\nexport function disposeChain(world: SeamWorld, chain: Chain): void {\n for (const joint of chain.joints) world.removeJoint(joint)\n for (const body of chain.bodies) world.removeBody(body)\n world.releaseGroup(chain.group)\n}\n\nconst swingTwist = (spec: ChainSpec, a: BodyId, b: BodyId, point: Vec3, direction: Vec3) => ({\n kind: 'swingTwist' as const,\n a,\n b,\n point,\n twistAxis: direction,\n planeAxis: perpendicular(direction),\n normalHalfCone: spec.halfCone,\n planeHalfCone: spec.halfCone,\n twistMin: -spec.twist,\n twistMax: spec.twist,\n friction: spec.jointFriction,\n})\n\nconst pose = new Float64Array(7)\n\n/** The end of link `index` now (x, y, z into `out` at `offset`): the body's centre moved half the link's length along its own +y (the unit quaternion's y axis, unrolled). */\nconst writeLinkEnd = (world: SeamWorld, chain: Chain, index: number, sign: 1 | -1, out: Float64Array, offset: number): void => {\n world.readPose(chain.bodies[index] as BodyId, pose, 0)\n const x = pose[3] as number\n const y = pose[4] as number\n const z = pose[5] as number\n const w = pose[6] as number\n const half = (chain.halfLengths[index] as number) * sign\n out[offset] = (pose[0] as number) + half * 2 * (x * y - w * z)\n out[offset + 1] = (pose[1] as number) + half * (1 - 2 * (x * x + z * z))\n out[offset + 2] = (pose[2] as number) + half * 2 * (y * z + w * x)\n}\n\n/** The two ends of every link now, as a polyline (x, y, z per point) for a host that draws the cord: the points a chain was built from, moved. */\nexport function chainPoints(world: SeamWorld, chain: Chain, out: Float64Array): void {\n const count = chain.bodies.length\n writeLinkEnd(world, chain, 0, -1, out, 0)\n for (let i = 0; i < count; i++) writeLinkEnd(world, chain, i, 1, out, (i + 1) * 3)\n}\n\n/** Only the free end of the chain (x, y, z into `out`): one pose read, for a host that wants where the tip is and not the whole line. */\nexport function chainEnd(world: SeamWorld, chain: Chain, out: Float64Array): void {\n writeLinkEnd(world, chain, chain.bodies.length - 1, 1, out, 0)\n}\n","import type { BodyId, SeamWorld } from '@adatechnology/game-physics'\n\nimport { buildChain, chainEnd, disposeChain } from './engine-chain'\nimport type { Chain } from './engine-chain'\nimport { localToWorld, rotY } from './math'\nimport type { SoftDriver } from './part-physics'\nimport type { SoftSpec, Transform, Vec3 } from './types'\n\nconst STRIP_WIDTH = 0.12\nconst LINK_LENGTH = 0.15\nconst MAX_LINKS = 8\nconst FABRIC_KG_PER_M2 = 0.3\nconst FABRIC_HALF_DEPTH = 0.01\nconst TWIST_RANGE = 0.3\nconst DEFAULT_MAX_ANGLE = 0.7\nconst DEFAULT_DAMPING = 4\nconst JOINT_HOLD_NM = 0.002\n/** An actor's velocity (m/s) to the speed it gives a strip (the body only brushes the cloth). */\nconst PUSH_GAIN = 0.4\n\n/**\n * A curtain, cloth or strip as hanging chains from a rail along its anchor line, one chain per `STRIP_WIDTH` of width: they swing when an actor pushes through and\n * settle by the damping (the world's spring is not used). The world's `sway` reads back the mean tip offset of the chains as the two swing angles.\n */\nexport function attachStrips(world: SeamWorld, soft: SoftSpec, transform: Transform): SoftDriver {\n const [width, height, depth] = soft.size\n const strips = Math.max(1, Math.round(width / STRIP_WIDTH))\n const links = Math.min(MAX_LINKS, Math.max(2, Math.round(height / LINK_LENGTH)))\n const rail: BodyId = world.createBody({ shape: { kind: 'box', half: [width / 2, 0.01, Math.max(depth, 0.02) / 2] }, motion: 'static', position: localToWorld(transform, soft.anchor), layer: 'static', user: -3 })\n const damping = soft.damping ?? DEFAULT_DAMPING\n const chains: Chain[] = []\n const tops: Vec3[] = []\n for (let i = 0; i < strips; i++) {\n const x = soft.anchor[0] - width / 2 + (width * (i + 0.5)) / strips\n const top = localToWorld(transform, [x, soft.anchor[1], soft.anchor[2]])\n tops.push(top)\n chains.push(\n buildChain(world, {\n points: Array.from({ length: links + 1 }, (_, k): Vec3 => [top[0], top[1] - (height * k) / links, top[2]]),\n halfWidth: (width / strips) * 0.45,\n halfDepth: FABRIC_HALF_DEPTH,\n totalMass: (width / strips) * height * FABRIC_KG_PER_M2,\n startBody: rail,\n halfCone: soft.maxAngle ?? DEFAULT_MAX_ANGLE,\n twist: TWIST_RANGE,\n jointFriction: JOINT_HOLD_NM,\n damping: damping / 4,\n }),\n )\n }\n const tip = new Float64Array(3)\n const lastLinks = chains.map((chain) => chain.bodies[chain.bodies.length - 1] as BodyId)\n const cosYaw = Math.cos(-transform.ry)\n const sinYaw = Math.sin(-transform.ry)\n let restedAx = 0\n let restedAz = 0\n let isRested = false\n let disposed = false\n const everyLinkAsleep = (): boolean => {\n for (let i = 0; i < lastLinks.length; i++) if (!world.isSleeping(lastLinks[i] as BodyId)) return false\n return true\n }\n return {\n swing(out) {\n const asleep = everyLinkAsleep()\n if (asleep && isRested) {\n out[0] = restedAx\n out[1] = restedAz\n return\n }\n let dx = 0\n let dz = 0\n for (let i = 0; i < chains.length; i++) {\n chainEnd(world, chains[i] as Chain, tip)\n const top = tops[i] as Vec3\n const offsetX = (tip[0] as number) - top[0]\n const offsetZ = (tip[2] as number) - top[2]\n // the object's yaw undone (the same turn about y as `worldToLocal`)\n dx += offsetX * cosYaw + offsetZ * sinYaw\n dz += -offsetX * sinYaw + offsetZ * cosYaw\n }\n // rotation about x turns the tip toward -z for a positive angle (and about z toward +x), as the world's spring has it\n out[0] = -Math.asin(Math.max(-1, Math.min(1, dz / strips / height)))\n out[1] = Math.asin(Math.max(-1, Math.min(1, dx / strips / height)))\n restedAx = out[0]\n restedAz = out[1]\n isRested = asleep\n },\n push(velocity) {\n const world3 = rotY(velocity, transform.ry)\n for (const chain of chains) {\n for (const body of chain.bodies) world.addImpulse(body, [world3[0] * PUSH_GAIN * linkMass(soft, strips, links), world3[1] * PUSH_GAIN * linkMass(soft, strips, links), world3[2] * PUSH_GAIN * linkMass(soft, strips, links)])\n }\n },\n dispose() {\n if (disposed) return\n disposed = true\n for (const chain of chains) disposeChain(world, chain)\n world.removeBody(rail)\n },\n }\n}\n\nconst linkMass = (soft: SoftSpec, strips: number, links: number): number => (soft.size[0] / strips) * (soft.size[1] / links) * FABRIC_KG_PER_M2\n","import type { BodyId, JointId, Quat, SeamWorld } from '@adatechnology/game-physics'\n\nimport { clamp, rotateAxis } from './math'\nimport type { PartDriver } from './part-physics'\nimport type { Vec3 } from './types'\n\n/** A part driver whose leaf is a body of the engine: the host draws the part where the body is, and after a break the body is all that is left. */\nexport interface EnginePartDriver extends PartDriver {\n readonly leaf: BodyId\n}\n\n/** Units of t per second that close a gap of one t: the leaf slows as it arrives. */\nconst AIM_GAIN = 8\nconst ARRIVED_AT = 0.004\n\nconst axisAngle = (axis: Vec3, angle: number): Quat => {\n const size = Math.hypot(axis[0], axis[1], axis[2]) || 1\n const k = Math.sin(angle / 2) / size\n return [axis[0] * k, axis[1] * k, axis[2] * k, Math.cos(angle / 2)]\n}\nconst multiply = (a: Quat, b: Quat): Quat => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n]\n\n\nexport interface LeafDriverSpec {\n readonly world: SeamWorld\n readonly leaf: BodyId\n readonly frame: BodyId\n readonly ownsFrame: boolean\n readonly joint: JointId\n readonly onDispose: () => void\n readonly drive: { readonly isHinge: boolean; readonly axis: Vec3; readonly pivot: Vec3; readonly centre: Vec3; readonly range: number; readonly speed: number; readonly base: Quat }\n}\n\n\n/** Scratch of every leaf: a driver reads and writes a pose, a velocity pair at a time, so no pose or vector is made per frame. */\nconst pose = new Float64Array(7)\nconst linearScratch: Vec3 = [0, 0, 0]\nconst angularScratch: Vec3 = [0, 0, 0]\nconst NO_SPIN: Vec3 = [0, 0, 0]\n\nexport function createLeafDriver(spec: LeafDriverSpec): EnginePartDriver {\n const { world, leaf, frame, joint, drive } = spec\n const { axis, pivot, centre, range } = drive\n let target = 0\n let settled = true\n let broken = false\n let disposed = false\n let lastT = 0\n /** t of the leaf at rest, kept while it sleeps: nothing moves it, so the joint is not asked again. */\n let restedT: number | undefined\n const measure = (): number => {\n if (drive.isHinge) return world.jointAngles(joint).hinge / range\n world.readPose(leaf, pose, 0)\n return (((pose[0] as number) - centre[0]) * axis[0] + ((pose[1] as number) - centre[1]) * axis[1] + ((pose[2] as number) - centre[2]) * axis[2]) / range\n }\n const read = (): number => {\n if (broken) return lastT\n if (settled && world.isSleeping(leaf)) {\n restedT ??= measure()\n lastT = restedT\n return lastT\n }\n restedT = undefined\n lastT = measure()\n return lastT\n }\n const stop = (): void => {\n world.setVelocity(leaf, NO_SPIN, NO_SPIN)\n settled = true\n }\n // t per second to the leaf's own velocity: a turn about the hinge carries the centre round, a slide is a line\n const move = (rate: number): void => {\n world.wake(leaf)\n const speed = rate * range\n angularScratch[0] = axis[0] * speed\n angularScratch[1] = axis[1] * speed\n angularScratch[2] = axis[2] * speed\n if (!drive.isHinge) return world.setVelocity(leaf, angularScratch, NO_SPIN)\n world.readPose(leaf, pose, 0)\n const armX = (pose[0] as number) - pivot[0]\n const armY = (pose[1] as number) - pivot[1]\n const armZ = (pose[2] as number) - pivot[2]\n linearScratch[0] = angularScratch[1] * armZ - angularScratch[2] * armY\n linearScratch[1] = angularScratch[2] * armX - angularScratch[0] * armZ\n linearScratch[2] = angularScratch[0] * armY - angularScratch[1] * armX\n world.setVelocity(leaf, linearScratch, angularScratch)\n }\n const place = (t: number): void => {\n const amount = t * drive.range\n if (drive.isHinge) {\n const centre = rotateAxis([drive.centre[0] - drive.pivot[0], drive.centre[1] - drive.pivot[1], drive.centre[2] - drive.pivot[2]], drive.axis, amount)\n world.setPose(leaf, [drive.pivot[0] + centre[0], drive.pivot[1] + centre[1], drive.pivot[2] + centre[2]], multiply(axisAngle(drive.axis, amount), drive.base), true)\n } else {\n world.setPose(leaf, [drive.centre[0] + drive.axis[0] * amount, drive.centre[1] + drive.axis[1] * amount, drive.centre[2] + drive.axis[2] * amount], drive.base, true)\n }\n world.setVelocity(leaf, [0, 0, 0], [0, 0, 0])\n }\n return {\n leaf,\n aim(next) {\n if (broken) return\n target = next\n settled = false\n restedT = undefined\n },\n snap(t) {\n target = t\n settled = true\n restedT = undefined\n if (!broken) place(t)\n },\n update() {\n if (broken) return\n if (!world.jointExists(joint)) {\n broken = true\n settled = true\n return\n }\n if (settled) return\n const error = target - read()\n if (Math.abs(error) < ARRIVED_AT) return stop()\n move(clamp(error * AIM_GAIN, -drive.speed, drive.speed))\n },\n read,\n get settled() {\n return settled\n },\n get broken() {\n return broken\n },\n dispose() {\n if (disposed) return\n disposed = true\n spec.onDispose()\n if (!broken) world.removeJoint(joint)\n world.removeBody(leaf)\n if (spec.ownsFrame) world.removeBody(frame)\n },\n }\n}\n","import type { BodyId, Quat, SeamWorld } from '@adatechnology/game-physics'\n\nimport { attachStrips } from './engine-soft'\nimport { createLeafDriver } from './engine-leaf'\nimport type { EnginePartDriver } from './engine-leaf'\nimport { localToWorld, rotY } from './math'\nimport type { PartPhysics } from './part-physics'\nimport type { PartSpec, SoftSpec, Transform, Vec3 } from './types'\n\n/** What a host tells the engine about its objects. */\nexport interface EnginePartOptions {\n /** The object's own static body when the host has one: a leaf does not collide with it. Without it each part gets a hidden anchor at its pivot. */\n readonly frameOf?: (object: string) => BodyId | undefined\n /** The impulse (N s) over which a part's joint breaks, or undefined for a part that never breaks. */\n readonly breakImpulse?: (object: string, part: PartSpec) => number | undefined\n /** Mass of a leaf (kg); default its volume at the density of a hollow door. */\n readonly leafMass?: (object: string, part: PartSpec) => number\n}\n\nexport interface EnginePartPhysics extends PartPhysics {\n /** The leaf body of a part the engine took (also after it broke: then it is a loose body the host draws where it is), or undefined. */\n leafOf(object: string, part: string): BodyId | undefined\n dispose(): void\n}\n\nconst HOLLOW_DOOR_DENSITY = 150\nconst MIN_LEAF_MASS = 1\n/** Newtons that hold a drawer still against its slide, and N m a hinge, so a part stays where it is left. */\nconst SLIDE_HOLD_N = 4\nconst HINGE_HOLD_NM = 0.4\nconst SOFT_KINDS: ReadonlySet<SoftSpec['kind']> = new Set(['cloth', 'curtain', 'strip'])\n\nexport const quatY = (ry: number): Quat => [0, Math.sin(ry / 2), 0, Math.cos(ry / 2)]\nconst cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]\n\nconst perpendicularTo = (axis: Vec3): Vec3 => {\n const side = Math.abs(axis[0]) < 0.9 ? cross(axis, [1, 0, 0]) : cross(axis, [0, 0, 1])\n const size = Math.hypot(side[0], side[1], side[2])\n return [side[0] / size, side[1] / size, side[2] / size]\n}\n\n/** The engine under the movable parts and soft volumes of an interactables world (`WorldOptions.partPhysics`), made of the contract's bodies and joints only. */\nexport function createEnginePartPhysics(world: SeamWorld, options: EnginePartOptions = {}): EnginePartPhysics {\n const disposers = new Set<() => void>()\n const leaves = new Map<string, BodyId>()\n return {\n attachPart(object, part, transform) {\n const key = `${object}:${part.id}`\n const retire = (): void => {\n leaves.delete(key)\n disposers.delete(dispose)\n }\n const dispose = (): void => driver?.dispose()\n const driver = attachLeaf(world, options, { object, part, transform, onDispose: retire })\n if (!driver) return undefined\n leaves.set(key, driver.leaf)\n disposers.add(dispose)\n return driver\n },\n leafOf: (object, part) => leaves.get(`${object}:${part}`),\n attachSoft(_object, soft, transform) {\n const driver = SOFT_KINDS.has(soft.kind) ? attachStrips(world, soft, transform) : undefined\n if (!driver) return undefined\n const dispose = (): void => driver.dispose()\n disposers.add(dispose)\n return { swing: driver.swing, push: driver.push, dispose: () => { disposers.delete(dispose); driver.dispose() } }\n },\n dispose() {\n for (const dispose of [...disposers]) dispose()\n disposers.clear()\n },\n }\n}\n\ninterface LeafRequest {\n readonly object: string\n readonly part: PartSpec\n readonly transform: Transform\n readonly onDispose: () => void\n}\n\n/** A door, lid or drawer: a leaf box on a hinge or a slider, driven toward its target and free once it gets there. Undefined without `bounds` or for another motion. */\nfunction attachLeaf(world: SeamWorld, options: EnginePartOptions, request: LeafRequest): EnginePartDriver | undefined {\n const { object, part, transform } = request\n const motion = part.motion\n const bounds = part.bounds\n if (!bounds || (motion.kind !== 'hinge' && motion.kind !== 'slide')) return undefined\n const isHinge = motion.kind === 'hinge'\n const axisLocal = rotY(motion.axis ?? [0, 1, 0], part.ry ?? 0)\n const axis = rotY(axisLocal, transform.ry)\n const pivot = localToWorld(transform, part.pivot)\n const half: Vec3 = [(bounds[3] - bounds[0]) / 2, (bounds[4] - bounds[1]) / 2, (bounds[5] - bounds[2]) / 2]\n const centre = localToWorld(transform, [(bounds[0] + bounds[3]) / 2, (bounds[1] + bounds[4]) / 2, (bounds[2] + bounds[5]) / 2])\n const rotation = quatY(transform.ry)\n const range = isHinge ? (motion.angle ?? Math.PI / 2) : (motion.distance ?? 0.4)\n const speed = motion.speed ?? 2.5\n const frame = options.frameOf?.(object) ?? world.createBody({ shape: { kind: 'box', half: [0.01, 0.01, 0.01] }, motion: 'static', position: pivot, layer: 'static', user: -3 })\n const ownsFrame = options.frameOf?.(object) === undefined\n const mass = options.leafMass?.(object, part) ?? Math.max(MIN_LEAF_MASS, 8 * half[0] * half[1] * half[2] * HOLLOW_DOOR_DENSITY)\n const leaf = world.createBody({ shape: { kind: 'box', half }, motion: 'dynamic', mass, position: centre, rotation, layer: 'prop', allowSleep: true, user: -3 })\n world.ignorePair(frame, leaf, true)\n const limits = { min: Math.min(0, range), max: Math.max(0, range) }\n const breakImpulse = options.breakImpulse?.(object, part)\n const joint = world.createJoint(\n isHinge\n ? { kind: 'hinge', a: frame, b: leaf, point: pivot, axis, normal: perpendicularTo(axis), ...limits, friction: HINGE_HOLD_NM, ...(breakImpulse === undefined ? {} : { breakImpulse }) }\n : { kind: 'slider', a: frame, b: leaf, point: pivot, axis, ...limits, friction: SLIDE_HOLD_N, ...(breakImpulse === undefined ? {} : { breakImpulse }) },\n )\n return createLeafDriver({ world, leaf, frame, ownsFrame, joint, onDispose: request.onDispose, drive: { isHinge, axis, pivot, centre, range, speed, base: rotation } })\n}\n\n","// A wire hung between two points (a service drop from a pole to a house, a clothesline): its length is what was strung, and the shape it takes between where its\n// ends are now is a catenary of that length. Pulled past its length it stretches as its material does and snaps where its stress passes the material's\n// strength. The ends are where the host says (one may be on a pole that falls): the span never holds them back, since the energy a wire takes in before it\n// snaps (half σ² / E per cubic metre: a few joules for a drop) is nothing beside what a falling pole carries.\nimport type { Vec3 } from './types'\n\n/** Standard gravity, m/s². */\nconst GRAVITY = 9.81\n/** Bisection steps on the shape of the catenary: the arc length comes out within a micrometre for any span the kit strings. */\nconst SHAPE_STEPS = 60\n/** Ends nearer each other than this (metres, across) hang the wire as a loop straight down. */\nconst VERTICAL_SPAN = 1e-4\n\n/** What a span is made of, in real units (`MaterialDef.tension` and `density` of game-destruction). */\nexport type SpanMaterial = {\n /** kg/m³ of the conductor. */\n readonly density: number\n /** Modulus of elasticity, GPa. */\n readonly elasticGPa: number\n /** Ultimate tensile strength, MPa. */\n readonly ultimateMPa: number\n}\n\n/** A wire strung between two points. */\nexport type Span = {\n /** Length of the wire as it was strung, metres. */\n readonly length: number\n /** Cross-section that carries the pull, m² (the conductors, not the insulation). */\n readonly section: number\n readonly material: SpanMaterial\n}\n\n/** Where a span's ends are and how it is drawn. */\nexport type SolveSpanParams = {\n readonly span: Span\n readonly from: Vec3\n readonly to: Vec3\n /** Points along the wire, both ends included (default 16). */\n readonly segments?: number\n /** Height of the ground under a point (x, z): the wire lies on it where it would hang lower. */\n readonly ground?: (x: number, z: number) => number\n /** How far above the ground the wire's axis lies (its radius). */\n readonly clearance?: number\n}\n\n/** The shape a span takes and the pull at its ends. */\nexport type SpanShape = {\n readonly points: Vec3[]\n /** The larger pull at an end, newtons. */\n readonly tension: number\n /** Pulled straight past its strung length. */\n readonly taut: boolean\n /** The end where the stress passed the material's strength, else null. */\n readonly snaps: 'from' | 'to' | null\n}\n\n/** Length of a polyline. */\nexport function polylineLength(points: readonly Vec3[]): number {\n let length = 0\n for (let i = 1; i < points.length; i++) length += Math.hypot(points[i]![0] - points[i - 1]![0], points[i]![1] - points[i - 1]![1], points[i]![2] - points[i - 1]![2])\n return length\n}\n\n/** z with sinh(z) / z = ratio (ratio ≥ 1): the half span over the catenary's parameter. */\nfunction shapeOf(ratio: number): number {\n let low = 1e-9\n let high = 1\n while (Math.sinh(high) / high < ratio && high < 700) high *= 2\n for (let i = 0; i < SHAPE_STEPS; i++) {\n const mid = (low + high) / 2\n if (Math.sinh(mid) / mid < ratio) low = mid\n else high = mid\n }\n return (low + high) / 2\n}\n\n/** The breaking pull of a span, newtons. */\nexport function spanStrength(span: Span): number {\n return span.material.ultimateMPa * 1e6 * span.section\n}\n\ntype EndPulls = { readonly points: Vec3[]; readonly pullFrom: number; readonly pullTo: number }\n\n/** Pulled straight past its length: the stretch pulls both ends, and each carries its share of the wire's weight (the upper one more). */\nfunction straight(params: SolveSpanParams, count: number, weight: number, chord: number): EndPulls {\n const { span, from, to } = params\n const pull = span.material.elasticGPa * 1e9 * span.section * ((chord - span.length) / span.length)\n const rise = to[1] - from[1]\n const points = Array.from({ length: count }, (_, i): Vec3 => {\n const t = i / (count - 1)\n return [from[0] + (to[0] - from[0]) * t, from[1] + rise * t, from[2] + (to[2] - from[2]) * t]\n })\n return { points, pullFrom: pull + (weight * (span.length - rise)) / 2, pullTo: pull + (weight * (span.length + rise)) / 2 }\n}\n\n/** Ends one over the other: straight down from each to the bottom of the loop. */\nfunction loop(params: SolveSpanParams, count: number, weight: number): EndPulls {\n const { span, from, to } = params\n const bottom = (from[1] + to[1] - span.length) / 2\n const down = from[1] - bottom\n const points = Array.from({ length: count }, (_, i): Vec3 => {\n const s = (i / (count - 1)) * span.length\n return s <= down ? [from[0], from[1] - s, from[2]] : [to[0], bottom + (s - down), to[2]]\n })\n return { points, pullFrom: weight * down, pullTo: weight * (to[1] - bottom) }\n}\n\n/** y = c cosh((x - x0) / c) with its arc length the wire's (sqrt(L² - v²) = 2 c sinh(h / 2c)); the pull at an end is the weight per metre times c cosh there. */\nfunction hanging(params: SolveSpanParams, count: number, weight: number, across: number): EndPulls {\n const { span, from, to } = params\n const rise = to[1] - from[1]\n const c = across / (2 * shapeOf(Math.sqrt(span.length * span.length - rise * rise) / across))\n const x0 = across / 2 - c * Math.atanh(rise / span.length)\n const base = Math.cosh(-x0 / c)\n const points = Array.from({ length: count }, (_, i): Vec3 => {\n const t = i / (count - 1)\n return [from[0] + (to[0] - from[0]) * t, from[1] + c * (Math.cosh((across * t - x0) / c) - base), from[2] + (to[2] - from[2]) * t]\n })\n return { points, pullFrom: weight * c * base, pullTo: weight * c * Math.cosh((across - x0) / c) }\n}\n\n/** The shape of a span between its ends now, the pull at its ends and whether it snaps (at the end that pulls the harder). */\nexport function solveSpan(params: SolveSpanParams): SpanShape {\n const { span, from, to } = params\n const count = Math.max(2, Math.floor(params.segments ?? 16))\n const weight = span.material.density * span.section * GRAVITY\n const across = Math.hypot(to[0] - from[0], to[2] - from[2])\n const chord = Math.hypot(across, to[1] - from[1])\n const taut = chord >= span.length\n const shape = taut ? straight(params, count, weight, chord) : across < VERTICAL_SPAN ? loop(params, count, weight) : hanging(params, count, weight, across)\n const ground = params.ground\n if (ground) for (const p of shape.points) p[1] = Math.max(p[1], ground(p[0], p[2]) + (params.clearance ?? 0))\n const tension = Math.max(shape.pullFrom, shape.pullTo)\n const snaps = tension > spanStrength(span) ? (shape.pullFrom >= shape.pullTo ? 'from' : 'to') : null\n return { points: shape.points, tension, taut, snaps }\n}\n\n/** A wire hung by one end, the other loose: what a snapped span leaves on the end that held. */\nexport type HangTailParams = {\n readonly anchor: Vec3\n readonly length: number\n /** The way the loose end lies along the ground (horizontal; default +x). */\n readonly toward?: Vec3\n readonly segments?: number\n readonly ground?: (x: number, z: number) => number\n readonly clearance?: number\n}\n\n/** Straight down from its anchor to the ground, and the rest of its length lying along the ground toward `toward`. */\nexport function hangTail(params: HangTailParams): Vec3[] {\n const { anchor, length } = params\n const count = Math.max(2, Math.floor(params.segments ?? 16))\n const clearance = params.clearance ?? 0\n const floorAt = (x: number, z: number): number => (params.ground ? params.ground(x, z) + clearance : -Infinity)\n const drop = Math.max(0, Math.min(length, anchor[1] - floorAt(anchor[0], anchor[2])))\n const toward = params.toward ?? [1, 0, 0]\n const flat = Math.hypot(toward[0], toward[2]) || 1\n return Array.from({ length: count }, (_, i): Vec3 => {\n const s = (i / (count - 1)) * length\n if (s <= drop) return [anchor[0], anchor[1] - s, anchor[2]]\n const x = anchor[0] + (toward[0] / flat) * (s - drop)\n const z = anchor[2] + (toward[2] / flat) * (s - drop)\n return [x, Math.max(anchor[1] - drop, floorAt(x, z)), z]\n })\n}\n","// A wire fixed along what it runs on (a conduit strapped up a pole, a cable clipped along a wall): each stretch of it goes with the part under it. Where the\n// part under it changes (two stretches of a pole), the wire is cut in two at the seam: whole, the two runs meet there and read as one; when the parts come\n// apart each run goes with its own, and the wire is broken at the seam, never drawn straight through the air from one part to the other.\nimport type { Vec3 } from './types'\n\n/** One stretch of a wire and what holds it. */\nexport type WireRun<THolder> = {\n readonly holder: THolder\n readonly points: Vec3[]\n}\n\nexport type WireRunsParams<THolder> = {\n readonly points: readonly Vec3[]\n /** Longest step (metres) between two points the holder is read at: where the holder changes is found within it. */\n readonly step: number\n /** What holds the wire at a point (the part it is fixed on there). */\n readonly holderOf: (point: Vec3) => THolder\n}\n\nconst lerp = (a: Vec3, b: Vec3, t: number): Vec3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]\n\n/** The points of the wire every `step` at most along it, its own points kept. */\nfunction along(points: readonly Vec3[], step: number): Vec3[] {\n const out: Vec3[] = points.length ? [[...points[0]!] as Vec3] : []\n for (let i = 1; i < points.length; i++) {\n const a = points[i - 1]!\n const b = points[i]!\n const steps = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) / step))\n for (let k = 1; k <= steps; k++) out.push(lerp(a, b, k / steps))\n }\n return out\n}\n\n/** The runs of a wire by what holds it, in order along it; two runs that follow each other share the point half way between their last and first readings. */\nexport function wireRuns<THolder>(params: WireRunsParams<THolder>): WireRun<THolder>[] {\n const points = along(params.points, Math.max(1e-3, params.step))\n if (points.length < 2) return []\n const holders = points.map((p) => params.holderOf(p))\n const runs: WireRun<THolder>[] = []\n let current: { holder: THolder; points: Vec3[] } = { holder: holders[0]!, points: [points[0]!] }\n for (let i = 1; i < points.length; i++) {\n if (holders[i] === current.holder) {\n current.points.push(points[i]!)\n continue\n }\n const seam = lerp(points[i - 1]!, points[i]!, 0.5)\n current.points.push(seam)\n runs.push(current)\n current = { holder: holders[i]!, points: [[...seam] as Vec3, points[i]!] }\n }\n runs.push(current)\n return runs\n}\n","// What is drawn on an upright member (a pole's shaft laid in stretches) and is the same casting as it: a collar round a stretch (the bands on a pole) or a\n// foot or a cap on its end (the flared base of a pole). Such a primitive is one piece with the stretch, with the same concrete round the same cage, worn by the\n// rounds as the member is: never a block of its own the rounds tunnel through, or a ring left on the stub.\n\n/** An axis-aligned box as [min x, min y, min z, max x, max y, max z], metres. */\nexport type CastBox = readonly number[]\n\n/** Metres a collar, a foot or a cap may stand out of the member, each side. */\nexport const COLLAR_REACH = 0.03\n/** Metres a foot or a cap may stand apart from the end of the member (the seam between two primitives drawn end to end). */\nexport const END_GAP = 0.005\n\n/** Centred on the member across (x and z) and standing out of it by `COLLAR_REACH` at most. */\nfunction centredOn(member: CastBox, other: CastBox): boolean {\n for (const k of [0, 2]) {\n if (other[k]! < member[k]! - COLLAR_REACH || other[k + 3]! > member[k + 3]! + COLLAR_REACH) return false\n if (Math.abs((other[k]! + other[k + 3]!) / 2 - (member[k]! + member[k + 3]!) / 2) > COLLAR_REACH) return false\n }\n return true\n}\n\n/** A collar drawn round the stretch: most of its height on it (a band on the seam of two goes with the one it is mostly on). */\nexport function wrapsMember(member: CastBox, collar: CastBox): boolean {\n const overlap = Math.min(collar[4]!, member[4]!) - Math.max(collar[1]!, member[1]!)\n return overlap >= (collar[4]! - collar[1]!) / 2 && centredOn(member, collar)\n}\n\n/** A foot under the stretch or a cap over it, no taller than it. */\nexport function endsMember(member: CastBox, end: CastBox): boolean {\n const under = Math.abs(end[4]! - member[1]!) <= END_GAP\n const over = Math.abs(end[1]! - member[4]!) <= END_GAP\n return (under || over) && end[4]! - end[1]! <= member[4]! - member[1]! && centredOn(member, end)\n}\n\n/** Whether `other` is cast with the stretch `member`: a collar round it, or a foot or a cap on its end. */\nexport function castWithMember(member: CastBox, other: CastBox): boolean {\n return wrapsMember(member, other) || endsMember(member, other)\n}\n","import type { Vec3 } from './types'\n\n/** Whether a thing of `size` (any turn of it) goes into a box of `half` sizes: each of its sides, longest first, against the box's, longest first. */\nexport function fitsInVolume(size: readonly [number, number, number], half: Vec3): boolean {\n const thing = [...size].sort((a, b) => b - a)\n const room = half.map((h) => h * 2).sort((a, b) => b - a)\n return thing.every((side, i) => side <= (room[i] ?? 0))\n}\n","/**\n * The uses at a fixture's water (`do: 'wash'` and `do: 'drink'` of `ObjectSpec.uses`): whether they can run now (the things they need at hand, dishes dirty in the\n * basin, a vessel to drink from) and the routine each runs over its seconds once started: open the water, scrub foam in, let the water rinse it off, close the water;\n * or fill the vessel under the stream, close the water, drink and put the vessel back. Pure: the host lends the hand, the items, the body's hand uses and the foam\n * (`ItemControlsHost`); the water is the object's own fixture in its interactables world, so it runs as fast as the fixture does and stops when its tank is dry.\n */\nimport type { ItemControlsHost, ReachedItem } from '@adatechnology/game-contracts'\n\nimport type { DrinkUseSpec, FixtureSpec, ObjectSpec, UseNeed, Vec3, WashUseSpec, World } from './types'\nimport { FLOW_DEFAULTS } from './world'\n\n/** Seconds of scrubbing per thing washed, when the use does not say. */\nexport const WASH_SCRUB_SECONDS = 3\n/** Litres drunk at most from a vessel filled at a tap: a glass of water. */\nexport const DRINK_LITRES = 0.25\n/** A vessel filled at a tap is stopped this full (share of what it takes). */\nexport const FILL_SHARE = 0.85\n/** Litres a mouth drinks per second. */\nexport const DRINK_LPS = 0.06\n/** Seconds the hand takes to reach the tap's lever, and to put a thing down. */\nexport const REACH_SECONDS = 0.6\n/** Seconds the water may take to start running after the lever opens (the fixture flows from the next step) before the tap counts as dry. */\nexport const DRY_SECONDS = 0.5\n/** Dirt left on a dish once scrubbed: the rest goes with the rinse. */\nconst SCRUBBED_DIRT = 0.15\n\nexport type SinkUseSpec = WashUseSpec | DrinkUseSpec\n\nexport type SinkVerdict = { readonly available: true } | { readonly available: false; readonly reason: string; readonly vars?: Record<string, string> }\nconst YES: SinkVerdict = { available: true }\n\n/** What a routine says when it ends: a locale key and its words. */\nexport interface RoutineEnd {\n readonly key: string\n readonly ok: boolean\n readonly vars?: Record<string, string>\n}\n\n/** A use at the water running over its seconds. `step` answers the end once it is over. */\nexport interface SinkRoutine {\n readonly use: string\n step(dt: number): RoutineEnd | null\n}\n\nexport interface SinkRoutines {\n start(use: SinkUseSpec, host: ItemControlsHost): SinkRoutine\n}\n\nexport interface SinkUsesOptions {\n readonly spec: ObjectSpec\n readonly world: World\n readonly objectId: string\n}\n\n/** A routine as a list of phases, each run until it answers true (done). */\ntype Phase = (dt: number) => boolean\n\nconst idsOf = (need: UseNeed): readonly string[] => (typeof need === 'string' ? [need] : need)\n\n/** The item of each need, or the ids of the first need nothing answers. */\nexport function findNeeds(needs: readonly UseNeed[], host: ItemControlsHost): { readonly items: readonly ReachedItem[]; readonly missing?: readonly string[] } {\n const items: ReachedItem[] = []\n for (const need of needs) {\n const item = host.itemAt?.(idsOf(need)) ?? null\n if (!item) return { items, missing: idsOf(need) }\n items.push(item)\n }\n return { items }\n}\n\n/** The dirty dishes lying in the use's basin. */\nexport function dirtyDishes(use: WashUseSpec, spec: ObjectSpec, host: ItemControlsHost): readonly ReachedItem[] {\n const dishes = use.dishes\n const basin = dishes ? (spec.basins ?? []).find((b) => b.id === dishes.basin) : undefined\n if (!dishes || !basin) return []\n return (host.itemsInside?.(dishes.ids, basin.from, basin.to) ?? []).filter((item) => (item.dirt ?? 0) > 0)\n}\n\n/** Whether a use at the water can run now, and why not (a locale key with its words). `flowing`: the use's fixture runs now. */\nexport function sinkVerdict(use: SinkUseSpec, spec: ObjectSpec, host: ItemControlsHost, flowing: boolean): SinkVerdict {\n if (use.do === 'wash' && use.requiresFlowing && !flowing) return { available: false, reason: 'needs_running' }\n const found = findNeeds(use.needs ?? [], host)\n if (found.missing) return { available: false, reason: 'needs_item', vars: { need: found.missing[0] ?? '' } }\n if (use.do === 'drink') return YES\n const dosed = use.dose ? found.items[use.dose.need] : undefined\n if (dosed && (dosed.remaining ?? 1) <= 0) return { available: false, reason: 'item_spent', vars: { item: dosed.name } }\n if (use.dishes && dirtyDishes(use, spec, host).length === 0) return { available: false, reason: 'no_dirty_dishes' }\n return YES\n}\n\n/** Litres per second the fixture runs fully open. */\nexport const fixtureFlowLps = (fixture: FixtureSpec | undefined): number => (fixture ? (fixture.flow ?? FLOW_DEFAULTS[fixture.kind] ?? 6) / 60 : 0)\n\n/** Runs the phases in turn, one step each at most: a phase that ends starts the next on the next step, so no phase ever runs a step of no time. */\nfunction runPhases(phases: readonly Phase[]): (dt: number) => boolean {\n let index = 0\n return (dt) => {\n if (index < phases.length && phases[index]?.(dt)) index++\n return index >= phases.length\n }\n}\n\nfunction wait(seconds: number): Phase {\n let left = seconds\n return (dt) => (left -= dt) <= 0\n}\n\n/** The thing goes down on `spot` (a washed dish on the drainboard). */\nfunction placePhase(host: ItemControlsHost, item: ReachedItem, spot: Vec3 | readonly [number, number, number] | undefined): Phase {\n return () => {\n if (spot) host.placeItem?.(item.objectId, [spot[0], spot[1], spot[2]])\n return true\n }\n}\n\nexport function createSinkRoutines(options: SinkUsesOptions): SinkRoutines {\n const { spec, world, objectId } = options\n const fixtureOf = (id: string): FixtureSpec | undefined => (spec.fixtures ?? []).find((f) => f.id === id)\n const flowing = (use: SinkUseSpec): boolean => world.water.isFlowing(objectId, use.fixture)\n const water = (use: SinkUseSpec): number => (flowing(use) ? fixtureFlowLps(fixtureOf(use.fixture)) : 0)\n /** The water running now, litres per second; 0 while it starts; null once it stayed dry past `DRY_SECONDS`. */\n const waterOf = (use: SinkUseSpec): ((dt: number) => number | null) => {\n let dry = 0\n return (dt) => {\n const flow = water(use)\n dry = flow > 0 ? 0 : dry + dt\n return dry > DRY_SECONDS ? null : flow\n }\n }\n\n /** Opens the water (when the use opens it, after the hand reaches the lever) and closes it again at the end, if this use opened it. */\n const tapPhases = (use: SinkUseSpec): { readonly open: Phase; readonly close: Phase } => {\n let opened = false\n const reach = wait(REACH_SECONDS)\n return {\n open: (dt) => {\n if (opened || use.opensFixture === false || flowing(use)) return true\n if (!reach(dt)) return false\n opened = world.setFixture(objectId, use.fixture, true)\n return true\n },\n close: () => {\n if (opened) world.setFixture(objectId, use.fixture, false)\n return true\n },\n }\n }\n\n /** Scrubbing foam into one thing (dirt coming off with it), then rinsing until the foam is gone (the rest of the dirt with it). */\n const scrubAndRinse = (use: WashUseSpec, host: ItemControlsHost, target: ReachedItem | string, fail: (end: RoutineEnd) => void): Phase[] => {\n const item = typeof target === 'string' ? undefined : target\n const id = item?.objectId ?? (target as string)\n const seconds = use.scrubSeconds ?? WASH_SCRUB_SECONDS\n const dirt = item?.dirt ?? 0\n let scrubbed = -1\n const scrub: Phase = (dt) => {\n if (scrubbed < 0) {\n scrubbed = 0\n host.playUse?.(use.clip, item?.objectId)\n }\n scrubbed = Math.min(seconds, scrubbed + dt)\n host.lather?.(id, dt / seconds)\n if (dirt > 0) host.setDirt?.(id, dirt - (dirt - Math.min(dirt, SCRUBBED_DIRT)) * (scrubbed / seconds))\n return scrubbed >= seconds\n }\n const running = waterOf(use)\n const rinse: Phase = (dt) => {\n const flow = running(dt)\n if (flow === null) {\n fail({ key: 'no_water', ok: false })\n return true\n }\n if (flow <= 0 || (host.rinse?.(id, flow, dt) ?? 0) > 0) return false\n if (dirt > 0) host.setDirt?.(id, 0)\n return true\n }\n return [scrub, rinse]\n }\n\n const startWash = (use: WashUseSpec, host: ItemControlsHost): SinkRoutine => {\n const { items } = findNeeds(use.needs ?? [], host)\n let end: RoutineEnd | null = null\n const fail = (reason: RoutineEnd): void => {\n end ??= reason\n }\n const tap = tapPhases(use)\n const dosed = use.dose ? items[use.dose.need] : undefined\n const dose: Phase = () => {\n if (dosed && host.takeDose?.(dosed.objectId, use.dose?.amount).taken === 0) fail({ key: 'item_spent', ok: false, vars: { item: dosed.name } })\n return true\n }\n const dishes = use.dishes ? dirtyDishes(use, spec, host) : []\n const rack = use.dishes?.rack ?? []\n const work: Phase[] = use.dishes\n ? dishes.flatMap((dish, index) => [...scrubAndRinse(use, host, dish, fail), placePhase(host, dish, rack[Math.min(index, rack.length - 1)])])\n : scrubAndRinse(use, host, use.surface, fail)\n const guarded = work.map((phase): Phase => (dt) => end !== null || phase(dt))\n const run = runPhases([tap.open, dose, ...guarded, tap.close])\n const done: RoutineEnd = use.dishes ? { key: 'done_wash_dishes', ok: true, vars: { n: String(dishes.length) } } : { key: 'done_wash', ok: true, vars: { surface: use.surface } }\n return { use: use.id, step: (dt) => (run(dt) ? (end ?? done) : null) }\n }\n\n const startDrink = (use: DrinkUseSpec, host: ItemControlsHost, vessel: ReachedItem): SinkRoutine => {\n const tap = tapPhases(use)\n const want = Math.min(use.litres ?? DRINK_LITRES, (vessel.liquid?.capacity ?? DRINK_LITRES) * FILL_SHARE)\n let filled = vessel.liquid?.kind === 'water' ? vessel.liquid.litres : 0\n let drunk = 0\n let end: RoutineEnd | null = null\n const take: Phase = () => {\n if (vessel.where !== 'hand' && host.holdItem?.(vessel.objectId) === false) end = { key: 'needs_item', ok: false, vars: { need: vessel.itemId } }\n else host.playUse?.(use.fillClip ?? 'fill_cup', vessel.objectId)\n return true\n }\n const running = waterOf(use)\n const fill: Phase = (dt) => {\n if (end) return true\n const flow = running(dt)\n if (flow === null) {\n end = { key: 'no_water', ok: false }\n return true\n }\n if (flow <= 0) return false\n const took = host.fillItem?.(vessel.objectId, 'water', Math.min(flow * dt, want - filled)) ?? 0\n filled += took\n return filled >= want - 1e-6 || took <= 0\n }\n let sipping = false\n const drink: Phase = (dt) => {\n if (end) return true\n if (!sipping) sipping = host.playUse?.(use.clip, vessel.objectId) ?? true\n const sip = host.drinkItem?.(vessel.objectId, Math.min(DRINK_LPS * dt, filled - drunk)) ?? 0\n drunk += sip\n return drunk >= filled - 1e-6 || sip <= 0\n }\n const giveBack = vessel.where === 'reach' ? placePhase(host, vessel, vessel.at) : (): boolean => true\n const run = runPhases([take, tap.open, fill, tap.close, drink, wait(REACH_SECONDS), giveBack])\n return { use: use.id, step: (dt) => (run(dt) ? (end ?? { key: 'done_drink', ok: true, vars: { litres: drunk.toFixed(2) } }) : null) }\n }\n\n return {\n start(use, host) {\n if (use.do === 'wash') return startWash(use, host)\n const vessel = findNeeds(use.needs, host).items[0]\n if (!vessel) return { use: use.id, step: () => ({ key: 'needs_item', ok: false, vars: { need: idsOf(use.needs[0] ?? '')[0] ?? '' } }) }\n return startDrink(use, host, vessel)\n },\n }\n}\n","/**\n * What an object does with the player's hand or on its own time (`ObjectSpec.uses`), for `createObjectControls`: a device's program that runs for its seconds, what\n * the hand holds put inside when it fits, a container emptied, a bowl filled from the hand, a basin soiled and washed by its flush. The rules are the data's: the\n * container's inside, the bowl's capacity and what it accepts, the access part that must be open (or closed, for a program).\n */\nimport type { ControlledHand, ItemControl, ItemControlResult, ItemControlsHost } from '@adatechnology/game-contracts'\n\nimport { fitsInVolume } from './fits-volume'\nimport { createSinkRoutines, sinkVerdict } from './sink-uses'\nimport type { SinkRoutine } from './sink-uses'\nimport type { BowlSpec, ContainerSpec, ObjectSpec, UseSpec, World } from './types'\n\n/** What a basin holds, worst last: a flush washes it back to clean. */\nexport type Soil = 'clean' | 'urine' | 'feces'\n\nexport interface UsesState {\n /** kg of food or litres of water in each bowl. */\n readonly bowls: Readonly<Record<string, number>>\n readonly soil: Readonly<Record<string, Soil>>\n /** The program running, with its seconds left. */\n readonly program: { readonly use: string; readonly device: string; readonly left: number } | null\n /** The use at the water running now (`wash`, `drink`), by id. */\n readonly routine: string | null\n}\n\nexport interface Uses {\n has(id: string): boolean\n list(host: ItemControlsHost): ItemControl[]\n run(id: string, host: ItemControlsHost): ItemControlResult\n update(dt: number): void\n /** A fixture of the object ran its water: the basin it cleans is clean again. */\n flushed(fixture: string): void\n state(): UsesState\n}\n\nexport interface UsesOptions {\n readonly spec: ObjectSpec\n readonly world: World\n readonly objectId: string\n}\n\nconst OPEN = 0.5\nconst PREFIX = 'use.'\nconst SOIL_RANK: Record<Soil, number> = { clean: 0, urine: 1, feces: 2 }\n\nconst clock = (seconds: number): string => {\n const s = Math.max(0, Math.ceil(seconds))\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`\n}\n\n/** Whether the hand's item is one the bowl accepts: its id, or a room id that ends with it (`item_dog_food` for `dog_food`). */\nconst accepts = (bowl: BowlSpec, hand: ControlledHand): boolean => (bowl.accepts ?? []).some((id) => hand.itemId === id || hand.itemId.endsWith(`_${id}`))\n\ntype Verdict = { readonly available: true } | { readonly available: false; readonly reason: string; readonly vars?: Record<string, string> }\nconst YES: Verdict = { available: true }\nconst no = (reason: string): Verdict => ({ available: false, reason })\n\nexport function createUses(options: UsesOptions): Uses {\n const { spec, world, objectId } = options\n const all = spec.uses ?? []\n const containers = new Map<string, ContainerSpec>((spec.containers ?? []).map((c) => [c.id, c]))\n const bowls = new Map<string, BowlSpec>((spec.bowls ?? []).map((b) => [b.id, b]))\n const level = new Map<string, number>((spec.bowls ?? []).map((b) => [b.id, Math.min(b.capacity, b.level ?? 0)]))\n const soil = new Map<string, Soil>((spec.basins ?? []).filter((b) => b.soils).map((b) => [b.id, 'clean']))\n const cleans = new Map<string, string>((spec.fixtures ?? []).flatMap((f) => (f.cleans ? [[f.id, f.cleans] as const] : [])))\n let program: { use: Extract<UseSpec, { do: 'program' }>; left: number } | null = null\n let lastHost: ItemControlsHost | null = null\n const sinkRoutines = createSinkRoutines({ spec, world, objectId })\n let routine: SinkRoutine | null = null\n\n const typeKey = `type.${spec.type}`\n const name = (): string => {\n const text = world.t(typeKey)\n return text === typeKey ? spec.type.replace(/_/g, ' ') : text.charAt(0).toLowerCase() + text.slice(1)\n }\n const accessOpen = (host: ItemControlsHost, part: string | undefined): boolean => !part || host.partOpening(part) >= OPEN\n\n const verdict = (use: UseSpec, host: ItemControlsHost): Verdict => {\n const hand = host.hand()\n switch (use.do) {\n case 'program':\n if (!world.power.isPowered(objectId, use.device)) return no('no_power')\n return use.access && host.partOpening(use.access) >= OPEN ? no('needs_closed') : YES\n case 'put_in': {\n const c = containers.get(use.container)\n if (!hand) return no('hand_empty')\n if (!c || !accessOpen(host, c.access)) return no('requires_open')\n return fitsInVolume(hand.size, c.volume.half) ? YES : no('not_fit')\n }\n case 'empty':\n return accessOpen(host, containers.get(use.container)?.access) ? YES : no('requires_open')\n case 'fill': {\n const bowl = bowls.get(use.bowl)\n if (!bowl) return no('empty')\n if ((level.get(bowl.id) ?? 0) >= bowl.capacity - 1e-6) return no('bowl_full')\n if (!hand) return no('hand_empty')\n if (bowl.holds === 'water' && hand.liquid?.kind === 'water' && hand.liquid.closed) return no('requires_open')\n const fits = bowl.holds === 'water' ? hand.liquid?.kind === 'water' && hand.liquid.litres > 0 : accepts(bowl, hand)\n return fits ? YES : no('not_accepted')\n }\n case 'relieve':\n return YES\n case 'wash':\n case 'drink':\n return routine ? no('busy') : sinkVerdict(use, spec, host, world.water.isFlowing(objectId, use.fixture))\n }\n }\n\n /** A catalogue item's name in the content pack's strings (`item.<id>`), or its id in words. */\n const itemName = (id: string): string => {\n const text = world.t(`item.${id}`)\n return text === `item.${id}` ? id.replace(/_/g, ' ') : text\n }\n const reasonOf = (v: Extract<Verdict, { available: false }>, use: UseSpec, host: ItemControlsHost): string => {\n const words = { ...textVars(use, host), ...v.vars }\n return world.t(v.reason, words.need ? { ...words, need: itemName(words.need) } : words)\n }\n\n const textVars = (use: UseSpec, host: ItemControlsHost): Record<string, string> => ({\n name: name(),\n item: host.hand()?.name ?? '',\n bowl: world.t(`bowl.${use.do === 'fill' ? (bowls.get(use.bowl)?.holds ?? 'food') : 'food'}`),\n })\n\n const labelOf = (use: UseSpec, host: ItemControlsHost): string => world.t(use.do === 'put_in' && !host.hand() ? 'use.put_in.none' : use.label, textVars(use, host))\n\n const runUse = (use: UseSpec, host: ItemControlsHost): ItemControlResult => {\n const vars = textVars(use, host)\n switch (use.do) {\n case 'program': {\n world.setDevice(objectId, use.device, true)\n program = { use, left: use.seconds }\n return { ok: true, text: world.t('done_program', { ...vars, program: world.t(use.label), time: clock(use.seconds) }) }\n }\n case 'put_in': {\n const c = containers.get(use.container) as ContainerSpec\n return host.placeHand(c.volume.center) ? { ok: true, text: world.t('done_put_in', vars) } : { ok: false, text: world.t('not_fit', vars) }\n }\n case 'empty': {\n const c = containers.get(use.container) as ContainerSpec\n const [cx, cy, cz] = c.volume.center\n const [hx, hy, hz] = c.volume.half\n const n = host.emptyInside([cx - hx, cy - hy, cz - hz], [cx + hx, cy + hy, cz + hz])\n return { ok: n > 0, text: world.t(n > 0 ? 'done_empty' : 'empty', { ...vars, n }) }\n }\n case 'fill':\n return fill(bowls.get(use.bowl) as BowlSpec, host, vars)\n case 'relieve': {\n const now = soil.get(use.basin) ?? 'clean'\n soil.set(use.basin, SOIL_RANK[use.kind] > SOIL_RANK[now] ? use.kind : now)\n return { ok: true, text: world.t(`done_relieve_${use.kind}`, vars) }\n }\n case 'wash':\n case 'drink':\n routine = sinkRoutines.start(use, host)\n return { ok: true, text: world.t(`started_${use.do}`, { ...vars, label: world.t(use.label, vars) }) }\n }\n }\n\n const fill = (bowl: BowlSpec, host: ItemControlsHost, vars: Record<string, string>): ItemControlResult => {\n const now = level.get(bowl.id) ?? 0\n const added = bowl.holds === 'water' ? host.pourHand(bowl.capacity - now) : bowl.capacity - now\n level.set(bowl.id, Math.min(bowl.capacity, now + added))\n return { ok: added > 0, text: world.t(added > 0 ? 'done_fill' : 'not_accepted', vars) }\n }\n\n const stopProgram = (): string => {\n if (!program) return ''\n world.setDevice(objectId, program.use.device, false)\n program = null\n return world.t('done_program_stop', { name: name() })\n }\n\n const stepRoutine = (dt: number): void => {\n const end = routine?.step(dt)\n if (!end) return\n routine = null\n const words = end.vars?.need ? { ...end.vars, need: itemName(end.vars.need) } : end.vars\n lastHost?.say(world.t(end.key, { name: name(), ...words }))\n }\n\n const visible = (use: UseSpec): boolean => use.do !== 'program' || program === null\n\n return {\n has: (id) => id.startsWith(PREFIX),\n list(host) {\n lastHost = host\n const entries: ItemControl[] = []\n if (program) entries.push({ id: `${PREFIX}stop`, label: world.t('use.program.stop', { name: name(), left: clock(program.left) }), available: true })\n for (const use of all.filter(visible)) {\n const v = verdict(use, host)\n entries.push({ id: `${PREFIX}${use.id}`, label: labelOf(use, host), available: v.available, ...(v.available ? {} : { reason: reasonOf(v, use, host) }) })\n }\n return entries\n },\n run(id, host) {\n lastHost = host\n if (id === `${PREFIX}stop`) return { ok: program !== null, text: stopProgram() }\n const use = all.find((u) => `${PREFIX}${u.id}` === id)\n if (!use || !visible(use)) return { ok: false, text: '' }\n const v = verdict(use, host)\n return v.available ? runUse(use, host) : { ok: false, text: reasonOf(v, use, host) }\n },\n update(dt) {\n stepRoutine(dt)\n if (!program) return\n program.left -= dt\n if (program.left > 0) return\n const done = world.t('done_program_end', { name: name(), program: world.t(program.use.label) })\n world.setDevice(objectId, program.use.device, false)\n program = null\n lastHost?.say(done)\n },\n flushed(fixture) {\n const basin = cleans.get(fixture)\n if (!basin || soil.get(basin) === 'clean') return\n soil.set(basin, 'clean')\n lastHost?.say(world.t('done_clean', { name: name() }))\n },\n state: () => ({\n bowls: Object.fromEntries(level),\n soil: Object.fromEntries(soil),\n program: program ? { use: program.use.id, device: program.use.device, left: program.left } : null,\n routine: routine?.use ?? null,\n }),\n }\n}\n","/**\n * The controls of one object for a host that moves the object's parts itself (a test room plays the parts' clips, a game its own animation): what the object's spec\n * says it does (its devices, fixtures, burners and fuel, run by an interactables world of its own fed by the mains), plus what it does with the player's hand or on\n * its own time (`ObjectSpec.uses`: a program, putting in, emptying, filling a bowl, relieving oneself). Data-driven: nothing here knows a TV from a toilet. Pure: no\n * three.js; the drawing of what the state shows (a screen's picture, a bowl's level, a fire) reads `state()`.\n */\nimport type { ItemControl, ItemControlResult, ItemControls, ItemControlsHost } from '@adatechnology/game-contracts'\n\nimport { createUses } from './object-uses'\nimport type { UsesState } from './object-uses'\nimport type { Action, ActiveEmitter, Interactable, InteractablesLocale, ObjectSpec, Strings, Vec3 } from './types'\nimport { createWorld } from './world'\n\n/** The id the object has in its own world. */\nexport const CONTROLLED_OBJECT = 'object'\nconst MAINS = 'mains'\nconst MAINS_TANK = 'water'\n\n/** World interactions a host that moves the parts itself does on its own (opening, taking, reading, sitting) or that belong to a building (a breaker). */\nconst HOST_KINDS: ReadonlySet<Action['do']> = new Set(['toggle_part', 'open_container', 'take', 'read', 'sit', 'toggle_breaker'])\n\nexport interface ObjectControlsOptions {\n readonly spec: ObjectSpec\n readonly locale?: string\n /** The content pack's strings (`Household.strings`). */\n readonly strings?: Partial<Record<InteractablesLocale, Strings>>\n /** Whether the mains give power and water. Default both: a piece standing on its own in a test room is plugged in and piped. */\n readonly mains?: { readonly power?: boolean; readonly water?: boolean }\n}\n\n/** What the object shows now, for its drawing. */\nexport interface ObjectControlsState extends UsesState {\n /** Screens on and powered, with their channel. */\n readonly screens: ReadonlyArray<{ readonly device: string; readonly channel: number }>\n /** Fires and smoke of its burners, object-local (the water runs from the parts the host moves). */\n readonly emitters: readonly ActiveEmitter[]\n}\n\nexport interface ObjectControls extends ItemControls {\n state(): ObjectControlsState\n}\n\nconst PLUG_FALLBACK: Vec3 = [0, 0.3, 0]\n\n/**\n * A wall socket at each plugged device's plug and, when the mains give water, one tank behind every fixture: the mains of a piece standing on its own. Without water\n * there is no tank at all, since the world takes the first tank it is given as every fixture's default.\n */\nfunction mainsSpec(spec: ObjectSpec, water: boolean): ObjectSpec {\n const plugged = (spec.devices ?? []).filter((d) => d.socket !== undefined && !d.circuit)\n return { type: MAINS, sockets: plugged.map((d, i) => ({ id: `socket_${i}`, pos: d.plug ?? PLUG_FALLBACK })), tanks: water ? [{ id: MAINS_TANK, capacity: 1e9 }] : [] }\n}\n\nexport function createObjectControls(options: ObjectControlsOptions): ObjectControls {\n const { spec } = options\n const forwarded = new Map<string, boolean>()\n const said: string[] = []\n let host: ItemControlsHost | null = null\n const world = createWorld({\n locale: options.locale ?? 'en',\n ...(options.strings ? { strings: options.strings } : {}),\n grid: options.mains?.power ?? true,\n takeContents: false,\n onEvent: (event) => {\n if (event.type === 'message') said.push(event.text)\n if (event.type === 'part' && event.object === CONTROLLED_OBJECT) forwardPart(event.part, event.target >= 0.5)\n if (event.type === 'fixture' && event.object === CONTROLLED_OBJECT && event.flowing) uses.flushed(event.fixture)\n },\n })\n /** A part the world moved goes to the host, once per change of where it is headed. */\n const forwardPart = (part: string, open: boolean): void => {\n if (forwarded.get(part) === open) return\n forwarded.set(part, open)\n host?.setPart(part, open)\n }\n const piped = options.mains?.water ?? true\n world.add(MAINS, mainsSpec(spec, piped), { x: 0, y: 0, z: 0, ry: 0 })\n if (piped) world.water.setDefaultTank(`${MAINS}:${MAINS_TANK}`)\n world.add(CONTROLLED_OBJECT, spec, { x: 0, y: 0, z: 0, ry: 0 })\n const uses = createUses({ spec, world, objectId: CONTROLLED_OBJECT })\n // a device a program runs (a washing machine) is started by its programs, not switched on bare\n const programmedDevices = new Set((spec.uses ?? []).flatMap((u) => (u.do === 'program' ? [u.device] : [])))\n const switchesOf = (device: string): string[] => [\n `device.${device}`,\n ...(spec.interactions ?? []).flatMap((i) => (i.action.do === 'toggle_device' && i.action.device === device ? [i.id] : [])),\n ]\n const programmed = new Set([...programmedDevices].flatMap(switchesOf).map((id) => `${CONTROLLED_OBJECT}:${id}`))\n const own = (i: Interactable): boolean => i.object === CONTROLLED_OBJECT && !HOST_KINDS.has(i.kind) && !programmed.has(i.id)\n const interactions = (): Interactable[] => world.interactables().filter(own)\n const lend = (lent: ItemControlsHost): void => {\n host = lent\n }\n\n return {\n list(lent) {\n lend(lent)\n const fromWorld: ItemControl[] = interactions().map((i) => ({ id: i.id, label: i.label, available: i.available, ...(i.reason ? { reason: world.t(i.reason) } : {}) }))\n return [...fromWorld, ...uses.list(lent)]\n },\n run(id, lent): ItemControlResult {\n lend(lent)\n if (uses.has(id)) return uses.run(id, lent)\n const found = interactions().find((i) => i.id === id)\n if (!found) return { ok: false, text: '' }\n said.length = 0\n const ok = world.act(id)\n return { ok, text: said.length > 0 ? said.join(' · ') : found.label }\n },\n update(dt, lent) {\n lend(lent)\n world.update(dt)\n uses.update(dt)\n },\n state() {\n const screens = (spec.devices ?? [])\n .filter((d) => d.kind === 'screen' && world.power.isOn(CONTROLLED_OBJECT, d.id) && world.power.isPowered(CONTROLLED_OBJECT, d.id))\n .map((d) => ({ device: d.id, channel: world.power.channel(CONTROLLED_OBJECT, d.id) }))\n const emitters = world.emitters().filter((e) => e.object === CONTROLLED_OBJECT && e.kind !== 'water')\n return { ...uses.state(), screens, emitters }\n },\n dispose() {\n host = null\n world.remove(CONTROLLED_OBJECT)\n world.remove(MAINS)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,MAAM,oBAAoB;AAEjC,MAAM,gBAAgB;AAEtB,MAAM,UAAU;AAEhB,MAAM,aAAa;AAwBZ,WAAS,sBAAsB,MAAkE;AACtG,UAAM,WAAW,IAAI,KAAK,KAAK,YAAY,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,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,EAAG,QAAO,KAAK,IAAI,IAAI,IAAI;AAC1C,cAAM,QAAQ,aAAa,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE;AACpD,YAAI,CAAC,MAAO,QAAO,EAAE,IAAI,OAAO,MAAM,GAAG;AACzC,aAAK,SAAS;AACd,cAAM,KAAK,MAAM,IAAI,EAAE;AACvB,eAAO,EAAE,IAAI,MAAM,KAAK,SAAS,IAAI,KAAK,KAAK,QAAK,IAAI,MAAM,MAAM;AAAA,MACtE;AAAA,MACA,OAAO,IAAI,MAAM;AACf,aAAK,IAAI;AACT,cAAM,OAAO,EAAE;AACf,aAAK,OAAO,EAAE;AAAA,MAChB;AAAA,MACA,QAAQ;AACN,cAAM,WAAW,KAAK,WAAW,CAAC,GAC/B,OAAO,CAAC,MAAM,EAAE,SAAS,YAAY,MAAM,MAAM,KAAK,mBAAmB,EAAE,EAAE,KAAK,MAAM,MAAM,UAAU,mBAAmB,EAAE,EAAE,CAAC,EAChI,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,SAAS,MAAM,MAAM,QAAQ,mBAAmB,EAAE,EAAE,EAAE,EAAE;AACvF,cAAM,WAAW,MAAM,SAAS,EAAE,OAAO,CAAC,MAAM,EAAE,WAAW,qBAAqB,EAAE,SAAS,OAAO;AACpG,eAAO,EAAE,GAAG,KAAK,MAAM,GAAG,SAAS,SAAS;AAAA,MAC9C;AAAA,MACA,UAAU;AACR,eAAO;AACP,cAAM,OAAO,iBAAiB;AAC9B,cAAM,OAAO,KAAK;AAAA,MACpB;AAAA,IACF;AAAA,EACF;","names":["pose","cross","target","add","local","volume","sub","pos","destroyed","PUSH_GAIN","pose","centre","cross","length","overlap","YES"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/basin-drain.ts","../src/gestures.ts","../src/fixture-emitters.ts","../src/colliders.ts","../src/rng.ts","../src/loot.ts","../src/locale.ts","../src/math.ts","../src/world.ts","../src/engine-chain.ts","../src/engine-soft.ts","../src/engine-leaf.ts","../src/engine-parts.ts","../src/span.ts","../src/wire-runs.ts","../src/cast-with-member.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/fireball.ts","../../game-contracts/src/blast-wave.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/body-measures.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/hands.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/item-controls.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/rain-cover.ts","../../game-contracts/src/nav-obstacles.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/workers.ts","../../game-contracts/src/index.ts","../src/drain-uses.ts","../src/fits-volume.ts","../src/sink-uses.ts","../src/use-body.ts","../src/object-uses.ts","../src/object-controls.ts"],"sourcesContent":["export type * from './types'\nexport type { PartDriver, PartPhysics, SoftDriver } from './part-physics'\nexport { createWorld } from './world'\nexport { rng, hashString } from './rng'\nexport { generateLoot, fitsSize, fitsSlot } from './loot'\nexport { poseOf, localToWorld, worldToLocal, rotY, rotateAxis } from './math'\nexport type { Pose } from './math'\nexport { resolveStrings, locales, format, pickLocale } from './locale'\nexport { mergeColliders } from './colliders'\nexport { FLUSH_RUN_SECONDS, createFixtureEmitters } from './fixture-emitters'\nexport type { FixtureEmitters, RunningEmitter } from './fixture-emitters'\nexport { createEnginePartPhysics } from './engine-parts'\nexport type { EnginePartDriver } from './engine-leaf'\nexport type { EnginePartOptions, EnginePartPhysics } from './engine-parts'\nexport { alignY, buildChain, chainPoints, disposeChain } from './engine-chain'\nexport { hangTail, polylineLength, solveSpan, spanStrength } from './span'\nexport { wireRuns } from './wire-runs'\nexport { COLLAR_REACH, END_GAP, castWithMember, endsMember, wrapsMember } from './cast-with-member'\nexport type { CastBox } from './cast-with-member'\nexport type { WireRun, WireRunsParams } from './wire-runs'\nexport type { HangTailParams, SolveSpanParams, Span, SpanMaterial, SpanShape } from './span'\nexport type { Chain, ChainSpec } from './engine-chain'\nexport { CONTROLLED_OBJECT, createObjectControls } from './object-controls'\nexport type { ObjectControls, ObjectControlsOptions, ObjectControlsState } from './object-controls'\nexport { devicePointOf } from './object-uses'\nexport type { Soil, UsesState } from './object-uses'\nexport { CLOGGED, FLUSH_POUR_SECONDS, createBasinDrain } from './basin-drain'\nexport { createUseBody } from './use-body'\nexport type { UseBody, UseBodyPose } from './use-body'\nexport type { BasinContent, BasinContentInput, BasinContentKind, BasinContentSave, BasinContentStage, BasinDrain, BasinDrainSave, BasinDrainState, BasinDrainStep, BasinWater, ClogCause, DrainPhase } from './basin-drain'\nexport { createDrainUses } from './drain-uses'\nexport type { DrainUses, DrainUsesOptions, PlungeUseSpec } from './drain-uses'\nexport { fitsInVolume } from './fits-volume'\nexport { DRINK_HANDS_LITRES, DRINK_HANDS_LPS, DRINK_LITRES, DRINK_LPS, DRY_SECONDS, FILL_SHARE, REACH_SECONDS, WASH_SCRUB_SECONDS, createSinkRoutines, dirtyDishes, findNeeds, fixtureFlowLps, sinkVerdict } from './sink-uses'\nexport type { RoutineEnd, SinkRoutine, SinkRoutines, SinkUseSpec, SinkUsesOptions, SinkVerdict } from './sink-uses'\nexport { FLOW_DEFAULTS } from './world'\nexport { GESTURE_OF_ACTION, GESTURE_OF_USE } from './gestures'\n","/**\n * The water of a basin with a trap (`BasinSpec.drain`, a toilet's bowl and siphon), as a real one runs: the still water stands at the weir; a flush pours the\n * cistern's water in from under the rim, the level rises over the weir and, `prime` metres over it, the siphon primes and pulls the bowl down, swirling, until air\n * breaks it below the weir; the refill tube then brings the water back to the weir while the cistern fills. What lies in the bowl rides the siphon's swirl down to the\n * trap: a thing whose second size is wider than the trap lodges there, more soft waste than one flush carries packs there; either clogs the trap, and the next flush\n * rises over the rim instead of going down (the litres over it come out as `spilled`). A plunger's strokes break a packed clog and pull a lodged thing back up.\n * Pure: no three.js, no clock of its own (the host's `dt`), deterministic.\n */\nimport type { BasinSpec, DrainSpec } from './types'\n\nexport type BasinContentKind = 'urine' | 'feces' | 'paper' | 'object'\n\n/** Where a thing in the bowl is: `afloat` in the bowl, `going` down the swirl to the trap, `lodged` in the trap, `gone` through it. */\nexport type BasinContentStage = 'afloat' | 'going' | 'lodged' | 'gone'\n\nexport interface BasinContent {\n readonly id: string\n readonly kind: BasinContentKind\n readonly kg: number\n /** Width, height and depth, metres. */\n readonly size: readonly [number, number, number]\n /** The world's id of a loose thing (an object dropped in the bowl). */\n readonly objectId?: string\n readonly stage: BasinContentStage\n /** Around the bowl's axis, radians, and out from it (0 the axis to 1 the wall at the water's level). */\n readonly angle: number\n readonly radius: number\n /** 0 at the water's surface to 1 at the trap. */\n readonly depth: number\n}\n\nexport type DrainPhase = 'still' | 'filling' | 'siphon' | 'refill'\n\nexport type ClogCause = 'none' | 'object' | 'packed'\n\nexport interface BasinDrainState {\n readonly litres: number\n /** Metres of water over the basin's floor. */\n readonly level: number\n readonly phase: DrainPhase\n /** How hard the water turns, 0 still to 1 the full siphon. */\n readonly swirl: number\n /** Radians the water has turned in the bowl since it was made: the rim's jets and the siphon turn it by the litres they move. */\n readonly turned: number\n /** 0 a clear trap to 1 shut. */\n readonly clog: number\n readonly cause: ClogCause\n /** How full the cistern is, 0 to 1. */\n readonly cistern: number\n readonly contents: readonly BasinContent[]\n}\n\n/** What one step did beyond the state: litres that went over the rim and the loose things that went down the trap. The drain reuses it: read it before the next step. */\nexport interface BasinDrainStep {\n readonly spilled: number\n readonly swallowed: readonly string[]\n}\n\nexport interface BasinContentInput {\n readonly kind: BasinContentKind\n readonly kg: number\n readonly size: readonly [number, number, number]\n readonly objectId?: string\n /** Litres of liquid it brings (urine). */\n readonly litres?: number\n}\n\nexport interface BasinDrain {\n /** Pours `litres` of the cistern's water in over the next seconds (the flush); the cistern gives only what it has. Returns the litres poured. */\n flush(litres: number): number\n /** Something lands in the bowl: urine adds its litres to the water, a solid floats in it until the siphon takes it. */\n add(content: BasinContentInput): void\n /** One push and pull of a plunger: it needs the cup under water. Returns false when it found no water to work. */\n plunge(): boolean\n update(dt: number): BasinDrainStep\n state(): BasinDrainState\n /** What a step reads of the state without building it: the litres, the level in metres, the clog and its cause. */\n litres(): number\n level(): number\n clog(): number\n cause(): ClogCause\n /** Whether the water holds waste (urine, feces, paper), not only loose things: what goes over the rim is sewage. */\n dirty(): boolean\n /** Everything the drain is now, as plain JSON (`WorldState`): the water, the cistern, the clog and what is in the bowl or stuck in the trap. */\n save(): BasinDrainSave\n /** Puts the drain back where `save` found it. */\n restore(saved: BasinDrainSave): void\n}\n\n/** The water of a basin with a trap as a save keeps it (`BasinDrain.save`). */\nexport interface BasinWater {\n litres: number\n phase: DrainPhase\n swirl: number\n turned: number\n clog: number\n cause: ClogCause\n cistern: number\n /** Seconds the flush still pours, and its litres a second. */\n pouring: number\n pourRate: number\n /** Kg of soft waste the siphon of this flush has carried through. */\n carried: number\n}\n\n/** A thing in the bowl as a save keeps it: what the state shows plus where it came in and how far down the siphon has taken it. */\nexport type BasinContentSave = BasinContent & {\n /** Where it was round the axis when it came, and out from it. */\n readonly start: number\n readonly startRadius: number\n /** 0 at the surface to 1 at the trap: the share of `TRAP_LITRES` the siphon has pulled since it took the thing. */\n readonly travel: number\n}\n\nexport interface BasinDrainSave {\n readonly water: Readonly<BasinWater>\n /** How many things have come into the bowl: the next one's id and place. */\n readonly serial: number\n readonly contents: readonly BasinContentSave[]\n}\n\n/** Seconds a flush pours its water in. */\nexport const FLUSH_POUR_SECONDS = 3\n/** Over this the trap counts as clogged. */\nexport const CLOGGED = 0.5\n/** Litres a second the refill tube brings back to the weir. */\nconst REFILL_RATE = 0.12\n/** Metres under the weir the level falls before air breaks the siphon. */\nconst BREAK_DEPTH = 0.035\n/** Of the siphon's rate, what spills over a weir that is not primed. */\nconst WEIR_SHARE = 0.25\n/** What a shut trap still lets through, of its rate (water seeps round a clog). */\nconst SEEP = 0.04\n/** Radians the bowl's water turns for each litre the rim's jets pour in or the siphon pulls out (the jets are angled round the rim). */\nconst TURN_PER_LITRE = 2.4\n/** Litres the siphon pulls while a thing rides the water from the surface to the trap. */\nconst TRAP_LITRES = 3.5\n/** How much of a packed clog one plunger stroke breaks, and of a lodged thing's hold. */\nconst PLUNGE_PACKED = 0.34\nconst PLUNGE_LODGED = 0.2\n/** Metres of water the plunger's cup needs over the trap's mouth. */\nexport const PLUNGER_WATER = 0.03\n/** A soft lump this much wider than the trap does not pass it (it squeezes, a hard thing does not). */\nconst SOFT_SQUEEZE = 1.6\n/** How close the swirl gets to where it is headed before it is there (it eases in for ever otherwise, and the water would never be still). */\nconst SWIRL_SETTLED = 1e-4\n\nconst clamp01 = (v: number): number => Math.min(1, Math.max(0, v))\n/** The second size of a thing: what must pass the trap's round passage when it goes in lengthwise. */\nconst passingSize = (size: readonly [number, number, number]): number => [...size].sort((a, b) => b - a)[1] ?? 0\n\ntype Content = { -readonly [K in keyof BasinContentSave]: BasinContentSave[K] }\n\nexport function createBasinDrain(basin: BasinSpec, drain: DrainSpec): BasinDrain {\n const width = basin.to[0] - basin.from[0]\n const deep = basin.to[2] - basin.from[2]\n const radius = Math.min(width, deep) / 2\n /** m² of the bowl's water at any level (the basin is upright). */\n const area = basin.shape === 'round' ? Math.PI * radius * radius : width * deep\n const litresAt = (level: number): number => area * level * 1000\n const levelOf = (litres: number): number => litres / (area * 1000)\n const capacity = litresAt(basin.to[1] - basin.from[1])\n const still = litresAt(drain.weir)\n const water: BasinWater = { litres: still, phase: 'still', swirl: 0, turned: 0, clog: 0, cause: 'none', cistern: 1, pouring: 0, pourRate: 0, carried: 0 }\n let serial = 0\n let contents: Content[] = []\n /** The state built once and kept while nothing changes (a still bowl is read every frame). */\n let shown: BasinDrainState | null = null\n const step: { spilled: number; swallowed: string[] } = { spilled: 0, swallowed: [] }\n\n const open = (): number => Math.max(SEEP, 1 - water.clog)\n\n const lodge = (c: Content, packed: boolean): void => {\n c.stage = 'lodged'\n c.depth = 1\n c.radius = 0\n water.clog = packed ? Math.max(water.clog, Math.min(0.95, water.clog + 0.55 + 0.3 * (c.kg / drain.carries))) : 0.97\n water.cause = water.cause === 'object' || !packed ? 'object' : 'packed'\n }\n\n /** A thing reaches the trap: it passes when it fits and the flush still carries (true), else it lodges. */\n const reachTrap = (c: Content, swallowed: string[]): boolean => {\n const hard = c.kind === 'object'\n if (passingSize(c.size) > drain.trap * (hard ? 1 : SOFT_SQUEEZE) || (!hard && water.carried + c.kg > drain.carries)) {\n lodge(c, !hard)\n return false\n }\n if (!hard) water.carried += c.kg\n c.stage = 'gone'\n if (c.objectId) swallowed.push(c.objectId)\n return true\n }\n\n /** What is in the bowl rides the water: round with it by the litres moved, and down to the trap by the litres the siphon pulls. */\n const stepContents = (moved: number, pulled: number, swallowed: string[]): void => {\n water.turned += moved * TURN_PER_LITRE\n // urine is in the water itself: the siphon's water takes it\n const takesUrine = water.phase === 'siphon' && water.swirl > 0.3\n let leaving = false\n for (const c of contents) {\n if (c.kind === 'urine' && takesUrine) leaving = true\n if (c.stage === 'gone' || c.stage === 'lodged') continue\n c.angle = c.start + water.turned\n if (water.phase !== 'siphon' || c.kind === 'urine') continue\n c.stage = 'going'\n c.travel = clamp01(c.travel + pulled / TRAP_LITRES)\n c.depth = Math.max(c.depth, c.travel)\n c.radius = c.startRadius * (1 - c.travel)\n if (c.travel >= 1 && reachTrap(c, swallowed)) leaving = true\n }\n if (leaving) contents = contents.filter((c) => c.stage !== 'gone' && !(c.kind === 'urine' && takesUrine))\n }\n\n /** The water that leaves down the trap in `dt`: over the weir, or pulled by the primed siphon. */\n const outflow = (dt: number): number => {\n const level = levelOf(water.litres)\n if (water.phase === 'siphon') return drain.siphon * open() * dt * Math.sqrt(clamp01(level / Math.max(1e-3, drain.weir)))\n const head = level - drain.weir\n if (head <= 0) return 0\n return drain.siphon * WEIR_SHARE * open() * dt * Math.sqrt(clamp01(head / drain.prime))\n }\n\n const stepPhase = (): void => {\n const head = levelOf(water.litres) - drain.weir\n if (water.phase !== 'siphon' && head >= drain.prime && open() > CLOGGED) {\n water.phase = 'siphon'\n water.carried = 0\n return\n }\n if (water.phase === 'siphon' && (head <= -BREAK_DEPTH || open() <= CLOGGED)) water.phase = 'refill'\n if (water.phase === 'refill' && water.litres >= still - 1e-6 && water.pouring <= 0) water.phase = 'still'\n if (water.phase === 'still' && water.pouring > 0) water.phase = 'filling'\n if (water.phase === 'filling' && water.pouring <= 0 && head <= 1e-4) water.phase = 'still'\n }\n\n /** The water a step brings: the flush's pour and the refill tube's back to the weir (none past a clog: the bowl is already full). */\n const stepInflow = (dt: number): number => {\n const poured = water.pouring > 0 ? water.pourRate * Math.min(dt, water.pouring) : 0\n water.pouring = Math.max(0, water.pouring - dt)\n water.litres += poured\n if ((water.phase === 'refill' || water.phase === 'still') && water.litres < still && water.clog < CLOGGED) water.litres = Math.min(still, water.litres + REFILL_RATE * dt)\n return poured\n }\n\n return {\n flush(asked) {\n shown = null\n const litresIn = asked * water.cistern\n water.cistern = 0\n if (litresIn <= 0) return 0\n water.pouring = FLUSH_POUR_SECONDS\n water.pourRate = litresIn / FLUSH_POUR_SECONDS\n if (water.phase === 'still') water.phase = 'filling'\n return litresIn\n },\n add(content) {\n shown = null\n water.litres += content.litres ?? 0\n const k = serial++\n const start = k * 2.39996\n const startRadius = 0.25 + ((k * 0.37) % 0.45)\n contents.push({\n start,\n startRadius,\n travel: 0,\n id: `c${k}`,\n kind: content.kind,\n kg: content.kg,\n size: content.size,\n ...(content.objectId ? { objectId: content.objectId } : {}),\n stage: 'afloat',\n angle: start + water.turned,\n radius: startRadius,\n depth: content.kind === 'object' ? 0.5 : 0,\n })\n },\n plunge() {\n shown = null\n if (levelOf(water.litres) < PLUNGER_WATER) return false\n if (water.clog <= 0) return true\n const lodged = contents.filter((c) => c.stage === 'lodged')\n const hard = lodged.some((c) => c.kind === 'object')\n water.clog = Math.max(0, water.clog - (hard ? PLUNGE_LODGED : PLUNGE_PACKED))\n if (water.clog > CLOGGED * 0.4) return true\n // the strokes broke the pack (it goes down with the water over the weir) or pulled the lodged thing back up into the bowl\n water.clog = 0\n water.cause = 'none'\n for (const c of lodged) {\n if (c.kind === 'object') Object.assign(c, { stage: 'afloat', depth: 0.6, radius: 0.3, startRadius: 0.3, travel: 0 })\n else c.stage = 'gone'\n }\n contents = contents.filter((c) => c.stage !== 'gone')\n return true\n },\n update(dt) {\n step.spilled = 0\n step.swallowed.length = 0\n if (dt <= 0) return step\n const { litres, swirl, cistern, phase, clog } = water\n const count = contents.length\n water.cistern = clamp01(water.cistern + dt / drain.refill)\n const poured = stepInflow(dt)\n const out = Math.min(water.litres, outflow(dt))\n water.litres -= out\n stepPhase()\n const pull = water.phase === 'siphon' ? clamp01(out / (drain.siphon * dt)) : 0\n const jets = poured > 0 ? 0.35 : 0\n const swirlTo = Math.max(pull, jets)\n water.swirl = Math.abs(swirlTo - water.swirl) < SWIRL_SETTLED ? swirlTo : water.swirl + (swirlTo - water.swirl) * clamp01(dt * 6)\n const moved = poured + out\n stepContents(moved, water.phase === 'siphon' ? out : 0, step.swallowed)\n step.spilled = Math.max(0, water.litres - capacity)\n water.litres -= step.spilled\n const changed = moved > 0 || water.litres !== litres || water.swirl !== swirl || water.cistern !== cistern || water.phase !== phase || water.clog !== clog || contents.length !== count\n if (changed) shown = null\n return step\n },\n state() {\n shown ??= {\n litres: water.litres,\n level: levelOf(water.litres),\n phase: water.phase,\n swirl: water.swirl,\n turned: water.turned,\n clog: water.clog,\n cause: water.cause,\n cistern: water.cistern,\n contents: contents.map(({ start: _start, startRadius: _startRadius, travel: _travel, ...c }) => c),\n }\n return shown\n },\n litres: () => water.litres,\n level: () => levelOf(water.litres),\n clog: () => water.clog,\n cause: () => water.cause,\n dirty: () => contents.some((c) => c.kind !== 'object'),\n save: () => ({ water: { ...water }, serial, contents: contents.map((c) => ({ ...c })) }),\n restore(saved) {\n shown = null\n Object.assign(water, saved.water)\n serial = saved.serial\n contents = saved.contents.map((c) => ({ ...c }))\n },\n }\n}\n","/**\n * What the player's body does for each interaction and use of an object (CLAUDE.md §18: every action has a body animation): the gesture the host plays with the free hand\n * (`ItemControl.gesture`, `createGestureTimeline` of game-player) before the object reacts. Null: the host plays the action with a body move of its own (a leaf opened by\n * the door code, a seat sat on, an item taken by the take sequence) or the use plays a hand use clip or a body pose of its own (washing, drinking, relieving oneself, working a plunger).\n */\nimport type { BodyGesture } from '@adatechnology/game-contracts'\n\nimport type { Action, UseSpec } from './types'\n\nexport const GESTURE_OF_ACTION: Readonly<Record<Action['do'], BodyGesture | null>> = {\n toggle_part: null,\n open_container: null,\n take: null,\n sit: null,\n toggle_device: 'press',\n cycle_device: 'press',\n toggle_switch: 'flip',\n toggle_breaker: 'flip',\n toggle_main: 'flip',\n toggle_fixture: 'turn',\n toggle_burner: 'turn',\n ignite: 'strike',\n toggle_fuel: 'turn',\n read: 'read',\n}\n\nexport const GESTURE_OF_USE: Readonly<Record<UseSpec['do'], BodyGesture | null>> = {\n program: 'press',\n put_in: 'put_in',\n empty: 'tip',\n fill: 'pour',\n relieve: null,\n plunge: null,\n wash: null,\n drink: null,\n}\n","// The water a piece runs while its handle is worked, for a host that moves the parts itself (a test room plays the part's clip, a game its own animation) and has\n// no interactables world: from the piece's spec and how open each part is now, which of its water emitters run and how hard. A tap runs as far as its handle\n// is turned; a flush runs for its seconds once its button goes down, whatever the button does next. Pure: no three.js, object-local, no allocation per call once\n// warmed up but the answer list.\nimport type { EmitterSpec, FixtureSpec, ObjectSpec } from './types'\n\n/** Seconds a flush runs once its button goes down (the interactables world's own flush time). */\nexport const FLUSH_RUN_SECONDS = 2\n/** How open a handle has to be before the water starts, 0..1: a tap barely touched drips nothing. */\nconst START_OPENING = 0.05\n/** A flush button counts as pressed past this far down. */\nconst PRESSED = 0.5\n/** Seconds the end of a flush takes to die down. */\nconst FLUSH_FADE = 0.4\n\n/** One emitter running now, object-local, with its strength 0..1. */\nexport interface RunningEmitter {\n readonly emitter: EmitterSpec\n readonly intensity: number\n}\n\nexport interface FixtureEmitters {\n /** The water emitters of the piece that run now: `opening(part)` is how open that part is, 0 closed to 1 open. Advances the flushes by `dt` seconds. */\n update(dt: number, opening: (part: string) => number): RunningEmitter[]\n /** Whether the piece has any emitter a handle runs (a sink, a shower, a toilet): a host can skip the others. */\n readonly runs: boolean\n}\n\ninterface Driven {\n readonly emitter: EmitterSpec\n readonly fixture: FixtureSpec & { part: string }\n /** Flush only: seconds of run left, and whether the button was down the last time. */\n left: number\n down: boolean\n}\n\n/** The driver of one piece's water emitters by its handles. */\nexport function createFixtureEmitters(spec: Pick<ObjectSpec, 'emitters' | 'fixtures'>): FixtureEmitters {\n const fixtures = new Map((spec.fixtures ?? []).map((fixture) => [fixture.id, fixture]))\n const driven: Driven[] = []\n for (const emitter of spec.emitters ?? []) {\n if (emitter.kind !== 'water') continue\n const fixture = fixtures.get(emitter.source)\n if (!fixture?.part) continue\n driven.push({ emitter, fixture: { ...fixture, part: fixture.part }, left: 0, down: false })\n }\n return {\n runs: driven.length > 0,\n update(dt, opening) {\n const out: RunningEmitter[] = []\n for (const d of driven) {\n const open = Math.min(1, Math.max(0, opening(d.fixture.part)))\n if (d.fixture.kind === 'flush') {\n const down = open >= PRESSED\n if (down && !d.down) d.left = FLUSH_RUN_SECONDS\n d.down = down\n if (d.left <= 0) continue\n d.left = Math.max(0, d.left - dt)\n out.push({ emitter: d.emitter, intensity: Math.min(1, (d.left + 1e-6) / FLUSH_FADE) })\n continue\n }\n if (open > START_OPENING) out.push({ emitter: d.emitter, intensity: open })\n }\n return out\n },\n }\n}\n","import type { ColliderOptions, WorldCollider } from './types'\n\ninterface Box {\n ids: string[]\n object: string\n u0: number\n u1: number\n v0: number\n v1: number\n y0: number\n y1: number\n}\n\nconst volume = (b: Box): number => (b.u1 - b.u0) * (b.v1 - b.v0) * (b.y1 - b.y0)\nconst overlap = (a0: number, a1: number, b0: number, b1: number): number => Math.max(0, Math.min(a1, b1) - Math.max(a0, b0))\n\nfunction tryMerge(a: Box, b: Box, gap: number, slack: number): Box | null {\n if (a.u0 - gap > b.u1 || b.u0 - gap > a.u1) return null\n if (a.v0 - gap > b.v1 || b.v0 - gap > a.v1) return null\n if (a.y0 - gap > b.y1 || b.y0 - gap > a.y1) return null\n const u0 = Math.min(a.u0, b.u0)\n const u1 = Math.max(a.u1, b.u1)\n const v0 = Math.min(a.v0, b.v0)\n const v1 = Math.max(a.v1, b.v1)\n const y0 = Math.min(a.y0, b.y0)\n const y1 = Math.max(a.y1, b.y1)\n const hull = (u1 - u0) * (v1 - v0) * (y1 - y0)\n const common = overlap(a.u0, a.u1, b.u0, b.u1) * overlap(a.v0, a.v1, b.v0, b.v1) * overlap(a.y0, a.y1, b.y0, b.y1)\n const real = volume(a) + volume(b) - common\n if (hull > real * (1 + slack) + 1e-9) return null\n return { ids: [...a.ids, ...b.ids], object: a.object, u0, u1, v0, v1, y0, y1 }\n}\n\n/**\n * Union overlapping or adjacent colliders of the same object (same rotation) into fewer OBBs.\n * A merge happens only when the merged box adds at most `slack` extra volume over the real union, so coverage is never lost\n * and never grows noticeably. Colliders of different objects or rotations are left alone.\n */\nexport function mergeColliders(list: WorldCollider[], options: Pick<ColliderOptions, 'gap' | 'slack'> = {}): WorldCollider[] {\n const gap = options.gap ?? 0.02\n const slack = options.slack ?? 0.1\n const groups = new Map<string, WorldCollider[]>()\n for (const c of list) {\n const key = `${c.object}|${Math.round(c.ry * 1000)}`\n const g = groups.get(key)\n if (g) g.push(c)\n else groups.set(key, [c])\n }\n const out: WorldCollider[] = []\n for (const g of groups.values()) {\n const ry = g[0]?.ry ?? 0\n const cs = Math.cos(ry)\n const sn = Math.sin(ry)\n let boxes: Box[] = g.map((c) => {\n const u = c.cx * cs - c.cz * sn\n const v = c.cx * sn + c.cz * cs\n return { ids: [c.id], object: c.object, u0: u - c.hw, u1: u + c.hw, v0: v - c.hd, v1: v + c.hd, y0: c.y0, y1: c.y1 }\n })\n let changed = boxes.length > 1\n while (changed) {\n changed = false\n outer: for (let i = 0; i < boxes.length; i++) {\n for (let j = i + 1; j < boxes.length; j++) {\n const m = tryMerge(boxes[i] as Box, boxes[j] as Box, gap, slack)\n if (!m) continue\n boxes = boxes.filter((_, k) => k !== i && k !== j)\n boxes.push(m)\n changed = true\n break outer\n }\n }\n }\n for (const b of boxes) {\n const u = (b.u0 + b.u1) / 2\n const v = (b.v0 + b.v1) / 2\n out.push({\n id: b.ids.length === 1 ? (b.ids[0] as string) : `${b.ids[0]}+${b.ids.length - 1}`,\n object: b.object,\n cx: u * cs + v * sn,\n cz: -u * sn + v * cs,\n hw: (b.u1 - b.u0) / 2,\n hd: (b.v1 - b.v0) / 2,\n ry,\n y0: b.y0,\n y1: b.y1,\n })\n }\n }\n return out\n}\n","/** FNV-1a hash of a string to a 32-bit unsigned integer. */\nexport function hashString(text: string): number {\n let h = 2166136261\n for (let i = 0; i < text.length; i++) {\n h ^= text.charCodeAt(i)\n h = Math.imul(h, 16777619)\n }\n return h >>> 0\n}\n\n/** Deterministic random generator (mulberry32). Returns a function producing floats in [0, 1). Numbers and strings are accepted as seeds. */\nexport function rng(seed: number | string = 1): () => number {\n let a = (typeof seed === 'number' ? Math.floor(seed) >>> 0 : hashString(seed)) || 0x9e3779b9\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n","import { rng } from './rng'\nimport type { ItemCatalog, ItemStack, LootTables, SlotSpec, Vec3 } from './types'\n\n/** True when an item of `size` [w, h, d] fits in a slot of `max`; width and depth may be swapped (the item is turned). */\nexport function fitsSize(size: Vec3, max: Vec3): boolean {\n const eps = 1e-9\n if (size[1] > max[1] + eps) return false\n return (size[0] <= max[0] + eps && size[2] <= max[2] + eps) || (size[2] <= max[0] + eps && size[0] <= max[2] + eps)\n}\n\n/** Does the item type fit the slot. Types missing from the catalog are accepted (the host owns unknown items). */\nexport function fitsSlot(type: string, slot: SlotSpec, items?: ItemCatalog): boolean {\n const def = items?.[type]\n return def ? fitsSize(def.size, slot.max) : true\n}\n\n/**\n * Deterministic contents for a container: one entry per slot. A slot is filled with probability `fill`; the entry is a weighted pick\n * among the table entries whose item fits the slot. Same seed, same table and same slots always give the same result.\n */\nexport function generateLoot(\n tables: LootTables | undefined,\n tableId: string,\n slots: SlotSpec[],\n seed: number | string,\n items?: ItemCatalog,\n): Array<ItemStack | null> {\n const table = tables?.[tableId]\n const out: Array<ItemStack | null> = slots.map(() => null)\n if (!table) return out\n const rand = rng(seed)\n slots.forEach((slot, i) => {\n // Always draw the same number of random values per slot so a change in one slot does not shift the others.\n const roll = rand()\n const pick = rand()\n const q = rand()\n if (roll >= table.fill) return\n const candidates = table.entries.filter((e) => e.weight > 0 && fitsSlot(e.type, slot, items))\n const total = candidates.reduce((s, e) => s + e.weight, 0)\n if (total <= 0) return\n let r = pick * total\n let chosen = candidates[candidates.length - 1]\n for (const e of candidates) {\n r -= e.weight\n if (r < 0) {\n chosen = e\n break\n }\n }\n const [lo, hi] = chosen.qty ?? [1, 1]\n const def = items?.[chosen.type]\n const stackMax = def ? (def.stack ?? 1) : Number.POSITIVE_INFINITY\n const qty = Math.max(1, Math.min(stackMax, lo + Math.floor(q * (hi - lo + 1))))\n out[i] = { type: chosen.type, qty }\n })\n return out\n}\n","import type { InteractablesLocale, Strings } from './types'\n\n/** Engine-level prompts and messages. Content packs add their own keys through `WorldOptions.strings`. */\nexport const locales: Record<InteractablesLocale, Strings> = {\n en: {\n 'prompt.open': 'Open {name}',\n 'prompt.close': 'Close {name}',\n 'prompt.turn_on': 'Turn on {name}',\n 'prompt.turn_off': 'Turn off {name}',\n 'prompt.take': 'Take',\n 'prompt.sit': 'Sit',\n 'prompt.lie_down': 'Lie down',\n 'prompt.get_up': 'Get up',\n 'prompt.light': 'Light',\n 'prompt.change_channel': 'Change channel',\n 'prompt.read': 'Read',\n 'prompt.breaker_on': 'Switch on {circuit}',\n 'prompt.breaker_off': 'Switch off {circuit}',\n 'prompt.main_on': 'Switch on the main breaker',\n 'prompt.main_off': 'Switch off the main breaker',\n 'prompt.open_valve': 'Open valve',\n 'prompt.close_valve': 'Close valve',\n no_power: 'No power',\n no_gas: 'No gas',\n no_water: 'No water',\n locked: 'Locked',\n requires_open: 'Open it first',\n already_lit: 'Already lit',\n needs_ignition: 'Light it first',\n turn_on_first: 'Turn it on first',\n empty: 'Empty',\n full: 'Full',\n 'use.put_in': 'Put {item} in {name}',\n 'use.put_in.none': 'Put what you hold in {name}',\n 'use.empty': 'Empty {name}',\n 'use.fill': 'Fill the {bowl} bowl',\n 'use.program.stop': 'Stop {name} ({left} left)',\n 'use.relieve.urine': 'Pee',\n 'use.relieve.feces': 'Poo',\n 'bowl.food': 'food',\n 'bowl.water': 'water',\n hand_empty: 'Your hand is empty',\n not_fit: '{item} does not fit in {name}',\n not_accepted: '{item} does not go in the {bowl} bowl',\n bowl_full: 'The {bowl} bowl is already full',\n needs_closed: 'Close it first',\n already_soiled: 'Flush first',\n done_put_in: '{item} went into {name}',\n done_empty: '{name} emptied ({n} things)',\n done_fill: 'The {bowl} bowl is full',\n done_program: '{name}: {program} started ({time})',\n done_program_end: '{name}: {program} finished',\n done_program_stop: '{name} stopped',\n done_relieve_urine: 'You peed in {name}',\n done_relieve_feces: 'You pooed in {name}',\n done_clean: '{name} flushed clean',\n 'use.wash_dishes': 'Wash the dishes',\n 'use.drink_water': 'Drink water from the glass',\n 'use.drink_from_hands': 'Drink water from your hands',\n needs_in_hand: 'Pick up {item} first',\n needs_vessel: 'You need a glass',\n vessel_not_empty: 'Empty {item} first',\n hands_busy: 'Your hands are busy',\n no_animation: 'Cannot be done here: the body has no movement for it',\n needs_free_hand: 'You need your hands free',\n not_drunk: 'No water was drunk',\n drink_from_vessel: 'You have a glass in your hand: drink from it',\n done_drink_hands: 'You drank {litres} l of water from your hands',\n busy: 'Already in use',\n needs_running: 'Turn the water on first',\n needs_item: 'You need {need}',\n item_spent: '{item} is empty',\n no_dirty_dishes: 'No dirty dishes in the sink',\n started_wash: '{label}…',\n started_drink: '{label}…',\n done_wash: 'Washed and rinsed',\n done_wash_dishes: 'Dishes washed: {n} on the rack',\n done_drink: 'You drank {litres} l of water',\n 'use.plunge': 'Unclog {name} with the plunger',\n needs_plunger: 'Hold a plunger',\n plunge_no_water: 'No water over the trap for the plunger',\n done_plunge: 'You work the plunger in {name}',\n plunge_cleared: '{name} unclogged: the water goes down',\n plunge_object: '{name} unclogged: something came back up the trap',\n plunge_still: '{name} is still clogged',\n clogged: '{name} is clogged',\n overflow: '{name} is overflowing',\n needs_body: 'There is no body here to use {name}',\n host_lacks: 'This place cannot run {name} (it lacks {capability})',\n body_no_seat: '{name} has no seat to sit on',\n body_object_gone: '{name} is not here',\n body_busy: 'You are busy with something else',\n },\n 'pt-BR': {\n 'prompt.open': 'Abrir {name}',\n 'prompt.close': 'Fechar {name}',\n 'prompt.turn_on': 'Ligar {name}',\n 'prompt.turn_off': 'Desligar {name}',\n 'prompt.take': 'Pegar',\n 'prompt.sit': 'Sentar',\n 'prompt.lie_down': 'Deitar',\n 'prompt.get_up': 'Levantar',\n 'prompt.light': 'Acender',\n 'prompt.change_channel': 'Trocar de canal',\n 'prompt.read': 'Ler',\n 'prompt.breaker_on': 'Ligar {circuit}',\n 'prompt.breaker_off': 'Desligar {circuit}',\n 'prompt.main_on': 'Ligar o disjuntor geral',\n 'prompt.main_off': 'Desligar o disjuntor geral',\n 'prompt.open_valve': 'Abrir registro',\n 'prompt.close_valve': 'Fechar registro',\n no_power: 'Sem energia',\n no_gas: 'Sem gás',\n no_water: 'Sem água',\n locked: 'Trancado',\n requires_open: 'Abra primeiro',\n already_lit: 'Já está aceso',\n needs_ignition: 'Acenda primeiro',\n turn_on_first: 'Ligue primeiro',\n empty: 'Vazio',\n full: 'Cheio',\n 'use.put_in': 'Pôr {item} em {name}',\n 'use.put_in.none': 'Pôr o que está na mão em {name}',\n 'use.empty': 'Esvaziar {name}',\n 'use.fill': 'Encher o pote de {bowl}',\n 'use.program.stop': 'Parar {name} (faltam {left})',\n 'use.relieve.urine': 'Fazer xixi (1)',\n 'use.relieve.feces': 'Fazer cocô (2)',\n 'bowl.food': 'ração',\n 'bowl.water': 'água',\n hand_empty: 'A mão está vazia',\n not_fit: '{item} não cabe em {name}',\n not_accepted: '{item} não vai no pote de {bowl}',\n bowl_full: 'O pote de {bowl} já está cheio',\n needs_closed: 'Feche primeiro',\n already_soiled: 'Dê a descarga primeiro',\n done_put_in: '{item} foi para dentro de {name}',\n done_empty: '{name} esvaziado ({n} coisas)',\n done_fill: 'O pote de {bowl} está cheio',\n done_program: '{name}: {program} começou ({time})',\n done_program_end: '{name}: {program} terminou',\n done_program_stop: '{name} parou',\n done_relieve_urine: 'Você fez xixi em {name}',\n done_relieve_feces: 'Você fez cocô em {name}',\n done_clean: 'Descarga dada: {name} limpo',\n 'use.wash_dishes': 'Lavar a louça',\n 'use.drink_water': 'Beber água no copo',\n 'use.drink_from_hands': 'Beber água com a mão',\n needs_in_hand: 'Pegue {item} antes',\n needs_vessel: 'Precisa de um copo',\n vessel_not_empty: 'Esvazie {item} antes',\n hands_busy: 'As mãos estão ocupadas',\n no_animation: 'Não dá para fazer isso aqui: o corpo não tem o movimento',\n needs_free_hand: 'Precisa das mãos livres',\n not_drunk: 'Nenhuma água foi bebida',\n drink_from_vessel: 'Você está com um copo na mão: beba nele',\n done_drink_hands: 'Você bebeu {litres} l de água com a mão',\n busy: 'Já está em uso',\n needs_running: 'Abra a água primeiro',\n needs_item: 'Precisa de {need}',\n item_spent: '{item} acabou',\n no_dirty_dishes: 'Não há louça suja na pia',\n started_wash: '{label}…',\n started_drink: '{label}…',\n done_wash: 'Lavado e enxaguado',\n done_wash_dishes: 'Louça lavada: {n} no escorredor',\n done_drink: 'Você bebeu {litres} l de água',\n 'use.plunge': 'Desentupir {name} com o desentupidor',\n needs_plunger: 'Segure um desentupidor',\n plunge_no_water: 'Sem água sobre o sifão para o desentupidor',\n done_plunge: 'Você bombeia o desentupidor em {name}',\n plunge_cleared: '{name} desentupido: a água desce',\n plunge_object: '{name} desentupido: uma coisa voltou do sifão',\n plunge_still: '{name} ainda está entupido',\n clogged: '{name} entupiu',\n overflow: '{name} está transbordando',\n needs_body: 'Não há corpo aqui para usar {name}',\n host_lacks: 'Este lugar não sabe usar {name} (falta {capability})',\n body_no_seat: '{name} não tem assento para sentar',\n body_object_gone: '{name} não está aqui',\n body_busy: 'Você está ocupado com outra coisa',\n },\n}\n\n/** Pick a built-in locale for an arbitrary tag (`pt`, `pt-br`, `en-GB`...). Unknown tags give `en`. */\nexport function pickLocale(locale: string | undefined): InteractablesLocale {\n if (!locale) return 'en'\n const l = locale.toLowerCase()\n if (l === 'pt-br' || l === 'pt') return 'pt-BR'\n return 'en'\n}\n\n/**\n * Merged table for a locale: built-in `en`, then the built-in table of `locale`, then the extra strings for `en` and for `locale`.\n * Lookup therefore falls back to English, and the caller never gets undefined for engine keys.\n */\nexport function resolveStrings(locale?: string, extra?: Partial<Record<InteractablesLocale, Strings>>): Strings {\n const loc = pickLocale(locale)\n return { ...locales.en, ...locales[loc], ...(extra?.en ?? {}), ...(loc === 'en' ? {} : (extra?.[loc] ?? {})) }\n}\n\n/** Replace `{name}` placeholders. Unknown placeholders are left untouched. */\nexport function format(text: string, vars?: Record<string, string | number>): string {\n if (!vars) return text\n return text.replace(/\\{(\\w+)\\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m))\n}\n","import type { Motion, Transform, Vec3 } from './types'\n\nexport interface Pose {\n /** Translation relative to the pivot. */\n position: Vec3\n /** Rotation around `axis` (in the part frame) by `angle` radians. */\n rotation: { axis: Vec3; angle: number }\n scale: Vec3\n}\n\nconst DEFAULT_AXIS: Vec3 = [0, 1, 0]\n\n/**\n * Pose of a part at animation value `t` (0..1), relative to its pivot, so any renderer can apply it:\n * `position`, then `rotation` around the pivot, then `scale` along the axis.\n */\nexport function poseOf(motion: Motion, t: number): Pose {\n const tt = Math.max(0, Math.min(1, t))\n const axis = motion.axis ?? DEFAULT_AXIS\n const pose: Pose = { position: [0, 0, 0], rotation: { axis: [axis[0], axis[1], axis[2]], angle: 0 }, scale: [1, 1, 1] }\n switch (motion.kind) {\n case 'hinge':\n case 'rocker':\n case 'knob':\n pose.rotation.angle = (motion.angle ?? Math.PI / 2) * tt\n break\n case 'slide': {\n const d = (motion.distance ?? 0.4) * tt\n pose.position = [axis[0] * d, axis[1] * d, axis[2] * d]\n break\n }\n case 'scale': {\n const k = 1 + ((motion.scale ?? 0.2) - 1) * tt\n pose.scale = [axis[0] !== 0 ? k : 1, axis[1] !== 0 ? k : 1, axis[2] !== 0 ? k : 1]\n break\n }\n }\n return pose\n}\n\n/** Rotate a vector around +y by `ry` radians (same convention as three.js `rotation.y`). */\nexport function rotY(v: Vec3, ry: number): Vec3 {\n const c = Math.cos(ry)\n const s = Math.sin(ry)\n return [c * v[0] + s * v[2], v[1], -s * v[0] + c * v[2]]\n}\n\n/** Object-local point to world space. */\nexport function localToWorld(transform: Transform, v: Vec3): Vec3 {\n const r = rotY(v, transform.ry)\n return [transform.x + r[0], transform.y + r[1], transform.z + r[2]]\n}\n\n/** World point to object-local space. */\nexport function worldToLocal(transform: Transform, v: Vec3): Vec3 {\n return rotY([v[0] - transform.x, v[1] - transform.y, v[2] - transform.z], -transform.ry)\n}\n\n/** Rodrigues rotation of `v` around a unit-length-normalised `axis` by `angle`. */\nexport function rotateAxis(v: Vec3, axis: Vec3, angle: number): Vec3 {\n const len = Math.hypot(axis[0], axis[1], axis[2]) || 1\n const k: Vec3 = [axis[0] / len, axis[1] / len, axis[2] / len]\n const c = Math.cos(angle)\n const s = Math.sin(angle)\n const dot = k[0] * v[0] + k[1] * v[1] + k[2] * v[2]\n const cross: Vec3 = [k[1] * v[2] - k[2] * v[1], k[2] * v[0] - k[0] * v[2], k[0] * v[1] - k[1] * v[0]]\n return [v[0] * c + cross[0] * s + k[0] * dot * (1 - c), v[1] * c + cross[1] * s + k[1] * dot * (1 - c), v[2] * c + cross[2] * s + k[2] * dot * (1 - c)]\n}\n\nexport function clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v\n}\n\nexport function dist3(a: Vec3, b: Vec3): number {\n return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2])\n}\n","import type { BodyGesture } from '@adatechnology/game-contracts'\nimport { createBasinDrain } from './basin-drain'\nimport type { BasinDrain } from './basin-drain'\nimport { GESTURE_OF_ACTION } from './gestures'\nimport { FLUSH_RUN_SECONDS } from './fixture-emitters'\nimport { mergeColliders } from './colliders'\nimport { fitsSlot, generateLoot } from './loot'\nimport { format, resolveStrings } from './locale'\nimport type { PartDriver, SoftDriver } from './part-physics'\nimport { clamp, dist3, localToWorld, rotateAxis, rotY, worldToLocal } from './math'\nimport type {\n ActiveEmitter,\n BurnerSpec,\n ColliderOptions,\n DeviceSpec,\n FixtureSpec,\n FuelSourceSpec,\n Interactable,\n InteractionSpec,\n ItemStack,\n ObjectSpec,\n PartSpec,\n SeatResult,\n SoftSpec,\n TankSpec,\n TargetOptions,\n Transform,\n Vec3,\n World,\n WorldCollider,\n WorldEvent,\n WorldObject,\n WorldOptions,\n WorldState,\n} from './types'\n\n// ---------------------------------------------------------------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------------------------------------------------------------\n\nconst DEFAULT_ACTOR = 'player'\nconst DEFAULT_RADIUS = 1.2\n/** Local id prefix of the `take` a stack in an open container offers (`<object>:take.<container>.<slot>`). */\nconst TAKE_PREFIX = 'take.'\n/** Reach radius of one contained item, metres. */\nconst TAKE_RADIUS = 0.6\nconst AUTO_RANGE = 2\n/** How far behind a socket's face (m) a plug may be and still take it: a plug on the wall's other side is a wall's thickness (10 cm or more) behind it. */\nconst SOCKET_BEHIND = 0.05\nconst SMOKE_TAIL = 20\nconst FLUSH_SECONDS = FLUSH_RUN_SECONDS\nconst ACTOR_HEIGHT = 1.7\nconst PUSH_GAIN = 1.2\nconst SWEEP_STEPS = 24\nexport const FLOW_DEFAULTS: Readonly<Record<string, number>> = { tap: 6, shower: 8, utility_sink: 6, flush: 0, hose: 10, filter: 1 }\n\n// ---------------------------------------------------------------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------------------------------------------------------------\n\ninterface PartState {\n spec: PartSpec\n t: number\n target: number\n maxT: number\n /** With `WorldOptions.partPhysics`: the engine moves the part, and `t` is read from it. */\n driver?: PartDriver\n /** The target the driver was last told (`aim`). */\n commanded?: number\n /** The driver is going to a target: arriving reports the part event. */\n moving?: boolean\n broken?: boolean\n}\n\ninterface DeviceState {\n spec: DeviceSpec\n on: boolean\n channel: number\n}\n\ninterface FuelState {\n spec: FuelSourceSpec\n level: number\n}\n\ninterface BurnerState {\n spec: BurnerSpec\n on: boolean\n lit: boolean\n /** Seconds of smoke left after a solid-fuel fire went out. */\n smoke: number\n}\n\ninterface TankState {\n spec: TankSpec\n level: number\n}\n\ninterface FixtureState {\n spec: FixtureSpec\n on: boolean\n flowing: boolean\n /** Delivered / wanted in the last step, 0..1. */\n frac: number\n /** Seconds left of a flush. */\n timer: number\n}\n\ninterface SoftState {\n spec: SoftSpec\n ax: number\n az: number\n vax: number\n vaz: number\n phase: number\n /** With `WorldOptions.partPhysics`: the engine swings the volume (the spring is not used). */\n driver?: SoftDriver\n}\n\ninterface DamageState {\n max: number\n hp: number\n}\n\ninterface ObjState {\n id: string\n public: WorldObject\n spec: ObjectSpec\n parts: Map<string, PartState>\n contents: Map<string, Array<ItemStack | null>>\n devices: Map<string, DeviceState>\n fuels: Map<string, FuelState>\n burners: Map<string, BurnerState>\n tanks: Map<string, TankState>\n fixtures: Map<string, FixtureState>\n /** The water of each basin with a trap (a toilet's bowl), by the basin's id. */\n drains: Map<string, BasinDrain>\n soft: Map<string, SoftState>\n hp: Map<string, DamageState>\n interactions: InteractionSpec[]\n}\n\nfunction cloneStack(s: ItemStack | null): ItemStack | null {\n return s ? { type: s.type, qty: s.qty, ...(s.data ? { data: JSON.parse(JSON.stringify(s.data)) as Record<string, unknown> } : {}) } : null\n}\n\nfunction humanize(id: string): string {\n const s = id.replace(/[_-]+/g, ' ').trim()\n return s.charAt(0).toUpperCase() + s.slice(1)\n}\n\n// ---------------------------------------------------------------------------------------------------------------------------------\n// World\n// ---------------------------------------------------------------------------------------------------------------------------------\n\nexport function createWorld(options: WorldOptions = {}): World {\n const seed = options.seed ?? 1\n const objs = new Map<string, ObjState>()\n const breakers = new Map<string, boolean>()\n const seats = new Map<string, { object: string; seat: string }>()\n const plugs = new Map<string, string | null>()\n let locale = options.locale ?? 'en'\n let table = resolveStrings(locale, options.strings)\n let grid = options.grid ?? true\n // the main breaker of the service entrance, after the meter: off, nothing of the building has power whatever the grid and its circuits say\n let main = true\n let rain = options.rain ?? 0\n let wind: [number, number] = options.wind ? [options.wind[0], options.wind[1]] : [0, 0]\n let defaultTank: string | null = null\n let defaultTankExplicit = false\n let time = 0\n\n // ------------------------------------------------------------------ text & events\n function t(key: string, vars?: Record<string, string | number>): string {\n return format(table[key] ?? key, vars)\n }\n\n function emit(e: WorldEvent): void {\n options.onEvent?.(e)\n }\n\n function message(key: string): void {\n emit({ type: 'message', key, text: t(key) })\n }\n\n // ------------------------------------------------------------------ lookup helpers\n function gid(o: ObjState, local: string): string {\n return `${o.id}:${local}`\n }\n\n /** Find the first entity matching a world-wide id `objectId:localId`. */\n function findGlobal<T>(id: string, pick: (o: ObjState, local: string) => T | undefined): { o: ObjState; value: T; local: string } | null {\n for (const o of objs.values()) {\n if (!id.startsWith(o.id + ':')) continue\n const local = id.slice(o.id.length + 1)\n const value = pick(o, local)\n if (value !== undefined) return { o, value, local }\n }\n return null\n }\n\n function objectOrThrow(id: string): ObjState {\n const o = objs.get(id)\n if (!o) throw new Error(`Unknown object \"${id}\"`)\n return o\n }\n\n function originOf(o: ObjState): Vec3 {\n const tr = o.public.transform\n return [tr.x, tr.y, tr.z]\n }\n\n function toWorld(o: ObjState, v: Vec3): Vec3 {\n return localToWorld(o.public.transform, v)\n }\n\n // ------------------------------------------------------------------ parts\n function openThreshold(p: PartState): number {\n return Math.min(0.5, p.maxT * 0.9)\n }\n\n function isOpen(o: ObjState, partId: string | undefined): boolean {\n if (!partId) return true\n const p = o.parts.get(partId)\n if (!p) return true\n return p.maxT >= 0.1 && p.t >= openThreshold(p)\n }\n\n function targetIsOpen(p: PartState): boolean {\n return p.maxT >= 0.1 && p.target >= openThreshold(p)\n }\n\n function writeT(o: ObjState, p: PartState, v: number): void {\n p.t = v\n o.public.parts[p.spec.id] = v\n }\n\n function gated(o: ObjState, p: PartState): boolean {\n return !!p.spec.requires && o.parts.has(p.spec.requires) && !isOpen(o, p.spec.requires)\n }\n\n function setOnePart(o: ObjState, p: PartState, target: number, instant: boolean): void {\n const next = clamp(target, 0, p.maxT)\n const changed = next !== p.target\n p.target = next\n if (instant) {\n p.driver?.snap(next)\n p.commanded = next\n writeT(o, p, next)\n }\n if (changed || instant) emit({ type: 'part', object: o.id, part: p.spec.id, t: p.t, target: p.target })\n }\n\n function setPartTarget(o: ObjState, partId: string, target: number, instant = false): void {\n const p = o.parts.get(partId)\n if (!p) return\n const group = p.spec.group\n const members = group ? [...o.parts.values()].filter((q) => q.spec.group === group) : [p]\n for (const q of members) {\n setOne(o, q, target, instant)\n }\n }\n\n function setOne(o: ObjState, p: PartState, target: number, instant: boolean): void {\n setOnePart(o, p, target, instant)\n // a part that other parts require closes them with it (the drawer behind a door closes with the door)\n if (!targetIsOpen(p)) {\n for (const q of o.parts.values()) {\n if (q.spec.requires === p.spec.id && q.target > 0) setPartTarget(o, q.spec.id, 0, instant)\n }\n }\n }\n\n /** Frame of a part right now: rotation (axis in object-local, angle) and translation, both about its pivot. */\n function partFrame(o: ObjState, partId: string | undefined): { pivot: Vec3; axis: Vec3; angle: number; offset: Vec3 } | null {\n if (!partId) return null\n const p = o.parts.get(partId)\n if (!p) return null\n const m = p.spec.motion\n const axis = rotY(m.axis ?? [0, 1, 0], p.spec.ry ?? 0)\n const frame = { pivot: p.spec.pivot, axis, angle: 0, offset: [0, 0, 0] as Vec3 }\n if (m.kind === 'slide') {\n const d = (m.distance ?? 0.4) * p.t\n frame.offset = [axis[0] * d, axis[1] * d, axis[2] * d]\n } else if (m.kind !== 'scale') {\n frame.angle = (m.angle ?? Math.PI / 2) * p.t\n }\n return frame\n }\n\n function applyPart(o: ObjState, partId: string | undefined, local: Vec3): Vec3 {\n const f = partFrame(o, partId)\n if (!f) return local\n const rel: Vec3 = [local[0] - f.pivot[0], local[1] - f.pivot[1], local[2] - f.pivot[2]]\n const r = f.angle !== 0 ? rotateAxis(rel, f.axis, f.angle) : rel\n return [f.pivot[0] + r[0] + f.offset[0], f.pivot[1] + r[1] + f.offset[1], f.pivot[2] + r[2] + f.offset[2]]\n }\n\n /** Moves the full closed-pose slab of a part and returns the largest t whose pose keeps every sampled point clear. */\n function fitBounds(o: ObjState, p: PartState, b: NonNullable<PartSpec['bounds']>, blockedAt: (x: number, z: number) => boolean): number {\n const STEP = 0.05\n const ANGLES = 48\n const m = p.spec.motion\n const axis = rotY(m.axis ?? [0, 1, 0], p.spec.ry ?? 0)\n const lo: Vec3 = [Math.min(b[0], b[3]), Math.min(b[1], b[4]), Math.min(b[2], b[5])]\n const hi: Vec3 = [Math.max(b[0], b[3]), Math.max(b[1], b[4]), Math.max(b[2], b[5])]\n const axisPoints = (i: number): number[] => {\n const n = Math.max(1, Math.ceil((hi[i] - lo[i]) / STEP))\n return Array.from({ length: n + 1 }, (_, k) => lo[i] + ((hi[i] - lo[i]) * k) / n)\n }\n const xs = axisPoints(0)\n const ys = axisPoints(1)\n const zs = axisPoints(2)\n // `blocked` only sees x/z, so only the floor footprint matters. About a vertical axis (and for slides) y never changes\n // the footprint, so the x/z outline is enough; otherwise the footprint boundary is the projection of the box edges.\n const flat = m.kind === 'slide' || Math.abs(axis[1]) > 0.999\n const seen = new Set<string>()\n const pts: Vec3[] = []\n const add = (x: number, y: number, z: number): void => {\n const key = `${x.toFixed(5)},${y.toFixed(5)},${z.toFixed(5)}`\n if (seen.has(key)) return\n seen.add(key)\n pts.push([x, y, z])\n }\n if (flat) {\n for (const x of xs) for (const z of [lo[2], hi[2]]) add(x, lo[1], z)\n for (const z of zs) for (const x of [lo[0], hi[0]]) add(x, lo[1], z)\n } else {\n for (const x of xs) for (const y of [lo[1], hi[1]]) for (const z of [lo[2], hi[2]]) add(x, y, z)\n for (const y of ys) for (const x of [lo[0], hi[0]]) for (const z of [lo[2], hi[2]]) add(x, y, z)\n for (const z of zs) for (const x of [lo[0], hi[0]]) for (const y of [lo[1], hi[1]]) add(x, y, z)\n }\n const tr = o.public.transform\n const pivot = p.spec.pivot\n for (let i = 1; i <= ANGLES; i++) {\n const tt = i / ANGLES\n const angle = m.kind === 'slide' ? 0 : (m.angle ?? Math.PI / 2) * tt\n const d = m.kind === 'slide' ? (m.distance ?? 0.4) * tt : 0\n for (const [x, y, z] of pts) {\n let q: Vec3 = [x, y, z]\n if (angle !== 0) {\n const r = rotateAxis([x - pivot[0], y - pivot[1], z - pivot[2]], axis, angle)\n q = [pivot[0] + r[0], pivot[1] + r[1], pivot[2] + r[2]]\n }\n const w = localToWorld(tr, [q[0] + axis[0] * d, 0, q[2] + axis[2] * d])\n if (blockedAt(w[0], w[2])) return (i - 1) / ANGLES\n }\n }\n return 1\n }\n\n function fitSweep(objectId: string, partId: string, blocked: (x: number, z: number) => boolean): number {\n const o = objectOrThrow(objectId)\n const p = o.parts.get(partId)\n if (!p) throw new Error(`Unknown part \"${partId}\" on \"${objectId}\"`)\n const sweep = p.spec.sweep\n let result = 1\n const bounds = p.spec.bounds\n const mk = p.spec.motion.kind\n if (bounds && (mk === 'hinge' || mk === 'rocker' || mk === 'knob' || mk === 'slide')) {\n result = fitBounds(o, p, bounds, blocked)\n } else if (sweep) {\n const x0 = Math.min(sweep[0], sweep[2])\n const x1 = Math.max(sweep[0], sweep[2])\n const z0 = Math.min(sweep[1], sweep[3])\n const z1 = Math.max(sweep[1], sweep[3])\n const tr = o.public.transform\n const hit = (lx: number, lz: number): boolean => {\n const w = localToWorld(tr, [lx, 0, lz])\n return blocked(w[0], w[2])\n }\n const m = p.spec.motion\n const axis = rotY(m.axis ?? [0, 1, 0], p.spec.ry ?? 0)\n if (m.kind === 'hinge' || m.kind === 'rocker' || m.kind === 'knob') {\n if (Math.abs(axis[1]) >= 0.5) {\n const angle = m.angle ?? Math.PI / 2\n const total = -angle * Math.sign(axis[1])\n const [px, , pz] = p.spec.pivot\n const cx = (x0 + x1) / 2\n const cz = (z0 + z1) / 2\n const w = x1 - x0\n const d = z1 - z0\n const radius = Math.abs(angle) > 1.7 ? Math.min(w, d) : Math.max(w, d)\n const tol = 0.05\n const inRect = (x: number, z: number) => x >= x0 - tol && x <= x1 + tol && z >= z0 - tol && z <= z1 + tol\n const centered = Math.hypot(cx - px, cz - pz) < 1e-6\n const mid = Math.atan2(cz - pz, cx - px)\n for (let i = 1; i <= SWEEP_STEPS && result === 1; i++) {\n const tt = i / SWEEP_STEPS\n let isHit = false\n if (centered) {\n for (let x = x0; x <= x1 + 1e-9 && !isHit; x += 0.1) for (let z = z0; z <= z1 + 1e-9 && !isHit; z += 0.1) isHit = hit(x, z)\n } else {\n const phi = mid - total / 2 + total * tt\n const steps = Math.max(2, Math.ceil(radius / 0.1))\n for (let k = 1; k <= steps && !isHit; k++) {\n const r = (radius * k) / steps\n const x = px + Math.cos(phi) * r\n const z = pz + Math.sin(phi) * r\n if (inRect(x, z)) isHit = hit(x, z)\n }\n }\n if (isHit) result = (i - 1) / SWEEP_STEPS\n }\n }\n } else if (m.kind === 'slide') {\n const len = Math.hypot(axis[0], axis[2])\n if (len > 1e-6) {\n const dx = axis[0] / len\n const dz = axis[2] / len\n const proj = [x0 * dx + z0 * dz, x1 * dx + z0 * dz, x0 * dx + z1 * dz, x1 * dx + z1 * dz]\n const pmin = Math.min(...proj)\n const pmax = Math.max(...proj)\n const nx = Math.max(1, Math.ceil((x1 - x0) / 0.1))\n const nz = Math.max(1, Math.ceil((z1 - z0) / 0.1))\n for (let i = 1; i <= SWEEP_STEPS && result === 1; i++) {\n const limit = pmin + (pmax - pmin) * (i / SWEEP_STEPS)\n let isHit = false\n for (let a = 0; a <= nx && !isHit; a++) {\n for (let b = 0; b <= nz && !isHit; b++) {\n const x = x0 + ((x1 - x0) * a) / nx\n const z = z0 + ((z1 - z0) * b) / nz\n if (x * dx + z * dz <= limit + 1e-9 && hit(x, z)) isHit = true\n }\n }\n if (isHit) result = (i - 1) / SWEEP_STEPS\n }\n }\n }\n }\n p.maxT = result\n if (p.target > result) p.target = result\n if (p.t > result) writeT(o, p, result)\n return result\n }\n\n // ------------------------------------------------------------------ containers\n function containerOf(o: ObjState, id: string) {\n return o.spec.containers?.find((c) => c.id === id)\n }\n\n function accessible(objectId: string, containerId: string): boolean {\n const o = objs.get(objectId)\n if (!o) return false\n const c = containerOf(o, containerId)\n if (!c) return false\n return isOpen(o, c.access)\n }\n\n function contents(objectId: string, containerId: string): Array<ItemStack | null> {\n return (objs.get(objectId)?.contents.get(containerId) ?? []).map(cloneStack)\n }\n\n function take(objectId: string, containerId: string, slot: number, actor: string = DEFAULT_ACTOR): ItemStack | null {\n const o = objs.get(objectId)\n if (!o) return null\n const list = o.contents.get(containerId)\n if (!list || !accessible(objectId, containerId)) return null\n const stack = list[slot]\n if (!stack) return null\n const def = options.items?.[stack.type]\n if (def && def.pickable === false) return null\n list[slot] = null\n emit({ type: 'pickup', object: objectId, container: containerId, slot, stack: cloneStack(stack) as ItemStack, actor })\n return stack\n }\n\n function put(objectId: string, containerId: string, stack: ItemStack): number | null {\n const o = objs.get(objectId)\n if (!o) return null\n const c = containerOf(o, containerId)\n const list = o.contents.get(containerId)\n if (!c || !list || !accessible(objectId, containerId)) return null\n const maxStack = options.items?.[stack.type]?.stack ?? 1\n for (let i = 0; i < list.length; i++) {\n const cur = list[i]\n if (cur && cur.type === stack.type && !cur.data && !stack.data && cur.qty + stack.qty <= maxStack) {\n cur.qty += stack.qty\n return i\n }\n }\n for (let i = 0; i < list.length; i++) {\n if (!list[i] && fitsSlot(stack.type, c.slots[i], options.items)) {\n list[i] = cloneStack(stack)\n return i\n }\n }\n message('full')\n return null\n }\n\n function slotPosition(objectId: string, containerId: string, slot: number): Vec3 {\n const o = objectOrThrow(objectId)\n const c = containerOf(o, containerId)\n const s = c?.slots[slot]\n if (!c || !s) throw new Error(`Unknown slot ${slot} of \"${containerId}\" on \"${objectId}\"`)\n return toWorld(o, applyPart(o, s.part, s.pos))\n }\n\n // ------------------------------------------------------------------ power\n function rebuildPlugs(): void {\n plugs.clear()\n const sockets: Array<{ id: string; pos: Vec3; circuit?: string; local: string; facing: Vec3 }> = []\n for (const o of objs.values()) {\n for (const s of o.spec.sockets ?? []) {\n const pos = toWorld(o, s.pos)\n const ahead = toWorld(o, [s.pos[0], s.pos[1], s.pos[2] + 1])\n sockets.push({ id: gid(o, s.id), local: s.id, pos, circuit: s.circuit, facing: [ahead[0] - pos[0], ahead[1] - pos[1], ahead[2] - pos[2]] })\n }\n }\n const used = new Set<string>()\n const autos: Array<{ o: ObjState; d: DeviceState }> = []\n for (const o of objs.values()) {\n for (const d of o.devices.values()) {\n const key = gid(o, d.spec.id)\n const want = d.spec.socket\n if (want === undefined || d.spec.circuit) {\n plugs.set(key, null)\n } else if (want === 'auto') {\n plugs.set(key, null)\n autos.push({ o, d })\n } else {\n const s = sockets.find((x) => x.id === want) ?? sockets.find((x) => x.id === gid(o, want)) ?? sockets.find((x) => x.local === want)\n plugs.set(key, s ? s.id : null)\n if (s) used.add(s.id)\n }\n }\n }\n for (const { o, d } of autos) {\n const from = d.spec.plug ? toWorld(o, d.spec.plug) : originOf(o)\n let best: (typeof sockets)[number] | null = null\n let bestD = AUTO_RANGE\n for (const s of sockets) {\n if (used.has(s.id)) continue\n // a socket faces out of its wall (+z): a plug behind its face is on the wall's other side, in the next room, and its cord would cross the wall\n if ((from[0] - s.pos[0]) * s.facing[0] + (from[1] - s.pos[1]) * s.facing[1] + (from[2] - s.pos[2]) * s.facing[2] < -SOCKET_BEHIND) continue\n const dd = dist3(from, s.pos)\n if (dd <= bestD) {\n best = s\n bestD = dd\n }\n }\n if (best) {\n used.add(best.id)\n plugs.set(gid(o, d.spec.id), best.id)\n }\n }\n }\n\n function breaker(circuit: string): boolean {\n return breakers.get(circuit) ?? true\n }\n\n function devicePowered(o: ObjState, d: DeviceState): boolean {\n if (d.spec.electric === false) return true\n if (!grid || !main) return false\n if (d.spec.circuit) return breaker(d.spec.circuit)\n if (d.spec.socket === undefined) return false\n const sid = plugs.get(gid(o, d.spec.id))\n if (!sid) return false\n const found = findGlobal(sid, (oo, local) => oo.spec.sockets?.find((s) => s.id === local))\n if (!found) return false\n return found.value.circuit ? breaker(found.value.circuit) : true\n }\n\n function getDevice(objectId: string, deviceId: string): { o: ObjState; d: DeviceState } | null {\n const o = objs.get(objectId)\n const d = o?.devices.get(deviceId)\n return o && d ? { o, d } : null\n }\n\n function powerSnapshot(): Map<string, boolean> {\n const m = new Map<string, boolean>()\n for (const o of objs.values()) for (const d of o.devices.values()) m.set(gid(o, d.spec.id), d.on && devicePowered(o, d))\n return m\n }\n\n function emitPowerChanges(before: Map<string, boolean>): void {\n for (const o of objs.values()) {\n for (const d of o.devices.values()) {\n const key = gid(o, d.spec.id)\n const now = d.on && devicePowered(o, d)\n if (before.get(key) !== now && d.on) emit({ type: 'device', object: o.id, device: d.spec.id, on: d.on, powered: devicePowered(o, d), channel: d.spec.kind === 'screen' ? d.channel : undefined })\n }\n }\n }\n\n function setDeviceOn(o: ObjState, d: DeviceState, on: boolean): void {\n d.on = on\n if (d.spec.part) setPartTarget(o, d.spec.part, on ? 1 : 0)\n const powered = devicePowered(o, d)\n emit({ type: 'device', object: o.id, device: d.spec.id, on, powered, channel: d.spec.kind === 'screen' ? d.channel : undefined })\n if (on && !powered) message('no_power')\n }\n\n function setDevice(objectId: string, deviceId: string, on: boolean): boolean {\n const f = getDevice(objectId, deviceId)\n if (!f) return false\n if (f.d.on !== on) setDeviceOn(f.o, f.d, on)\n return true\n }\n\n function setFixture(objectId: string, fixtureId: string, on: boolean): boolean {\n const fx = objs.get(objectId)?.fixtures.get(fixtureId)\n if (!fx) return false\n if (fx.on !== on) toggleFixture(objs.get(objectId) as ObjState, fixtureId)\n return fx.on === on\n }\n\n function setBurner(objectId: string, burnerId: string, on: boolean): boolean {\n const o = objs.get(objectId)\n const b = o?.burners.get(burnerId)\n if (!o || !b) return false\n const isOn = b.on || b.lit\n if (on === isOn) return true\n if (!on) return toggleBurner(o, burnerId)\n return b.spec.needsIgnition ? ignite(o, burnerId) : toggleBurner(o, burnerId)\n }\n\n function resolveDevice(o: ObjState, id: string): { o: ObjState; d: DeviceState } | null {\n if (id.includes(':')) {\n const f = findGlobal(id, (oo, local) => oo.devices.get(local))\n return f ? { o: f.o, d: f.value } : null\n }\n const local = o.devices.get(id)\n if (local) return { o, d: local }\n for (const oo of objs.values()) {\n const d = oo.devices.get(id)\n if (d) return { o: oo, d }\n }\n return null\n }\n\n function switchIsOn(o: ObjState, spec: { part?: string; controls: string[] }): boolean {\n if (spec.part && o.parts.has(spec.part)) return targetIsOpen(o.parts.get(spec.part) as PartState)\n return spec.controls.some((id) => resolveDevice(o, id)?.d.on)\n }\n\n function toggleSwitch(o: ObjState, id: string): boolean {\n const sw = o.spec.switches?.find((s) => s.id === id)\n if (!sw) return false\n const on = !switchIsOn(o, sw)\n if (sw.part) setPartTarget(o, sw.part, on ? 1 : 0)\n let unpowered = false\n for (const ref of sw.controls) {\n const r = resolveDevice(o, ref)\n if (!r) continue\n r.d.on = on\n if (r.d.spec.part) setPartTarget(r.o, r.d.spec.part, on ? 1 : 0)\n const powered = devicePowered(r.o, r.d)\n if (on && !powered) unpowered = true\n emit({ type: 'device', object: r.o.id, device: r.d.spec.id, on, powered })\n }\n emit({ type: 'switch', object: o.id, switch: sw.id, on })\n if (unpowered) message('no_power')\n return true\n }\n\n // ------------------------------------------------------------------ fuel\n function resolveFuel(o: ObjState, b: BurnerState): { o: ObjState; f: FuelState } | null {\n const want = b.spec.fuel\n if (want === 'auto') {\n const from = toWorld(o, b.spec.pos)\n let best: { o: ObjState; f: FuelState } | null = null\n let bestD = AUTO_RANGE\n for (const oo of objs.values()) {\n for (const f of oo.fuels.values()) {\n if (f.spec.kind !== 'gas') continue\n const d = dist3(from, originOf(oo))\n if (d <= bestD) {\n best = { o: oo, f }\n bestD = d\n }\n }\n }\n return best\n }\n if (want.includes(':')) {\n const f = findGlobal(want, (oo, local) => oo.fuels.get(local))\n return f ? { o: f.o, f: f.value } : null\n }\n const local = o.fuels.get(want)\n return local ? { o, f: local } : null\n }\n\n function valveOpen(o: ObjState, f: FuelState): boolean {\n const v = f.spec.valve\n if (!v || !o.parts.has(v)) return true\n return targetIsOpen(o.parts.get(v) as PartState)\n }\n\n function canBurn(b: BurnerState, ref: { o: ObjState; f: FuelState } | null): boolean {\n return !!ref && ref.f.level > 0 && valveOpen(ref.o, ref.f)\n }\n\n function isSolid(ref: { f: FuelState } | null): boolean {\n return !!ref && ref.f.spec.kind !== 'gas'\n }\n\n function emitBurner(o: ObjState, b: BurnerState): void {\n emit({ type: 'burner', object: o.id, burner: b.spec.id, on: b.on, lit: b.lit })\n }\n\n function extinguish(o: ObjState, b: BurnerState, turnOff: boolean): void {\n const ref = resolveFuel(o, b)\n const wasLit = b.lit\n b.lit = false\n if (turnOff) b.on = false\n if (b.spec.part) setPartTarget(o, b.spec.part, b.on ? 1 : 0)\n if (wasLit && isSolid(ref)) b.smoke = SMOKE_TAIL\n emitBurner(o, b)\n }\n\n function toggleBurner(o: ObjState, id: string): boolean {\n const b = o.burners.get(id)\n if (!b) return false\n if (b.on || b.lit) {\n extinguish(o, b, true)\n return true\n }\n if (b.spec.needsIgnition) return false\n const ref = resolveFuel(o, b)\n b.on = true\n b.lit = canBurn(b, ref)\n if (b.lit) b.smoke = 0\n if (b.spec.part) setPartTarget(o, b.spec.part, 1)\n emitBurner(o, b)\n if (!b.lit) message(ref && ref.f.level <= 0 ? 'empty' : 'no_gas')\n return true\n }\n\n function ignite(o: ObjState, id: string): boolean {\n const b = o.burners.get(id)\n if (!b || b.lit) return false\n const ref = resolveFuel(o, b)\n if (!canBurn(b, ref)) {\n message(ref && ref.f.level <= 0 ? 'empty' : 'no_gas')\n return false\n }\n b.on = true\n b.lit = true\n b.smoke = 0\n if (b.spec.part) setPartTarget(o, b.spec.part, 1)\n emitBurner(o, b)\n return true\n }\n\n function toggleFuel(o: ObjState, id: string): boolean {\n const f = o.fuels.get(id)\n if (!f || !f.spec.valve || !o.parts.has(f.spec.valve)) return false\n const p = o.parts.get(f.spec.valve) as PartState\n setPartTarget(o, f.spec.valve, targetIsOpen(p) ? 0 : 1)\n return true\n }\n\n // ------------------------------------------------------------------ water\n function resolveTank(o: ObjState, id: string | undefined): { o: ObjState; t: TankState } | null {\n const want = id === undefined || id === 'auto' ? defaultTank : id\n if (!want) return null\n const f = findGlobal(want, (oo, local) => oo.tanks.get(local))\n if (f) return { o: f.o, t: f.value }\n const local = o.tanks.get(want)\n return local ? { o, t: local } : null\n }\n\n function drawWater(o: ObjState, fx: FixtureState, liters: number): number {\n if (liters <= 0) return 0\n if (options.waterSupply) return Math.max(0, Math.min(liters, options.waterSupply.draw(gid(o, fx.spec.id), liters)))\n const tank = resolveTank(o, fx.spec.tank)\n if (!tank) return 0\n const got = Math.min(liters, tank.t.level)\n tank.t.level -= got\n return got\n }\n\n function emitFixture(o: ObjState, fx: FixtureState): void {\n emit({ type: 'fixture', object: o.id, fixture: fx.spec.id, on: fx.on, flowing: fx.flowing })\n }\n\n function flowOf(fx: FixtureState): number {\n return fx.spec.flow ?? FLOW_DEFAULTS[fx.spec.kind] ?? 6\n }\n\n function stepFixture(o: ObjState, fx: FixtureState, dt: number): void {\n if (!fx.on) return\n if (fx.spec.kind === 'flush') {\n fx.timer -= dt\n if (fx.timer <= 0) {\n fx.on = false\n fx.flowing = false\n fx.frac = 0\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 0)\n emitFixture(o, fx)\n }\n return\n }\n if (dt <= 0) return\n const wanted = (flowOf(fx) / 60) * dt\n const got = drawWater(o, fx, wanted)\n const flowing = got > 1e-9\n fx.frac = wanted > 0 ? Math.min(1, got / wanted) : 0\n if (flowing !== fx.flowing) {\n fx.flowing = flowing\n emitFixture(o, fx)\n }\n }\n\n function toggleFixture(o: ObjState, id: string): boolean {\n const fx = o.fixtures.get(id)\n if (!fx) return false\n if (fx.on) {\n fx.on = false\n fx.flowing = false\n fx.frac = 0\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 0)\n emitFixture(o, fx)\n return true\n }\n fx.on = true\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 1)\n if (fx.spec.kind === 'flush') {\n const volume = fx.spec.volume ?? 6\n const got = drawWater(o, fx, volume)\n fx.flowing = got > 1e-9\n fx.frac = fx.flowing ? 1 : 0\n fx.timer = FLUSH_SECONDS\n if (!fx.flowing) {\n fx.on = false\n if (fx.spec.part) setPartTarget(o, fx.spec.part, 0)\n }\n } else {\n fx.flowing = false\n fx.frac = 0\n stepFixture(o, fx, 1 / 60)\n }\n emitFixture(o, fx)\n if (!fx.flowing) message('no_water')\n return true\n }\n\n // ------------------------------------------------------------------ seats\n function seatTaken(objectId: string, seatId: string): string | null {\n for (const [actor, s] of seats) if (s.object === objectId && s.seat === seatId) return actor\n return null\n }\n\n function stand(actor: string = DEFAULT_ACTOR): Vec3 | null {\n const s = seats.get(actor)\n if (!s) return null\n seats.delete(actor)\n const o = objs.get(s.object)\n const spec = o?.spec.seats?.find((x) => x.id === s.seat)\n emit({ type: 'seat', object: s.object, seat: s.seat, actor, seated: false })\n if (!o || !spec) return null\n return toWorld(o, spec.exit)\n }\n\n function sit(objectId: string, seatId: string, actor: string = DEFAULT_ACTOR): SeatResult | null {\n const o = objs.get(objectId)\n const seat = o?.spec.seats?.find((s) => s.id === seatId)\n if (!o || !seat) return null\n const holder = seatTaken(objectId, seatId)\n if (holder && holder !== actor) return null\n if (seats.has(actor) && !holder) stand(actor)\n seats.set(actor, { object: objectId, seat: seatId })\n const eye = seat.eye ?? (seat.pose === 'lie' ? 0.18 : 0.62)\n emit({ type: 'seat', object: objectId, seat: seatId, actor, seated: true })\n return { eye: toWorld(o, [seat.pos[0], seat.pos[1] + eye, seat.pos[2]]), yaw: o.public.transform.ry + seat.ry + Math.PI, pose: seat.pose }\n }\n\n // ------------------------------------------------------------------ soft volumes\n function push(pos: Vec3, radius: number, vel: Vec3): void {\n for (const o of objs.values()) {\n if (!o.soft.size) continue\n const tr = o.public.transform\n const lp = worldToLocal(tr, pos)\n const lv = rotY(vel, -tr.ry)\n for (const s of o.soft.values()) {\n const [w, h, d] = s.spec.size\n const hx = w / 2\n const hz = Math.max(d, 0.1) / 2\n const dx = Math.max(Math.abs(lp[0] - s.spec.anchor[0]) - hx, 0)\n const dz = Math.max(Math.abs(lp[2] - s.spec.anchor[2]) - hz, 0)\n if (Math.hypot(dx, dz) > radius) continue\n const top = tr.y + s.spec.anchor[1]\n if (pos[1] + ACTOR_HEIGHT < top - h || pos[1] > top) continue\n if (s.driver) {\n s.driver.push(lv)\n if (s.spec.kind === 'panel' && s.spec.part && lv[2] < -0.05 && lp[2] > s.spec.anchor[2]) setPartTarget(o, s.spec.part, 1)\n continue\n }\n const cap = 8\n s.vax = clamp(s.vax - lv[2] * PUSH_GAIN, -cap, cap)\n s.vaz = clamp(s.vaz + lv[0] * PUSH_GAIN, -cap, cap)\n if (s.spec.kind === 'panel' && s.spec.part && lv[2] < -0.05 && lp[2] > s.spec.anchor[2]) setPartTarget(o, s.spec.part, 1)\n }\n }\n }\n\n const swingOut: [number, number] = [0, 0]\n function stepSoft(dt: number): void {\n const sub = Math.max(1, Math.ceil(dt / (1 / 120)))\n const h = dt / sub\n for (const o of objs.values()) {\n if (!o.soft.size) continue\n const wl = rotY([wind[0], 0, wind[1]], -o.public.transform.ry)\n for (const s of o.soft.values()) {\n const k = s.spec.stiffness ?? 30\n const c = s.spec.damping ?? 4\n const max = s.spec.maxAngle ?? 0.7\n if (s.driver) {\n s.driver.swing(swingOut)\n s.ax = swingOut[0]\n s.az = swingOut[1]\n continue\n }\n const gain = s.spec.wind ?? (s.spec.kind === 'panel' ? 0 : 1)\n const gust = gain * (0.6 + 0.4 * Math.sin(time * 1.7 + s.phase)) * 0.1\n const fx = -wl[2] * gust\n const fz = wl[0] * gust\n for (let i = 0; i < sub; i++) {\n s.vax += (-k * s.ax - c * s.vax + fx) * h\n s.vaz += (-k * s.az - c * s.vaz + fz) * h\n s.ax += s.vax * h\n s.az += s.vaz * h\n }\n if (Math.abs(s.ax) > max) {\n s.ax = Math.sign(s.ax) * max\n s.vax = 0\n }\n if (Math.abs(s.az) > max) {\n s.az = Math.sign(s.az) * max\n s.vaz = 0\n }\n }\n }\n }\n\n // ------------------------------------------------------------------ damage\n function damage(objectId: string, target: string, amount: number, _kind?: string): { hp: number; destroyed: boolean } | null {\n const o = objs.get(objectId)\n if (o && options.destruction) {\n const pos = toWorld(o, [0, 0.5, 0])\n const type = _kind === 'gas' ? 'explosive' : _kind === 'fabric' ? 'slash' : 'blunt'\n const result = options.destruction.hitPart(objectId, target, { type, point: pos, energy: Math.max(0, amount), source: 'interactables' }) as { events?: Array<{ type?: string; part?: string }> } | null | undefined\n const destroyed = !!result?.events?.some((e) => e.type === 'fracture' && e.part === target)\n emit({ type: 'damage', object: objectId, target, hp: -1, destroyed })\n return { hp: -1, destroyed }\n }\n const st = o?.hp.get(target)\n if (!o || !st) return null\n if (st.hp <= 0) return { hp: 0, destroyed: true }\n const before = st.hp\n st.hp = Math.max(0, st.hp - Math.max(0, amount))\n const destroyed = st.hp <= 0\n emit({ type: 'damage', object: objectId, target, hp: st.hp, destroyed })\n const pos = toWorld(o, [0, 0.5, 0])\n const fuel = o.fuels.get(target)\n if (fuel && destroyed && fuel.spec.kind === 'gas' && fuel.level > 0) {\n emit({ type: 'explosion', object: objectId, pos, radius: 2 + fuel.level / 5 })\n fuel.level = 0\n }\n const tank = o.tanks.get(target)\n if (tank && before === st.max && st.hp < before) emit({ type: 'leak', object: objectId, target, pos })\n return { hp: st.hp, destroyed }\n }\n\n // ------------------------------------------------------------------ interactions\n function deriveInteractions(spec: ObjectSpec): InteractionSpec[] {\n const out: InteractionSpec[] = []\n const used = new Set<string>()\n const partPos = (id: string | undefined, fallback: Vec3): Vec3 => spec.parts?.find((p) => p.id === id)?.pivot ?? fallback\n const partLabel = (id: string | undefined): string => spec.parts?.find((p) => p.id === id)?.label ?? ''\n const claim = (id: string | undefined) => {\n if (id) used.add(id)\n }\n for (const d of spec.devices ?? []) {\n claim(d.part)\n const pos = d.part ? partPos(d.part, [0, 1, 0]) : (d.plug ?? [0, 1, 0])\n // a hard-wired lamp (circuit, no plug, no part to press) is driven by switches and `setDevice`: it never steals the interact key\n if (d.kind === 'lamp' && !d.part && !d.plug && d.electric !== false) continue\n out.push({ id: `device.${d.id}`, pos, action: { do: 'toggle_device', device: d.id }, label: partLabel(d.part) })\n if (d.kind === 'screen' && (d.channels ?? 1) > 1) out.push({ id: `channel.${d.id}`, pos, action: { do: 'cycle_device', device: d.id }, label: '' })\n }\n for (const s of spec.switches ?? []) {\n claim(s.part)\n out.push({ id: `switch.${s.id}`, pos: partPos(s.part, [0, 1.2, 0]), action: { do: 'toggle_switch', switch: s.id }, label: partLabel(s.part) })\n }\n const driven = new Set((spec.devices ?? []).map((d) => d.fixture))\n for (const f of spec.fixtures ?? []) {\n claim(f.part)\n if (driven.has(f.id)) continue\n out.push({ id: `fixture.${f.id}`, pos: f.part ? partPos(f.part, f.outlet) : f.outlet, action: { do: 'toggle_fixture', fixture: f.id }, label: partLabel(f.part) })\n }\n for (const b of spec.burners ?? []) {\n claim(b.part)\n const pos = b.part ? partPos(b.part, b.pos) : b.pos\n if (b.needsIgnition) out.push({ id: `ignite.${b.id}`, pos, action: { do: 'ignite', burner: b.id }, label: '' })\n out.push({ id: `burner.${b.id}`, pos, action: { do: 'toggle_burner', burner: b.id }, label: partLabel(b.part) })\n }\n for (const f of spec.fuels ?? []) {\n if (!f.valve) continue\n claim(f.valve)\n out.push({ id: `fuel.${f.id}`, pos: partPos(f.valve, [0, 0.5, 0]), action: { do: 'toggle_fuel', fuel: f.id }, label: partLabel(f.valve) })\n }\n for (const c of spec.containers ?? []) {\n if (!c.access) out.push({ id: `open.${c.id}`, pos: c.volume.center, action: { do: 'open_container', container: c.id }, label: '' })\n }\n for (const p of spec.parts ?? []) {\n if (used.has(p.id)) continue\n if (p.label) out.push({ id: `part.${p.id}`, pos: p.pivot, action: { do: 'toggle_part', part: p.id }, label: p.label })\n }\n for (const c of spec.containers ?? []) {\n if (c.access && !spec.parts?.find((p) => p.id === c.access)?.label) {\n out.push({ id: `open.${c.id}`, pos: partPos(c.access, c.volume.center), action: { do: 'open_container', container: c.id }, label: '' })\n }\n }\n for (const s of spec.seats ?? []) out.push({ id: `seat.${s.id}`, pos: s.pos, action: { do: 'sit', seat: s.id }, label: '' })\n return out\n }\n\n function typeName(o: ObjState): string {\n return table[`type.${o.spec.type}`] ?? humanize(o.spec.type)\n }\n\n function promptOf(o: ObjState, i: InteractionSpec): { label: string; verb: string; object: string } {\n const a = i.action\n let state: string | null = null\n let def = ''\n switch (a.do) {\n case 'toggle_part': {\n const p = o.parts.get(a.part)\n const open = !!p && targetIsOpen(p)\n state = open ? 'open' : 'closed'\n def = open ? 'prompt.close' : 'prompt.open'\n break\n }\n case 'open_container': {\n const c = containerOf(o, a.container)\n const p = c?.access ? o.parts.get(c.access) : undefined\n const open = p ? targetIsOpen(p) : false\n state = p ? (open ? 'open' : 'closed') : null\n def = open ? 'prompt.close' : 'prompt.open'\n break\n }\n case 'toggle_device': {\n const on = !!o.devices.get(a.device)?.on\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_switch': {\n const sw = o.spec.switches?.find((s) => s.id === a.switch)\n const on = !!sw && switchIsOn(o, sw)\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_breaker': {\n const on = breaker(a.circuit)\n state = on ? 'on' : 'off'\n def = on ? 'prompt.breaker_off' : 'prompt.breaker_on'\n break\n }\n case 'toggle_main': {\n state = main ? 'on' : 'off'\n def = main ? 'prompt.main_off' : 'prompt.main_on'\n break\n }\n case 'toggle_fixture': {\n const on = !!o.fixtures.get(a.fixture)?.on\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_burner': {\n const b = o.burners.get(a.burner)\n const on = !!b && (b.on || b.lit)\n state = on ? 'on' : 'off'\n def = on ? 'prompt.turn_off' : 'prompt.turn_on'\n break\n }\n case 'toggle_fuel': {\n const f = o.fuels.get(a.fuel)\n const open = !!f && valveOpen(o, f)\n state = open ? 'open' : 'closed'\n def = open ? 'prompt.close_valve' : 'prompt.open_valve'\n break\n }\n case 'take':\n def = 'prompt.take'\n break\n case 'read':\n def = 'prompt.read'\n break\n case 'ignite':\n def = 'prompt.light'\n break\n case 'cycle_device':\n def = 'prompt.change_channel'\n break\n case 'sit': {\n const seat = o.spec.seats?.find((s) => s.id === a.seat)\n const mine = seats.get(DEFAULT_ACTOR)\n def = mine && mine.object === o.id && mine.seat === a.seat ? 'prompt.get_up' : seat?.pose === 'lie' ? 'prompt.lie_down' : 'prompt.sit'\n break\n }\n }\n let key = def\n if (i.label) {\n if (state && table[`${i.label}.${state}`] !== undefined) key = `${i.label}.${state}`\n else if (table[i.label] !== undefined) key = i.label\n }\n const vars = { name: typeName(o), circuit: a.do === 'toggle_breaker' ? (a.name ?? a.circuit) : '' }\n const label = t(key, vars)\n // structured prompt: explicit `<key>.verb` / `<key>.object` entries win; otherwise the first word is the verb and the rest the object\n let verb: string\n let object: string\n if (table[`${key}.verb`] !== undefined) {\n verb = t(`${key}.verb`, vars)\n object = table[`${key}.object`] ? t(`${key}.object`, vars) : vars.name\n } else {\n const sp = label.indexOf(' ')\n verb = sp < 0 ? label : label.slice(0, sp)\n object = sp < 0 ? vars.name : label.slice(sp + 1)\n }\n return { label, verb, object }\n }\n\n /** Locale key of the reason an interaction cannot be used right now, or null when it can. */\n function unavailableReason(o: ObjState, i: InteractionSpec): string | null {\n const a = i.action\n if (!requirementMet(i)) return 'requires_open'\n switch (a.do) {\n case 'toggle_part': {\n const p = o.parts.get(a.part)\n return p && gated(o, p) ? 'requires_open' : null\n }\n case 'open_container': {\n const c = containerOf(o, a.container)\n const p = c?.access ? o.parts.get(c.access) : undefined\n return p && gated(o, p) ? 'requires_open' : null\n }\n case 'toggle_breaker':\n case 'toggle_main': {\n const rocker = a.part ? o.parts.get(a.part) : undefined\n return rocker && gated(o, rocker) ? 'requires_open' : null\n }\n case 'take':\n case 'read':\n return accessible(o.id, a.container) ? null : 'requires_open'\n case 'ignite':\n return o.burners.get(a.burner)?.lit ? 'already_lit' : null\n case 'toggle_burner': {\n const b = o.burners.get(a.burner)\n return !b?.spec.needsIgnition || b.lit ? null : 'needs_ignition'\n }\n case 'cycle_device': {\n const d = o.devices.get(a.device)\n if (!d || !d.on) return 'turn_on_first'\n return devicePowered(o, d) ? null : 'no_power'\n }\n default:\n return null\n }\n }\n\n function requirementMet(i: InteractionSpec): boolean {\n if (!i.requires) return true\n const p = objs.get(i.requires.object)?.parts.get(i.requires.part)\n return !!p && targetIsOpen(p)\n }\n\n function interactablesOf(o: ObjState): Array<{ item: Interactable; spec: InteractionSpec; o: ObjState }> {\n return o.interactions.map((i) => {\n const id = gid(o, i.id)\n const p = promptOf(o, i)\n const item: Interactable = {\n id,\n object: o.id,\n kind: i.action.do,\n ...(GESTURE_OF_ACTION[i.action.do] ? { gesture: GESTURE_OF_ACTION[i.action.do] as BodyGesture } : {}),\n pos: toWorld(o, i.pos),\n radius: i.radius ?? DEFAULT_RADIUS,\n label: p.label,\n verb: p.verb,\n noun: p.object,\n available: true,\n act: (actor) => act(id, actor),\n }\n const reason = unavailableReason(o, i) ?? (options.canInteract?.(item, DEFAULT_ACTOR) === false ? 'locked' : null)\n if (reason) {\n item.available = false\n item.reason = reason\n }\n return { item, spec: i, o }\n })\n }\n\n /**\n * One `take` per stack an open container shows, at its slot (it rides the drawer or door shelf with it): each item inside a piece of furniture is picked up\n * on its own, with one hand. Items the catalogue marks `pickable: false`, and stacks whose data says so, are left out.\n */\n function contentTakes(o: ObjState): Interactable[] {\n if (options.takeContents === false) return []\n const out: Interactable[] = []\n for (const c of o.spec.containers ?? []) {\n const list = o.contents.get(c.id)\n if (!list || !list.some((st) => st !== null) || !accessible(o.id, c.id)) continue\n list.forEach((stack, slot) => {\n if (!stack || options.items?.[stack.type]?.pickable === false || stack.data?.pickable === false) return\n const verb = t('prompt.take')\n const noun = table[`item.${stack.type}`] ?? humanize(stack.type)\n const item: Interactable = {\n id: `${o.id}:${TAKE_PREFIX}${c.id}.${slot}`,\n object: o.id,\n kind: 'take',\n pos: slotPosition(o.id, c.id, slot),\n radius: TAKE_RADIUS,\n label: `${verb} ${noun}`,\n verb,\n noun,\n hands: 1,\n itemType: stack.type,\n available: true,\n act: (actor) => takeAt(o.id, c.id, slot, actor ?? DEFAULT_ACTOR),\n }\n if (options.canInteract?.(item, DEFAULT_ACTOR) === false) {\n item.available = false\n item.reason = 'locked'\n }\n out.push(item)\n })\n }\n return out\n }\n\n function takeAt(objectId: string, containerId: string, slot: number, actor: string): boolean {\n const o = objs.get(objectId)\n if (!o) return false\n const probe = contentTakes(o).find((k) => k.id === `${objectId}:${TAKE_PREFIX}${containerId}.${slot}`)\n if (!probe || options.canInteract?.(probe, actor) === false) return false\n return take(objectId, containerId, slot, actor) !== null\n }\n\n function interactables(): Interactable[] {\n const out: Interactable[] = []\n for (const o of objs.values()) {\n for (const e of interactablesOf(o)) out.push(e.item)\n out.push(...contentTakes(o))\n }\n return out\n }\n\n function target(eye: { x: number; y: number; z: number; yaw: number; pitch: number }, opts: TargetOptions = {}): Interactable | null {\n const reach = opts.reach ?? 1.8\n const cone = opts.cone ?? 0.45\n const dir: Vec3 = [-Math.sin(eye.yaw) * Math.cos(eye.pitch), Math.sin(eye.pitch), -Math.cos(eye.yaw) * Math.cos(eye.pitch)]\n let best: Interactable | null = null\n let bestScore = Infinity\n for (const o of objs.values()) {\n for (const item of [...interactablesOf(o).map((e) => e.item), ...contentTakes(o)]) {\n if (!item.available && !opts.includeUnavailable) continue\n if (opts.kinds && !opts.kinds.includes(item.kind)) continue\n if (opts.filter && !opts.filter(item)) continue\n const v: Vec3 = [item.pos[0] - eye.x, item.pos[1] - eye.y, item.pos[2] - eye.z]\n const d = Math.hypot(v[0], v[1], v[2])\n if (d > reach) continue\n const cos = d < 1e-6 ? 1 : clamp((v[0] * dir[0] + v[1] * dir[1] + v[2] * dir[2]) / d, -1, 1)\n const angle = Math.acos(cos)\n if (angle > cone) continue\n const score = (angle / cone) * 0.6 + (d / reach) * 0.4\n if (score < bestScore) {\n bestScore = score\n best = item\n }\n }\n }\n return best\n }\n\n function act(interactableId: string, actor: string = DEFAULT_ACTOR): boolean {\n let found: { item: Interactable; spec: InteractionSpec; o: ObjState } | null = null\n for (const o of objs.values()) {\n if (!interactableId.startsWith(o.id + ':')) continue\n const local = interactableId.slice(o.id.length + 1)\n if (local.startsWith(TAKE_PREFIX)) {\n const at = contentTakes(o).find((k) => k.id === interactableId)\n if (at) return at.act(actor)\n }\n if (!o.interactions.some((i) => i.id === local)) continue\n found = interactablesOf(o).find((e) => e.spec.id === local) ?? null\n if (found) break\n }\n if (!found) return false\n if (!requirementMet(found.spec)) return false\n if (options.canInteract?.(found.item, actor) === false) return false\n return execute(found.o, found.spec.action, actor)\n }\n\n function execute(o: ObjState, a: InteractionSpec['action'], actor: string): boolean {\n switch (a.do) {\n case 'toggle_part': {\n const p = o.parts.get(a.part)\n if (!p || gated(o, p)) return false\n setPartTarget(o, a.part, targetIsOpen(p) ? 0 : 1)\n return true\n }\n case 'open_container': {\n const c = containerOf(o, a.container)\n if (!c) return false\n if (c.access) return execute(o, { do: 'toggle_part', part: c.access }, actor)\n emit({ type: 'container', object: o.id, container: c.id, open: true })\n return true\n }\n case 'take': {\n if (!accessible(o.id, a.container)) return false\n const list = o.contents.get(a.container)\n if (!list) return false\n const slot = a.slot ?? list.findIndex((s) => s !== null)\n if (slot < 0 || !list[slot]) {\n message('empty')\n return false\n }\n return take(o.id, a.container, slot, actor) !== null\n }\n case 'read': {\n if (!accessible(o.id, a.container)) return false\n const stack = o.contents.get(a.container)?.[a.slot]\n if (!stack) {\n message('empty')\n return false\n }\n const key = typeof stack.data?.text === 'string' ? stack.data.text : null\n if (!key) return false\n message(key)\n return true\n }\n case 'toggle_device': {\n const d = o.devices.get(a.device)\n if (!d) return false\n setDeviceOn(o, d, !d.on)\n return true\n }\n case 'cycle_device': {\n const d = o.devices.get(a.device)\n if (!d || !d.on) return false\n if (!devicePowered(o, d)) {\n message('no_power')\n return false\n }\n d.channel = (d.channel + 1) % Math.max(1, d.spec.channels ?? 1)\n emit({ type: 'device', object: o.id, device: d.spec.id, on: true, powered: true, channel: d.channel })\n return true\n }\n case 'toggle_switch':\n return toggleSwitch(o, a.switch)\n case 'toggle_breaker': {\n const rocker = a.part ? o.parts.get(a.part) : undefined\n if (rocker && gated(o, rocker)) return false\n const on = !breaker(a.circuit)\n if (a.part) setPartTarget(o, a.part, on ? 1 : 0)\n world.power.setBreaker(a.circuit, on)\n return true\n }\n case 'toggle_main': {\n const rocker = a.part ? o.parts.get(a.part) : undefined\n if (rocker && gated(o, rocker)) return false\n const on = !main\n if (a.part) setPartTarget(o, a.part, on ? 1 : 0)\n world.power.setMain(on)\n return true\n }\n case 'toggle_fixture':\n return toggleFixture(o, a.fixture)\n case 'toggle_burner':\n return toggleBurner(o, a.burner)\n case 'ignite':\n return ignite(o, a.burner)\n case 'toggle_fuel':\n return toggleFuel(o, a.fuel)\n case 'sit': {\n const mine = seats.get(actor)\n if (mine && mine.object === o.id && mine.seat === a.seat) {\n stand(actor)\n return true\n }\n return sit(o.id, a.seat, actor) !== null\n }\n }\n }\n\n // ------------------------------------------------------------------ emitters, mirrors, colliders\n function emitters(): ActiveEmitter[] {\n const out: ActiveEmitter[] = []\n for (const o of objs.values()) {\n for (const e of o.spec.emitters ?? []) {\n let intensity = 0\n const b = o.burners.get(e.source)\n const fx = o.fixtures.get(e.source)\n const dev = o.devices.get(e.source)\n const fuel = o.fuels.get(e.source)\n if (b) {\n const ref = resolveFuel(o, b)\n const frac = ref ? clamp(ref.f.level / ref.f.spec.capacity, 0, 1) : 0\n if (b.lit) intensity = 0.35 + 0.65 * frac\n else if (e.kind === 'smoke' && b.smoke > 0) intensity = 0.6 * (b.smoke / SMOKE_TAIL)\n } else if (fx) {\n if (fx.on && fx.flowing) intensity = fx.frac\n } else if (dev) {\n if (dev.on && devicePowered(o, dev)) intensity = 1\n } else if (fuel) {\n const lit = [...o.burners.values()].some((bb) => bb.lit && resolveFuel(o, bb)?.f === fuel)\n if (lit) intensity = 0.35 + 0.65 * clamp(fuel.level / fuel.spec.capacity, 0, 1)\n }\n if (intensity <= 0) continue\n const dir = rotY(e.dir ?? [0, 1, 0], o.public.transform.ry)\n out.push({ id: gid(o, e.id), object: o.id, kind: e.kind, pos: toWorld(o, e.pos), dir, size: e.size ?? 0.3, ...(e.reach !== undefined ? { reach: e.reach } : {}), ...(e.bowl ? { bowl: e.bowl } : {}), intensity: clamp(intensity, 0, 1) })\n }\n }\n return out\n }\n\n function mirrors(eye: Vec3, maxDistance = 10, count = 4) {\n const out: Array<{ id: string; center: Vec3; normal: Vec3; w: number; h: number; distance: number }> = []\n for (const o of objs.values()) {\n for (const m of o.spec.mirrors ?? []) {\n const center = toWorld(o, applyPart(o, m.part, m.center))\n const f = partFrame(o, m.part)\n const ln = f && f.angle !== 0 ? rotateAxis(m.normal, f.axis, f.angle) : m.normal\n const normal = rotY(ln, o.public.transform.ry)\n const len = Math.hypot(normal[0], normal[1], normal[2]) || 1\n const n: Vec3 = [normal[0] / len, normal[1] / len, normal[2] / len]\n const to: Vec3 = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]]\n if (n[0] * to[0] + n[1] * to[1] + n[2] * to[2] <= 0) continue\n const distance = Math.hypot(to[0], to[1], to[2])\n if (distance > maxDistance) continue\n out.push({ id: gid(o, m.id), center, normal: n, w: m.w, h: m.h, distance })\n }\n }\n return out.sort((a, b) => a.distance - b.distance).slice(0, count)\n }\n\n function colliders(opts: ColliderOptions = {}): WorldCollider[] {\n const out: WorldCollider[] = []\n const fixed: WorldCollider[] = []\n for (const o of objs.values()) {\n const tr = o.public.transform\n for (const c of o.spec.colliders ?? []) {\n if (c.part && c.offWhenOpen && (o.parts.get(c.part)?.t ?? 0) > 0.5) continue\n let extra = 0\n if (c.part) {\n const f = partFrame(o, c.part)\n if (f && f.angle !== 0 && Math.abs(f.axis[1]) >= 0.5) extra = f.angle * Math.sign(f.axis[1])\n }\n const center = toWorld(o, applyPart(o, c.part, c.center))\n ;(c.part ? out : fixed).push({\n id: gid(o, c.id),\n object: o.id,\n cx: center[0],\n cz: center[2],\n hw: c.half[0],\n hd: c.half[2],\n ry: tr.ry + (c.ry ?? 0) + extra,\n y0: center[1] - c.half[1],\n y1: center[1] + c.half[1],\n })\n }\n }\n if (opts.merge) return [...mergeColliders(fixed, { gap: opts.gap, slack: opts.slack }), ...out]\n return [...fixed, ...out]\n }\n\n // ------------------------------------------------------------------ update\n /** A part the engine moves: it aims at the target when that changed, then `t` is what the joint says; a broken one stays where it broke. */\n function updateDriven(o: ObjState, p: PartState, dt: number): void {\n const driver = p.driver as PartDriver\n if (p.broken) return\n if (p.commanded !== p.target && !(gated(o, p) && p.target > p.t)) {\n driver.aim(p.target)\n p.commanded = p.target\n p.moving = true\n }\n driver.update(dt)\n if (driver.broken) {\n p.broken = true\n emit({ type: 'broke', object: o.id, part: p.spec.id })\n return\n }\n const next = clamp(driver.read(), 0, p.maxT)\n if (next !== p.t) writeT(o, p, next)\n if (!driver.settled) return\n // let go (or pushed by hand): what the joint holds is the target, so the next interaction toggles from there\n p.target = next\n p.commanded = next\n if (p.moving) emit({ type: 'part', object: o.id, part: p.spec.id, t: next, target: next })\n p.moving = false\n }\n\n function update(dt: number): void {\n if (!(dt > 0)) return\n time += dt\n for (const o of objs.values()) {\n for (const p of o.parts.values()) {\n if (p.driver) {\n updateDriven(o, p, dt)\n continue\n }\n if (p.t === p.target) continue\n if (gated(o, p) && p.target > p.t) continue // a gated part may still close\n const step = (p.spec.motion.speed ?? 2.5) * dt\n const next = p.t < p.target ? Math.min(p.target, p.t + step) : Math.max(p.target, p.t - step)\n writeT(o, p, next)\n if (next === p.target) emit({ type: 'part', object: o.id, part: p.spec.id, t: next, target: p.target })\n }\n }\n stepSoft(dt)\n for (const o of objs.values()) {\n for (const b of o.burners.values()) {\n if (b.lit) {\n const ref = resolveFuel(o, b)\n if (!ref || !valveOpen(ref.o, ref.f)) {\n extinguish(o, b, !!b.spec.needsIgnition)\n } else {\n ref.f.level = Math.max(0, ref.f.level - b.spec.rate * dt)\n if (ref.f.level <= 0) extinguish(o, b, !!b.spec.needsIgnition)\n }\n } else if (b.on && !b.spec.needsIgnition && canBurn(b, resolveFuel(o, b))) {\n // a gas knob left open without gas lights as soon as the bottle valve opens\n b.lit = true\n b.smoke = 0\n emitBurner(o, b)\n } else if (b.smoke > 0) {\n b.smoke = Math.max(0, b.smoke - dt)\n }\n }\n if (rain > 0) {\n for (const tk of o.tanks.values()) {\n if (tk.spec.rainArea) tk.level = Math.min(tk.spec.capacity, tk.level + ((rain * tk.spec.rainArea) / 3600) * dt)\n }\n }\n for (const tk of o.tanks.values()) {\n const st = o.hp.get(tk.spec.id)\n if (st && st.hp < st.max && tk.level > 0) {\n const rate = 0.5 + 2.5 * (1 - st.hp / st.max)\n tk.level = Math.max(0, tk.level - rate * dt)\n }\n }\n }\n for (const o of objs.values()) {\n for (const d of o.devices.values()) {\n const fx = d.spec.fixture ? o.fixtures.get(d.spec.fixture) : undefined\n if (!fx) continue\n const run = d.on && devicePowered(o, d)\n if (fx.on === run) continue\n fx.on = run\n if (!run) {\n fx.flowing = false\n fx.frac = 0\n emitFixture(o, fx)\n }\n }\n for (const fx of o.fixtures.values()) stepFixture(o, fx, dt)\n }\n }\n\n // ------------------------------------------------------------------ add / remove\n function add(id: string, spec: ObjectSpec, transform: Transform): WorldObject {\n if (objs.has(id)) throw new Error(`Object \"${id}\" already exists`)\n const pub: WorldObject = { id, spec, transform: { ...transform }, parts: {} }\n const o: ObjState = {\n id,\n public: pub,\n spec,\n parts: new Map(),\n contents: new Map(),\n devices: new Map(),\n fuels: new Map(),\n burners: new Map(),\n tanks: new Map(),\n fixtures: new Map(),\n drains: new Map(),\n soft: new Map(),\n hp: new Map(),\n interactions: spec.interactions ?? deriveInteractions(spec),\n }\n for (const p of spec.parts ?? []) {\n const t0 = clamp(p.t0 ?? 0, 0, 1)\n const driver = options.partPhysics?.attachPart(id, p, pub.transform)\n o.parts.set(p.id, { spec: p, t: t0, target: t0, maxT: 1, ...(driver ? { driver, commanded: t0 } : {}) })\n driver?.snap(t0)\n pub.parts[p.id] = t0\n }\n for (const c of spec.containers ?? []) {\n let list: Array<ItemStack | null>\n if (c.contents) list = c.slots.map((_, i) => cloneStack(c.contents?.[i] ?? null))\n else if (c.loot) list = generateLoot(options.loot, c.loot, c.slots, `${seed}|${id}|${c.id}`, options.items)\n else list = c.slots.map(() => null)\n o.contents.set(c.id, list)\n }\n for (const d of spec.devices ?? []) {\n o.devices.set(d.id, { spec: d, on: !!d.on, channel: 0 })\n if (d.on && d.part) {\n const p = o.parts.get(d.part)\n if (p) {\n p.target = p.maxT\n writeT(o, p, p.maxT)\n }\n }\n }\n for (const f of spec.fuels ?? []) o.fuels.set(f.id, { spec: f, level: clamp(f.level ?? f.capacity, 0, f.capacity) })\n for (const b of spec.burners ?? []) o.burners.set(b.id, { spec: b, on: false, lit: false, smoke: 0 })\n for (const tk of spec.tanks ?? []) o.tanks.set(tk.id, { spec: tk, level: clamp(tk.level ?? tk.capacity, 0, tk.capacity) })\n for (const f of spec.fixtures ?? []) o.fixtures.set(f.id, { spec: f, on: false, flowing: false, frac: 0, timer: 0 })\n for (const b of spec.basins ?? []) if (b.drain) o.drains.set(b.id, createBasinDrain(b, b.drain))\n let n = 0\n for (const s of spec.soft ?? []) {\n const driver = options.partPhysics?.attachSoft?.(id, s, pub.transform)\n o.soft.set(s.id, { spec: s, ax: 0, az: 0, vax: 0, vaz: 0, phase: (n++ * 2.399963) % (Math.PI * 2), ...(driver ? { driver } : {}) })\n }\n for (const d of spec.damage ?? []) o.hp.set(d.target, { max: d.hp, hp: d.hp })\n objs.set(id, o)\n if (!defaultTankExplicit && defaultTank === null && o.tanks.size) defaultTank = gid(o, [...o.tanks.keys()][0])\n rebuildPlugs()\n return pub\n }\n\n function remove(id: string): void {\n const o = objs.get(id)\n if (!o) return\n for (const [actor, s] of [...seats]) if (s.object === id) seats.delete(actor)\n for (const p of o.parts.values()) p.driver?.dispose()\n for (const s of o.soft.values()) s.driver?.dispose()\n objs.delete(id)\n if (defaultTank && defaultTank.startsWith(id + ':')) defaultTank = null\n rebuildPlugs()\n }\n\n // ------------------------------------------------------------------ save / load\n function serialize(): WorldState {\n const objects: WorldState['objects'] = {}\n for (const o of objs.values()) {\n objects[o.id] = {\n parts: Object.fromEntries([...o.parts].map(([k, p]) => [k, p.t])),\n contents: Object.fromEntries([...o.contents].map(([k, v]) => [k, v.map(cloneStack)])),\n devices: Object.fromEntries([...o.devices].map(([k, d]) => [k, { on: d.on, channel: d.channel }])),\n fuels: Object.fromEntries([...o.fuels].map(([k, f]) => [k, { level: f.level, open: valveOpen(o, f) }])),\n burners: Object.fromEntries([...o.burners].map(([k, b]) => [k, { on: b.on, lit: b.lit }])),\n tanks: Object.fromEntries([...o.tanks].map(([k, tk]) => [k, tk.level])),\n fixtures: Object.fromEntries([...o.fixtures].map(([k, f]) => [k, f.on])),\n hp: Object.fromEntries([...o.hp].map(([k, h]) => [k, h.hp])),\n drains: Object.fromEntries([...o.drains].map(([k, d]) => [k, d.save()])),\n }\n }\n return {\n version: 1,\n objects,\n grid,\n main,\n breakers: Object.fromEntries(breakers),\n seats: Object.fromEntries([...seats].map(([a, s]) => [a, { object: s.object, seat: s.seat }])),\n defaultTank,\n }\n }\n\n function load(state: WorldState): void {\n for (const [id, st] of Object.entries(state.objects)) {\n const o = objs.get(id)\n if (!o) continue\n for (const [k, v] of Object.entries(st.parts)) {\n const p = o.parts.get(k)\n if (p) {\n // keep the limit found by fitSweep: a loaded save must not let a door open through a wall again\n p.target = clamp(v, 0, p.maxT)\n p.driver?.snap(p.target)\n p.commanded = p.target\n writeT(o, p, p.target)\n }\n }\n for (const [k, v] of Object.entries(st.contents)) {\n const c = containerOf(o, k)\n if (c) o.contents.set(k, c.slots.map((_, i) => cloneStack(v[i] ?? null)))\n }\n for (const [k, v] of Object.entries(st.devices)) {\n const d = o.devices.get(k)\n if (d) {\n d.on = v.on\n d.channel = v.channel\n }\n }\n for (const [k, v] of Object.entries(st.fuels)) {\n const f = o.fuels.get(k)\n if (f) f.level = v.level\n }\n for (const [k, v] of Object.entries(st.burners)) {\n const b = o.burners.get(k)\n if (b) {\n b.on = v.on\n b.lit = v.lit\n b.smoke = 0\n }\n }\n for (const [k, v] of Object.entries(st.tanks)) {\n const tk = o.tanks.get(k)\n if (tk) tk.level = v\n }\n for (const [k, v] of Object.entries(st.fixtures)) {\n const f = o.fixtures.get(k)\n if (f) {\n f.on = v\n f.flowing = false\n f.frac = 0\n f.timer = v && f.spec.kind === 'flush' ? FLUSH_SECONDS : 0\n }\n }\n for (const [k, v] of Object.entries(st.hp)) {\n const h = o.hp.get(k)\n if (h) h.hp = v\n }\n for (const [k, v] of Object.entries(st.drains ?? {})) o.drains.get(k)?.restore(v)\n }\n grid = state.grid\n main = state.main ?? true\n breakers.clear()\n for (const [k, v] of Object.entries(state.breakers)) breakers.set(k, v)\n seats.clear()\n for (const [a, s] of Object.entries(state.seats)) if (objs.has(s.object)) seats.set(a, { object: s.object, seat: s.seat })\n defaultTank = state.defaultTank\n defaultTankExplicit = true\n }\n\n // ------------------------------------------------------------------ public surface\n const world: World = {\n add,\n remove,\n get: (id) => objs.get(id)?.public,\n objects: () => [...objs.values()].map((o) => o.public),\n update,\n interactables,\n target,\n act,\n partT: (objectId, partId) => objs.get(objectId)?.parts.get(partId)?.t ?? 0,\n setDevice,\n setFixture,\n setBurner,\n setPart: (objectId, partId, targetT, instant) => {\n const o = objs.get(objectId)\n if (o) setPartTarget(o, partId, targetT, instant)\n },\n fitSweep,\n contents,\n accessible,\n take,\n put,\n slotPosition,\n power: {\n get grid() {\n return grid\n },\n set grid(on: boolean) {\n world.power.setGrid(on)\n },\n setGrid(on) {\n if (on === grid) return\n const before = powerSnapshot()\n grid = on\n emit({ type: 'power', grid, main })\n emitPowerChanges(before)\n },\n get main() {\n return main\n },\n setMain(on) {\n if (on === main) return\n const before = powerSnapshot()\n main = on\n emit({ type: 'power', grid, main })\n emitPowerChanges(before)\n },\n setBreaker(circuit, on) {\n if (breaker(circuit) === on) {\n breakers.set(circuit, on)\n return\n }\n const before = powerSnapshot()\n breakers.set(circuit, on)\n emitPowerChanges(before)\n },\n breaker,\n isPowered: (objectId, deviceId) => {\n const r = getDevice(objectId, deviceId)\n return r ? devicePowered(r.o, r.d) : false\n },\n isOn: (objectId, deviceId) => getDevice(objectId, deviceId)?.d.on ?? false,\n pluggedInto: (objectId, deviceId) => plugs.get(`${objectId}:${deviceId}`) ?? null,\n channel: (objectId, deviceId) => getDevice(objectId, deviceId)?.d.channel ?? 0,\n },\n fuelLevel: (objectId, fuelId) => objs.get(objectId)?.fuels.get(fuelId)?.level ?? 0,\n isLit: (objectId, burnerId) => objs.get(objectId)?.burners.get(burnerId)?.lit ?? false,\n water: {\n setDefaultTank(tankId) {\n defaultTank = tankId\n defaultTankExplicit = true\n },\n level(tankId) {\n return findGlobal(tankId, (oo, local) => oo.tanks.get(local))?.value.level ?? 0\n },\n refill(tankId, liters) {\n const f = findGlobal(tankId, (oo, local) => oo.tanks.get(local))\n if (!f) return 0\n const added = Math.max(0, Math.min(liters, f.value.spec.capacity - f.value.level))\n f.value.level += added\n return added\n },\n setRain(mm) {\n rain = Math.max(0, mm)\n },\n isFlowing: (objectId, fixtureId) => {\n const fx = objs.get(objectId)?.fixtures.get(fixtureId)\n return !!fx && fx.on && fx.flowing\n },\n },\n sit,\n stand,\n seatOf: (actor = DEFAULT_ACTOR) => {\n const s = seats.get(actor)\n return s ? { object: s.object, seat: s.seat } : null\n },\n push,\n sway: (objectId, softId) => {\n const s = objs.get(objectId)?.soft.get(softId)\n return s ? { ax: s.ax, az: s.az } : { ax: 0, az: 0 }\n },\n setWind: (x, z) => {\n wind = [x, z]\n },\n emitters,\n mirrors,\n colliders,\n damage,\n hp: (objectId, target) => (options.destruction ? null : (objs.get(objectId)?.hp.get(target)?.hp ?? null)),\n t,\n setLocale: (l) => {\n locale = l\n table = resolveStrings(locale, options.strings)\n },\n drain: (objectId, basin) => objs.get(objectId)?.drains.get(basin),\n serialize,\n load,\n }\n return world\n}\n","import type { BodyId, JointId, Quat, SeamWorld, Vec3 } from '@adatechnology/game-physics'\n\n/** A chain of boxes along a polyline, each joined to the one before by a swing-twist joint: a cord, a cable, a strip of a curtain. */\nexport interface ChainSpec {\n /** From the start to the end of the chain; one link between each two points. */\n readonly points: readonly Vec3[]\n /** Half the width and the depth of a link (m); its length is the segment's. */\n readonly halfWidth: number\n readonly halfDepth: number\n readonly totalMass: number\n /** What the first link hangs from (a static body, or a kinematic one a host moves). */\n readonly startBody: BodyId\n /** What the last link is tied to; undefined: it hangs free. */\n readonly endBody?: BodyId\n /** Half cone of every joint (radians) and the most it twists either way. */\n readonly halfCone: number\n readonly twist: number\n /** Torque (N m) that holds a joint still against the swing: the chain's stiffness at rest. */\n readonly jointFriction: number\n /** Share of velocity lost per second by every link (the air, the cloth). */\n readonly damping: number\n}\n\nexport interface Chain {\n readonly bodies: readonly BodyId[]\n readonly joints: readonly JointId[]\n /** Half the length of each link, for reading its ends. */\n readonly halfLengths: readonly number[]\n /** The collision group the links share (released with the chain). */\n readonly group: number\n}\n\nconst UP: Vec3 = [0, 1, 0]\n\nconst sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]\nconst length = (v: Vec3): number => Math.hypot(v[0], v[1], v[2])\nconst cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]\n\n/** The turn that takes +y (a link's length) onto `direction` (unit). */\nexport function alignY(direction: Vec3): Quat {\n const axis = cross(UP, direction)\n const sine = length(axis)\n if (sine < 1e-9) return direction[1] >= 0 ? [0, 0, 0, 1] : [1, 0, 0, 0]\n const angle = Math.atan2(sine, direction[1])\n const half = Math.sin(angle / 2) / sine\n return [axis[0] * half, axis[1] * half, axis[2] * half, Math.cos(angle / 2)]\n}\n\n/** A vector turned by a unit quaternion. */\nexport function rotateByQuat(v: Vec3, q: Quat): 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 perpendicular = (direction: Vec3): Vec3 => {\n const side = Math.abs(direction[0]) < 0.9 ? cross(direction, [1, 0, 0]) : cross(direction, [0, 0, 1])\n const size = length(side)\n return [side[0] / size, side[1] / size, side[2] / size]\n}\n\n/** Builds the links and joints of a chain in the world, in the pose its points give (so a cord starts already sagging). */\nexport function buildChain(world: SeamWorld, spec: ChainSpec): Chain {\n const count = spec.points.length - 1\n const lengths = Array.from({ length: count }, (_, i) => length(sub(spec.points[i + 1] as Vec3, spec.points[i] as Vec3)))\n const total = lengths.reduce((sum, each) => sum + each, 0)\n const pairs: Array<readonly [number, number]> = []\n for (let a = 0; a < count; a++) for (let b = a + 1; b < count; b++) pairs.push([a, b])\n const group = world.createGroup(count, pairs)\n const bodies: BodyId[] = []\n const joints: JointId[] = []\n for (let i = 0; i < count; i++) {\n const from = spec.points[i] as Vec3\n const to = spec.points[i + 1] as Vec3\n const span = lengths[i] as number\n const direction: Vec3 = [(to[0] - from[0]) / span, (to[1] - from[1]) / span, (to[2] - from[2]) / span]\n const link = world.createBody({\n shape: { kind: 'box', half: [spec.halfWidth, span / 2, spec.halfDepth] },\n motion: 'dynamic',\n mass: spec.totalMass * (span / total),\n position: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2, (from[2] + to[2]) / 2],\n rotation: alignY(direction),\n layer: 'debris',\n group: { id: group, sub: i },\n linearDamping: spec.damping,\n angularDamping: spec.damping,\n user: -4,\n })\n const previous = i === 0 ? spec.startBody : (bodies[i - 1] as BodyId)\n if (i === 0) world.ignorePair(spec.startBody, link, true)\n joints.push(world.createJoint(swingTwist(spec, previous, link, from, direction)))\n bodies.push(link)\n }\n if (spec.endBody !== undefined) {\n const last = spec.points[count] as Vec3\n const direction = sub(last, spec.points[count - 1] as Vec3)\n const size = length(direction)\n world.ignorePair(spec.endBody, bodies[count - 1] as BodyId, true)\n joints.push(world.createJoint(swingTwist(spec, bodies[count - 1] as BodyId, spec.endBody, last, [direction[0] / size, direction[1] / size, direction[2] / size])))\n }\n return { bodies, joints, halfLengths: lengths.map((each) => each / 2), group }\n}\n\n/** Takes a chain out of the world: its joints, its links, then the group the links shared. */\nexport function disposeChain(world: SeamWorld, chain: Chain): void {\n for (const joint of chain.joints) world.removeJoint(joint)\n for (const body of chain.bodies) world.removeBody(body)\n world.releaseGroup(chain.group)\n}\n\nconst swingTwist = (spec: ChainSpec, a: BodyId, b: BodyId, point: Vec3, direction: Vec3) => ({\n kind: 'swingTwist' as const,\n a,\n b,\n point,\n twistAxis: direction,\n planeAxis: perpendicular(direction),\n normalHalfCone: spec.halfCone,\n planeHalfCone: spec.halfCone,\n twistMin: -spec.twist,\n twistMax: spec.twist,\n friction: spec.jointFriction,\n})\n\nconst pose = new Float64Array(7)\n\n/** The end of link `index` now (x, y, z into `out` at `offset`): the body's centre moved half the link's length along its own +y (the unit quaternion's y axis, unrolled). */\nconst writeLinkEnd = (world: SeamWorld, chain: Chain, index: number, sign: 1 | -1, out: Float64Array, offset: number): void => {\n world.readPose(chain.bodies[index] as BodyId, pose, 0)\n const x = pose[3] as number\n const y = pose[4] as number\n const z = pose[5] as number\n const w = pose[6] as number\n const half = (chain.halfLengths[index] as number) * sign\n out[offset] = (pose[0] as number) + half * 2 * (x * y - w * z)\n out[offset + 1] = (pose[1] as number) + half * (1 - 2 * (x * x + z * z))\n out[offset + 2] = (pose[2] as number) + half * 2 * (y * z + w * x)\n}\n\n/** The two ends of every link now, as a polyline (x, y, z per point) for a host that draws the cord: the points a chain was built from, moved. */\nexport function chainPoints(world: SeamWorld, chain: Chain, out: Float64Array): void {\n const count = chain.bodies.length\n writeLinkEnd(world, chain, 0, -1, out, 0)\n for (let i = 0; i < count; i++) writeLinkEnd(world, chain, i, 1, out, (i + 1) * 3)\n}\n\n/** Only the free end of the chain (x, y, z into `out`): one pose read, for a host that wants where the tip is and not the whole line. */\nexport function chainEnd(world: SeamWorld, chain: Chain, out: Float64Array): void {\n writeLinkEnd(world, chain, chain.bodies.length - 1, 1, out, 0)\n}\n","import type { BodyId, SeamWorld } from '@adatechnology/game-physics'\n\nimport { buildChain, chainEnd, disposeChain } from './engine-chain'\nimport type { Chain } from './engine-chain'\nimport { localToWorld, rotY } from './math'\nimport type { SoftDriver } from './part-physics'\nimport type { SoftSpec, Transform, Vec3 } from './types'\n\nconst STRIP_WIDTH = 0.12\nconst LINK_LENGTH = 0.15\nconst MAX_LINKS = 8\nconst FABRIC_KG_PER_M2 = 0.3\nconst FABRIC_HALF_DEPTH = 0.01\nconst TWIST_RANGE = 0.3\nconst DEFAULT_MAX_ANGLE = 0.7\nconst DEFAULT_DAMPING = 4\nconst JOINT_HOLD_NM = 0.002\n/** An actor's velocity (m/s) to the speed it gives a strip (the body only brushes the cloth). */\nconst PUSH_GAIN = 0.4\n\n/**\n * A curtain, cloth or strip as hanging chains from a rail along its anchor line, one chain per `STRIP_WIDTH` of width: they swing when an actor pushes through and\n * settle by the damping (the world's spring is not used). The world's `sway` reads back the mean tip offset of the chains as the two swing angles.\n */\nexport function attachStrips(world: SeamWorld, soft: SoftSpec, transform: Transform): SoftDriver {\n const [width, height, depth] = soft.size\n const strips = Math.max(1, Math.round(width / STRIP_WIDTH))\n const links = Math.min(MAX_LINKS, Math.max(2, Math.round(height / LINK_LENGTH)))\n const rail: BodyId = world.createBody({ shape: { kind: 'box', half: [width / 2, 0.01, Math.max(depth, 0.02) / 2] }, motion: 'static', position: localToWorld(transform, soft.anchor), layer: 'static', user: -3 })\n const damping = soft.damping ?? DEFAULT_DAMPING\n const chains: Chain[] = []\n const tops: Vec3[] = []\n for (let i = 0; i < strips; i++) {\n const x = soft.anchor[0] - width / 2 + (width * (i + 0.5)) / strips\n const top = localToWorld(transform, [x, soft.anchor[1], soft.anchor[2]])\n tops.push(top)\n chains.push(\n buildChain(world, {\n points: Array.from({ length: links + 1 }, (_, k): Vec3 => [top[0], top[1] - (height * k) / links, top[2]]),\n halfWidth: (width / strips) * 0.45,\n halfDepth: FABRIC_HALF_DEPTH,\n totalMass: (width / strips) * height * FABRIC_KG_PER_M2,\n startBody: rail,\n halfCone: soft.maxAngle ?? DEFAULT_MAX_ANGLE,\n twist: TWIST_RANGE,\n jointFriction: JOINT_HOLD_NM,\n damping: damping / 4,\n }),\n )\n }\n const tip = new Float64Array(3)\n const lastLinks = chains.map((chain) => chain.bodies[chain.bodies.length - 1] as BodyId)\n const cosYaw = Math.cos(-transform.ry)\n const sinYaw = Math.sin(-transform.ry)\n let restedAx = 0\n let restedAz = 0\n let isRested = false\n let disposed = false\n const everyLinkAsleep = (): boolean => {\n for (let i = 0; i < lastLinks.length; i++) if (!world.isSleeping(lastLinks[i] as BodyId)) return false\n return true\n }\n return {\n swing(out) {\n const asleep = everyLinkAsleep()\n if (asleep && isRested) {\n out[0] = restedAx\n out[1] = restedAz\n return\n }\n let dx = 0\n let dz = 0\n for (let i = 0; i < chains.length; i++) {\n chainEnd(world, chains[i] as Chain, tip)\n const top = tops[i] as Vec3\n const offsetX = (tip[0] as number) - top[0]\n const offsetZ = (tip[2] as number) - top[2]\n // the object's yaw undone (the same turn about y as `worldToLocal`)\n dx += offsetX * cosYaw + offsetZ * sinYaw\n dz += -offsetX * sinYaw + offsetZ * cosYaw\n }\n // rotation about x turns the tip toward -z for a positive angle (and about z toward +x), as the world's spring has it\n out[0] = -Math.asin(Math.max(-1, Math.min(1, dz / strips / height)))\n out[1] = Math.asin(Math.max(-1, Math.min(1, dx / strips / height)))\n restedAx = out[0]\n restedAz = out[1]\n isRested = asleep\n },\n push(velocity) {\n const world3 = rotY(velocity, transform.ry)\n for (const chain of chains) {\n for (const body of chain.bodies) world.addImpulse(body, [world3[0] * PUSH_GAIN * linkMass(soft, strips, links), world3[1] * PUSH_GAIN * linkMass(soft, strips, links), world3[2] * PUSH_GAIN * linkMass(soft, strips, links)])\n }\n },\n dispose() {\n if (disposed) return\n disposed = true\n for (const chain of chains) disposeChain(world, chain)\n world.removeBody(rail)\n },\n }\n}\n\nconst linkMass = (soft: SoftSpec, strips: number, links: number): number => (soft.size[0] / strips) * (soft.size[1] / links) * FABRIC_KG_PER_M2\n","import type { BodyId, JointId, Quat, SeamWorld } from '@adatechnology/game-physics'\n\nimport { clamp, rotateAxis } from './math'\nimport type { PartDriver } from './part-physics'\nimport type { Vec3 } from './types'\n\n/** A part driver whose leaf is a body of the engine: the host draws the part where the body is, and after a break the body is all that is left. */\nexport interface EnginePartDriver extends PartDriver {\n readonly leaf: BodyId\n}\n\n/** Units of t per second that close a gap of one t: the leaf slows as it arrives. */\nconst AIM_GAIN = 8\nconst ARRIVED_AT = 0.004\n\nconst axisAngle = (axis: Vec3, angle: number): Quat => {\n const size = Math.hypot(axis[0], axis[1], axis[2]) || 1\n const k = Math.sin(angle / 2) / size\n return [axis[0] * k, axis[1] * k, axis[2] * k, Math.cos(angle / 2)]\n}\nconst multiply = (a: Quat, b: Quat): Quat => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n]\n\n\nexport interface LeafDriverSpec {\n readonly world: SeamWorld\n readonly leaf: BodyId\n readonly frame: BodyId\n readonly ownsFrame: boolean\n readonly joint: JointId\n readonly onDispose: () => void\n readonly drive: { readonly isHinge: boolean; readonly axis: Vec3; readonly pivot: Vec3; readonly centre: Vec3; readonly range: number; readonly speed: number; readonly base: Quat }\n}\n\n\n/** Scratch of every leaf: a driver reads and writes a pose, a velocity pair at a time, so no pose or vector is made per frame. */\nconst pose = new Float64Array(7)\nconst linearScratch: Vec3 = [0, 0, 0]\nconst angularScratch: Vec3 = [0, 0, 0]\nconst NO_SPIN: Vec3 = [0, 0, 0]\n\nexport function createLeafDriver(spec: LeafDriverSpec): EnginePartDriver {\n const { world, leaf, frame, joint, drive } = spec\n const { axis, pivot, centre, range } = drive\n let target = 0\n let settled = true\n let broken = false\n let disposed = false\n let lastT = 0\n /** t of the leaf at rest, kept while it sleeps: nothing moves it, so the joint is not asked again. */\n let restedT: number | undefined\n const measure = (): number => {\n if (drive.isHinge) return world.jointAngles(joint).hinge / range\n world.readPose(leaf, pose, 0)\n return (((pose[0] as number) - centre[0]) * axis[0] + ((pose[1] as number) - centre[1]) * axis[1] + ((pose[2] as number) - centre[2]) * axis[2]) / range\n }\n const read = (): number => {\n if (broken) return lastT\n if (settled && world.isSleeping(leaf)) {\n restedT ??= measure()\n lastT = restedT\n return lastT\n }\n restedT = undefined\n lastT = measure()\n return lastT\n }\n const stop = (): void => {\n world.setVelocity(leaf, NO_SPIN, NO_SPIN)\n settled = true\n }\n // t per second to the leaf's own velocity: a turn about the hinge carries the centre round, a slide is a line\n const move = (rate: number): void => {\n world.wake(leaf)\n const speed = rate * range\n angularScratch[0] = axis[0] * speed\n angularScratch[1] = axis[1] * speed\n angularScratch[2] = axis[2] * speed\n if (!drive.isHinge) return world.setVelocity(leaf, angularScratch, NO_SPIN)\n world.readPose(leaf, pose, 0)\n const armX = (pose[0] as number) - pivot[0]\n const armY = (pose[1] as number) - pivot[1]\n const armZ = (pose[2] as number) - pivot[2]\n linearScratch[0] = angularScratch[1] * armZ - angularScratch[2] * armY\n linearScratch[1] = angularScratch[2] * armX - angularScratch[0] * armZ\n linearScratch[2] = angularScratch[0] * armY - angularScratch[1] * armX\n world.setVelocity(leaf, linearScratch, angularScratch)\n }\n const place = (t: number): void => {\n const amount = t * drive.range\n if (drive.isHinge) {\n const centre = rotateAxis([drive.centre[0] - drive.pivot[0], drive.centre[1] - drive.pivot[1], drive.centre[2] - drive.pivot[2]], drive.axis, amount)\n world.setPose(leaf, [drive.pivot[0] + centre[0], drive.pivot[1] + centre[1], drive.pivot[2] + centre[2]], multiply(axisAngle(drive.axis, amount), drive.base), true)\n } else {\n world.setPose(leaf, [drive.centre[0] + drive.axis[0] * amount, drive.centre[1] + drive.axis[1] * amount, drive.centre[2] + drive.axis[2] * amount], drive.base, true)\n }\n world.setVelocity(leaf, [0, 0, 0], [0, 0, 0])\n }\n return {\n leaf,\n aim(next) {\n if (broken) return\n target = next\n settled = false\n restedT = undefined\n },\n snap(t) {\n target = t\n settled = true\n restedT = undefined\n if (!broken) place(t)\n },\n update() {\n if (broken) return\n if (!world.jointExists(joint)) {\n broken = true\n settled = true\n return\n }\n if (settled) return\n const error = target - read()\n if (Math.abs(error) < ARRIVED_AT) return stop()\n move(clamp(error * AIM_GAIN, -drive.speed, drive.speed))\n },\n read,\n get settled() {\n return settled\n },\n get broken() {\n return broken\n },\n dispose() {\n if (disposed) return\n disposed = true\n spec.onDispose()\n if (!broken) world.removeJoint(joint)\n world.removeBody(leaf)\n if (spec.ownsFrame) world.removeBody(frame)\n },\n }\n}\n","import type { BodyId, Quat, SeamWorld } from '@adatechnology/game-physics'\n\nimport { attachStrips } from './engine-soft'\nimport { createLeafDriver } from './engine-leaf'\nimport type { EnginePartDriver } from './engine-leaf'\nimport { localToWorld, rotY } from './math'\nimport type { PartPhysics } from './part-physics'\nimport type { PartSpec, SoftSpec, Transform, Vec3 } from './types'\n\n/** What a host tells the engine about its objects. */\nexport interface EnginePartOptions {\n /** The object's own static body when the host has one: a leaf does not collide with it. Without it each part gets a hidden anchor at its pivot. */\n readonly frameOf?: (object: string) => BodyId | undefined\n /** The impulse (N s) over which a part's joint breaks, or undefined for a part that never breaks. */\n readonly breakImpulse?: (object: string, part: PartSpec) => number | undefined\n /** Mass of a leaf (kg); default its volume at the density of a hollow door. */\n readonly leafMass?: (object: string, part: PartSpec) => number\n}\n\nexport interface EnginePartPhysics extends PartPhysics {\n /** The leaf body of a part the engine took (also after it broke: then it is a loose body the host draws where it is), or undefined. */\n leafOf(object: string, part: string): BodyId | undefined\n dispose(): void\n}\n\nconst HOLLOW_DOOR_DENSITY = 150\nconst MIN_LEAF_MASS = 1\n/** Newtons that hold a drawer still against its slide, and N m a hinge, so a part stays where it is left. */\nconst SLIDE_HOLD_N = 4\nconst HINGE_HOLD_NM = 0.4\nconst SOFT_KINDS: ReadonlySet<SoftSpec['kind']> = new Set(['cloth', 'curtain', 'strip'])\n\nexport const quatY = (ry: number): Quat => [0, Math.sin(ry / 2), 0, Math.cos(ry / 2)]\nconst cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]\n\nconst perpendicularTo = (axis: Vec3): Vec3 => {\n const side = Math.abs(axis[0]) < 0.9 ? cross(axis, [1, 0, 0]) : cross(axis, [0, 0, 1])\n const size = Math.hypot(side[0], side[1], side[2])\n return [side[0] / size, side[1] / size, side[2] / size]\n}\n\n/** The engine under the movable parts and soft volumes of an interactables world (`WorldOptions.partPhysics`), made of the contract's bodies and joints only. */\nexport function createEnginePartPhysics(world: SeamWorld, options: EnginePartOptions = {}): EnginePartPhysics {\n const disposers = new Set<() => void>()\n const leaves = new Map<string, BodyId>()\n return {\n attachPart(object, part, transform) {\n const key = `${object}:${part.id}`\n const retire = (): void => {\n leaves.delete(key)\n disposers.delete(dispose)\n }\n const dispose = (): void => driver?.dispose()\n const driver = attachLeaf(world, options, { object, part, transform, onDispose: retire })\n if (!driver) return undefined\n leaves.set(key, driver.leaf)\n disposers.add(dispose)\n return driver\n },\n leafOf: (object, part) => leaves.get(`${object}:${part}`),\n attachSoft(_object, soft, transform) {\n const driver = SOFT_KINDS.has(soft.kind) ? attachStrips(world, soft, transform) : undefined\n if (!driver) return undefined\n const dispose = (): void => driver.dispose()\n disposers.add(dispose)\n return { swing: driver.swing, push: driver.push, dispose: () => { disposers.delete(dispose); driver.dispose() } }\n },\n dispose() {\n for (const dispose of [...disposers]) dispose()\n disposers.clear()\n },\n }\n}\n\ninterface LeafRequest {\n readonly object: string\n readonly part: PartSpec\n readonly transform: Transform\n readonly onDispose: () => void\n}\n\n/** A door, lid or drawer: a leaf box on a hinge or a slider, driven toward its target and free once it gets there. Undefined without `bounds` or for another motion. */\nfunction attachLeaf(world: SeamWorld, options: EnginePartOptions, request: LeafRequest): EnginePartDriver | undefined {\n const { object, part, transform } = request\n const motion = part.motion\n const bounds = part.bounds\n if (!bounds || (motion.kind !== 'hinge' && motion.kind !== 'slide')) return undefined\n const isHinge = motion.kind === 'hinge'\n const axisLocal = rotY(motion.axis ?? [0, 1, 0], part.ry ?? 0)\n const axis = rotY(axisLocal, transform.ry)\n const pivot = localToWorld(transform, part.pivot)\n const half: Vec3 = [(bounds[3] - bounds[0]) / 2, (bounds[4] - bounds[1]) / 2, (bounds[5] - bounds[2]) / 2]\n const centre = localToWorld(transform, [(bounds[0] + bounds[3]) / 2, (bounds[1] + bounds[4]) / 2, (bounds[2] + bounds[5]) / 2])\n const rotation = quatY(transform.ry)\n const range = isHinge ? (motion.angle ?? Math.PI / 2) : (motion.distance ?? 0.4)\n const speed = motion.speed ?? 2.5\n const frame = options.frameOf?.(object) ?? world.createBody({ shape: { kind: 'box', half: [0.01, 0.01, 0.01] }, motion: 'static', position: pivot, layer: 'static', user: -3 })\n const ownsFrame = options.frameOf?.(object) === undefined\n const mass = options.leafMass?.(object, part) ?? Math.max(MIN_LEAF_MASS, 8 * half[0] * half[1] * half[2] * HOLLOW_DOOR_DENSITY)\n const leaf = world.createBody({ shape: { kind: 'box', half }, motion: 'dynamic', mass, position: centre, rotation, layer: 'prop', allowSleep: true, user: -3 })\n world.ignorePair(frame, leaf, true)\n const limits = { min: Math.min(0, range), max: Math.max(0, range) }\n const breakImpulse = options.breakImpulse?.(object, part)\n const joint = world.createJoint(\n isHinge\n ? { kind: 'hinge', a: frame, b: leaf, point: pivot, axis, normal: perpendicularTo(axis), ...limits, friction: HINGE_HOLD_NM, ...(breakImpulse === undefined ? {} : { breakImpulse }) }\n : { kind: 'slider', a: frame, b: leaf, point: pivot, axis, ...limits, friction: SLIDE_HOLD_N, ...(breakImpulse === undefined ? {} : { breakImpulse }) },\n )\n return createLeafDriver({ world, leaf, frame, ownsFrame, joint, onDispose: request.onDispose, drive: { isHinge, axis, pivot, centre, range, speed, base: rotation } })\n}\n\n","// A wire hung between two points (a service drop from a pole to a house, a clothesline): its length is what was strung, and the shape it takes between where its\n// ends are now is a catenary of that length. Pulled past its length it stretches as its material does and snaps where its stress passes the material's\n// strength. The ends are where the host says (one may be on a pole that falls): the span never holds them back, since the energy a wire takes in before it\n// snaps (half σ² / E per cubic metre: a few joules for a drop) is nothing beside what a falling pole carries.\nimport type { Vec3 } from './types'\n\n/** Standard gravity, m/s². */\nconst GRAVITY = 9.81\n/** Bisection steps on the shape of the catenary: the arc length comes out within a micrometre for any span the kit strings. */\nconst SHAPE_STEPS = 60\n/** Ends nearer each other than this (metres, across) hang the wire as a loop straight down. */\nconst VERTICAL_SPAN = 1e-4\n\n/** What a span is made of, in real units (`MaterialDef.tension` and `density` of game-destruction). */\nexport type SpanMaterial = {\n /** kg/m³ of the conductor. */\n readonly density: number\n /** Modulus of elasticity, GPa. */\n readonly elasticGPa: number\n /** Ultimate tensile strength, MPa. */\n readonly ultimateMPa: number\n}\n\n/** A wire strung between two points. */\nexport type Span = {\n /** Length of the wire as it was strung, metres. */\n readonly length: number\n /** Cross-section that carries the pull, m² (the conductors, not the insulation). */\n readonly section: number\n readonly material: SpanMaterial\n}\n\n/** Where a span's ends are and how it is drawn. */\nexport type SolveSpanParams = {\n readonly span: Span\n readonly from: Vec3\n readonly to: Vec3\n /** Points along the wire, both ends included (default 16). */\n readonly segments?: number\n /** Height of the ground under a point (x, z): the wire lies on it where it would hang lower. */\n readonly ground?: (x: number, z: number) => number\n /** How far above the ground the wire's axis lies (its radius). */\n readonly clearance?: number\n}\n\n/** The shape a span takes and the pull at its ends. */\nexport type SpanShape = {\n readonly points: Vec3[]\n /** The larger pull at an end, newtons. */\n readonly tension: number\n /** Pulled straight past its strung length. */\n readonly taut: boolean\n /** The end where the stress passed the material's strength, else null. */\n readonly snaps: 'from' | 'to' | null\n}\n\n/** Length of a polyline. */\nexport function polylineLength(points: readonly Vec3[]): number {\n let length = 0\n for (let i = 1; i < points.length; i++) length += Math.hypot(points[i]![0] - points[i - 1]![0], points[i]![1] - points[i - 1]![1], points[i]![2] - points[i - 1]![2])\n return length\n}\n\n/** z with sinh(z) / z = ratio (ratio ≥ 1): the half span over the catenary's parameter. */\nfunction shapeOf(ratio: number): number {\n let low = 1e-9\n let high = 1\n while (Math.sinh(high) / high < ratio && high < 700) high *= 2\n for (let i = 0; i < SHAPE_STEPS; i++) {\n const mid = (low + high) / 2\n if (Math.sinh(mid) / mid < ratio) low = mid\n else high = mid\n }\n return (low + high) / 2\n}\n\n/** The breaking pull of a span, newtons. */\nexport function spanStrength(span: Span): number {\n return span.material.ultimateMPa * 1e6 * span.section\n}\n\ntype EndPulls = { readonly points: Vec3[]; readonly pullFrom: number; readonly pullTo: number }\n\n/** Pulled straight past its length: the stretch pulls both ends, and each carries its share of the wire's weight (the upper one more). */\nfunction straight(params: SolveSpanParams, count: number, weight: number, chord: number): EndPulls {\n const { span, from, to } = params\n const pull = span.material.elasticGPa * 1e9 * span.section * ((chord - span.length) / span.length)\n const rise = to[1] - from[1]\n const points = Array.from({ length: count }, (_, i): Vec3 => {\n const t = i / (count - 1)\n return [from[0] + (to[0] - from[0]) * t, from[1] + rise * t, from[2] + (to[2] - from[2]) * t]\n })\n return { points, pullFrom: pull + (weight * (span.length - rise)) / 2, pullTo: pull + (weight * (span.length + rise)) / 2 }\n}\n\n/** Ends one over the other: straight down from each to the bottom of the loop. */\nfunction loop(params: SolveSpanParams, count: number, weight: number): EndPulls {\n const { span, from, to } = params\n const bottom = (from[1] + to[1] - span.length) / 2\n const down = from[1] - bottom\n const points = Array.from({ length: count }, (_, i): Vec3 => {\n const s = (i / (count - 1)) * span.length\n return s <= down ? [from[0], from[1] - s, from[2]] : [to[0], bottom + (s - down), to[2]]\n })\n return { points, pullFrom: weight * down, pullTo: weight * (to[1] - bottom) }\n}\n\n/** y = c cosh((x - x0) / c) with its arc length the wire's (sqrt(L² - v²) = 2 c sinh(h / 2c)); the pull at an end is the weight per metre times c cosh there. */\nfunction hanging(params: SolveSpanParams, count: number, weight: number, across: number): EndPulls {\n const { span, from, to } = params\n const rise = to[1] - from[1]\n const c = across / (2 * shapeOf(Math.sqrt(span.length * span.length - rise * rise) / across))\n const x0 = across / 2 - c * Math.atanh(rise / span.length)\n const base = Math.cosh(-x0 / c)\n const points = Array.from({ length: count }, (_, i): Vec3 => {\n const t = i / (count - 1)\n return [from[0] + (to[0] - from[0]) * t, from[1] + c * (Math.cosh((across * t - x0) / c) - base), from[2] + (to[2] - from[2]) * t]\n })\n return { points, pullFrom: weight * c * base, pullTo: weight * c * Math.cosh((across - x0) / c) }\n}\n\n/** The shape of a span between its ends now, the pull at its ends and whether it snaps (at the end that pulls the harder). */\nexport function solveSpan(params: SolveSpanParams): SpanShape {\n const { span, from, to } = params\n const count = Math.max(2, Math.floor(params.segments ?? 16))\n const weight = span.material.density * span.section * GRAVITY\n const across = Math.hypot(to[0] - from[0], to[2] - from[2])\n const chord = Math.hypot(across, to[1] - from[1])\n const taut = chord >= span.length\n const shape = taut ? straight(params, count, weight, chord) : across < VERTICAL_SPAN ? loop(params, count, weight) : hanging(params, count, weight, across)\n const ground = params.ground\n if (ground) for (const p of shape.points) p[1] = Math.max(p[1], ground(p[0], p[2]) + (params.clearance ?? 0))\n const tension = Math.max(shape.pullFrom, shape.pullTo)\n const snaps = tension > spanStrength(span) ? (shape.pullFrom >= shape.pullTo ? 'from' : 'to') : null\n return { points: shape.points, tension, taut, snaps }\n}\n\n/** A wire hung by one end, the other loose: what a snapped span leaves on the end that held. */\nexport type HangTailParams = {\n readonly anchor: Vec3\n readonly length: number\n /** The way the loose end lies along the ground (horizontal; default +x). */\n readonly toward?: Vec3\n readonly segments?: number\n readonly ground?: (x: number, z: number) => number\n readonly clearance?: number\n}\n\n/** Straight down from its anchor to the ground, and the rest of its length lying along the ground toward `toward`. */\nexport function hangTail(params: HangTailParams): Vec3[] {\n const { anchor, length } = params\n const count = Math.max(2, Math.floor(params.segments ?? 16))\n const clearance = params.clearance ?? 0\n const floorAt = (x: number, z: number): number => (params.ground ? params.ground(x, z) + clearance : -Infinity)\n const drop = Math.max(0, Math.min(length, anchor[1] - floorAt(anchor[0], anchor[2])))\n const toward = params.toward ?? [1, 0, 0]\n const flat = Math.hypot(toward[0], toward[2]) || 1\n return Array.from({ length: count }, (_, i): Vec3 => {\n const s = (i / (count - 1)) * length\n if (s <= drop) return [anchor[0], anchor[1] - s, anchor[2]]\n const x = anchor[0] + (toward[0] / flat) * (s - drop)\n const z = anchor[2] + (toward[2] / flat) * (s - drop)\n return [x, Math.max(anchor[1] - drop, floorAt(x, z)), z]\n })\n}\n","// A wire fixed along what it runs on (a conduit strapped up a pole, a cable clipped along a wall): each stretch of it goes with the part under it. Where the\n// part under it changes (two stretches of a pole), the wire is cut in two at the seam: whole, the two runs meet there and read as one; when the parts come\n// apart each run goes with its own, and the wire is broken at the seam, never drawn straight through the air from one part to the other.\nimport type { Vec3 } from './types'\n\n/** One stretch of a wire and what holds it. */\nexport type WireRun<THolder> = {\n readonly holder: THolder\n readonly points: Vec3[]\n}\n\nexport type WireRunsParams<THolder> = {\n readonly points: readonly Vec3[]\n /** Longest step (metres) between two points the holder is read at: where the holder changes is found within it. */\n readonly step: number\n /** What holds the wire at a point (the part it is fixed on there). */\n readonly holderOf: (point: Vec3) => THolder\n}\n\nconst lerp = (a: Vec3, b: Vec3, t: number): Vec3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]\n\n/** The points of the wire every `step` at most along it, its own points kept. */\nfunction along(points: readonly Vec3[], step: number): Vec3[] {\n const out: Vec3[] = points.length ? [[...points[0]!] as Vec3] : []\n for (let i = 1; i < points.length; i++) {\n const a = points[i - 1]!\n const b = points[i]!\n const steps = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) / step))\n for (let k = 1; k <= steps; k++) out.push(lerp(a, b, k / steps))\n }\n return out\n}\n\n/** The runs of a wire by what holds it, in order along it; two runs that follow each other share the point half way between their last and first readings. */\nexport function wireRuns<THolder>(params: WireRunsParams<THolder>): WireRun<THolder>[] {\n const points = along(params.points, Math.max(1e-3, params.step))\n if (points.length < 2) return []\n const holders = points.map((p) => params.holderOf(p))\n const runs: WireRun<THolder>[] = []\n let current: { holder: THolder; points: Vec3[] } = { holder: holders[0]!, points: [points[0]!] }\n for (let i = 1; i < points.length; i++) {\n if (holders[i] === current.holder) {\n current.points.push(points[i]!)\n continue\n }\n const seam = lerp(points[i - 1]!, points[i]!, 0.5)\n current.points.push(seam)\n runs.push(current)\n current = { holder: holders[i]!, points: [[...seam] as Vec3, points[i]!] }\n }\n runs.push(current)\n return runs\n}\n","// What is drawn on an upright member (a pole's shaft laid in stretches) and is the same casting as it: a collar round a stretch (the bands on a pole) or a\n// foot or a cap on its end (the flared base of a pole). Such a primitive is one piece with the stretch, with the same concrete round the same cage, worn by the\n// rounds as the member is: never a block of its own the rounds tunnel through, or a ring left on the stub.\n\n/** An axis-aligned box as [min x, min y, min z, max x, max y, max z], metres. */\nexport type CastBox = readonly number[]\n\n/** Metres a collar, a foot or a cap may stand out of the member, each side. */\nexport const COLLAR_REACH = 0.03\n/** Metres a foot or a cap may stand apart from the end of the member (the seam between two primitives drawn end to end). */\nexport const END_GAP = 0.005\n\n/** Centred on the member across (x and z) and standing out of it by `COLLAR_REACH` at most. */\nfunction centredOn(member: CastBox, other: CastBox): boolean {\n for (const k of [0, 2]) {\n if (other[k]! < member[k]! - COLLAR_REACH || other[k + 3]! > member[k + 3]! + COLLAR_REACH) return false\n if (Math.abs((other[k]! + other[k + 3]!) / 2 - (member[k]! + member[k + 3]!) / 2) > COLLAR_REACH) return false\n }\n return true\n}\n\n/** A collar drawn round the stretch: most of its height on it (a band on the seam of two goes with the one it is mostly on). */\nexport function wrapsMember(member: CastBox, collar: CastBox): boolean {\n const overlap = Math.min(collar[4]!, member[4]!) - Math.max(collar[1]!, member[1]!)\n return overlap >= (collar[4]! - collar[1]!) / 2 && centredOn(member, collar)\n}\n\n/** A foot under the stretch or a cap over it, no taller than it. */\nexport function endsMember(member: CastBox, end: CastBox): boolean {\n const under = Math.abs(end[4]! - member[1]!) <= END_GAP\n const over = Math.abs(end[1]! - member[4]!) <= END_GAP\n return (under || over) && end[4]! - end[1]! <= member[4]! - member[1]! && centredOn(member, end)\n}\n\n/** Whether `other` is cast with the stretch `member`: a collar round it, or a foot or a cap on its end. */\nexport function castWithMember(member: CastBox, other: CastBox): boolean {\n return wrapsMember(member, other) || endsMember(member, other)\n}\n","/**\n * The push a blast gives a standing body, from the physics of the blast wave and not from a game coupling: the impulse of the wave per square metre at a distance from a charge of\n * `tnt` kg of TNT equivalent (Kinney and Graham's fit of the side-on impulse, scaled by the cube root of the charge), reflected on the body, over the area the body shows the wave,\n * divided by its mass. A hand grenade at 3 m gives a person a few tenths of a metre per second; what floors that person is the fragments, not the wave. A big charge close throws.\n */\n\n/** The numbers of the body a blast wave pushes. All have a default for a standing adult. */\nexport interface BlastImpulseOptions {\n /** Square metres of the body the wave meets: about 1.75 m tall by 0.4 m wide (default 0.7). */\n readonly bodyArea?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised (default 0.15: the wave runs along the ground). */\n readonly lift?: number\n /** Below this speed (m/s) the body does not move (default 0.3). */\n readonly minSpeed?: number\n /**\n * Kilograms of TNT per joule of the blast `energy`, for a blast that does not say its charge (`BlastSource.tnt`). Default 0.24 / 200000: the arsenal's energy scale, where the M67 (180 g\n * of Composition B, 0.24 kg of TNT) is 200 kJ. It is a game equivalence for blasts without a charge, not a physical constant.\n */\n readonly tntPerJoule?: number\n}\n\nexport const DEFAULT_BLAST_IMPULSE: Readonly<Required<BlastImpulseOptions>> = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 200000 }\n\n/** Closest distance (m) the fit is read at by default: inside it the charge is in contact and the body is torn apart anyway (a caller that loads a part next to the charge passes a smaller `nearest`). */\nconst NEAREST = 0.3\n\n/**\n * Side-on (incident) specific impulse of the wave, in Pa·s, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `I/W^(1/3) = 0.067 sqrt(1 + (Z/0.23)^4) / (Z^2 (1 + (Z/1.55)^3)^(1/3))` bar·ms per kg^(1/3), with the scaled distance `Z = R / W^(1/3)`.\n */\nexport function sideOnImpulse(tnt: number, distance: number, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, nearest) / w3\n // products, not `**` past 2: V8 gives `x ** 3` a different last bit on Node 22 and 24, and the goldens must agree on both\n const near = (z / 0.23) * (z / 0.23)\n const far = z / 1.55\n const scaled = (0.067 * Math.sqrt(1 + near * near)) / (z * z * Math.cbrt(1 + far * far * far))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/** Sea-level atmospheric pressure, Pa. */\nconst ATMOSPHERE = 101325\n\n/**\n * Peak side-on (incident) overpressure of the wave, in Pa, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `Ps/Pa = 808 (1 + (Z/4.5)^2) / (sqrt(1 + (Z/0.048)^2) sqrt(1 + (Z/0.32)^2) sqrt(1 + (Z/1.35)^2))`, with the scaled distance `Z = R / W^(1/3)` (m/kg^(1/3)).\n * What a wall takes from a blast is read against it: about 7 kPa cracks plaster and breaks windows, 14 to 20 kPa knocks parts of a brick wall out, 35 kPa and over brings an\n * unreinforced brick wall down (Glasstone and Dolan, \"The Effects of Nuclear Weapons\", 1977, table 5.139; UFC 3-340-02).\n */\nexport function sideOnOverpressure(tnt: number, distance: number, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, nearest) / Math.cbrt(tnt)\n const ratio = (808 * (1 + (z / 4.5) ** 2)) / (Math.sqrt(1 + (z / 0.048) ** 2) * Math.sqrt(1 + (z / 0.32) ** 2) * Math.sqrt(1 + (z / 1.35) ** 2))\n return ratio * ATMOSPHERE\n}\n\n/**\n * The impulse per square metre a body facing the wave takes, Pa·s: the side-on impulse reflected. The reflection doubles a weak wave and grows up to about six times close to the charge,\n * where the wave is strong (the ratio of reflected to side-on impulse of the Kingery-Bulmash charts, fitted as `2 + 4 / (1 + Z^2)`).\n */\nexport function bodyImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n return sideOnImpulse(tnt, distance) * (2 + 4 / (1 + z * z))\n}\n\n/** The speed (m/s) a blast wave gives a free body of `mass` kg at `distance` metres from `tnt` kg of TNT, `reach` (0..1) of it getting through what stands in the way. */\nexport function blastBodySpeed(tnt: number, distance: number, mass: number, reach = 1, options: BlastImpulseOptions = {}): number {\n const area = options.bodyArea ?? DEFAULT_BLAST_IMPULSE.bodyArea\n return (bodyImpulse(tnt, distance) * area * Math.max(0, reach)) / Math.max(mass, 1)\n}\n","import { bodyImpulse, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n /**\n * Kilograms of TNT equivalent of the charge. With it a body is pushed by the blast wave itself (`blast-impulse`), and the shove of loose items keeps this module's rule; without it the body\n * takes the charge from `energy` by `BlastImpulseOptions.tntPerJoule`.\n */\n readonly tnt?: number\n /** Inside this radius (metres) the blast is lethal: a body there that the blast reaches (not behind cover) goes down, wounded, wherever the wave pushed it. */\n readonly lethalRadius?: number\n}\n\n/** What a blast does to one body: how fast it leaves (m/s), the unit direction it leaves in, and how far from the centre it was. */\nexport interface BlastShove {\n readonly speed: number\n readonly direction: Vec3\n readonly distance: number\n /** The falloff applied, 0..1. */\n readonly falloff: number\n}\n\nconst clampShare = (share: number): number => Math.min(1, Math.max(0, share))\n\n/**\n * The shove a blast gives to a body of `mass` kg whose centre is at `position`: away from the centre, lifted a little, with the speed\n * `sqrt(reach) * min(maxSpeed, sqrt(2 * energy * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * A target that says its `area` (m2 it shows the wave) is pushed by the blast wave itself instead (`bodyImpulse`: Kinney-Graham impulse of the charge `blast.tnt`, or of `energy` by\n * `tntPerJoule`, reflected on that area, divided by the mass): a 2 kg shovel 0.8 m from a hand grenade gets a few m/s, not the cap. `maxSpeed` still caps it (a light thing next to the charge would otherwise tunnel through what stands in its way); `coupling` and `falloffPower` do not apply.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number; readonly area?: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n // cover takes its share off the push itself, past the cap too: a light thing behind a cupboard is not thrown as fast as one in the open\n const reach = clampShare(blast.reach ?? 1)\n const speed =\n target.area !== undefined\n ? Math.min(o.maxSpeed, (bodyImpulse(blast.tnt ?? blast.energy * DEFAULT_BLAST_IMPULSE.tntPerJoule, distance) * target.area * reach) / mass)\n : Math.sqrt(reach) * Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * o.coupling) / mass)) * falloff\n if (!(speed >= o.minSpeed)) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const direction: Vec3 = distance > 1e-4 ? [dx / distance, dy / distance + o.lift, dz / distance] : [0, 1, 0]\n const length = Math.hypot(direction[0], direction[1], direction[2])\n return { speed, direction: [direction[0] / length, direction[1] / length, direction[2] / length], distance, falloff }\n}\n","/**\n * The heat of a blast, from the size and life of its fireball and not from the game radius of the blast. Pure functions in SI units (m, s, W/m2, J/m2).\n *\n * A condensed charge (TNT, Composition B, C4) makes a small fireball that lives milliseconds: its radius and its life both grow as the cube root of the charge\n * (Hopkinson-Cranz scaling, as the wave does). A burning fuel (the gas of a cylinder that bursts, petrol) makes a fireball metres wide that lives about a second:\n * the BLEVE correlations of the CCPS guidelines, `D = 5.8 M^(1/3)` m and `t = 0.45 M^(1/3)` s for `M` kg of fuel, with a surface emissive power of a few hundred kW/m2.\n * What a surface takes is the heat per square metre over the life of the fireball: the whole flux inside it, and outside it the share a sphere of radius `R` sends to a\n * surface that faces it at `d` from its centre (the view factor `(R / d)^2`). A surface catches fire when that dose passes what its material needs (`ignitionDose`).\n */\n\n/** The fireball of a blast: how wide, how long and how hot it burns on what it touches. */\nexport interface Fireball {\n /** Metres. */\n readonly radius: number\n /** Seconds the fireball lives. */\n readonly seconds: number\n /** W/m2 it puts on a surface inside it (radiation and the hot gases together). */\n readonly flux: number\n}\n\n/** m/kg^(1/3): radius of the luminous fireball of a condensed charge (an engineering estimate; the M67, 0.24 kg of TNT, is 0.8 m). */\nconst CHARGE_RADIUS = 1.3\n/** s/kg^(1/3): its life (the M67 burns 6 ms). */\nconst CHARGE_SECONDS = 0.01\n/** W/m2 on a surface inside the fireball of a condensed charge: detonation products at some 2500 K, radiation and convection. */\nconst CHARGE_FLUX = 1.5e6\n/** m/kg^(1/3): radius of a fuel fireball, half of the CCPS diameter 5.8 M^(1/3). */\nconst FUEL_RADIUS = 2.9\n/** s/kg^(1/3): life of a fuel fireball (CCPS, below 30 t of fuel). */\nconst FUEL_SECONDS = 0.45\n/** W/m2: surface emissive power of a hydrocarbon fireball (CCPS gives 200 to 350). */\nconst FUEL_FLUX = 250e3\n/** J/m2 per degree between the room and the ignition temperature: the dose a solid needs to light under a brief heat (paper at 230 °C takes 63 kJ/m2, hard wood at 330 °C 93). */\nconst DOSE_PER_DEGREE = 300\n\n/** The fireball of `tnt` kg of TNT equivalent of a condensed charge. */\nexport function chargeFireball(tnt: number): Fireball {\n const cube = Math.cbrt(Math.max(0, tnt))\n return { radius: CHARGE_RADIUS * cube, seconds: CHARGE_SECONDS * cube, flux: CHARGE_FLUX }\n}\n\n/** The fireball of `fuel` kg of a burning hydrocarbon (the gas of a cylinder, petrol). */\nexport function fuelFireball(fuel: number): Fireball {\n const cube = Math.cbrt(Math.max(0, fuel))\n return { radius: FUEL_RADIUS * cube, seconds: FUEL_SECONDS * cube, flux: FUEL_FLUX }\n}\n\n/** J/m2 a surface facing the fireball takes at `distance` metres from its centre: the whole flux inside it, the view factor `(R / d)^2` of the sphere outside. */\nexport function fireballDose(fireball: Fireball, distance: number): number {\n const share = distance <= fireball.radius ? 1 : (fireball.radius / distance) ** 2\n return fireball.flux * fireball.seconds * share\n}\n\n/** J/m2 a surface of a material that ignites at `ignitionC` needs to catch fire from a brief heat, starting at `ambientC`. */\nexport function ignitionDose(ignitionC: number, ambientC = 20): number {\n return DOSE_PER_DEGREE * Math.max(1, ignitionC - ambientC)\n}\n","import { sideOnImpulse, sideOnOverpressure } from './blast-impulse'\n\n/**\n * The blast wave on a part, from Hopkinson-Cranz scaling: the reflected load of a charge of TNT equivalent at a distance (Kinney and Graham's side-on fits, reflected by\n * Rankine-Hugoniot for the pressure and the Kingery-Bulmash ratio for the impulse), and the work it puts into a part of a given area, mass and thickness (the smaller\n * asymptote of its pressure-impulse diagram, Baker et al. 1983). Shared by the destruction world and every module that takes blasts on its own parts (vehicles).\n */\n\n/** Pa */\nconst ATMOSPHERE = 101325\n/** Scaled distance (m/kg^(1/3)) below which the far-field fits are held: closer is a charge in contact, where the fits stop being the wave. */\nconst NEAREST_SCALED = 0.2\n/** m: a charge's near field and the size of a charge add this much to the standoff when the area the wave loads evenly is taken. */\nconst LOADED_MARGIN = 0.15\n/** J/kg: the TNT equivalent's definition. */\nexport const TNT_JOULES = 4.184e6\n/**\n * Share of the charge energy that a target crushes and spalls when the charge is in contact with it, at the scaled distance 0 (an engineering estimate of the cratering efficiency of\n * contact charges in concrete and masonry: a few percent of the energy goes into breaking the material, the rest into air and ground shock).\n */\nconst SHOCK_COUPLING = 0.04\n/** m/kg^(1/3): scaled distance at which the crushing and spalling of a surface is a quarter of that at contact (they fall off as `(1 + (Z / Z0)^2)^-2`; spalling of concrete stops near Z = 1.5). */\nconst SHOCK_SCALED = 0.6\n\n/** The wave on a face that looks at the charge: reflected peak overpressure (Pa) and reflected positive impulse (Pa s). */\nexport interface WaveLoad {\n readonly pressure: number\n readonly impulse: number\n}\n\n/** The reflected load at `distance` m from `tnt` kg of TNT. */\nexport function reflectedLoad(tnt: number, distance: number): WaveLoad {\n if (!(tnt > 0)) return { pressure: 0, impulse: 0 }\n const cube = Math.cbrt(tnt)\n const nearest = NEAREST_SCALED * cube\n const side = sideOnOverpressure(tnt, distance, nearest)\n const z = Math.max(distance, nearest) / cube\n // ideal gas, normal reflection: Pr = 2 Ps (7 Pa + 4 Ps) / (7 Pa + Ps), 2 for a weak wave, up to 8 for a strong one\n const pressure = (2 * side * (7 * ATMOSPHERE + 4 * side)) / (7 * ATMOSPHERE + side)\n const impulse = sideOnImpulse(tnt, distance, nearest) * (2 + 4 / (1 + z * z))\n return { pressure, impulse }\n}\n\n\nexport interface WaveWorkInput {\n /** Kilograms of TNT. */\n readonly tnt: number\n /** Metres from the charge to the nearest point of the part. */\n readonly distance: number\n /** 0..1: the share of the wave that gets through what stands in between. */\n readonly reach: number\n /** m2 the part shows the charge. */\n readonly area: number\n readonly mass: number\n /** m: how far the part moves under the wave before it fails (its own thickness). */\n readonly thickness: number\n}\n\nexport interface WaveWork {\n /** m2 the wave loads evenly. */\n readonly loaded: number\n /** Joules the wave puts into the part as a whole (it moves and bends, the P-I work). */\n readonly energy: number\n /** Joules that crush and spall the face next to the charge (`shockWork`), on top of `energy`. */\n readonly shock: number\n /** Reflected peak overpressure on the part (Pa), after cover. */\n readonly pressure: number\n}\n\n/**\n * What a blast puts into a part: `min(J^2 / 2 m, P A d)` with the load `P`, `J / A` of `reflectedLoad` cut by `reach`, over the area the wave loads evenly (a disc as wide as the\n * standoff, so a wall 10 m wide is not loaded as one block by a charge 1 m from it) and the mass of the piece of the part under that area. A 2 mm steel blade 0.8 m from an M67 gets\n * about 75 J (a dent); a 2 tonne wall 1.5 m away gets about 120 J (a scuff), so the damage depends on how much the part weighs for the area it shows.\n */\nexport function waveWork(input: WaveWorkInput): WaveWork {\n const load = reflectedLoad(input.tnt, input.distance)\n const reach = Math.min(1, Math.max(0, input.reach))\n const pressure = load.pressure * reach\n if (!(input.area > 0) || !(input.mass > 0) || pressure <= 0) return { energy: 0, shock: 0, pressure, loaded: 0 }\n const loaded = Math.min(input.area, Math.PI * (input.distance + LOADED_MARGIN) ** 2)\n const mass = input.mass * (loaded / input.area)\n const impulse = load.impulse * reach * loaded\n const impulsive = (impulse * impulse) / (2 * mass)\n const quasiStatic = pressure * loaded * Math.max(input.thickness, 1e-4)\n return { energy: Math.min(impulsive, quasiStatic), shock: shockWork(input), pressure, loaded }\n}\n\n/**\n * Crushing and spalling of the face next to a charge, which the far-field fits do not see: the charge energy `W * 4.184 MJ`, times the share that crushes material at that scaled\n * distance (`SHOCK_COUPLING (1 + (Z / 0.6)^2)^-2`), times the share of the sphere around the charge that the part intercepts (`A / 4 pi (R + r_c)^2`, at most a half: a face on the charge).\n * A grenade 0.8 m from a blade gives it about 1 J of this; a block of C4 against a wall gives it tens of kilojoules.\n */\nfunction shockWork(input: WaveWorkInput): number {\n const cube = Math.cbrt(input.tnt)\n if (!(cube > 0) || !(input.area > 0)) return 0\n const z = Math.max(input.distance, 0) / cube\n const radius = Math.cbrt((3 * input.tnt) / (4 * Math.PI * 1600))\n const share = Math.min(0.5, input.area / (4 * Math.PI * (input.distance + radius) ** 2))\n // products, not `**` past 2: V8 gives `x ** -2` a different last bit on Node 22 and 24, and the goldens must agree on both\n const falloff = 1 + (z / SHOCK_SCALED) * (z / SHOCK_SCALED)\n const reach = Math.min(1, Math.max(0, input.reach))\n return (SHOCK_COUPLING * input.tnt * TNT_JOULES * share * reach * reach) / (falloff * falloff)\n}\n","import { blastBodySpeed, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { BlastImpulseOptions } from './blast-impulse'\nimport type { BlastShoveOptions, BlastSource } from './blast-shove'\nimport type { Vec3 } from './destruction'\n\n/** From this speed (m/s) a blast takes a standing body off its feet. Below it the body is only pushed. */\nexport const KNOCK_DOWN_SPEED = 2.5\n/** The angle of a body lying where it fell (the same tilt a dead body takes). */\nexport const KNOCKED_DOWN_ANGLE = 1.35\n/** Seconds the body lies after it lands: this plus the landing speed times `STAND_UP_PER_SPEED`. */\nconst LIE_SECONDS = 1.6\n/** Seconds a body floored by its wounds (inside the lethal radius) lies before it gets up, when it is not dead. */\nconst WOUNDED_LIE_SECONDS = 6\n/** The share of the blast that has to get through for its fragments to reach a body: behind cover that stops half of it the fragments stop too. */\nexport const FRAGMENT_COVER = 0.5\n/** Seconds a body is stunned at the edge of the lethal radius (the ringing ears, the dizziness); it falls with the square of the way to the edge of the blast. */\nconst STUN_SECONDS = 4\nconst STAND_UP_PER_SPEED = 0.25\nconst FALL_SECONDS = 0.25\nconst RISE_SECONDS = 0.6\n/** m/s squared that slows a body sliding on the ground. */\nconst GROUND_FRICTION = 7\nconst GRAVITY = 9.81\n/** Height of the chest above the feet: where the blast takes the body. */\nexport const KNOCK_CHEST = 1.1\nconst CHEST = KNOCK_CHEST\n\n/** What a blast is doing to one body: its velocity (m/s), whether it is in the air, and how far down it is (0 on its feet, 1 lying). */\nexport interface Knock {\n velocity: [number, number, number]\n airborne: boolean\n /** 0..1 */\n lying: number\n /** Seconds left to lie on the ground after it stopped. */\n lieLeft: number\n /** Knocked off its feet by this blast. */\n down: boolean\n /** Floored by its wounds: inside the lethal radius and not behind cover. It lies longer and falls where it stood. */\n wounded?: boolean\n /** Seconds of stun the blast gave the body: dizziness and ringing ears. */\n stunSeconds?: number\n /** The horizontal unit direction away from the blast, even when the push is too weak to move the body: the way it falls. */\n away?: Vec3\n}\n\n/** The mass of a body in kg from its height (m) and its build (1 = average): 70 kg at 1.75 m. */\nexport const bodyMass = (height: number, build = 1): number => 70 * (height / 1.75) ** 2 * build\n\n/**\n * What a blast does to a body standing at `feet`, of `mass` kg. Undefined when the blast does not reach it or does nothing to it.\n *\n * The body is pushed by the blast wave (`blastBodySpeed`, from the charge `blast.tnt`, or from `energy` by `tntPerJoule`), taken at the chest and cut by `reach`, the share that got through\n * cover. It is floored when that push is `KNOCK_DOWN_SPEED` or more, or when it stands inside `lethalRadius` with the blast reaching it (the fragments and the overpressure fell it where it\n * stands). It is stunned for a while inside the radius. `options` are the shove numbers of the host's loose items; only their `minSpeed` applies to a body.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions, impulse: BlastImpulseOptions = {}): Knock | undefined {\n const o = { ...DEFAULT_BLAST_IMPULSE, ...impulse }\n const chest: Vec3 = [feet[0], feet[1] + CHEST, feet[2]]\n const dx = chest[0] - blast.point[0]\n const dy = chest[1] - blast.point[1]\n const dz = chest[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const reach = Math.max(0, Math.min(1, blast.reach ?? 1))\n const tnt = blast.tnt ?? blast.energy * o.tntPerJoule\n let speed = blastBodySpeed(tnt, distance, mass, reach, o)\n const minSpeed = impulse.minSpeed ?? options?.minSpeed ?? o.minSpeed\n if (speed < minSpeed) speed = 0\n const struck = reach >= FRAGMENT_COVER\n const wounded = struck && blast.lethalRadius !== undefined && distance <= blast.lethalRadius\n const edge = 1 - distance / blast.radius\n const stunSeconds = struck ? STUN_SECONDS * edge * edge * reach : 0\n if (speed === 0 && !wounded && stunSeconds < 0.25) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const horizontal = Math.hypot(dx, dz)\n const away: Vec3 = horizontal > 1e-4 ? [dx / horizontal, o.lift, dz / horizontal] : [0, 1, 0]\n const length = Math.hypot(away[0], away[1], away[2])\n const velocity: [number, number, number] = [(away[0] / length) * speed, (away[1] / length) * speed, (away[2] / length) * speed]\n return {\n velocity,\n airborne: velocity[1] > 0.5,\n lying: 0,\n lieLeft: wounded ? WOUNDED_LIE_SECONDS : 0,\n away: horizontal > 1e-4 ? [dx / horizontal, 0, dz / horizontal] : [0, 0, 0],\n down: speed >= KNOCK_DOWN_SPEED || wounded,\n ...(wounded ? { wounded } : {}),\n ...(stunSeconds >= 0.25 ? { stunSeconds } : {}),\n }\n}\n\n/**\n * Moves a body one step: it slides on the ground and slows, falls when it was knocked down, lies a while and gets up (a dead body stays down). Moves `position` in place; returns true when the\n * body is on its feet and still, and the knock can be dropped.\n */\nexport function stepKnock(knock: Knock, position: { x: number; y: number; z: number }, dt: number, groundAt: (x: number, z: number) => number, alive: boolean): boolean {\n const v = knock.velocity\n position.x += v[0] * dt\n position.z += v[2] * dt\n const ground = groundAt(position.x, position.z)\n if (knock.airborne || position.y > ground + 1e-4) {\n v[1] -= GRAVITY * dt\n position.y += v[1] * dt\n if (position.y <= ground) {\n position.y = ground\n v[1] = 0\n knock.airborne = false\n }\n } else position.y = ground\n const horizontal = Math.hypot(v[0], v[2])\n if (!knock.airborne && horizontal > 0) {\n const slowed = Math.max(0, horizontal - GROUND_FRICTION * dt)\n v[0] *= slowed / horizontal\n v[2] *= slowed / horizontal\n }\n const moving = horizontal > 0.05 || knock.airborne\n if (knock.down) {\n // a body floored where it stands (its wounds, not the push) still takes the time of a fall to reach the ground\n if (moving || knock.lying < 1) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else if (alive) {\n knock.lieLeft = knock.lieLeft > 0 ? knock.lieLeft : LIE_SECONDS + Math.hypot(v[0], v[2]) * STAND_UP_PER_SPEED\n knock.lieLeft -= dt\n if (knock.lieLeft <= 0) knock.down = false\n }\n } else if (knock.lying > 0) knock.lying = Math.max(0, knock.lying - dt / RISE_SECONDS)\n return !moving && !knock.down && knock.lying === 0\n}\n\n/** Where `launchBody` leaves the throw on the body's root until the module that animates it takes it. */\nconst LAUNCHED = 'launched'\n\n/**\n * Throws a body at `velocity` (m/s, world): an occupant leaving a car through the glass, a pedestrian run over. The module that animates the body\n * takes it on its next frame (`takeLaunch`) and moves it as it moves a body a blast knocked down: flying, landing, sliding, lying, getting up.\n */\nexport function launchBody(root: { userData: Record<string, unknown> }, velocity: Vec3): void {\n root.userData[LAUNCHED] = [velocity[0], velocity[1], velocity[2]]\n}\n\n/** The throw `launchBody` left on the root, as a knock (knocked down, in the air), once; undefined when nothing threw it. */\nexport function takeLaunch(root: { userData: Record<string, unknown> }): Knock | undefined {\n const velocity = root.userData[LAUNCHED] as Vec3 | undefined\n if (!velocity) return undefined\n delete root.userData[LAUNCHED]\n return { velocity: [velocity[0], velocity[1], velocity[2]], airborne: true, lying: 0, lieLeft: 0, down: true }\n}\n","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\n/**\n * One drawn piece of a hosted body as a solid for a physics engine, in the impl's frame (`DestructibleImpl.colliders`): a box turned as drawn where a box fits the piece\n * (every corner within 1 cm of a vertex), else the piece's triangles (`mesh`, with the box around them). `id` is the part of `describe()` the piece is.\n * A piece handed back is never changed in place: a piece that changed is a new object (the world reuses what it made of an object it has seen, `hostedSolids`).\n */\nexport interface DrawnCollider {\n readonly id: string\n /** Names the piece across lists (a piece measured again is the same piece): without it, the place in the list. */\n readonly key?: string\n readonly center: Vec3\n readonly half: Vec3\n readonly rotation: [number, number, number, number]\n readonly mesh?: { readonly vertices: Float32Array; readonly indices: Uint32Array }\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /**\n * The pieces the impl draws, as what an engine collides with in their place (in the frame `describe()` answers in): one per drawn piece, none for a part that broke or\n * came off. Without it the engine takes the boxes of `describe()`. Same cost contract as `describe()`: the world asks again only when state, place or a pose changes.\n */\n colliders?(): readonly DrawnCollider[]\n /** True while `colliders()` still has pieces to make (a vehicle that just spawned fills in over several updates): the world asks again at the next update. */\n collidersPending?(): boolean\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source', 'pieces'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n if (hit.pieces !== undefined && !(Number.isFinite(hit.pieces) && hit.pieces >= 1)) out.push(`${hit.type} hit \"pieces\" must be a finite number of at least 1`)\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { Vec3 } from './destruction'\n\n/** Anthropometric measures of a standing/seated body derived from stature and lateral build (metres). */\nexport type BodyMeasures = {\n /** Standing stature from sole to top of skull (excluding hair/hat), in metres. */\n readonly heightMetres: number\n /** Lateral build multiplier (1.0 = reference adult). */\n readonly build: number\n /** Vertical distance from seat surface (H-point) to top of skull, in metres. */\n readonly seatedHeightMetres: number\n /** Vertical distance from seat surface (H-point) to eye level, in metres. */\n readonly seatedEyeHeightMetres: number\n /** Bideltoid shoulder width, in metres. */\n readonly shoulderWidthMetres: number\n /** Horizontal buttock-to-knee length (hip to front of knee), in metres. */\n readonly thighLengthMetres: number\n /** Vertical knee-to-sole length (popliteal/knee height), in metres. */\n readonly shinLengthMetres: number\n}\n\n/** Functional roles a vehicle seat can play. */\nexport const SEAT_ROLES = ['driver', 'front_passenger', 'rear', 'cargo', 'rider', 'pilot', 'crew'] as const\n\n/** Functional role of a vehicle seat. */\nexport type SeatRole = (typeof SEAT_ROLES)[number]\n\n/** Usable interior clearance of one seat in vehicle local coordinates (+x front, +y up, +z right), in metres. */\nexport type SeatSpace = {\n /** Stable seat identifier within the vehicle (e.g. 'driver', 'front_right', 'rear_left', 'rider'). */\n readonly id: string\n /** Functional role of the seat. */\n readonly role: SeatRole\n /** Seat hip point (H-point, cushion top centre) in vehicle local coordinates, in metres. */\n readonly hipPoint: Vec3\n /** Clear vertical height from hipPoint to headliner/roof (minimum of 5 rays). `Infinity` for open vehicles/bikes/boats. */\n readonly headroomMetres: number\n /** Clear longitudinal knee/leg space from hipPoint along seat facing direction to first obstruction. `Infinity` if open. */\n readonly legroomMetres: number\n /** Available lateral width at shoulder height for this seat, in metres. `Infinity` for open-sided seats. */\n readonly widthMetres: number\n /** Id of the door opening that serves this seat (matches `DoorOpening.id`); `undefined` for open entry. */\n readonly doorId?: string\n /** How far the seat's backrest leans back from upright, radians, when the seat has one drawn. */\n readonly recline?: number\n}\n\n/** Clear opening of a vehicle door or hatch, in metres. */\nexport type DoorOpening = {\n /** Matches the vehicle door zone id (e.g. 'door_front_left', 'hatch_commander'). */\n readonly id: string\n /** Clear horizontal opening width, in metres. `Infinity` if open entry. */\n readonly widthMetres: number\n /** Clear vertical opening height, in metres. `Infinity` if open entry. */\n readonly heightMetres: number\n}\n\n/** Canonical reasons a body cannot fit a seat/door pair (Spec 012 D2). */\nexport const FIT_REJECT_REASONS = ['head', 'legs', 'shoulders', 'door'] as const\n\n/** Why a body does not fit a seat/door pair (binary with reason). */\nexport type FitRejectReason = (typeof FIT_REJECT_REASONS)[number]\n\n/** Result of checking whether a body fits a seat (and optionally its access door). */\nexport type FitResult =\n | { readonly fits: true }\n | { readonly fits: false; readonly reason: FitRejectReason }\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-', 'all']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * Where a hand should be, in world space. `position` is the middle of the palm; the orientation follows one convention for every hand: the hand-local +x runs from the wrist to the\n * knuckles (the way the fingers point when open), +y is the back of the hand and +z completes the frame (for a right hand the little finger side; the thumb is at -z). A left hand is the\n * mirror image of a right one, so the same numbers describe the same grip: its thumb is at +z.\n */\nexport interface HandPose {\n position: Vec3\n /** Unit quaternion `[x, y, z, w]`, hand-local to world. */\n quaternion: [number, number, number, number]\n}\n\n/**\n * What a tool in the hands asks of the hands that hold it (a weapon asks for a grip on its grip and handguard, a carried item for a hand under it). A side left out or null is not held:\n * the hand stays in its rest stance. Nothing here knows what the tool is.\n */\nexport interface HandTargets {\n R?: HandPose | null\n L?: HandPose | null\n /**\n * The shaft of a two-handed tool (a shovel, an axe, a sledgehammer) the left hand may slide along, world space: a left grip out of the arm's reach is taken at the nearest point of\n * this segment the hand reaches, the hand still closed on the shaft, as one shortens the grip on a handle. Absent, the left hand goes to `L` or stops short of it.\n */\n slideL?: { readonly from: Vec3; readonly to: Vec3 } | null\n /** How closed the fingers are, 0 open to 1 closed on a grip. Default 1. */\n grip?: number\n /** The same for the left hand, when it differs from `grip` (a hand laid on a forend is looser than the one on the trigger). */\n gripL?: number\n /** The size of the hands against life size (a tool drawn smaller than real takes smaller hands). Default 1. */\n scale?: number\n /** Fingers of the right hand that curl by themselves, 0 extended to 1 fully curled (the index finger of a trigger hand); the others follow `grip`. */\n fingers?: { index?: number }\n /** The same for the left hand (its index on the trigger of a tool of its own, with a tool in each hand); absent, the left hand's fingers all follow `gripL`. */\n fingersL?: { index?: number }\n /**\n * Where the elbows go: `view` puts them on screen beside the hand, out to the side, as a tool held out in front (default); `body` lets them hang down and back by the body, as an item\n * carried close (a can, a bottle), where an elbow out to the side would lift it above the shoulder.\n */\n elbows?: 'view' | 'body'\n}\n\n/** Read every frame by whoever draws the arms; answers null while nothing is held. */\nexport type HandTargetSource = () => HandTargets | null\n\n/**\n * Told every frame, after the arms reached for the targets, where the hands really are (world space, `HandPose`): an arm stops where a person's stops (the wrist turns only so far, the\n * elbow folds only so far), so a hand may end short of its target or turned from it. A tool held rigid in that hand (a knife, a bat, a spanner) is moved with it, its grip staying in the\n * palm, and the next read of the source answers the targets of the tool where it now is (the other hand comes to it). A side left out was not drawn. Answers whether the tool moved: only\n * then are the targets read again and the arms reach again (a gun keeps its aim and never moves; a blade in a hand that came to its grip does not either).\n */\nexport type HandSeat = (reached: { readonly R?: HandPose | null; readonly L?: HandPose | null }) => boolean\n\n/** The muzzle of the tool in the hands as it is drawn now (world space): where a shot's flash and tracer leave, and which way the barrel points. */\nexport interface MuzzlePose {\n readonly position: Vec3\n /** Unit vector along the barrel, out of the muzzle. */\n readonly direction: Vec3\n /** The module draws the muzzle flash itself: the host draws none of its own. */\n readonly drawsFlash: boolean\n}\n\n/** A hand of the body: `R` the right, `L` the left. A tool in one hand alone is in the right; the left holds one of its own only with a tool in each hand (`HostTool.offHand`). */\nexport type ToolHand = 'R' | 'L'\n\n/**\n * Read by the host at each shot; null while the tool in the hands has no muzzle (a knife, a bare hand). `hand` is the hand that fired (absent: the right one); a source that draws\n * one tool only answers the same for both.\n */\nexport type MuzzleSource = (hand?: ToolHand) => MuzzlePose | null\n\n/**\n * The layer of what the first-person view draws over the world (three.js `Object3D.layers`): the tool in the hands and the arms that hold it. A host with a first-person view draws\n * the world without this layer, then this layer alone over it with the depth cleared and its own field of view (`ModuleHost.setViewmodelFov`), as shooters draw the weapon in the hands:\n * it never goes into a wall, and the gun and the arms are framed by the lens chosen for them. Seen from outside (third person) nothing is on it.\n */\nexport const FIRST_PERSON_LAYER = 9\n\n/**\n * The `userData` flag of the part of a drawn thing that is its carry handle (a bucket's bail, a jerrycan's or a toolbox's handle): a hand takes the thing there and carries it\n * hanging (`gripOnHandle` of game-player). The model that draws the thing sets it; the host finds it in the drawing.\n */\nexport const CARRY_HANDLE_TAG = 'carryHandle'\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** A rotation as a unit quaternion [x, y, z, w]. */\nexport type ClipQuat = [number, number, number, number]\n\n/** Euler XYZ (three.js' default order, as in `AnimationPose.rotation`) to a quaternion. */\nexport const quatFromEuler = (e: readonly number[]): ClipQuat => {\n const c1 = Math.cos((e[0] ?? 0) / 2), c2 = Math.cos((e[1] ?? 0) / 2), c3 = Math.cos((e[2] ?? 0) / 2)\n const s1 = Math.sin((e[0] ?? 0) / 2), s2 = Math.sin((e[1] ?? 0) / 2), s3 = Math.sin((e[2] ?? 0) / 2)\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n}\n\n/** A quaternion to Euler XYZ (three.js' default order). */\nexport const eulerFromQuat = (q: readonly number[]): [number, number, number] => {\n const [x = 0, y = 0, z = 0, w = 1] = q\n const m13 = 2 * (x * z + w * y)\n const ey = Math.asin(Math.max(-1, Math.min(1, m13)))\n if (Math.abs(m13) < 0.9999999) return [Math.atan2(-2 * (y * z - w * x), 1 - 2 * (x * x + y * y)), ey, Math.atan2(-2 * (x * y - w * z), 1 - 2 * (y * y + z * z))]\n return [Math.atan2(2 * (y * z + w * x), 1 - 2 * (x * x + z * z)), ey, 0]\n}\n\n/** Spherical interpolation, the short way round. */\nexport const slerpQuat = (a: readonly number[], b: readonly number[], f: number): ClipQuat => {\n const [ax = 0, ay = 0, az = 0, aw = 1] = a\n let [bx = 0, by = 0, bz = 0, bw = 1] = b\n let cos = ax * bx + ay * by + az * bz + aw * bw\n if (cos < 0) {\n cos = -cos\n bx = -bx; by = -by; bz = -bz; bw = -bw\n }\n let ka = 1 - f\n let kb = f\n if (cos < 0.9999) {\n const angle = Math.acos(cos)\n const sin = Math.sin(angle)\n ka = Math.sin((1 - f) * angle) / sin\n kb = Math.sin(f * angle) / sin\n }\n const out: ClipQuat = [ax * ka + bx * kb, ay * ka + by * kb, az * ka + bz * kb, aw * ka + bw * kb]\n const size = Math.hypot(out[0], out[1], out[2], out[3]) || 1\n return [out[0] / size, out[1] / size, out[2] / size, out[3] / size]\n}\n\n/**\n * The turn between two keys. Euler angles cannot be mixed one by one: a door that opens past 90 degrees about y is the key (180, 82, 180)\n * degrees, and mixing those three numbers from (0, 0, 0) tips the door out of its plane on the way. So a turn about one axis (only one\n * angle changes: it may be more than a full turn, a fan or a knob) is mixed as that angle, and any other turn goes the short way round.\n */\nconst mixTurn = (from: readonly number[], to: readonly number[], fraction: number): { euler: [number, number, number]; quat: ClipQuat } => {\n let changed = 0\n for (let i = 0; i < 3; i++) if (Math.abs((to[i] ?? 0) - (from[i] ?? 0)) > 1e-9) changed++\n if (changed <= 1) {\n const euler = mix(from, to, fraction)\n return { euler, quat: quatFromEuler(euler) }\n }\n const quat = slerpQuat(quatFromEuler(from), quatFromEuler(to), fraction)\n return { euler: eulerFromQuat(quat), quat }\n}\n\n/** A pose sampled from a clip: `rotation` is Euler XYZ and `quaternion` the same turn; apply the quaternion on top of the rest rotation (rest × turn). */\nexport interface ClipSample {\n readonly position: [number, number, number]\n readonly rotation: [number, number, number]\n readonly quaternion: ClipQuat\n}\n\nconst IDENTITY: ClipQuat = [0, 0, 0, 1]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys (the turn as in `mixTurn`); a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): ClipSample => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: [0, 0, 0], rotation: [0, 0, 0], quaternion: [...IDENTITY] }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0), quaternion: quatFromEuler(last.rotation) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: [0, 0, 0], rotation: [0, 0, 0], quaternion: [...IDENTITY] }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n const turn = mixTurn(from.rotation, to.rotation, fraction)\n return { position: mix(from.position, to.position, fraction), rotation: turn.euler, quaternion: turn.quat }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n /** The queue runs to empty in the drain of its phase, outside the frame deadline and the budget (the blow's visible effect). Counted apart. Default false. */\n readonly mustDrain?: boolean\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n BREACH_CUT: 'floorplan.breach-cut',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n AUDIO_OCCLUSION: 'audio.occlusion',\n FLUID_FILM: 'fluids.film',\n VEHICLE_LOD_BATCH: 'vehicles.lod-batch',\n SETTLED_BATCH: 'destruction.settled-batch',\n STATIC_BATCH: 'render.static-batch',\n ANIMALS_STATIC_BATCH: 'animals.static-batch',\n CHARACTERS_STATIC_BATCH: 'characters.static-batch',\n HOUSE_SHADOW_BATCH: 'floorplan.shadow-batch',\n DESTRUCTION_PREFIT: 'destruction.prefit',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n // every frame: the walls cut since the last frame are painted once each, and a hole must show in the frame of the blast\n [DEFERRED_QUEUE_ID.BREACH_CUT]: { priority: 260, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_OCCLUSION]: { priority: 190, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.FLUID_FILM]: { priority: 120, phase: 'idle', minEveryFrames: 2 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n [DEFERRED_QUEUE_ID.VEHICLE_LOD_BATCH]: { priority: 90, phase: 'idle', minEveryFrames: 4 },\n [DEFERRED_QUEUE_ID.SETTLED_BATCH]: { priority: 70, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.ANIMALS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.CHARACTERS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.HOUSE_SHADOW_BATCH]: { priority: 50, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.DESTRUCTION_PREFIT]: { priority: 40, phase: 'idle', minEveryFrames: 30 },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\n/** The queues that may register with `mustDrain: true`: a new one needs the owner's decision (CLAUDE.md §15), and `budget.register` throws for any other. */\nexport const MUST_DRAIN_QUEUE_IDS: ReadonlySet<string> = new Set([DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS, DEFERRED_QUEUE_ID.BREACH_CUT])\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n\n/** Drains a queue no budget registered (D2): runs it until `budgetMs` from now. The one place outside game-runtime that times deferred work. */\nexport function drainDetached(queue: DeferredQueue, budgetMs: number, clock: () => number = () => performance.now()): number {\n return queue.run(clock() + budgetMs, clock)\n}\n","/**\n * What an object of a module does beyond what every host does with any piece (open its doors, take it, push it, sit on it): a TV turned on and its channel\n * changed, a tap opened, a washing machine run, a bin given what the hand holds. The module owns the state and the rules (`TestableItem.controls`); the host\n * lists the controls in its menu, runs the one the player picks, lends its hand and its parts, and advances the object every frame.\n */\ntype Vec3Tuple = readonly [number, number, number]\n\n/** What an item works as for an object's uses (`ItemDef.tools` of game-items): a `plunger` pumps a clogged trap. */\nexport const ITEM_TOOLS = ['plunger'] as const\nexport type ItemTool = (typeof ITEM_TOOLS)[number]\n\n/** What the player's hand holds, as an object of the world can take it. */\nexport interface ControlledHand {\n /** The catalogue id of the item. */\n readonly itemId: string\n readonly name: string\n readonly kg: number\n /** Width, height and depth, metres. */\n readonly size: Vec3Tuple\n /** The liquid it holds now, when it is a container with something in it (`water`, `milk`...); `closed`: shut (a capped bottle), it pours nothing until opened. */\n readonly liquid?: { readonly kind: string; readonly litres: number; readonly closed?: boolean }\n /** What the item works as (its catalogue `tools`): an object's use that needs a tool asks for it here, never by the item's id. */\n readonly tools?: readonly ItemTool[]\n}\n\n/** What an object's controls ask of the host. */\nexport interface ItemControlsHost {\n /** What the hand holds now; null when it is empty. */\n hand(): ControlledHand | null\n /** The hand lets go of what it holds inside the object, at `point` (object-local, metres): a thing of the world again, lying there. False when it could not. */\n placeHand(point: Vec3Tuple): boolean\n /** Pours up to `litres` of the hand's liquid into the object; returns the litres that left the hand. */\n pourHand(litres: number): number\n /** Works one of the object's moving parts the host moves itself (a tap handle, a rocker, a lid): `open` true to its open or on end. False when there is no such part. */\n setPart(part: string, open: boolean): boolean\n /** How open that part is now, 0 closed (or off) to 1 open (or on). */\n partOpening(part: string): number\n /** Takes out of the world every loose thing and every drawn content inside the object-local box from `from` to `to` (a bin emptied); returns how many. */\n emptyInside(from: Vec3Tuple, to: Vec3Tuple): number\n /** Tells the player something the object did on its own time (a wash finished). */\n say(text: string): void\n /**\n * The first item of one of the catalogue `ids` the player can use now: the one in the hand first, then the nearest within reach of the player (a cup on the\n * counter, the soap on the basin). Null when there is none. A host without items to lend leaves it out (the uses that need one are then unavailable).\n */\n itemAt?(ids: readonly string[]): ReachedItem | null\n /**\n * The vessel the player can drink from now: an item whose container is open, takes liquid and holds no things (a glass, a mug, a coffee cup; not a mug with a\n * toothbrush in it), the one in the hand first, then the nearest clean one within reach. Known by what the item is, never by its name.\n */\n vesselAt?(): ReachedItem | null\n /**\n * The body steps toward the object-local point `at` for `dt` seconds (up to the sink, to reach under its tap) and turns the eye to it; answers true once it stands\n * there or the object stops it. A host whose player does not walk leaves it out (the use then reaches from where the body is).\n */\n approach?(at: Vec3Tuple, dt: number): boolean\n /** Both hands are free: nothing held, no weapon or tool in them (what drinking from the cupped hands needs). */\n handsFree?(): boolean\n /** The items of one of the catalogue `ids` lying inside the object-local box from `from` to `to` (the dishes in a sink's basin). */\n itemsInside?(ids: readonly string[], from: Vec3Tuple, to: Vec3Tuple): readonly ReachedItem[]\n /** Takes one dose (`dose` in the item's own unit, its usual dose when left out) out of a consumable item (detergent, soap, toothpaste). */\n takeDose?(objectId: string, dose?: number): ItemDose\n /**\n * The player's body plays the hand use `clip` (a hand use of the host's catalogue: `wash_dishes`, `fill_cup`, `drink`), with the item `objectId` in the hand when given;\n * `at` (object-local) is where the use reaches to: the hands bring the glass, the dish or themselves under the stream there (the use's `reach` keys).\n */\n playUse?(clip: string, objectId?: string, at?: Vec3Tuple): boolean\n /** The hand takes the item `objectId` (a cup from the counter); false when it cannot. */\n holdItem?(objectId: string): boolean\n /** The item `objectId` goes down, still, at the object-local `point` (a washed plate on the drainboard, the cup back where it was). */\n placeItem?(objectId: string, point: Vec3Tuple): boolean\n /** How dirty the item `objectId` is now, 0 clean to 1 caked (what is left of food on a plate); the host keeps and draws it. */\n setDirt?(objectId: string, dirt: number): void\n /** Pours up to `litres` of `liquid` into the item `objectId` (a cup under the tap); returns the litres it took. */\n fillItem?(objectId: string, liquid: string, litres: number): number\n /** The player drinks up to `litres` out of the item `objectId`; returns the litres drunk. */\n drinkItem?(objectId: string, litres: number): number\n /**\n * The player drinks up to `litres` of `liquid` caught in the cupped hands from a running fixture's stream; the hands are wet and what they do not hold runs off\n * through the fingers. Returns the litres drunk.\n */\n drinkFromHands?(liquid: string, litres: number): number\n /** Scrubs `amount` (0..1 of a full layer) of foam onto `target` (an item's `objectId`, or a part of the body: `hands`, `hair`, `body`, `mouth`); returns the foam on it now, 0..1. */\n lather?(target: string, amount: number): number\n /** Runs `flowLps` litres per second of water over `target` for `dt` seconds; returns the foam left on it, 0..1. */\n rinse?(target: string, flowLps: number, dt: number): number\n /**\n * The body that uses the object (the player's): its sex decides how it uses a toilet, and it takes the pose of a use that has one (`ItemControlResult.body`). The\n * object runs the use's time and tells the body; the host only moves and draws it. A host without a body leaves it out: the uses that need one are then refused,\n * with the reason, never answered as done. This and the four below are optional for a host whose objects have no such use; an object that needs them refuses\n * its uses without them.\n */\n body?(): ControlledBody | null\n /** Shows `litres` of liquid in the object's basin (`BasinSpec.id` of game-interactables): the host's liquid there rises or falls to it. */\n setBasin?(basin: string, litres: number): void\n /** Liquid that went over the object's rim at `point` (object-local, metres), gathered by the object over a short while: the host spills it there as its own liquid (a puddle). */\n spill?(point: Vec3Tuple, litres: number, liquid: string): void\n /** The loose things of the world lying inside the object-local box from `from` to `to` (an object dropped in a toilet bowl), with their size. */\n looseInside?(from: Vec3Tuple, to: Vec3Tuple): readonly LooseThing[]\n /**\n * The loose thing `id` goes down the object's drain toward `point` (object-local): `progress` runs from 0 where it lay to 1, once a step while it goes (the object\n * runs the time). At 1 it leaves the world; the host draws the way down.\n */\n swallow?(id: string, point: Vec3Tuple, progress: number): void\n}\n\n/** An item the host lends an object's use (`ItemControlsHost.itemAt`). */\nexport interface ReachedItem {\n /** The host's id of the item in the world. */\n readonly objectId: string\n /** Its catalogue id. */\n readonly itemId: string\n /** Localized. */\n readonly name: string\n /** In the player's hand, within the player's reach, or inside a box of the object. */\n readonly where: 'hand' | 'reach' | 'inside'\n /** Where it lies now, object-local metres (the place a cup goes back to). */\n readonly at?: Vec3Tuple\n /** 0 clean to 1 caked. */\n readonly dirt?: number\n /** Share of a consumable still in it, 0 (spent) to 1 (full). */\n readonly remaining?: number\n /** The liquid it holds now and how much it takes full, litres. */\n readonly liquid?: { readonly kind?: string; readonly litres: number; readonly capacity: number }\n}\n\n/** What one dose taken out of a consumable did (`ItemControlsHost.takeDose`): how much came out, whether it was less than asked, and whether it is spent now. */\nexport interface ItemDose {\n readonly taken: number\n readonly short: boolean\n readonly empty: boolean\n}\n\n/**\n * What the body does to work a control (CLAUDE.md §18: every action has a body animation): the hand reaches the point and `press`es a button, `turn`s a knob or a tap's\n * handle, `flip`s a rocker or a lever, `strike`s a match at a burner, `pour`s what it holds over a bowl, `put_in` lets what it holds go inside a container, `tip`s a\n * container over to empty it, `stow`s the thing aimed at into the bag on the body, holds a paper up to the eyes to `read` it, or closes on a pull, a latch or a curtain's edge and\n * `pull`s it toward the body (a drawer, a cabinet's door, a gate, a curtain drawn).\n */\nexport type BodyGesture = 'press' | 'turn' | 'flip' | 'strike' | 'pour' | 'put_in' | 'tip' | 'stow' | 'read' | 'pull'\n\n/** Why a body cannot take a use's pose (`ControlledBody.blocked`): the object has no such seat, the object is not there, the body is busy with another. */\nexport type ControlBodyBlock = 'no_seat' | 'object_gone' | 'busy'\n\n/**\n * The body that uses an object (`ItemControlsHost.body`). The object decides and times what the body does for a use (`ControlBodyAction`): it asks `blocked` before\n * it answers the use is available, `begin` when it runs, `step` once a step with the time, and `end` when the seconds are over; the host moves and draws the body.\n */\nexport interface ControlledBody {\n readonly sex: 'male' | 'female'\n /** Why the body cannot take `action` now, or null when it can. */\n blocked(action: ControlBodyAction): ControlBodyBlock | null\n /** The body takes the action's pose: seated on its seat, or on its feet at its spot facing the object with the walk held. False when it could not. */\n begin(action: ControlBodyAction): boolean\n /** While it lasts: `time` seconds since it began and `progress` 0 to 1 of its length, for the host to draw the pose. False when the body has left it (got up, walked off). */\n step(time: number, progress: number): boolean\n /** Its seconds are over (or the object left the world): up from the seat at its exit, or the walk let go. */\n end(): void\n}\n\n/** Seconds of one push and pull of a plunger: the strokes the object counts (the clog it breaks) and the ones the body draws are the same. */\nexport const PLUNGE_STROKE_SECONDS = 0.8\n\n/** A loose thing of the world inside an object (`ItemControlsHost.looseInside`). */\nexport interface LooseThing {\n readonly id: string\n /** Width, height and depth, metres. */\n readonly size: Vec3Tuple\n readonly kg: number\n}\n\n/**\n * What the body does while a control runs (`ItemControlResult.body`), for the host to animate: `relieve_stand` stands at `at` facing `faces` (a man peeing in a\n * toilet), `relieve_sit` sits on the object's seat `seat` (peeing or pooing seated), `plunge` stands at `at` working a plunger in the bowl at `faces`.\n */\nexport interface ControlBodyAction {\n readonly pose: 'relieve_stand' | 'relieve_sit' | 'plunge'\n readonly seconds: number\n /** Object-local point under the feet (standing poses). */\n readonly at?: Vec3Tuple\n /** Object-local point the body faces. */\n readonly faces?: Vec3Tuple\n /** The object's seat the body sits on (`relieve_sit`). */\n readonly seat?: string\n}\n\n/** One control of an object as the host lists it. */\nexport interface ItemControl {\n readonly id: string\n /** What the body does to work it; with `at`, the host's body plays it and runs the control when the hand gets there. Absent: the host runs it at once. */\n readonly gesture?: BodyGesture\n /** Where the hand goes, object-local metres (the button, the knob, the inside of the bin). */\n readonly at?: Vec3Tuple\n /** Localized, the verb first (`Ligar a TV`, `Trocar de canal`). */\n readonly label: string\n /** False when it cannot be used now: the host still lists it, greyed, with `reason`. */\n readonly available: boolean\n /** Localized, why it cannot be used now. */\n readonly reason?: string\n}\n\n/** What running a control did, in words for the player. */\nexport interface ItemControlResult {\n readonly ok: boolean\n readonly text: string\n /** What the body does for it, which the host animates (CLAUDE.md §18). */\n readonly body?: ControlBodyAction\n}\n\n/** The controls of one object in the world (`TestableItem.controls`). */\nexport interface ItemControls {\n /** The controls the object offers now, in the order the menu shows them. */\n list(host: ItemControlsHost): readonly ItemControl[]\n run(id: string, host: ItemControlsHost): ItemControlResult\n /** Advances the object's own time (a program running, a fire burning, a flush) by `dt` seconds. */\n update(dt: number, host: ItemControlsHost): void\n /** Lets go of what the controls drew or kept; called when the object leaves the world. */\n dispose(): void\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A picture of the real thing the card is about, with its author and licence: the host shows it on the card, linked to `page`. */\n readonly image?: { readonly url: string; readonly alt: string; readonly credit?: string; readonly page?: string }\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n\n/** A fixed box a module gives the host as the body of an obstacle (`ModuleHost.addBlocker`): centre and half sizes in the world, the turn as a quaternion (default none). */\nexport interface HostSolid {\n readonly center: readonly [number, number, number]\n readonly half: readonly [number, number, number]\n readonly rotation?: readonly [number, number, number, number]\n /** Names the box across calls (a box measured again is the same box): without it, the place in the list. */\n readonly key?: string\n}\n\n/**\n * The fixed box of `footprint` on `object`, `height` metres tall from the floor: the body of what `footprintBlocker` stops the player at. An object out of the scene (no parent) has no box.\n * The turn is read from the object's x and z columns (a turn about the vertical axis, as the blocker reads it).\n */\nexport function footprintSolid(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined), height: number): HostSolid[] {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return []\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n const sx = Math.hypot(e[0] as number, e[2] as number) || 1\n const sz = Math.hypot(e[8] as number, e[10] as number) || 1\n const angle = Math.atan2(-(e[2] as number), e[0] as number)\n const cx = (fp.minX + fp.maxX) / 2\n const cz = (fp.minZ + fp.maxZ) / 2\n const centreX = (e[12] as number) + cx * (e[0] as number) + cz * (e[8] as number)\n const centreZ = (e[14] as number) + cx * (e[2] as number) + cz * (e[10] as number)\n return [{ center: [centreX, height / 2, centreZ], half: [((fp.maxX - fp.minX) / 2) * sx, height / 2, ((fp.maxZ - fp.minZ) / 2) * sz], rotation: [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)] }]\n}\n","/** A world rectangle `[x0, z0, x1, z1]`, metres. */\nexport type RainCoverBounds = readonly [x0: number, z0: number, x1: number, z1: number]\n\n/**\n * Something with a roof or a slab over it (a house, a shed, a bus stop, a car): it says, for a point on the ground plan, how high the cover over it is.\n * The rain asks before it falls, splashes or wets the ground: under a cover there is none.\n */\nexport interface RainCoverSource {\n /** Where the source may cover anything; a point outside is never asked. */\n bounds(): RainCoverBounds\n /** Top (world y, metres) of the highest intact roof or slab over (x, z); `undefined` for open sky, or for a hole a blast or a collapse opened. */\n coverTopAt(x: number, z: number): number | undefined\n /** Grows whenever the covers change (a roof panel broke, a hole opened): whoever caches reads it. */\n version(): number\n}\n\n/** What the rain reads (`ModuleHost.rainCover`): every source of the host together. */\nexport interface RainCover {\n /** The highest cover over (x, z) among the sources, or `undefined` for open sky. */\n coverTopAt(x: number, z: number): number | undefined\n /** Changes whenever a source is added or removed or one of them changes. */\n version(): number\n /** True while there is no source: the rain skips the test. */\n isEmpty(): boolean\n /** Adds a source; returns the function that takes it away. */\n add(source: RainCoverSource): () => void\n}\n\nexport function createRainCover(): RainCover {\n const sources = new Set<RainCoverSource>()\n let list: RainCoverSource[] = []\n let membership = 0\n return {\n coverTopAt(x, z) {\n let top: number | undefined\n for (const source of list) {\n const [x0, z0, x1, z1] = source.bounds()\n if (x < x0 || x > x1 || z < z0 || z > z1) continue\n const value = source.coverTopAt(x, z)\n if (value !== undefined && (top === undefined || value > top)) top = value\n }\n return top\n },\n version() {\n let sum = membership\n for (const source of list) sum += source.version()\n return sum\n },\n isEmpty: () => list.length === 0,\n add(source) {\n sources.add(source)\n list = [...sources]\n membership++\n return () => {\n if (!sources.delete(source)) return\n list = [...sources]\n membership++\n }\n },\n }\n}\n\nexport type GridRainCoverOptions = {\n readonly bounds: RainCoverBounds\n /** Side of a cell, metres (default 0.25: a blast hole is bigger). */\n readonly cellSize?: number\n /** The exact answer at a cell centre; called again for every cell only after `invalidate`. */\n readonly coverTopAt: (x: number, z: number) => number | undefined\n}\n\nexport type GridRainCoverSource = RainCoverSource & {\n /** The covers changed (a roof panel broke): the grid is cut again on the next question, and `version` grows. */\n invalidate(): void\n}\n\nconst NO_COVER = -Infinity\n\n/** A source answered from a grid cut once from `coverTopAt`: a question is two array reads, however many panels the roof has. */\nexport function createGridRainCover(options: GridRainCoverOptions): GridRainCoverSource {\n const [x0, z0, x1, z1] = options.bounds\n const cell = options.cellSize ?? 0.25\n const columns = Math.max(1, Math.ceil((x1 - x0) / cell))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cell))\n const cells = new Float32Array(columns * rows)\n let revision = 0\n let isCut = false\n const cut = (): void => {\n for (let row = 0; row < rows; row++) {\n for (let column = 0; column < columns; column++) {\n const top = options.coverTopAt(x0 + (column + 0.5) * cell, z0 + (row + 0.5) * cell)\n cells[row * columns + column] = top === undefined ? NO_COVER : top\n }\n }\n isCut = true\n }\n return {\n bounds: () => options.bounds,\n coverTopAt(x, z) {\n if (!isCut) cut()\n const column = Math.floor((x - x0) / cell)\n const row = Math.floor((z - z0) / cell)\n if (column < 0 || row < 0 || column >= columns || row >= rows) return undefined\n const top = cells[row * columns + column]!\n return top === NO_COVER ? undefined : top\n },\n version: () => revision,\n invalidate() {\n isCut = false\n revision++\n },\n }\n}\n\n/** A roof or slab seen from above: the rectangle it covers and the height of its top. */\nexport type RainCoverRect = { readonly bounds: RainCoverBounds; readonly top: number }\n\n/** A round opening in a cover (a blast hole), centre and radius in the ground plan. */\nexport type RainCoverHole = { readonly x: number; readonly z: number; readonly radius: number }\n\n/** The exact answer for a list of rectangles with holes: the highest rectangle over the point whose hole does not take the point. */\nexport function rainCoverTopOf(rects: readonly RainCoverRect[], holes: readonly RainCoverHole[], x: number, z: number): number | undefined {\n let top: number | undefined\n for (const rect of rects) {\n if (x < rect.bounds[0] || x > rect.bounds[2] || z < rect.bounds[1] || z > rect.bounds[3]) continue\n if (top !== undefined && rect.top <= top) continue\n if (holes.some((hole) => (x - hole.x) ** 2 + (z - hole.z) ** 2 <= hole.radius ** 2)) continue\n top = rect.top\n }\n return top\n}\n\n/** A roof seen from above as a turned rectangle: its centre on the ground plan, half sides along its own axes, the turn about y and the height of its top. */\nexport type RainCoverFootprint = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly yaw: number; readonly top: number }\n\nexport type FootprintRainCoverSource = RainCoverSource & {\n /**\n * Puts the roofs and the openings where they are now (a car moved, a window broke). The answer follows at once; the version grows only with `bumpVersion`,\n * which a mover asks once it has gone far enough for whoever caches (the far curtain) to cut again.\n */\n set(footprints: readonly RainCoverFootprint[], openings: readonly RainCoverFootprint[], bumpVersion: boolean): void\n}\n\ntype Prepared = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly cos: number; readonly sin: number; readonly top: number }\n\nconst prepare = (f: RainCoverFootprint): Prepared => ({ x: f.x, z: f.z, halfX: f.halfX, halfZ: f.halfZ, cos: Math.cos(f.yaw), sin: Math.sin(f.yaw), top: f.top })\n\nconst insideTurned = (f: Prepared, x: number, z: number): boolean => {\n const dx = x - f.x\n const dz = z - f.z\n return Math.abs(dx * f.cos + dz * f.sin) <= f.halfX && Math.abs(-dx * f.sin + dz * f.cos) <= f.halfZ\n}\n\n/**\n * A source of turned rectangles with openings (a car's cabin, a tent, a kiosk): a question is a few multiplications per rectangle, no allocation, so the near rain\n * asks it for every drop. `set` moves the rectangles whenever the thing moves; nothing else is cut or cached.\n */\nexport function createFootprintRainCover(): FootprintRainCoverSource {\n let roofs: Prepared[] = []\n let openings: Prepared[] = []\n let bounds: RainCoverBounds = [0, 0, 0, 0]\n let revision = 0\n return {\n bounds: () => bounds,\n version: () => revision,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) {\n if ((top !== undefined && roof.top <= top) || !insideTurned(roof, x, z)) continue\n top = roof.top\n }\n if (top === undefined) return undefined\n for (const opening of openings) if (insideTurned(opening, x, z)) return undefined\n return top\n },\n set(footprints, cutouts, bumpVersion) {\n roofs = footprints.map(prepare)\n openings = cutouts.map(prepare)\n let x0 = Infinity\n let z0 = Infinity\n let x1 = -Infinity\n let z1 = -Infinity\n for (const roof of roofs) {\n const reach = Math.abs(roof.halfX * roof.cos) + Math.abs(roof.halfZ * roof.sin)\n const reachZ = Math.abs(roof.halfX * roof.sin) + Math.abs(roof.halfZ * roof.cos)\n x0 = Math.min(x0, roof.x - reach)\n x1 = Math.max(x1, roof.x + reach)\n z0 = Math.min(z0, roof.z - reachZ)\n z1 = Math.max(z1, roof.z + reachZ)\n }\n bounds = roofs.length === 0 ? [0, 0, 0, 0] : [x0, z0, x1, z1]\n if (bumpVersion) revision++\n },\n }\n}\n\n/** The most cells a fixed footprint cover cuts: a wide district gets a coarser cell instead of a bigger grid. */\nconst FIXED_COVER_MAX_CELLS = 1_000_000\n\n/** A source of turned rectangles that never move (the buildings of a district, a tent, a kiosk): answered from a grid cut once, two array reads a question however many roofs there are. */\nexport function createFixedFootprintRainCover(footprints: readonly RainCoverFootprint[], cellSize = 0.5): RainCoverSource {\n const roofs = footprints.map(prepare)\n if (roofs.length === 0) return { bounds: () => [0, 0, 0, 0], coverTopAt: () => undefined, version: () => 0 }\n const x0 = Math.min(...roofs.map((r) => r.x - Math.abs(r.halfX * r.cos) - Math.abs(r.halfZ * r.sin)))\n const x1 = Math.max(...roofs.map((r) => r.x + Math.abs(r.halfX * r.cos) + Math.abs(r.halfZ * r.sin)))\n const z0 = Math.min(...roofs.map((r) => r.z - Math.abs(r.halfX * r.sin) - Math.abs(r.halfZ * r.cos)))\n const z1 = Math.max(...roofs.map((r) => r.z + Math.abs(r.halfX * r.sin) + Math.abs(r.halfZ * r.cos)))\n const cell = Math.max(cellSize, Math.sqrt(((x1 - x0) * (z1 - z0)) / FIXED_COVER_MAX_CELLS))\n return createGridRainCover({\n bounds: [x0, z0, x1, z1],\n cellSize: cell,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) if ((top === undefined || roof.top > top) && insideTurned(roof, x, z)) top = roof.top\n return top\n },\n })\n}\n","/** What an obstacle on the ground is to a walker: a solid (a wall, a lot wall, a fence, a board) or a door (a door or a gate, which opens and can be broken). */\nexport const NAV_OBSTACLE_KIND = { SOLID: 'solid', DOOR: 'door' } as const\nexport type NavObstacleKind = (typeof NAV_OBSTACLE_KIND)[keyof typeof NAV_OBSTACLE_KIND]\n\n/** A box of an obstacle on the ground: world metres `[x0, z0, x1, z1]` and how high it stands over the ground (a low remnant of a wall can be climbed). */\nexport type NavObstacleBox = {\n readonly rect: readonly [number, number, number, number]\n readonly height: number\n}\n\n/**\n * One thing that stops a walker on the ground, as the SDK that builds it publishes it for a navigation grid (the crowd's): a whole wall is one box, a wall a blast\n * cut stands in the boxes of what is left of it, a wall that is gone has none. A door is one box, passable while `open`.\n */\nexport type NavObstacle = {\n /** Stable for the life of the source: a change names the same obstacle again. */\n readonly id: string\n readonly kind: NavObstacleKind\n readonly boxes: readonly NavObstacleBox[]\n /** A door or a gate that lets walkers through now (always false for a solid). */\n readonly open: boolean\n /** A door the barricade's boards cover, each making it harder to break (0 for none). */\n readonly boards: number\n}\n\n/**\n * The obstacles one or more SDKs put on the ground (the houses' walls, doors, lot walls and gates), for whoever keeps a navigation grid. Pulled once per fixed step, so a\n * grid that follows it changes at the same step on every run.\n */\nexport type NavObstacleSource = {\n /** Every obstacle as it stands now. */\n obstacles(): readonly NavObstacle[]\n /** The obstacles that changed since the last call (a door opened or closed, a wall cut or gone); empty when none did. */\n changes(): readonly NavObstacle[]\n /** A walker broke the door `id` open (the horde hit it until it gave way): the owner shows it open. */\n breakDoor(id: string): void\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n cobble: 'concrete',\n paver: 'concrete',\n plaster: 'concrete',\n asphalt: 'asphalt',\n wood_soft: 'wood',\n wood_hard: 'wood',\n green_wood: 'wood',\n plywood: 'wood',\n mdf: 'wood',\n ceramic: 'tile',\n plastic: 'tile',\n soil: 'dirt',\n mud: 'dirt',\n clay: 'dirt',\n laterite: 'gravel',\n wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n // no snow surface yet: packed snow crunches closest to sand underfoot\n snow: 'sand',\n steel: 'metal',\n spring_steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * The worker coordinator as the packages see it: a package declares its heavy work as a task kind (a pure function of plain data) or a\n * resident kind (an instance pinned to one worker), and takes a `WorkerCoordinator` through its options. The implementation is\n * `@adatechnology/game-workers`; nothing in a package makes a `Worker` of its own (CLAUDE.md §14).\n */\n\n/**\n * The pools a kind runs in. `sim`: physics and anything the next frames read; the result is applied in a fixed frame and computed on the\n * main thread when the worker is late, so it is the same whichever thread made it. `build`: generation at load (shapes, colliders,\n * normals), no frame deadline. `background`: the living world far from the player, the lowest priority, never takes a `sim` worker.\n */\nexport const WORKER_LANES = ['sim', 'build', 'background'] as const\nexport type WorkerLane = (typeof WORKER_LANES)[number]\n\n/**\n * What happens when no worker answers in time (or there is none). `sync`: the main thread runs the same kernel and the late answer is\n * thrown away (the only rule of the `sim` lane). `drop`: the job is given up and its promise rejects with `WorkerTaskDropped`.\n * `keep-waiting`: it waits for a worker (a fresh one after a crash); with no worker at all it runs on the main thread.\n */\nexport const WORKER_LATE_RULES = ['sync', 'drop', 'keep-waiting'] as const\nexport type WorkerLateRule = (typeof WORKER_LATE_RULES)[number]\n\n/** How a kind is scheduled: the defaults the kind declares, any of which a game may override by id (`CoordinatorOptions.kinds`). */\nexport interface WorkerKindSchedule {\n readonly lane: WorkerLane\n /** Higher runs first, as `DEFERRED_PRIORITY`. */\n readonly priority: number\n /** Frames between the frame a job is submitted in and the frame its result is applied in (`sim` lane; default 1). */\n readonly latencyFrames?: number\n readonly late: WorkerLateRule\n}\n\n/**\n * A job with no state: plain data in, plain data out, through `run`, the same function in the worker and on the main thread. `run` reads\n * nothing but its input (a seed travels inside it), so the bytes out are the same whichever thread ran it.\n */\nexport interface TaskKind<In, Out> extends WorkerKindSchedule {\n /** `package.thing`, unique in a coordinator: `destruction.ground-tiles`. */\n readonly id: string\n readonly kind: 'task'\n run(input: In): Out\n /** The buffers of the output to transfer back (zero copy). The input is copied, never transferred, when `late` is `sync` (unless `transferAwaitedInput`): the main thread may still need it. */\n transferOutput?(value: Out): readonly ArrayBuffer[]\n /** The buffers of the input to transfer when `late` is not `sync` (and on awaited jobs of a `sync` kind with `transferAwaitedInput`). */\n transferInput?(value: In): readonly ArrayBuffer[]\n /**\n * With `late: 'sync'`, transfer the input (`transferInput`) on awaited jobs (`run`) too, instead of copying it: for a caller that keeps its own copy of the input for its\n * own fallback (the ground tiles). Once sent, such a job is never run on the main thread (its input is gone): a worker that dies holding it rejects its promise with an\n * error named `WORKER_INPUT_LOST` (`isWorkerInputLost`: the caller makes it from its own copy), one that answers with an error rejects with that error. Jobs read through\n * `submit`/`collect` still copy their input.\n * Needs `transferInput`.\n */\n readonly transferAwaitedInput?: boolean\n /** One input each worker runs once at `warm` (the JIT compiles the kernel before the first real job). */\n readonly warmup?: In\n}\n\n/** One instance of a resident kind: built from `init` once per worker, then stepped. */\nexport interface ResidentInstance<Step, Result> {\n step(input: Step): Result\n dispose?(): void\n}\n\n/**\n * A kind with an instance pinned to one worker (the crowd physics, a region of the world). With `late: 'sync'` the step must be a pure\n * function of `init` and the step's input (the state lives on the main thread and travels each step), so a main-thread instance gives the\n * same result; a resident that keeps its own state in the worker uses `drop` or `keep-waiting`.\n */\nexport interface ResidentKind<Init, Step, Result> extends WorkerKindSchedule {\n readonly id: string\n readonly kind: 'resident'\n create(init: Init): ResidentInstance<Step, Result>\n transferOutput?(value: Result): readonly ArrayBuffer[]\n transferInput?(value: Step): readonly ArrayBuffer[]\n}\n\n/** A kind of any input and output, for registries (the methods are bivariant, so every `TaskKind<In, Out>` is one). */\nexport type AnyTaskKind = TaskKind<unknown, unknown>\nexport type AnyResidentKind = ResidentKind<unknown, unknown, unknown>\nexport type AnyWorkerKind = AnyTaskKind | AnyResidentKind\n\n/** Where a result came from. `worker`: on time. `main`: the main thread ran it (late worker, crash, or no worker). */\nexport type WorkerResultSource = 'worker' | 'main'\n\n/** A job of the `sim` lane: its result is read in `dueFrame`, never before, whichever thread made it. */\nexport interface TaskHandle<Out> {\n readonly dueFrame: number\n /**\n * The result in `frame` (>= `dueFrame`, an error before it): the worker's when it is back, otherwise the kernel run here now and the\n * late answer thrown away. The same value on every later call.\n */\n collect(frame: number): Out\n /** Resolves when the result exists (worker or main thread); for the `build` and `background` lanes. */\n readonly promise: Promise<Out>\n /** Where the collected result came from; `null` before `collect` or the promise settles. */\n readonly source: WorkerResultSource | null\n /** Drops a job not yet collected: it leaves the queue, or its answer is thrown away. */\n cancel(): void\n}\n\nexport interface ResidentHandle<Step, Result> {\n readonly id: string\n /** Steps the instance with `input` in `frame`; read the result with `collect(dueFrame)`. The input is the coordinator's from here on. */\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result>\n dispose(): void\n}\n\nexport interface WorkerKindStats {\n readonly id: string\n readonly lane: WorkerLane\n readonly submitted: number\n /** Answers that came back from a worker, on time or late. */\n readonly answered: number\n /** Results that came from a worker before they were needed. */\n readonly onTime: number\n /** Results the main thread computed (late worker, crash, no worker). */\n readonly fallback: number\n readonly dropped: number\n readonly cancelled: number\n readonly failed: number\n /** Milliseconds inside the worker, summed over `answered`. */\n readonly workerMs: number\n /** Milliseconds on the main thread, summed (fallbacks). */\n readonly mainMs: number\n /** Milliseconds waiting in the queue before a worker took the job, summed. */\n readonly queueMs: number\n}\n\nexport interface WorkerCoordinatorStats {\n readonly workers: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n readonly queued: number\n readonly running: number\n readonly respawned: number\n readonly kinds: readonly WorkerKindStats[]\n}\n\nexport interface WorkerCoordinator {\n /** A `sim` job submitted in `at.frame` (default: the last `tick`), due `latencyFrames` later. The input is the coordinator's from here on: do not change it. */\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out>\n /**\n * A job awaited instead of collected: a `build` or `background` job, or a `sim` job in the simulation thread (which may wait; with no worker\n * it runs on this thread). A promise, cancelled through `signal`.\n */\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out>\n /** An instance of a resident kind on one worker (or on the main thread when there is none). */\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result>\n /** The frame now; the runtime calls it at the start of each fixed step. Jobs are ordered by priority, then by the nearest due frame. */\n tick(frame: number): void\n /** Starts the workers and runs each kind's `warmup` in every worker; rejects when a worker does not know one of the kinds. */\n warm(kinds: readonly AnyWorkerKind[]): Promise<void>\n /** The schedule a kind runs with here (its own, with the game's overrides). */\n scheduleOf(kind: AnyWorkerKind): WorkerKindSchedule\n stats(): WorkerCoordinatorStats\n dispose(): void\n}\n\n/** The ids of the kit's kinds (`TaskKind.id` / `ResidentKind.id`), what `WORKER_KIND_DEFAULTS` is keyed by. */\nexport const WORKER_KIND_ID = {\n GROUND_TILES: 'destruction.ground-tiles',\n CROWD_PHYSICS: 'crowd.physics',\n PIECE_BOXES: 'destruction.piece-boxes',\n STATIC_COLLIDERS: 'destruction.static-colliders',\n SHAPES_GENERATE: 'shapes.generate',\n WORLD_REGION: 'world.region',\n VEHICLE_HULL_PLAN: 'vehicles.hull-plan',\n} as const\n\n/** Default schedule of the kit's kinds; each kind carries its own copy, a game overrides any of them by id. */\nexport const WORKER_KIND_DEFAULTS = {\n [WORKER_KIND_ID.GROUND_TILES]: { lane: 'sim', priority: 300, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.CROWD_PHYSICS]: { lane: 'sim', priority: 250, latencyFrames: 1, late: 'sync' },\n [WORKER_KIND_ID.PIECE_BOXES]: { lane: 'sim', priority: 200, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: 'build', priority: 150, late: 'sync' },\n [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: 'build', priority: 100, late: 'sync' },\n [WORKER_KIND_ID.WORLD_REGION]: { lane: 'background', priority: 10, latencyFrames: 10, late: 'drop' },\n [WORKER_KIND_ID.VEHICLE_HULL_PLAN]: { lane: 'build', priority: 120, late: 'keep-waiting' },\n} as const satisfies Readonly<Record<string, WorkerKindSchedule>>\n\n/** The name of the error an awaited job with a transferred input (`transferAwaitedInput`) rejects with when its worker died holding it. */\nexport const WORKER_INPUT_LOST = 'WorkerTaskInputLost'\n\n/** Whether a rejection is that of a job whose transferred input was lost with its worker (`WORKER_INPUT_LOST`): the caller's own fallback makes it, nothing else is wrong. */\nexport const isWorkerInputLost = (error: unknown): boolean => error instanceof Error && error.name === WORKER_INPUT_LOST\n\n/*\n * The simulation thread (spec 009, T22): a game's whole fixed step in one worker that may wait. A package declares its simulation as a\n * `SimModule`; `@adatechnology/game-workers` runs it (`installSimThread`, `startSimThread`, `runSimInline`).\n */\n\n/** One running simulation, built in the simulation thread from the start message's `init`. */\nexport interface SimInstance {\n /**\n * One fixed step. It may return a promise: the loop waits for it (jobs handed to the coordinator are awaited, not raced against a frame),\n * so the result never depends on how fast the other workers were.\n */\n step(frame: number, dt: number, commands: readonly Float64Array[]): void | Promise<void>\n /** Writes the state the page draws into `out` (the snapshot's bytes, `snapshotBytes` long). */\n write(out: Uint8Array, frame: number): void\n dispose?(): void\n}\n\n/** What the simulation thread can build, by id (the worker's file registers every module the game starts). */\nexport interface SimModule<Init> {\n /** `package.thing`: `crowd.horde`. */\n readonly id: string\n create(init: Init): SimInstance | Promise<SimInstance>\n}\nexport type AnySimModule = SimModule<unknown>\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n BendHinge,\n Dent,\n DestructibleSpec,\n BlastCasing,\n BlastCharge,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartAperture,\n PartShape,\n PartSpec,\n CarryHands,\n PartBreach,\n PartState,\n PartStatus,\n PartSolid,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n GroundLoss,\n PartSettlement,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { chargeFireball, fireballDose, fuelFireball, ignitionDose } from './fireball'\nexport { TNT_JOULES, reflectedLoad, waveWork } from './blast-wave'\nexport type { WaveLoad, WaveWork, WaveWorkInput } from './blast-wave'\nexport type { Fireball } from './fireball'\nexport { bodyMass, FRAGMENT_COVER, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, launchBody, stepKnock, takeLaunch } from './blast-knock'\nexport { blastBodySpeed, bodyImpulse, DEFAULT_BLAST_IMPULSE, sideOnImpulse, sideOnOverpressure } from './blast-impulse'\nexport type { BlastImpulseOptions } from './blast-impulse'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, DrawnCollider, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport type { ToolCondition } from './tool-condition'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { FIT_REJECT_REASONS, SEAT_ROLES } from './body-measures'\nexport type { BodyMeasures, DoorOpening, FitRejectReason, FitResult, SeatRole, SeatSpace } from './body-measures'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandSeat, HandTargetSource, HandTargets, MuzzlePose, MuzzleSource, ToolHand } from './hands'\nexport { CARRY_HANDLE_TAG, FIRST_PERSON_LAYER } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectPose, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, eulerFromQuat, leadClipEvents, quatFromEuler, sampleClip, scaleClip, slerpQuat, toolAnimationStep } from './tool-animation'\nexport type { ClipQuat, ClipSample, ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, MUST_DRAIN_QUEUE_IDS, checkDeferredQueue, drainDetached } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { BodyGesture, ControlBodyAction, ControlBodyBlock, ControlledBody, ControlledHand, ItemControl, ItemControlResult, ItemControls, ItemControlsHost, ItemDose, ItemTool, LooseThing, ReachedItem } from './item-controls'\nexport { ITEM_TOOLS, PLUNGE_STROKE_SECONDS } from './item-controls'\nexport type { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleItemUse, ModuleItemWash, ModuleItemConsumable, ModuleScenario, PlayerState, ItemSeat, HostSeatHolder, HostSeatState, HostSeating, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostGesture, HostReach, HostTakenItem, HostTap } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker, footprintSolid } from './footprint'\nexport { createFixedFootprintRainCover, createFootprintRainCover, createGridRainCover, createRainCover, rainCoverTopOf } from './rain-cover'\nexport type { FootprintRainCoverSource, GridRainCoverOptions, GridRainCoverSource, RainCover, RainCoverBounds, RainCoverFootprint, RainCoverHole, RainCoverRect, RainCoverSource } from './rain-cover'\nexport type { UtilityConnection, UtilityNetwork } from './utility'\nexport type { Footprint, FootprintObject, HostSolid } from './footprint'\nexport { NAV_OBSTACLE_KIND } from './nav-obstacles'\nexport type { NavObstacle, NavObstacleBox, NavObstacleKind, NavObstacleSource } from './nav-obstacles'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\nexport { WORKER_INPUT_LOST, WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES, WORKER_LATE_RULES, isWorkerInputLost } from './workers'\nexport type { AnyResidentKind, AnySimModule, AnyTaskKind, AnyWorkerKind, ResidentHandle, ResidentInstance, ResidentKind, SimInstance, SimModule, TaskHandle, TaskKind, WorkerCoordinator, WorkerCoordinatorStats, WorkerKindSchedule, WorkerKindStats, WorkerLane, WorkerLateRule, WorkerResultSource } from './workers'\n","/**\n * The uses of a basin with a trap (a toilet), for `createUses`: relieving oneself in it, with the body standing or seated by its sex and the lid and seat ring\n * set for it, what the body leaves landing in the water as it ends; the flush that pours the cistern into the bowl and primes the siphon; the plunger worked in\n * a clogged trap. The water and what is in it run in the world's drain (`World.drain`); the times run here, the same for every host: what goes over the rim is\n * gathered before the host spills it (`spill`, a puddle), and what the trap swallows goes down over its seconds (`swallow`, with its progress). The host shows\n * the water's litres (`setBasin`) and lends the loose things in the bowl (`looseInside`); a host without one of these refuses the uses (`hostBlocked`).\n */\nimport { PLUNGE_STROKE_SECONDS } from '@adatechnology/game-contracts'\nimport type { ControlBodyAction, ItemControlResult, ItemControlsHost } from '@adatechnology/game-contracts'\n\nimport { CLOGGED, PLUNGER_WATER } from './basin-drain'\nimport type { BasinContentInput, BasinDrain, BasinDrainState } from './basin-drain'\nimport type { BasinSpec, ObjectSpec, RelieveUseSpec, UseSpec, Vec3, World } from './types'\n\nexport type PlungeUseSpec = Extract<UseSpec, { do: 'plunge' }>\n\nexport type Soil = 'clean' | 'urine' | 'feces'\n\nexport interface DrainUses {\n /** Whether the basin has a trap these uses run. */\n has(basin: string): boolean\n /** The first of what these uses need of the host that it lacks (`setBasin`, `spill`, `looseInside`, `swallow`), or null when it has them all. */\n hostBlocked(host: ItemControlsHost): string | null\n /** What the body does to relieve itself (standing by its sex, or seated); null when the host lends no body. */\n relieveBody(use: RelieveUseSpec, host: ItemControlsHost): ControlBodyAction | null\n /** The use runs, the body already in its pose: the lid and the ring set, and what the body leaves on its way to the water. */\n relieve(use: RelieveUseSpec, host: ItemControlsHost, body: ControlBodyAction): ItemControlResult\n /** Why the plunger cannot be worked now, or null when it can. */\n plungeBlocked(use: PlungeUseSpec, host: ItemControlsHost): string | null\n plungeBody(use: PlungeUseSpec): ControlBodyAction\n plunge(use: PlungeUseSpec, body: ControlBodyAction): ItemControlResult\n /** A fixture ran (a flush): its basin takes the cistern's water. False when no trap of these uses takes it. */\n flushed(fixture: string, host: ItemControlsHost | null): boolean\n update(dt: number, host: ItemControlsHost | null): void\n /** The object leaves the world: what was going down the trap is gone at once. */\n dispose(host: ItemControlsHost | null): void\n /** What the body left in the basin and is still in the water. */\n soil(basin: string): Soil\n state(): Readonly<Record<string, BasinDrainState>>\n}\n\nexport interface DrainUsesOptions {\n readonly spec: ObjectSpec\n /** The world that keeps the basins' water (`World.drain`), so a save keeps it, and the object's id there. */\n readonly world: World\n readonly objectId: string\n readonly t: (key: string, vars?: Record<string, string | number>) => string\n}\n\n/** Seconds a body takes to relieve itself when the use does not say. */\nconst RELIEVE_SECONDS = 8\n/** Of the use's seconds, when what the body leaves lands in the water. */\nconst LANDS_AT = 0.7\n/** Litres a flush pours when its fixture does not say (a 6-litre Brazilian cistern). */\nconst FLUSH_LITRES = 6\n/** Seconds a loose thing takes down the trap before it leaves the world. */\nconst SWALLOW_SECONDS = 0.5\n/** Seconds what goes over the rim is gathered before the host spills it (one stain grows, not one per step). */\nconst SPILL_GATHER_SECONDS = 0.25\n/** What a body leaves: the litres of a pee, the lump of a poo and the paper wiped with after it (kg and width, height, depth in metres). */\nconst URINE: BasinContentInput = { kind: 'urine', kg: 0.3, litres: 0.3, size: [0.02, 0.02, 0.02] }\nconst FECES: BasinContentInput = { kind: 'feces', kg: 0.2, size: [0.12, 0.035, 0.035] }\nconst PAPER: BasinContentInput = { kind: 'paper', kg: 0.008, size: [0.06, 0.03, 0.03] }\nconst PEE: readonly BasinContentInput[] = [URINE]\nconst POO: readonly BasinContentInput[] = [FECES, PAPER, PAPER]\n/** What these uses need of the host, besides a body. */\nconst HOST_NEEDS = ['setBasin', 'spill', 'looseInside', 'swallow'] as const\n\ninterface Basin {\n readonly spec: BasinSpec\n readonly drain: BasinDrain\n readonly centre: Vec3\n /** The front of the rim (+z, where a body stands), where the water that rises over it falls. */\n readonly frontRim: Vec3\n clogged: boolean\n overflowing: boolean\n /** Litres gone over the rim not yet spilled, and for how long they have been gathered. */\n spill: number\n spillTime: number\n}\n\ninterface Pending {\n readonly basin: string\n readonly lands: readonly BasinContentInput[]\n left: number\n}\n\ninterface Plunging {\n readonly basin: string\n left: number\n stroke: number\n}\n\ninterface Swallowing {\n readonly id: string\n readonly point: Vec3\n time: number\n}\n\nexport function createDrainUses(options: DrainUsesOptions): DrainUses {\n const { spec, t, world, objectId } = options\n const basins = new Map<string, Basin>()\n for (const b of spec.basins ?? []) {\n const drain = world.drain(objectId, b.id)\n if (!drain) continue\n const centre: Vec3 = [(b.from[0] + b.to[0]) / 2, b.from[1], (b.from[2] + b.to[2]) / 2]\n basins.set(b.id, { spec: b, drain, centre, frontRim: [centre[0], b.to[1], b.to[2]], clogged: false, overflowing: false, spill: 0, spillTime: 0 })\n }\n const flushes = new Map<string, { basin: string; litres: number }>(\n (spec.fixtures ?? []).flatMap((f) => (f.cleans && basins.has(f.cleans) ? [[f.id, { basin: f.cleans, litres: f.volume ?? FLUSH_LITRES }] as const] : [])),\n )\n const list = [...basins.values()]\n /** The drains' states as last handed out: built again only when one of them changed (the drawing reads it every frame). */\n let states: Readonly<Record<string, BasinDrainState>> = {}\n const pending: Pending[] = []\n const swallowing: Swallowing[] = []\n let plunging: Plunging | null = null\n\n const typeKey = `type.${spec.type}`\n const name = (): string => {\n const text = t(typeKey)\n return text === typeKey ? spec.type.replace(/_/g, ' ') : text.charAt(0).toLowerCase() + text.slice(1)\n }\n\n /** The loose things lying in the bowl go into its water, to ride the next siphon. */\n const takeLoose = (b: Basin, host: ItemControlsHost | null): void => {\n const top: Vec3 = [b.spec.to[0], b.spec.to[1] + 0.08, b.spec.to[2]]\n // what the water already holds is known by the drain itself, so a loaded save does not take it twice\n const inWater = new Set(b.drain.state().contents.flatMap((c) => (c.objectId ? [c.objectId] : [])))\n for (const thing of host?.looseInside?.(b.spec.from, top) ?? []) {\n if (inWater.has(thing.id)) continue\n b.drain.add({ kind: 'object', kg: thing.kg, size: thing.size, objectId: thing.id })\n }\n }\n\n const report = (b: Basin, host: ItemControlsHost | null): void => {\n const clogged = b.drain.clog() >= CLOGGED\n if (clogged && !b.clogged) host?.say(t('clogged', { name: name() }))\n b.clogged = clogged\n }\n\n const stepPending = (dt: number): void => {\n let kept = 0\n for (const p of pending) {\n p.left -= dt\n if (p.left > 0) {\n pending[kept++] = p\n continue\n }\n for (const content of p.lands) basins.get(p.basin)?.drain.add(content)\n }\n pending.length = kept\n }\n\n const stepPlunge = (dt: number, host: ItemControlsHost | null): void => {\n if (!plunging) return\n const b = basins.get(plunging.basin)\n plunging.left -= dt\n plunging.stroke += dt\n if (b && plunging.stroke >= PLUNGE_STROKE_SECONDS) {\n plunging.stroke -= PLUNGE_STROKE_SECONDS\n const cause = b.drain.cause()\n b.drain.plunge()\n if (cause !== 'none' && b.drain.cause() === 'none') {\n host?.say(t(cause === 'object' ? 'plunge_object' : 'plunge_cleared', { name: name() }))\n b.clogged = false\n }\n }\n if (plunging.left > 0) return\n if (b && b.drain.clog() >= CLOGGED) host?.say(t('plunge_still', { name: name() }))\n plunging = null\n }\n\n const stepSwallowing = (dt: number, host: ItemControlsHost | null): void => {\n let kept = 0\n for (const s of swallowing) {\n s.time += dt\n const progress = Math.min(1, s.time / SWALLOW_SECONDS)\n host?.swallow?.(s.id, s.point, progress)\n if (progress < 1) swallowing[kept++] = s\n }\n swallowing.length = kept\n }\n\n const stepSpill = (b: Basin, spilled: number, dt: number, host: ItemControlsHost | null): void => {\n if (spilled > 0 && !b.overflowing) host?.say(t('overflow', { name: name() }))\n b.overflowing = spilled > 0\n b.spill += spilled\n if (b.spill <= 0) return\n b.spillTime += dt\n if (b.spillTime < SPILL_GATHER_SECONDS) return\n host?.spill?.(b.frontRim, b.spill, b.drain.dirty() ? 'sewage' : 'water')\n b.spill = 0\n b.spillTime = 0\n }\n\n const stepBasin = (b: Basin, dt: number, host: ItemControlsHost | null): void => {\n const step = b.drain.update(dt)\n for (const id of step.swallowed) swallowing.push({ id, point: b.centre, time: 0 })\n stepSpill(b, step.spilled, dt, host)\n host?.setBasin?.(b.spec.id, b.drain.litres())\n report(b, host)\n }\n\n return {\n has: (basin) => basins.has(basin),\n hostBlocked: (host) => HOST_NEEDS.find((need) => host[need] === undefined) ?? null,\n relieveBody(use, host) {\n const body = host.body?.()\n if (!body) return null\n const seconds = use.seconds ?? RELIEVE_SECONDS\n const b = basins.get(use.basin)\n if (use.kind === 'urine' && use.stand && body.sex === 'male') return { pose: 'relieve_stand', seconds, at: use.stand, faces: b ? b.centre : [0, 0, 0] }\n return { pose: 'relieve_sit', seconds, ...(use.seat ? { seat: use.seat } : {}) }\n },\n relieve(use, host, body) {\n if (use.cover) host.setPart(use.cover, true)\n if (use.ring) host.setPart(use.ring, body.pose === 'relieve_stand')\n pending.push({ basin: use.basin, lands: use.kind === 'urine' ? PEE : POO, left: body.seconds * LANDS_AT })\n return { ok: true, text: t(`done_relieve_${use.kind}`, { name: name() }), body }\n },\n plungeBlocked(use, host) {\n if (!host.hand()?.tools?.includes(use.tool)) return 'needs_plunger'\n const b = basins.get(use.basin)\n return b && b.drain.level() < PLUNGER_WATER ? 'plunge_no_water' : null\n },\n plungeBody(use) {\n const b = basins.get(use.basin)\n return { pose: 'plunge', seconds: use.seconds, at: use.stand, faces: b ? b.centre : [0, 0, 0] }\n },\n plunge(use, body) {\n plunging = { basin: use.basin, left: use.seconds, stroke: 0 }\n return { ok: true, text: t('done_plunge', { name: name() }), body }\n },\n flushed(fixture, host) {\n const flush = flushes.get(fixture)\n const b = flush ? basins.get(flush.basin) : undefined\n if (!flush || !b) return false\n takeLoose(b, host)\n b.drain.flush(flush.litres)\n return true\n },\n update(dt, host) {\n stepPending(dt)\n stepPlunge(dt, host)\n stepSwallowing(dt, host)\n for (const b of list) stepBasin(b, dt, host)\n },\n dispose(host) {\n for (const s of swallowing) host?.swallow?.(s.id, s.point, 1)\n swallowing.length = 0\n pending.length = 0\n plunging = null\n },\n soil(basin) {\n const contents = basins.get(basin)?.drain.state().contents ?? []\n if (contents.some((c) => c.kind === 'feces' || c.kind === 'paper')) return 'feces'\n return contents.some((c) => c.kind === 'urine') ? 'urine' : 'clean'\n },\n state() {\n for (const b of list) {\n if (states[b.spec.id] === b.drain.state()) continue\n states = Object.fromEntries(list.map((each) => [each.spec.id, each.drain.state()]))\n break\n }\n return states\n },\n }\n}\n","import type { Vec3 } from './types'\n\n/** Whether a thing of `size` (any turn of it) goes into a box of `half` sizes: each of its sides, longest first, against the box's, longest first. */\nexport function fitsInVolume(size: readonly [number, number, number], half: Vec3): boolean {\n const thing = [...size].sort((a, b) => b - a)\n const room = half.map((h) => h * 2).sort((a, b) => b - a)\n return thing.every((side, i) => side <= (room[i] ?? 0))\n}\n","/**\n * The uses at a fixture's water (`do: 'wash'` and `do: 'drink'` of `ObjectSpec.uses`): whether they can run now (the things they need at hand, dishes dirty in the\n * basin, a vessel to drink from) and the routine each runs over its seconds once started: open the water, scrub foam in, let the water rinse it off, close the water;\n * or fill the vessel under the stream, close the water, drink and put the vessel back. Pure: the host lends the hand, the items, the body's hand uses and the foam\n * (`ItemControlsHost`); the water is the object's own fixture in its interactables world, so it runs as fast as the fixture does and stops when its tank is dry.\n */\nimport type { ItemControlsHost, ReachedItem } from '@adatechnology/game-contracts'\n\nimport type { DrinkUseSpec, FixtureSpec, ObjectSpec, UseNeed, Vec3, WashUseSpec, World } from './types'\nimport { FLOW_DEFAULTS } from './world'\n\n/** Seconds of scrubbing per thing washed, when the use does not say. */\nexport const WASH_SCRUB_SECONDS = 3\n/** Litres drunk at most from a vessel filled at a tap: a glass of water. */\nexport const DRINK_LITRES = 0.25\n/** A vessel filled at a tap is stopped this full (share of what it takes). */\nexport const FILL_SHARE = 0.85\n/** Litres a mouth drinks per second. */\nexport const DRINK_LPS = 0.06\n/** Litres drunk from cupped hands under a tap: three or four handfuls of some 30 ml. */\nexport const DRINK_HANDS_LITRES = 0.12\n/** Litres a mouth takes from cupped hands per second: a handful a second, slower than from a glass. */\nexport const DRINK_HANDS_LPS = 0.03\n/** Seconds the hand takes to reach the tap's lever, and to put a thing down. */\nexport const REACH_SECONDS = 0.6\n/** Seconds the water may take to start running after the lever opens (the fixture flows from the next step) before the tap counts as dry. */\nexport const DRY_SECONDS = 0.5\n/** How far under a tap's outlet the hands hold what goes under its stream (a glass's rim, a dish, the cupped hands), metres. */\nexport const UNDER_STREAM = 0.14\n/** Dirt left on a dish once scrubbed: the rest goes with the rinse. */\nconst SCRUBBED_DIRT = 0.15\n\nexport type SinkUseSpec = WashUseSpec | DrinkUseSpec\n\nexport type SinkVerdict = { readonly available: true } | { readonly available: false; readonly reason: string; readonly vars?: Record<string, string> }\nconst YES: SinkVerdict = { available: true }\n\n/** What a routine says when it ends: a locale key and its words. */\nexport interface RoutineEnd {\n readonly key: string\n readonly ok: boolean\n readonly vars?: Record<string, string>\n}\n\n/** A use at the water running over its seconds. `step` answers the end once it is over. */\nexport interface SinkRoutine {\n readonly use: string\n step(dt: number): RoutineEnd | null\n}\n\nexport interface SinkRoutines {\n start(use: SinkUseSpec, host: ItemControlsHost): SinkRoutine\n}\n\nexport interface SinkUsesOptions {\n readonly spec: ObjectSpec\n readonly world: World\n readonly objectId: string\n}\n\n/** A routine as a list of phases, each run until it answers true (done). */\ntype Phase = (dt: number) => boolean\n\nconst idsOf = (need: UseNeed): readonly string[] => (typeof need === 'string' ? [need] : need)\n\n/** The item of each need, or the ids of the first need nothing answers. */\nexport function findNeeds(needs: readonly UseNeed[], host: ItemControlsHost): { readonly items: readonly ReachedItem[]; readonly missing?: readonly string[] } {\n const items: ReachedItem[] = []\n for (const need of needs) {\n const item = host.itemAt?.(idsOf(need)) ?? null\n if (!item) return { items, missing: idsOf(need) }\n items.push(item)\n }\n return { items }\n}\n\n/** The dirty dishes lying in the use's basin. */\nexport function dirtyDishes(use: WashUseSpec, spec: ObjectSpec, host: ItemControlsHost): readonly ReachedItem[] {\n const dishes = use.dishes\n const basin = dishes ? (spec.basins ?? []).find((b) => b.id === dishes.basin) : undefined\n if (!dishes || !basin) return []\n return (host.itemsInside?.(dishes.ids, basin.from, basin.to) ?? []).filter((item) => (item.dirt ?? 0) > 0)\n}\n\n/** What a host must lend for a wash to run with the body doing it: the hand use, the foam and, for dishes, the dishes in the bowl and their place on the rack. */\ntype WashBody = Required<Pick<ItemControlsHost, 'playUse' | 'lather' | 'rinse'>> & Pick<ItemControlsHost, 'itemsInside' | 'placeItem' | 'setDirt' | 'takeDose'>\n/** What a host must lend to drink from a vessel: the hand use, the vessel and its liquid. */\ntype VesselBody = Required<Pick<ItemControlsHost, 'playUse' | 'vesselAt' | 'fillItem' | 'drinkItem'>>\n/** What a host must lend to drink from the cupped hands: the hand use, the hands free and the water they catch. */\ntype HandsBody = Required<Pick<ItemControlsHost, 'playUse' | 'handsFree' | 'drinkFromHands'>>\n\n/** The host's wash capabilities, or null when it cannot show the body washing (CLAUDE.md §18: no action without its animation). */\nexport function washBody(use: WashUseSpec, host: ItemControlsHost): WashBody | null {\n const { playUse, lather, rinse, itemsInside, placeItem, setDirt, takeDose } = host\n if (!playUse || !lather || !rinse) return null\n if (use.dishes && (!itemsInside || !placeItem || !setDirt)) return null\n if (use.dose && !takeDose) return null\n return { playUse, lather, rinse, itemsInside, placeItem, setDirt, takeDose }\n}\n\n/** The host's capabilities to drink from a vessel, or null. */\nexport function vesselBody(host: ItemControlsHost): VesselBody | null {\n const { playUse, vesselAt, fillItem, drinkItem } = host\n return playUse && vesselAt && fillItem && drinkItem ? { playUse, vesselAt, fillItem, drinkItem } : null\n}\n\n/** The host's capabilities to drink from the cupped hands, or null. */\nexport function handsBody(host: ItemControlsHost): HandsBody | null {\n const { playUse, handsFree, drinkFromHands } = host\n return playUse && handsFree && drinkFromHands ? { playUse, handsFree, drinkFromHands } : null\n}\n\nconst NO_BODY: SinkVerdict = { available: false, reason: 'no_animation' }\nconst NEEDS_FREE_HAND: SinkVerdict = { available: false, reason: 'needs_free_hand' }\n\n/** Whether a use at the water can run now, and why not (a locale key with its words). `flowing`: the use's fixture runs now. */\nexport function sinkVerdict(use: SinkUseSpec, spec: ObjectSpec, host: ItemControlsHost, flowing: boolean): SinkVerdict {\n if (use.do === 'drink') return drinkVerdict(use, host)\n if (!washBody(use, host)) return NO_BODY\n if (use.requiresFlowing && !flowing) return { available: false, reason: 'needs_running' }\n const found = findNeeds(use.needs ?? [], host)\n if (!handsFreeFor(use, found.items, host)) return NEEDS_FREE_HAND\n if (found.missing) return { available: false, reason: 'needs_item', vars: { need: found.missing[0] ?? '' } }\n const dosed = use.dose ? found.items[use.dose.need] : undefined\n if (dosed && (dosed.remaining ?? 1) <= 0) return { available: false, reason: 'item_spent', vars: { item: dosed.name } }\n if (use.dishes && dirtyDishes(use, spec, host).length === 0) return { available: false, reason: 'no_dirty_dishes' }\n return YES\n}\n\n/** Both hands are free (nothing held, no weapon or tool in them), the one rule every use that takes the hands asks; a host that cannot say (no `handsFree`) is taken at its hand alone. */\nexport function handsAreFree(host: ItemControlsHost): boolean {\n return host.handsFree?.() ?? host.hand() === null\n}\n\n/**\n * Washing takes the hands: they are free, or hold only what the wash needs (the soap, the sponge) or a dish it washes. A weapon or anything else in them is put\n * away first. A host that cannot say what the hands hold (no `handsFree`) is taken at its hand alone.\n */\nfunction handsFreeFor(use: WashUseSpec, needed: readonly ReachedItem[], host: ItemControlsHost): boolean {\n if (handsAreFree(host)) return true\n if (host.hand() === null) return false\n if (needed.some((item) => item.where === 'hand')) return true\n return use.dishes !== undefined && host.itemAt?.(use.dishes.ids)?.where === 'hand'\n}\n\n/**\n * Drinking from a vessel only with it in the hand (one on the counter is taken first) and empty of any other liquid; from the cupped hands only with both hands\n * free (no glass, no weapon or tool in them). A vessel is what the host says holds liquid (`vesselAt`), never guessed from a name.\n */\nfunction drinkVerdict(use: DrinkUseSpec, host: ItemControlsHost): SinkVerdict {\n if (use.from === 'hands') {\n const body = handsBody(host)\n if (!body) return NO_BODY\n if (body.handsFree()) return YES\n return host.vesselAt?.()?.where === 'hand' ? { available: false, reason: 'drink_from_vessel' } : NEEDS_FREE_HAND\n }\n const body = vesselBody(host)\n if (!body) return NO_BODY\n const vessel = body.vesselAt()\n if (!vessel) return { available: false, reason: 'needs_vessel' }\n if (vessel.where !== 'hand') return { available: false, reason: 'needs_in_hand', vars: { item: vessel.name } }\n const other = vessel.liquid?.kind !== undefined && vessel.liquid.kind !== 'water' && vessel.liquid.litres > 1e-3\n return other ? { available: false, reason: 'vessel_not_empty', vars: { item: vessel.name } } : YES\n}\n\n/** Litres per second the fixture runs fully open. */\nexport const fixtureFlowLps = (fixture: FixtureSpec | undefined): number => (fixture ? (fixture.flow ?? FLOW_DEFAULTS[fixture.kind] ?? 6) / 60 : 0)\n\n/** Runs the phases in turn, one step each at most: a phase that ends starts the next on the next step, so no phase ever runs a step of no time. */\nfunction runPhases(phases: readonly Phase[]): (dt: number) => boolean {\n let index = 0\n return (dt) => {\n if (index < phases.length && phases[index]?.(dt)) index++\n return index >= phases.length\n }\n}\n\nfunction wait(seconds: number): Phase {\n let left = seconds\n return (dt) => (left -= dt) <= 0\n}\n\n/** The thing goes down on `spot` (a washed dish on the drainboard). */\nfunction placePhase(host: ItemControlsHost, item: ReachedItem, spot: Vec3 | readonly [number, number, number] | undefined): Phase {\n return () => {\n if (spot) host.placeItem?.(item.objectId, [spot[0], spot[1], spot[2]])\n return true\n }\n}\n\nexport function createSinkRoutines(options: SinkUsesOptions): SinkRoutines {\n const { spec, world, objectId } = options\n const fixtureOf = (id: string): FixtureSpec | undefined => (spec.fixtures ?? []).find((f) => f.id === id)\n const flowing = (use: SinkUseSpec): boolean => world.water.isFlowing(objectId, use.fixture)\n const water = (use: SinkUseSpec): number => (flowing(use) ? fixtureFlowLps(fixtureOf(use.fixture)) : 0)\n /** The point under the fixture's outlet the hands bring things to, object-local. */\n const underStream = (use: SinkUseSpec): readonly [number, number, number] | undefined => {\n const outlet = fixtureOf(use.fixture)?.outlet\n return outlet ? [outlet[0], outlet[1] - UNDER_STREAM, outlet[2]] : undefined\n }\n /** The water running now, litres per second; 0 while it starts; null once it stayed dry past `DRY_SECONDS`. */\n const waterOf = (use: SinkUseSpec): ((dt: number) => number | null) => {\n let dry = 0\n return (dt) => {\n const flow = water(use)\n dry = flow > 0 ? 0 : dry + dt\n return dry > DRY_SECONDS ? null : flow\n }\n }\n\n /** The body steps up to the fixture first (to reach under its stream), for at most `REACH_SECONDS * 3`; a host whose body does not walk goes on at once. */\n const approachPhase = (use: SinkUseSpec, host: ItemControlsHost): Phase => {\n let walked = 0\n const at = underStream(use)\n return (dt) => {\n walked += dt\n return !at || !host.approach || walked > REACH_SECONDS * 3 || host.approach(at, dt)\n }\n }\n\n /** Opens the water (when the use opens it, after the hand reaches the lever) and closes it again at the end, if this use opened it. */\n const tapPhases = (use: SinkUseSpec): { readonly open: Phase; readonly close: Phase } => {\n let opened = false\n const reach = wait(REACH_SECONDS)\n return {\n open: (dt) => {\n if (opened || use.opensFixture === false || flowing(use)) return true\n if (!reach(dt)) return false\n opened = world.setFixture(objectId, use.fixture, true)\n return true\n },\n close: () => {\n if (opened) world.setFixture(objectId, use.fixture, false)\n return true\n },\n }\n }\n\n /** Scrubbing foam into one thing (dirt coming off with it), then rinsing until the foam is gone (the rest of the dirt with it). */\n const scrubAndRinse = (use: WashUseSpec, body: WashBody, target: ReachedItem | string, fail: (end: RoutineEnd) => void): Phase[] => {\n const item = typeof target === 'string' ? undefined : target\n const id = item?.objectId ?? (target as string)\n const seconds = use.scrubSeconds ?? WASH_SCRUB_SECONDS\n const dirt = item?.dirt ?? 0\n let scrubbed = -1\n const scrub: Phase = (dt) => {\n if (scrubbed < 0) {\n scrubbed = 0\n // the body has to show the scrub (§18): with another use still playing, nothing is washed\n if (!body.playUse(use.clip, item?.objectId, underStream(use))) {\n fail({ key: 'hands_busy', ok: false })\n return true\n }\n }\n scrubbed = Math.min(seconds, scrubbed + dt)\n body.lather(id, dt / seconds)\n if (dirt > 0) body.setDirt?.(id, dirt - (dirt - Math.min(dirt, SCRUBBED_DIRT)) * (scrubbed / seconds))\n return scrubbed >= seconds\n }\n const running = waterOf(use)\n const rinse: Phase = (dt) => {\n const flow = running(dt)\n if (flow === null) {\n fail({ key: 'no_water', ok: false })\n return true\n }\n if (flow <= 0 || body.rinse(id, flow, dt) > 0) return false\n if (dirt > 0) body.setDirt?.(id, 0)\n return true\n }\n return [scrub, rinse]\n }\n\n const startWash = (use: WashUseSpec, host: ItemControlsHost, body: WashBody): SinkRoutine => {\n const { items } = findNeeds(use.needs ?? [], host)\n let end: RoutineEnd | null = null\n const fail = (reason: RoutineEnd): void => {\n end ??= reason\n }\n const tap = tapPhases(use)\n const dosed = use.dose ? items[use.dose.need] : undefined\n const dose: Phase = () => {\n if (dosed && body.takeDose?.(dosed.objectId, use.dose?.amount).taken === 0) fail({ key: 'item_spent', ok: false, vars: { item: dosed.name } })\n return true\n }\n const dishes = use.dishes ? dirtyDishes(use, spec, host) : []\n const rack = use.dishes?.rack ?? []\n const work: Phase[] = use.dishes\n ? dishes.flatMap((dish, index) => [...scrubAndRinse(use, body, dish, fail), placePhase(host, dish, rack[Math.min(index, rack.length - 1)])])\n : scrubAndRinse(use, body, use.surface, fail)\n const guarded = work.map((phase): Phase => (dt) => end !== null || phase(dt))\n const run = runPhases([approachPhase(use, host), tap.open, dose, ...guarded, tap.close])\n const done: RoutineEnd = use.dishes ? { key: 'done_wash_dishes', ok: true, vars: { n: String(dishes.length) } } : { key: 'done_wash', ok: true, vars: { surface: use.surface } }\n return { use: use.id, step: (dt) => (run(dt) ? (end ?? done) : null) }\n }\n\n /** The glass in the hand: the water opened, the glass held under it until nearly full, the water closed, the glass drunk from. */\n const startDrink = (use: DrinkUseSpec, host: ItemControlsHost, body: VesselBody, vessel: ReachedItem): SinkRoutine => {\n const tap = tapPhases(use)\n const want = Math.min(use.litres ?? DRINK_LITRES, (vessel.liquid?.capacity ?? DRINK_LITRES) * FILL_SHARE)\n let filled = vessel.liquid?.kind === 'water' ? vessel.liquid.litres : 0\n let drunk = 0\n let end: RoutineEnd | null = null\n const running = waterOf(use)\n const played = (clip: string, at?: readonly [number, number, number]): boolean => {\n if (body.playUse(clip, vessel.objectId, at)) return true\n end ??= { key: 'hands_busy', ok: false }\n return false\n }\n let filling = false\n const fill: Phase = (dt) => {\n if (end) return true\n if (!filling && !(filling = played(use.fillClip ?? 'fill_cup', underStream(use)))) return true\n const flow = running(dt)\n if (flow === null) {\n end = { key: 'no_water', ok: false }\n return true\n }\n if (flow <= 0) return false\n const took = body.fillItem(vessel.objectId, 'water', Math.min(flow * dt, want - filled))\n filled += took\n return filled >= want - 1e-6 || took <= 0\n }\n let sipping = false\n const drink: Phase = (dt) => {\n if (end) return true\n if (!sipping && !(sipping = played(use.clip))) return true\n const sip = body.drinkItem(vessel.objectId, Math.min(DRINK_LPS * dt, filled - drunk))\n drunk += sip\n return drunk >= filled - 1e-6 || sip <= 0\n }\n const run = runPhases([approachPhase(use, host), tap.open, fill, tap.close, drink])\n const done = (): RoutineEnd => (drunk > 1e-3 ? { key: 'done_drink', ok: true, vars: { litres: drunk.toFixed(2) } } : { key: 'not_drunk', ok: false })\n return { use: use.id, step: (dt) => (run(dt) ? (end ?? done()) : null) }\n }\n\n /** No glass: the water opened, the body bent over it drinking from the cupped hands while it runs, the water closed. */\n const startDrinkHands = (use: DrinkUseSpec, host: ItemControlsHost, body: HandsBody): SinkRoutine => {\n const tap = tapPhases(use)\n const want = use.litres ?? DRINK_HANDS_LITRES\n let drunk = 0\n let end: RoutineEnd | null = null\n const running = waterOf(use)\n let bent = false\n const drink: Phase = (dt) => {\n if (!bent) {\n bent = body.playUse(use.clip, undefined, underStream(use))\n if (!bent) {\n end = { key: 'hands_busy', ok: false }\n return true\n }\n }\n const flow = running(dt)\n if (flow === null) {\n end = { key: 'no_water', ok: false }\n return true\n }\n if (flow <= 0) return false\n const sip = body.drinkFromHands('water', Math.min(DRINK_HANDS_LPS * dt, flow * dt, want - drunk))\n drunk += sip\n return drunk >= want - 1e-6 || sip <= 0\n }\n const run = runPhases([approachPhase(use, host), tap.open, drink, tap.close])\n const done = (): RoutineEnd => (drunk > 1e-3 ? { key: 'done_drink_hands', ok: true, vars: { litres: drunk.toFixed(2) } } : { key: 'not_drunk', ok: false })\n return { use: use.id, step: (dt) => (run(dt) ? (end ?? done()) : null) }\n }\n\n /** A routine that ends at once, saying why (the verdict changed between the menu and the start). */\n const refused = (use: SinkUseSpec, key: string): SinkRoutine => ({ use: use.id, step: () => ({ key, ok: false }) })\n\n return {\n start(use, host) {\n if (use.do === 'wash') {\n const body = washBody(use, host)\n return body ? startWash(use, host, body) : refused(use, 'no_animation')\n }\n if (use.from === 'hands') {\n const body = handsBody(host)\n return body ? startDrinkHands(use, host, body) : refused(use, 'no_animation')\n }\n const body = vesselBody(host)\n const vessel = body?.vesselAt()\n if (!body) return refused(use, 'no_animation')\n return vessel ? startDrink(use, host, body, vessel) : refused(use, 'needs_vessel')\n },\n }\n}\n","/**\n * What the body does while an object's use runs (`ControlBodyAction`, CLAUDE.md §18), timed here so every host runs it the same: the body lent by the host\n * (`ItemControlsHost.body`) is asked whether it can take the pose before the use is offered, takes it when the use runs, is told the time once a step, and is let go\n * when the seconds are over or the object leaves the world. A host without a body refuses the use; it never answers it as done.\n */\nimport type { ControlBodyAction, ControlledBody, ItemControlsHost } from '@adatechnology/game-contracts'\n\n/** The pose running now, as the object's state shows it. */\nexport interface UseBodyPose {\n readonly pose: ControlBodyAction['pose']\n readonly time: number\n readonly progress: number\n}\n\nexport interface UseBody {\n /** Why the host's body cannot take `action` now (a reason key of the strings: `needs_body`, `body_no_seat`...), or null when it can. */\n blocked(action: ControlBodyAction, host: ItemControlsHost): string | null\n /** The body takes `action`; false when it could not (nothing else of the use should happen then). */\n begin(action: ControlBodyAction, host: ItemControlsHost): boolean\n update(dt: number): void\n /** Lets the body go at once (the object left the world). */\n end(): void\n readonly pose: UseBodyPose | null\n}\n\ninterface Running {\n readonly action: ControlBodyAction\n readonly body: ControlledBody\n time: number\n}\n\nexport function createUseBody(): UseBody {\n let running: Running | null = null\n\n const end = (): void => {\n const was = running\n running = null\n was?.body.end()\n }\n\n return {\n blocked(action, host) {\n const body = host.body?.()\n if (!body) return 'needs_body'\n const why = body.blocked(action)\n return why ? `body_${why}` : null\n },\n begin(action, host) {\n const body = host.body?.()\n if (!body) return false\n end()\n if (!body.begin(action)) return false\n running = { action, body, time: 0 }\n return true\n },\n update(dt) {\n if (!running) return\n running.time += dt\n const { action, body, time } = running\n // the body left the pose on its own (got up, walked off): nothing to let go\n if (!body.step(time, Math.min(1, time / action.seconds))) running = null\n else if (time >= action.seconds) end()\n },\n end,\n get pose() {\n return running ? { pose: running.action.pose, time: running.time, progress: Math.min(1, running.time / running.action.seconds) } : null\n },\n }\n}\n","/**\n * What an object does with the player's hand or on its own time (`ObjectSpec.uses`), for `createObjectControls`: a device's program that runs for its seconds, what\n * the hand holds put inside when it fits, a container emptied, a bowl filled from the hand, a basin soiled and washed by its flush. The rules are the data's: the\n * container's inside, the bowl's capacity and what it accepts, the access part that must be open (or closed, for a program).\n */\nimport type { BodyGesture, ControlBodyAction, ControlledHand, ItemControl, ItemControlResult, ItemControlsHost } from '@adatechnology/game-contracts'\n\nimport type { BasinDrainState } from './basin-drain'\nimport { createDrainUses } from './drain-uses'\nimport { GESTURE_OF_USE } from './gestures'\nimport { fitsInVolume } from './fits-volume'\nimport { createSinkRoutines, handsAreFree, sinkVerdict } from './sink-uses'\nimport { createUseBody } from './use-body'\nimport type { UseBodyPose } from './use-body'\nimport type { SinkRoutine } from './sink-uses'\nimport type { BowlSpec, ContainerSpec, ObjectSpec, UseSpec, Vec3, World } from './types'\n\n/**\n * Where the hand presses to run a device's program, object-local: the interaction the spec gives the device, else the part that shows it on (its button), else its plug,\n * the same point the world puts the device's own interaction at. Read from the spec, never from the id an interaction happens to get.\n */\nexport function devicePointOf(spec: ObjectSpec, device: string): Vec3 | undefined {\n const own = (spec.interactions ?? []).find((i) => i.action.do === 'toggle_device' && i.action.device === device)\n if (own) return own.pos\n const def = (spec.devices ?? []).find((d) => d.id === device)\n if (!def) return undefined\n const part = def.part ? spec.parts?.find((p) => p.id === def.part)?.pivot : undefined\n return part ?? def.plug ?? [0, 1, 0]\n}\n\nimport type { Soil } from './drain-uses'\n\n/** What a basin holds, worst last: a flush washes it back to clean. */\nexport type { Soil }\n\nexport interface UsesState {\n /** kg of food or litres of water in each bowl. */\n readonly bowls: Readonly<Record<string, number>>\n readonly soil: Readonly<Record<string, Soil>>\n /** The water of each basin with a trap (a toilet's bowl): its level, swirl, clog and what is in it. */\n readonly drains: Readonly<Record<string, BasinDrainState>>\n /** The program running, with its seconds left. */\n readonly program: { readonly use: string; readonly device: string; readonly left: number } | null\n /** The use at the water running now (`wash`, `drink`), by id. */\n readonly routine: string | null\n /** What the body does for the use running now (seated on a toilet, working a plunger), with its time; null when nothing. */\n readonly body: UseBodyPose | null\n}\n\nexport interface Uses {\n has(id: string): boolean\n list(host: ItemControlsHost): ItemControl[]\n run(id: string, host: ItemControlsHost): ItemControlResult\n /** Advances the object's own time; `host` is the one that runs it now. */\n update(dt: number, host?: ItemControlsHost): void\n /** A fixture of the object ran its water: the basin it cleans is clean again (a toilet's: its bowl takes the flush). */\n flushed(fixture: string, host?: ItemControlsHost): void\n /** The object leaves the world: the body is let go and what was going down its drain is gone. */\n dispose(host?: ItemControlsHost): void\n state(): UsesState\n}\n\nexport interface UsesOptions {\n readonly spec: ObjectSpec\n readonly world: World\n readonly objectId: string\n}\n\nconst OPEN = 0.5\nconst PREFIX = 'use.'\nconst SOIL_RANK: Record<Soil, number> = { clean: 0, urine: 1, feces: 2 }\n\nconst clock = (seconds: number): string => {\n const s = Math.max(0, Math.ceil(seconds))\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`\n}\n\n/** Whether the hand's item is one the bowl accepts: its id, or a room id that ends with it (`item_dog_food` for `dog_food`). */\nconst accepts = (bowl: BowlSpec, hand: ControlledHand): boolean => (bowl.accepts ?? []).some((id) => hand.itemId === id || hand.itemId.endsWith(`_${id}`))\n\ntype Verdict = { readonly available: true } | { readonly available: false; readonly reason: string; readonly vars?: Record<string, string> }\nconst YES: Verdict = { available: true }\nconst no = (reason: string, vars?: Record<string, string>): Verdict => ({ available: false, reason, ...(vars ? { vars } : {}) })\n\nexport function createUses(options: UsesOptions): Uses {\n const { spec, world, objectId } = options\n const all = spec.uses ?? []\n const containers = new Map<string, ContainerSpec>((spec.containers ?? []).map((c) => [c.id, c]))\n const bowls = new Map<string, BowlSpec>((spec.bowls ?? []).map((b) => [b.id, b]))\n const level = new Map<string, number>((spec.bowls ?? []).map((b) => [b.id, Math.min(b.capacity, b.level ?? 0)]))\n const soil = new Map<string, Soil>((spec.basins ?? []).filter((b) => b.soils).map((b) => [b.id, 'clean']))\n const cleans = new Map<string, string>((spec.fixtures ?? []).flatMap((f) => (f.cleans ? [[f.id, f.cleans] as const] : [])))\n let program: { use: Extract<UseSpec, { do: 'program' }>; left: number } | null = null\n let lastHost: ItemControlsHost | null = null\n const sinkRoutines = createSinkRoutines({ spec, world, objectId })\n let routine: SinkRoutine | null = null\n const drains = createDrainUses({ spec, world, objectId, t: (key, vars) => world.t(key, vars) })\n const useBody = createUseBody()\n\n const typeKey = `type.${spec.type}`\n const name = (): string => {\n const text = world.t(typeKey)\n return text === typeKey ? spec.type.replace(/_/g, ' ') : text.charAt(0).toLowerCase() + text.slice(1)\n }\n const accessOpen = (host: ItemControlsHost, part: string | undefined): boolean => !part || host.partOpening(part) >= OPEN\n\n const verdict = (use: UseSpec, host: ItemControlsHost): Verdict => {\n const hand = host.hand()\n switch (use.do) {\n case 'program':\n if (!world.power.isPowered(objectId, use.device)) return no('no_power')\n return use.access && host.partOpening(use.access) >= OPEN ? no('needs_closed') : YES\n case 'put_in': {\n const c = containers.get(use.container)\n if (!hand) return no('hand_empty')\n if (!c || !accessOpen(host, c.access)) return no('requires_open')\n return fitsInVolume(hand.size, c.volume.half) ? YES : no('not_fit')\n }\n case 'empty':\n return accessOpen(host, containers.get(use.container)?.access) ? YES : no('requires_open')\n case 'fill': {\n const bowl = bowls.get(use.bowl)\n if (!bowl) return no('empty')\n if ((level.get(bowl.id) ?? 0) >= bowl.capacity - 1e-6) return no('bowl_full')\n if (!hand) return no('hand_empty')\n if (bowl.holds === 'water' && hand.liquid?.kind === 'water' && hand.liquid.closed) return no('requires_open')\n const fits = bowl.holds === 'water' ? hand.liquid?.kind === 'water' && hand.liquid.litres > 0 : accepts(bowl, hand)\n return fits ? YES : no('not_accepted')\n }\n case 'relieve':\n return drains.has(use.basin) ? drainVerdict(host, () => (handsAreFree(host) ? null : 'needs_free_hand'), () => drains.relieveBody(use, host)) : YES\n case 'wash':\n case 'drink':\n return routine ? no('busy') : sinkVerdict(use, spec, host, world.water.isFlowing(objectId, use.fixture))\n case 'plunge':\n return drainVerdict(host, () => drains.plungeBlocked(use, host), () => drains.plungeBody(use))\n }\n }\n\n /** A use of a basin with a trap: the host must lend what the drain needs, the use's own rule must hold, and the body must be able to take its pose. */\n const drainVerdict = (host: ItemControlsHost, rule: () => string | null, body: () => ControlBodyAction | null): Verdict => {\n const missing = drains.hostBlocked(host)\n if (missing) return no('host_lacks', { capability: missing })\n const broken = rule()\n if (broken) return no(broken)\n const action = body()\n if (!action) return no('needs_body')\n const why = useBody.blocked(action, host)\n return why ? no(why) : YES\n }\n\n /** The body takes the use's pose, then the use runs; when the body cannot, nothing of the use happens. */\n const withBody = (action: ControlBodyAction | null, host: ItemControlsHost, vars: Record<string, string>, run: (action: ControlBodyAction) => ItemControlResult): ItemControlResult => {\n if (!action) return { ok: false, text: world.t('needs_body', vars) }\n return useBody.begin(action, host) ? run(action) : { ok: false, text: world.t('body_busy', vars) }\n }\n\n /** A catalogue item's name in the content pack's strings (`item.<id>`), or its id in words. */\n const itemName = (id: string): string => {\n const text = world.t(`item.${id}`)\n return text === `item.${id}` ? id.replace(/_/g, ' ') : text\n }\n const reasonOf = (v: Extract<Verdict, { available: false }>, use: UseSpec, host: ItemControlsHost): string => {\n const words = { ...textVars(use, host), ...v.vars }\n return world.t(v.reason, words.need ? { ...words, need: itemName(words.need) } : words)\n }\n\n const textVars = (use: UseSpec, host: ItemControlsHost): Record<string, string> => ({\n name: name(),\n item: host.hand()?.name ?? '',\n bowl: world.t(`bowl.${use.do === 'fill' ? (bowls.get(use.bowl)?.holds ?? 'food') : 'food'}`),\n })\n\n const labelOf = (use: UseSpec, host: ItemControlsHost): string => world.t(use.do === 'put_in' && !host.hand() ? 'use.put_in.none' : use.label, textVars(use, host))\n\n const runUse = (use: UseSpec, host: ItemControlsHost): ItemControlResult => {\n const vars = textVars(use, host)\n switch (use.do) {\n case 'program': {\n world.setDevice(objectId, use.device, true)\n program = { use, left: use.seconds }\n return { ok: true, text: world.t('done_program', { ...vars, program: world.t(use.label), time: clock(use.seconds) }) }\n }\n case 'put_in': {\n const c = containers.get(use.container) as ContainerSpec\n return host.placeHand(c.volume.center) ? { ok: true, text: world.t('done_put_in', vars) } : { ok: false, text: world.t('not_fit', vars) }\n }\n case 'empty': {\n const c = containers.get(use.container) as ContainerSpec\n const [cx, cy, cz] = c.volume.center\n const [hx, hy, hz] = c.volume.half\n const n = host.emptyInside([cx - hx, cy - hy, cz - hz], [cx + hx, cy + hy, cz + hz])\n return { ok: n > 0, text: world.t(n > 0 ? 'done_empty' : 'empty', { ...vars, n }) }\n }\n case 'fill':\n return fill(bowls.get(use.bowl) as BowlSpec, host, vars)\n case 'plunge':\n return withBody(drains.plungeBody(use), host, vars, (action) => drains.plunge(use, action))\n case 'relieve': {\n if (drains.has(use.basin)) return withBody(drains.relieveBody(use, host), host, vars, (action) => drains.relieve(use, host, action))\n const now = soil.get(use.basin) ?? 'clean'\n soil.set(use.basin, SOIL_RANK[use.kind] > SOIL_RANK[now] ? use.kind : now)\n return { ok: true, text: world.t(`done_relieve_${use.kind}`, vars) }\n }\n case 'wash':\n case 'drink':\n routine = sinkRoutines.start(use, host)\n return { ok: true, text: world.t(`started_${use.do}`, { ...vars, label: world.t(use.label, vars) }) }\n }\n }\n\n const fill = (bowl: BowlSpec, host: ItemControlsHost, vars: Record<string, string>): ItemControlResult => {\n const now = level.get(bowl.id) ?? 0\n const added = bowl.holds === 'water' ? host.pourHand(bowl.capacity - now) : bowl.capacity - now\n level.set(bowl.id, Math.min(bowl.capacity, now + added))\n return { ok: added > 0, text: world.t(added > 0 ? 'done_fill' : 'not_accepted', vars) }\n }\n\n const stopProgram = (): string => {\n if (!program) return ''\n world.setDevice(objectId, program.use.device, false)\n program = null\n return world.t('done_program_stop', { name: name() })\n }\n\n const stepRoutine = (dt: number): void => {\n const end = routine?.step(dt)\n if (!end) return\n routine = null\n const words = end.vars?.need ? { ...end.vars, need: itemName(end.vars.need) } : end.vars\n lastHost?.say(world.t(end.key, { name: name(), ...words }))\n }\n\n /** The gesture of the body for a use and the object-local point the hand goes to: the program's button, the inside of the bin, the bowl. */\n const gestureOf = (use: UseSpec): { gesture: BodyGesture; at: Vec3 } | null => {\n const gesture = GESTURE_OF_USE[use.do]\n if (!gesture) return null\n const at =\n use.do === 'program'\n ? devicePointOf(spec, use.device)\n : use.do === 'put_in' || use.do === 'empty'\n ? containers.get(use.container)?.volume.center\n : use.do === 'fill'\n ? bowls.get(use.bowl)?.center\n : undefined\n return at ? { gesture, at: [at[0], at[1], at[2]] } : null\n }\n\n const visible = (use: UseSpec): boolean => use.do !== 'program' || program === null\n\n return {\n has: (id) => id.startsWith(PREFIX),\n list(host) {\n lastHost = host\n const entries: ItemControl[] = []\n if (program) entries.push({ id: `${PREFIX}stop`, label: world.t('use.program.stop', { name: name(), left: clock(program.left) }), available: true })\n for (const use of all.filter(visible)) {\n const v = verdict(use, host)\n const body = gestureOf(use)\n entries.push({ id: `${PREFIX}${use.id}`, label: labelOf(use, host), available: v.available, ...(v.available ? {} : { reason: reasonOf(v, use, host) }), ...(body ?? {}) })\n }\n return entries\n },\n run(id, host) {\n lastHost = host\n if (id === `${PREFIX}stop`) return { ok: program !== null, text: stopProgram() }\n const use = all.find((u) => `${PREFIX}${u.id}` === id)\n if (!use || !visible(use)) return { ok: false, text: '' }\n const v = verdict(use, host)\n return v.available ? runUse(use, host) : { ok: false, text: reasonOf(v, use, host) }\n },\n update(dt, host) {\n if (host) lastHost = host\n drains.update(dt, lastHost)\n useBody.update(dt)\n stepRoutine(dt)\n if (!program) return\n program.left -= dt\n if (program.left > 0) return\n const done = world.t('done_program_end', { name: name(), program: world.t(program.use.label) })\n world.setDevice(objectId, program.use.device, false)\n program = null\n lastHost?.say(done)\n },\n flushed(fixture, host) {\n if (host) lastHost = host\n if (drains.flushed(fixture, lastHost)) return\n const basin = cleans.get(fixture)\n if (!basin || soil.get(basin) === 'clean') return\n soil.set(basin, 'clean')\n lastHost?.say(world.t('done_clean', { name: name() }))\n },\n dispose(host) {\n drains.dispose(host ?? lastHost)\n useBody.end()\n },\n state: () => ({\n bowls: Object.fromEntries(level),\n soil: Object.fromEntries([...soil].map(([id, now]) => [id, drains.has(id) ? drains.soil(id) : now])),\n drains: drains.state(),\n program: program ? { use: program.use.id, device: program.use.device, left: program.left } : null,\n routine: routine?.use ?? null,\n body: useBody.pose,\n }),\n }\n}\n","/**\n * The controls of one object for a host that moves the object's parts itself (a test room plays the parts' clips, a game its own animation): what the object's spec\n * says it does (its devices, fixtures, burners and fuel, run by an interactables world of its own fed by the mains), plus what it does with the player's hand or on\n * its own time (`ObjectSpec.uses`: a program, putting in, emptying, filling a bowl, relieving oneself). Data-driven: nothing here knows a TV from a toilet. Pure: no\n * three.js; the drawing of what the state shows (a screen's picture, a bowl's level, a fire) reads `state()`.\n */\nimport type { ItemControl, ItemControlResult, ItemControls, ItemControlsHost } from '@adatechnology/game-contracts'\n\nimport { createUses } from './object-uses'\nimport type { UsesState } from './object-uses'\nimport type { Action, ActiveEmitter, Interactable, InteractablesLocale, ObjectSpec, Strings, Vec3, WorldState } from './types'\nimport { createWorld } from './world'\n\n/** The id the object has in its own world. */\nexport const CONTROLLED_OBJECT = 'object'\nconst MAINS = 'mains'\nconst MAINS_TANK = 'water'\n\n/** World interactions a host that moves the parts itself does on its own (opening, taking, reading, sitting) or that belong to a building (a breaker). */\nconst HOST_KINDS: ReadonlySet<Action['do']> = new Set(['toggle_part', 'open_container', 'take', 'read', 'sit', 'toggle_breaker'])\n\nexport interface ObjectControlsOptions {\n readonly spec: ObjectSpec\n readonly locale?: string\n /** The content pack's strings (`Household.strings`). */\n readonly strings?: Partial<Record<InteractablesLocale, Strings>>\n /** Whether the mains give power and water. Default both: a piece standing on its own in a test room is plugged in and piped. */\n readonly mains?: { readonly power?: boolean; readonly water?: boolean }\n}\n\n/** What the object shows now, for its drawing. */\nexport interface ObjectControlsState extends UsesState {\n /** Screens on and powered, with their channel. */\n readonly screens: ReadonlyArray<{ readonly device: string; readonly channel: number }>\n /** Fires and smoke of its burners, object-local (the water runs from the parts the host moves). */\n readonly emitters: readonly ActiveEmitter[]\n}\n\nexport interface ObjectControls extends ItemControls {\n state(): ObjectControlsState\n /** What the object is now as plain JSON (its world's `serialize`: parts, devices, water, a toilet's drain), for a save. */\n serialize(): WorldState\n /** Puts the object back where `serialize` found it. */\n load(state: WorldState): void\n}\n\nconst PLUG_FALLBACK: Vec3 = [0, 0.3, 0]\n\n/**\n * A wall socket at each plugged device's plug and, when the mains give water, one tank behind every fixture: the mains of a piece standing on its own. Without water\n * there is no tank at all, since the world takes the first tank it is given as every fixture's default.\n */\nfunction mainsSpec(spec: ObjectSpec, water: boolean): ObjectSpec {\n const plugged = (spec.devices ?? []).filter((d) => d.socket !== undefined && !d.circuit)\n return { type: MAINS, sockets: plugged.map((d, i) => ({ id: `socket_${i}`, pos: d.plug ?? PLUG_FALLBACK })), tanks: water ? [{ id: MAINS_TANK, capacity: 1e9 }] : [] }\n}\n\nexport function createObjectControls(options: ObjectControlsOptions): ObjectControls {\n const { spec } = options\n const forwarded = new Map<string, boolean>()\n const said: string[] = []\n let host: ItemControlsHost | null = null\n const world = createWorld({\n locale: options.locale ?? 'en',\n ...(options.strings ? { strings: options.strings } : {}),\n grid: options.mains?.power ?? true,\n takeContents: false,\n onEvent: (event) => {\n if (event.type === 'message') said.push(event.text)\n if (event.type === 'part' && event.object === CONTROLLED_OBJECT) forwardPart(event.part, event.target >= 0.5)\n if (event.type === 'fixture' && event.object === CONTROLLED_OBJECT && event.flowing) uses.flushed(event.fixture, host ?? undefined)\n },\n })\n /** A part the world moved goes to the host, once per change of where it is headed. */\n const forwardPart = (part: string, open: boolean): void => {\n if (forwarded.get(part) === open) return\n forwarded.set(part, open)\n host?.setPart(part, open)\n }\n const piped = options.mains?.water ?? true\n world.add(MAINS, mainsSpec(spec, piped), { x: 0, y: 0, z: 0, ry: 0 })\n if (piped) world.water.setDefaultTank(`${MAINS}:${MAINS_TANK}`)\n world.add(CONTROLLED_OBJECT, spec, { x: 0, y: 0, z: 0, ry: 0 })\n const uses = createUses({ spec, world, objectId: CONTROLLED_OBJECT })\n // a device a program runs (a washing machine) is started by its programs, not switched on bare\n const programmedDevices = new Set((spec.uses ?? []).flatMap((u) => (u.do === 'program' ? [u.device] : [])))\n const switchesOf = (device: string): string[] => [\n `device.${device}`,\n ...(spec.interactions ?? []).flatMap((i) => (i.action.do === 'toggle_device' && i.action.device === device ? [i.id] : [])),\n ]\n const programmed = new Set([...programmedDevices].flatMap(switchesOf).map((id) => `${CONTROLLED_OBJECT}:${id}`))\n const own = (i: Interactable): boolean => i.object === CONTROLLED_OBJECT && !HOST_KINDS.has(i.kind) && !programmed.has(i.id)\n const interactions = (): Interactable[] => world.interactables().filter(own)\n const lend = (lent: ItemControlsHost): void => {\n host = lent\n }\n\n return {\n list(lent) {\n lend(lent)\n // the object stands at the origin of its own world: an interaction's point is object-local, where the hand goes\n const fromWorld: ItemControl[] = interactions().map((i) => {\n const gesture = i.gesture\n return { id: i.id, label: i.label, available: i.available, ...(i.reason ? { reason: world.t(i.reason) } : {}), ...(gesture ? { gesture, at: [i.pos[0], i.pos[1], i.pos[2]] as const } : {}) }\n })\n return [...fromWorld, ...uses.list(lent)]\n },\n run(id, lent): ItemControlResult {\n lend(lent)\n if (uses.has(id)) return uses.run(id, lent)\n const found = interactions().find((i) => i.id === id)\n if (!found) return { ok: false, text: '' }\n said.length = 0\n const ok = world.act(id)\n return { ok, text: said.length > 0 ? said.join(' · ') : found.label }\n },\n update(dt, lent) {\n lend(lent)\n world.update(dt)\n uses.update(dt, lent)\n },\n state() {\n const screens = (spec.devices ?? [])\n .filter((d) => d.kind === 'screen' && world.power.isOn(CONTROLLED_OBJECT, d.id) && world.power.isPowered(CONTROLLED_OBJECT, d.id))\n .map((d) => ({ device: d.id, channel: world.power.channel(CONTROLLED_OBJECT, d.id) }))\n const emitters = world.emitters().filter((e) => e.object === CONTROLLED_OBJECT && e.kind !== 'water')\n return { ...uses.state(), screens, emitters }\n },\n serialize: () => world.serialize(),\n load: (state) => world.load(state),\n dispose() {\n uses.dispose(host ?? undefined)\n host = null\n world.remove(CONTROLLED_OBJECT)\n world.remove(MAINS)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0HO,MAAM,qBAAqB;AAE3B,MAAM,UAAU;AAEvB,MAAM,cAAc;AAEpB,MAAM,cAAc;AAEpB,MAAM,aAAa;AAEnB,MAAM,OAAO;AAEb,MAAM,iBAAiB;AAEvB,MAAM,cAAc;AAEpB,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AAEf,MAAM,gBAAgB;AAE7B,MAAM,eAAe;AAErB,MAAM,gBAAgB;AAEtB,MAAM,UAAU,CAAC,MAAsB,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC;AAEjE,MAAM,cAAc,CAAC,SAAoD,CAAC,GAAG,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC,EAAE,CAAC,KAAK;AAIxG,WAAS,iBAAiB,OAAkB,OAA8B;AAC/E,UAAM,QAAQ,MAAM,GAAG,CAAC,IAAI,MAAM,KAAK,CAAC;AACxC,UAAM,OAAO,MAAM,GAAG,CAAC,IAAI,MAAM,KAAK,CAAC;AACvC,UAAM,SAAS,KAAK,IAAI,OAAO,IAAI,IAAI;AAEvC,UAAM,OAAO,MAAM,UAAU,UAAU,KA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AAG,KAAK,MAAM,GAAG,SAAS,SAAS;AAAA,MAC9C;AAAA,MACA,WAAW,MAAM,MAAM,UAAU;AAAA,MACjC,MAAM,CAAC,UAAU,MAAM,KAAK,KAAK;AAAA,MACjC,UAAU;AACR,aAAK,QAAQ,QAAQ,MAAS;AAC9B,eAAO;AACP,cAAM,OAAO,iBAAiB;AAC9B,cAAM,OAAO,KAAK;AAAA,MACpB;AAAA,IACF;AAAA,EACF;","names":["pose","cross","target","add","local","volume","sub","pos","destroyed","PUSH_GAIN","pose","centre","cross","length","overlap","body","YES"]}
|