poker-flopsolve 0.3.0 → 0.4.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/engine-worker.ts","../src/engine.ts"],"sourcesContent":["/**\n * An engine worker: one thread of a WebAssembly solve.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, when the main thread signals. The protocol\n * is src/parallel.ts's: the main thread collects the reach each entry needs,\n * every thread walks its slice from each entry, the main thread adds the\n * slices up and finishes. Here all of it happens in shared WebAssembly\n * memory, so nothing is copied between threads but a few numbers of control.\n */\n\nimport { parentPort, workerData } from 'node:worker_threads';\nimport type { EngineExports, EngineWorkerSetup } from './engine.ts';\nimport { ENGINE_CONTROL } from './engine.ts';\n\nconst setup = workerData as EngineWorkerSetup;\nconst { WebAssembly: wasm } = globalThis as unknown as {\n\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n};\nconst memory = setup.memory as { buffer: SharedArrayBuffer };\nconst instance = new wasm.Instance(setup.module, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\nconst engine = instance.exports as unknown as EngineExports;\nengine.init(setup.header);\nengine.setMaxActions(setup.maxActions);\nengine.setExchange(...setup.exchange);\nengine.setShard(...setup.shard);\nengine.setPhase(0, 1);\n\nconst control = new Int32Array(setup.control);\nconst settings = new Float64Array(setup.settings);\nconst entries = setup.entryNodes.length;\nconst rowBytes = setup.stride * 4;\nconst partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);\nconst [, reach] = setup.exchange;\n\n// Latch the generation before announcing readiness, so no dispatch is missed.\nlet generation = Atomics.load(control, ENGINE_CONTROL.generation);\nAtomics.add(control, ENGINE_CONTROL.ready, 1);\nAtomics.notify(control, ENGINE_CONTROL.ready);\n\nfor (;;) {\n\tAtomics.wait(control, ENGINE_CONTROL.generation, generation);\n\tgeneration = Atomics.load(control, ENGINE_CONTROL.generation);\n\tif (Atomics.load(control, ENGINE_CONTROL.command) === 1) break;\n\tconst mode = Atomics.load(control, ENGINE_CONTROL.mode);\n\tconst traverser = Atomics.load(control, ENGINE_CONTROL.traverser);\n\tconst [positive, negative, sum, weight, clamp] = settings;\n\tfor (let entry = 0; entry < entries; entry++) {\n\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\tconst out = engine.runChance(\n\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t);\n\t\tpartials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);\n\t}\n\tAtomics.add(control, ENGINE_CONTROL.done, 1);\n\tAtomics.notify(control, ENGINE_CONTROL.done);\n}\n\nparentPort?.close();\n","/**\n * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs single-threaded, with 32-bit storage,\n * where WebAssembly SIMD is available; otherwise the JavaScript traversal in\n * cfr.ts runs.\n */\n\nimport { COMBOS, DECK } from './cards.ts';\nimport type { ActiveLists, Layout, PlayerIndex, RootTraversal } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\tif (modules[kind] !== undefined) return modules[kind]!;\n\tmodules[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst text = kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tmodules[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tmodules[kind] = null;\n\t}\n\treturn modules[kind]!;\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory. */\n\treadonly regret: Float32Array;\n\treadonly strategySum: Float32Array;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\treadonly shard: readonly [number, number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\treadonly partial: number;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n}\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** Control slots shared with engine workers. */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the runouts at the plan's round, as src/parallel.ts does for\n * the JavaScript engine.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: { plan: ShardPlan; threads: number; spawn: SpawnEngineWorker },\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst compiledModule = compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tconst maxCount = Math.max(4, ...active.count);\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\tconst pieces: { data: ArrayBufferView | null; bytes: number }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16 });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(Int32Array.from(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.tieStart), add(active.ties), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * 4), // regret\n\t\tadd(null, layout.totalSlots * 4), // strategy sums\n\t];\n\tconst REGRET = common[27];\n\tconst SUMS = common[28];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\tconst partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;\n\n\tconst offsets: number[] = [];\n\tlet total = 64;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > 0xffff0000) return null; // past wasm32's 4 GB\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[29] = offsets[mine.buffers];\n\t\thead[30] = depthBytes;\n\t\thead[31] = rowBytes;\n\t\thead[32] = offsets[mine.cardSums];\n\t\thead[33] = input.chipScale;\n\t}\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\n\tconst regret = new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum = new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tpartial: offsets[partials] + (w - 1) * entries * rowBytes,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tAtomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst run = (mode: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t} else {\n\t\t\tconst plan = pool.plan;\n\t\t\t// Collect: walk above the split, recording what the workers need.\n\t\t\texports.setShard(plan.round, 0, 0);\n\t\t\texports.setPhase(1, 0);\n\t\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t\t// Every thread walks its slice of the split round.\n\t\t\tsettings!.set([positive, negative, sum, weight, clamp]);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\t\texports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);\n\t\t\texports.setPhase(0, 1);\n\t\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp);\n\t\t\t\tvalueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);\n\t\t\t}\n\t\t\tfor (;;) {\n\t\t\t\tconst done = Atomics.load(control!, ENGINE_CONTROL.done);\n\t\t\t\tif (done >= threads - 1 || failure) break;\n\t\t\t\tAtomics.wait(control!, ENGINE_CONTROL.done, done, 50);\n\t\t\t}\n\t\t\tif (failure) throw failure;\n\t\t\tconst partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);\n\t\t\tfor (let w = 0; w < threads - 1; w++) {\n\t\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];\n\t\t\t}\n\t\t\t// Finish above the split from the totals, now applying updates.\n\t\t\texports.setShard(plan.round, 0, 0);\n\t\t\texports.setPhase(2, 1);\n\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t\texports.setPhase(0, 1);\n\t\t\texports.setShard(-1, 0, 0);\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tthreads,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/** The engine's exports. */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\n"],"mappings":";AAWA,SAAS,YAAY,kBAAkB;;;ACqBvC,IAAM,OAAQ,WAAoD;AA0E3D,IAAM,iBAAiB,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,MAAM,EAAE;;;AD3F7G,IAAM,QAAQ;AACd,IAAM,EAAE,aAAaA,MAAK,IAAI;AAG9B,IAAM,SAAS,MAAM;AACrB,IAAM,WAAW,IAAIA,MAAK,SAAS,MAAM,QAAQ,EAAE,KAAK,EAAE,QAAQ,OAAO,MAAM;AAAE,QAAM,IAAI,MAAM,cAAc;AAAG,EAAE,EAAE,CAAC;AACvH,IAAM,SAAS,SAAS;AACxB,OAAO,KAAK,MAAM,MAAM;AACxB,OAAO,cAAc,MAAM,UAAU;AACrC,OAAO,YAAY,GAAG,MAAM,QAAQ;AACpC,OAAO,SAAS,GAAG,MAAM,KAAK;AAC9B,OAAO,SAAS,GAAG,CAAC;AAEpB,IAAM,UAAU,IAAI,WAAW,MAAM,OAAO;AAC5C,IAAM,WAAW,IAAI,aAAa,MAAM,QAAQ;AAChD,IAAM,UAAU,MAAM,WAAW;AACjC,IAAM,WAAW,MAAM,SAAS;AAChC,IAAM,WAAW,IAAI,aAAa,OAAO,QAAQ,MAAM,SAAS,UAAU,MAAM,MAAM;AACtF,IAAM,CAAC,EAAE,KAAK,IAAI,MAAM;AAGxB,IAAI,aAAa,QAAQ,KAAK,SAAS,eAAe,UAAU;AAChE,QAAQ,IAAI,SAAS,eAAe,OAAO,CAAC;AAC5C,QAAQ,OAAO,SAAS,eAAe,KAAK;AAE5C,WAAS;AACR,UAAQ,KAAK,SAAS,eAAe,YAAY,UAAU;AAC3D,eAAa,QAAQ,KAAK,SAAS,eAAe,UAAU;AAC5D,MAAI,QAAQ,KAAK,SAAS,eAAe,OAAO,MAAM,EAAG;AACzD,QAAM,OAAO,QAAQ,KAAK,SAAS,eAAe,IAAI;AACtD,QAAM,YAAY,QAAQ,KAAK,SAAS,eAAe,SAAS;AAChE,QAAM,CAAC,UAAU,UAAU,KAAK,QAAQ,KAAK,IAAI;AACjD,WAAS,QAAQ,GAAG,QAAQ,SAAS,SAAS;AAC7C,UAAM,OAAO,QAAQ,QAAQ,IAAI;AACjC,UAAM,MAAM,OAAO;AAAA,MAClB;AAAA,MAAM;AAAA,MAAW,MAAM,WAAW,KAAK;AAAA,MAAG;AAAA,MAAM,OAAO;AAAA,MAAU;AAAA,MAAU;AAAA,MAAU;AAAA,MAAK;AAAA,MAAQ;AAAA,IACnG;AACA,aAAS,IAAI,IAAI,aAAa,OAAO,QAAQ,KAAK,MAAM,MAAM,GAAG,QAAQ,MAAM,MAAM;AAAA,EACtF;AACA,UAAQ,IAAI,SAAS,eAAe,MAAM,CAAC;AAC3C,UAAQ,OAAO,SAAS,eAAe,IAAI;AAC5C;AAEA,YAAY,MAAM;","names":["wasm"]}
1
+ {"version":3,"sources":["../src/engine-worker.ts","../src/engine.ts"],"sourcesContent":["/**\n * An engine worker: one thread of a WebAssembly solve.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, when the main thread signals. The protocol\n * is src/parallel.ts's: the main thread collects the reach each entry needs,\n * every thread walks its slice from each entry, the main thread adds the\n * slices up and finishes. Here all of it happens in shared WebAssembly\n * memory, so nothing is copied between threads but a few numbers of control.\n */\n\nimport { parentPort, workerData } from 'node:worker_threads';\nimport type { EngineExports, EngineWorkerSetup } from './engine.ts';\nimport { ENGINE_CONTROL } from './engine.ts';\n\nconst setup = workerData as EngineWorkerSetup;\nconst { WebAssembly: wasm } = globalThis as unknown as {\n\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n};\nconst memory = setup.memory as { buffer: SharedArrayBuffer };\nconst instance = new wasm.Instance(setup.module, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\nconst engine = instance.exports as unknown as EngineExports;\nengine.init(setup.header);\nengine.setMaxActions(setup.maxActions);\nengine.setExchange(...setup.exchange);\nengine.setShard(...setup.shard);\nengine.setPhase(0, 1);\n\nconst control = new Int32Array(setup.control);\nconst settings = new Float64Array(setup.settings);\nconst entries = setup.entryNodes.length;\nconst rowBytes = setup.stride * 4;\nconst partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);\nconst [, reach] = setup.exchange;\n\n// Latch the generation before announcing readiness, so no dispatch is missed.\nlet generation = Atomics.load(control, ENGINE_CONTROL.generation);\nAtomics.add(control, ENGINE_CONTROL.ready, 1);\nAtomics.notify(control, ENGINE_CONTROL.ready);\n\nfor (;;) {\n\tAtomics.wait(control, ENGINE_CONTROL.generation, generation);\n\tgeneration = Atomics.load(control, ENGINE_CONTROL.generation);\n\tif (Atomics.load(control, ENGINE_CONTROL.command) === 1) break;\n\tconst mode = Atomics.load(control, ENGINE_CONTROL.mode);\n\tconst traverser = Atomics.load(control, ENGINE_CONTROL.traverser);\n\tconst [positive, negative, sum, weight, clamp] = settings;\n\tfor (let entry = 0; entry < entries; entry++) {\n\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\tconst out = engine.runChance(\n\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t);\n\t\tpartials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);\n\t}\n\tAtomics.add(control, ENGINE_CONTROL.done, 1);\n\tAtomics.notify(control, ENGINE_CONTROL.done);\n}\n\nparentPort?.close();\n","/**\n * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs single-threaded, with 32-bit storage,\n * where WebAssembly SIMD is available; otherwise the JavaScript traversal in\n * cfr.ts runs.\n */\n\nimport { COMBOS, DECK } from './cards.ts';\nimport type { ActiveLists, Layout, PlayerIndex, RootTraversal } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\tif (modules[kind] !== undefined) return modules[kind]!;\n\tmodules[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst text = kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tmodules[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tmodules[kind] = null;\n\t}\n\treturn modules[kind]!;\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory. */\n\treadonly regret: Float32Array;\n\treadonly strategySum: Float32Array;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\treadonly shard: readonly [number, number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\treadonly partial: number;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n}\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** Control slots shared with engine workers. */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the runouts at the plan's round, as src/parallel.ts does for\n * the JavaScript engine.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: { plan: ShardPlan; threads: number; spawn: SpawnEngineWorker },\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst compiledModule = compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tconst maxCount = Math.max(4, ...active.count);\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\tconst pieces: { data: ArrayBufferView | null; bytes: number }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16 });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(Int32Array.from(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.tieStart), add(active.ties), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * 4), // regret\n\t\tadd(null, layout.totalSlots * 4), // strategy sums\n\t];\n\tconst REGRET = common[27];\n\tconst SUMS = common[28];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\tconst partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;\n\n\tconst offsets: number[] = [];\n\tlet total = 64;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > 0xffff0000) return null; // past wasm32's 4 GB\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[29] = offsets[mine.buffers];\n\t\thead[30] = depthBytes;\n\t\thead[31] = rowBytes;\n\t\thead[32] = offsets[mine.cardSums];\n\t\thead[33] = input.chipScale;\n\t}\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\n\tconst regret = new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum = new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tpartial: offsets[partials] + (w - 1) * entries * rowBytes,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst run = (mode: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t} else {\n\t\t\tconst plan = pool.plan;\n\t\t\t// Collect: walk above the split, recording what the workers need.\n\t\t\texports.setShard(plan.round, 0, 0);\n\t\t\texports.setPhase(1, 0);\n\t\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t\t// Every thread walks its slice of the split round.\n\t\t\tsettings!.set([positive, negative, sum, weight, clamp]);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\t\texports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);\n\t\t\texports.setPhase(0, 1);\n\t\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp);\n\t\t\t\tvalueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);\n\t\t\t}\n\t\t\tfor (;;) {\n\t\t\t\tconst done = Atomics.load(control!, ENGINE_CONTROL.done);\n\t\t\t\tif (done >= threads - 1 || failure) break;\n\t\t\t\tAtomics.wait(control!, ENGINE_CONTROL.done, done, 50);\n\t\t\t}\n\t\t\tif (failure) throw failure;\n\t\t\tconst partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);\n\t\t\tfor (let w = 0; w < threads - 1; w++) {\n\t\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];\n\t\t\t}\n\t\t\t// Finish above the split from the totals, now applying updates.\n\t\t\texports.setShard(plan.round, 0, 0);\n\t\t\texports.setPhase(2, 1);\n\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t\texports.setPhase(0, 1);\n\t\t\texports.setShard(-1, 0, 0);\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tthreads,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/** The engine's exports. */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\n"],"mappings":";AAWA,SAAS,YAAY,kBAAkB;;;ACsBvC,IAAM,OAAQ,WAAoD;AA0E3D,IAAM,iBAAiB,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,MAAM,EAAE;;;AD5F7G,IAAM,QAAQ;AACd,IAAM,EAAE,aAAaA,MAAK,IAAI;AAG9B,IAAM,SAAS,MAAM;AACrB,IAAM,WAAW,IAAIA,MAAK,SAAS,MAAM,QAAQ,EAAE,KAAK,EAAE,QAAQ,OAAO,MAAM;AAAE,QAAM,IAAI,MAAM,cAAc;AAAG,EAAE,EAAE,CAAC;AACvH,IAAM,SAAS,SAAS;AACxB,OAAO,KAAK,MAAM,MAAM;AACxB,OAAO,cAAc,MAAM,UAAU;AACrC,OAAO,YAAY,GAAG,MAAM,QAAQ;AACpC,OAAO,SAAS,GAAG,MAAM,KAAK;AAC9B,OAAO,SAAS,GAAG,CAAC;AAEpB,IAAM,UAAU,IAAI,WAAW,MAAM,OAAO;AAC5C,IAAM,WAAW,IAAI,aAAa,MAAM,QAAQ;AAChD,IAAM,UAAU,MAAM,WAAW;AACjC,IAAM,WAAW,MAAM,SAAS;AAChC,IAAM,WAAW,IAAI,aAAa,OAAO,QAAQ,MAAM,SAAS,UAAU,MAAM,MAAM;AACtF,IAAM,CAAC,EAAE,KAAK,IAAI,MAAM;AAGxB,IAAI,aAAa,QAAQ,KAAK,SAAS,eAAe,UAAU;AAChE,QAAQ,IAAI,SAAS,eAAe,OAAO,CAAC;AAC5C,QAAQ,OAAO,SAAS,eAAe,KAAK;AAE5C,WAAS;AACR,UAAQ,KAAK,SAAS,eAAe,YAAY,UAAU;AAC3D,eAAa,QAAQ,KAAK,SAAS,eAAe,UAAU;AAC5D,MAAI,QAAQ,KAAK,SAAS,eAAe,OAAO,MAAM,EAAG;AACzD,QAAM,OAAO,QAAQ,KAAK,SAAS,eAAe,IAAI;AACtD,QAAM,YAAY,QAAQ,KAAK,SAAS,eAAe,SAAS;AAChE,QAAM,CAAC,UAAU,UAAU,KAAK,QAAQ,KAAK,IAAI;AACjD,WAAS,QAAQ,GAAG,QAAQ,SAAS,SAAS;AAC7C,UAAM,OAAO,QAAQ,QAAQ,IAAI;AACjC,UAAM,MAAM,OAAO;AAAA,MAClB;AAAA,MAAM;AAAA,MAAW,MAAM,WAAW,KAAK;AAAA,MAAG;AAAA,MAAM,OAAO;AAAA,MAAU;AAAA,MAAU;AAAA,MAAU;AAAA,MAAK;AAAA,MAAQ;AAAA,IACnG;AACA,aAAS,IAAI,IAAI,aAAa,OAAO,QAAQ,KAAK,MAAM,MAAM,GAAG,QAAQ,MAAM,MAAM;AAAA,EACtF;AACA,UAAQ,IAAI,SAAS,eAAe,MAAM,CAAC;AAC3C,UAAQ,OAAO,SAAS,eAAe,IAAI;AAC5C;AAEA,YAAY,MAAM;","names":["wasm"]}
package/dist/index.d.ts CHANGED
@@ -207,6 +207,14 @@ type BetSize = number | {
207
207
  } | 'allin';
208
208
  /** Sizes offered when facing a bet: one row for every round, or a row per round. */
209
209
  type RaiseSizes = readonly BetSize[] | readonly (readonly BetSize[])[];
210
+ /**
211
+ * A setting given once for both players, or apart: `{ oop: …, ip: … }`, each
212
+ * side in the setting's own form.
213
+ */
214
+ type PerPlayer<T> = T | {
215
+ readonly oop: T;
216
+ readonly ip: T;
217
+ };
210
218
  declare const NodeKind: {
211
219
  readonly Decision: 0;
212
220
  readonly Chance: 1;
@@ -715,20 +723,29 @@ interface SpotConfig {
715
723
  readonly oop: string | Float64Array;
716
724
  /** The in-position player's range, in either form. */
717
725
  readonly ip: string | Float64Array;
718
- /** Bet sizes per betting round; a single row applies to every round. */
719
- readonly betSizes: readonly (readonly BetSize[])[];
726
+ /**
727
+ * Bet sizes per betting round; a single row applies to every round.
728
+ *
729
+ * This and every other betting setting below (`raiseSizes`, `maxRaises`,
730
+ * `allowAllIn`, `allInThreshold`) can be given apart for each player as
731
+ * `{ oop: …, ip: … }`, each side in the setting's usual form:
732
+ * `betSizes: { oop: [[0.33]], ip: [[0.5, 1]] }`. They only shape the
733
+ * tree, so a solve costs the same either way.
734
+ */
735
+ readonly betSizes: PerPlayer<readonly (readonly BetSize[])[]>;
720
736
  /**
721
737
  * Sizes offered when facing a bet; unset, raises use the bet sizes. One
722
738
  * row for every round, or a row per round like `betSizes`.
723
739
  */
724
- readonly raiseSizes?: RaiseSizes;
740
+ readonly raiseSizes?: PerPlayer<RaiseSizes | undefined>;
725
741
  /**
726
742
  * Maximum aggressive actions per round; the opening bet is the first.
727
- * One number, or one per round. Default 1.
743
+ * One number, or one per round. Default 1. Given apart, a player may bet
744
+ * or raise only while the round's aggressions are under their own limit.
728
745
  */
729
- readonly maxRaises?: number | readonly number[];
746
+ readonly maxRaises?: PerPlayer<number | readonly number[]>;
730
747
  /** Offer a shove alongside the configured sizes; once, or per round. Default false. */
731
- readonly allowAllIn?: boolean | readonly boolean[];
748
+ readonly allowAllIn?: PerPlayer<boolean | readonly boolean[]>;
732
749
  /**
733
750
  * Turn a bet or raise into a shove when it would commit at least this
734
751
  * fraction of the actor's remaining stack — 0.67 makes any bet of two
@@ -736,7 +753,7 @@ interface SpotConfig {
736
753
  * multiply a tree for little strategic difference. Once, or per round.
737
754
  * Unset, never.
738
755
  */
739
- readonly allInThreshold?: number | readonly number[];
756
+ readonly allInThreshold?: PerPlayer<number | readonly number[] | undefined>;
740
757
  /**
741
758
  * Forbid donk bets: out of position may only check when opening a round
742
759
  * into the player who made the last bet or raise of the round before.
@@ -1118,4 +1135,4 @@ declare function solve(spot: Spot, options?: SolveOptions): Solution;
1118
1135
  */
1119
1136
  declare function predictCrossing(t1: number, e1: number, t2: number, e2: number, target: number): number;
1120
1137
 
1121
- export { ACTION_LABELS, ActionKind, type Algorithm, type Approximations, type BetSize, CATEGORY, CATEGORY_NAMES, COMBOS, COMBO_CARDS, COMBO_LANES, DECK, type Estimate, NodeKind, PLATFORM, PRECISION_BYTES, type Precision, type Progress, RANKS, type ResolvedBoard, SUITS, type Solution, type SolveOptions, type SolveRun, type Solver, type Spot, type SpotConfig, SpotTooLargeError, type StrategyView, type SubgameBetting, type WarmStartReport, activeCombos, cardOf, categoryOf, comboIndex, createRun, defineSpot, evaluate, evaluateCards, formatCard, formatCards, formatCombo, makeRegretStore, makeSumStore, parseCard, parseCards, parseRange, predictCrossing, rangeWeight, rankOf, simdAvailable, solve, suitLanes, suitOf };
1138
+ export { ACTION_LABELS, ActionKind, type Algorithm, type Approximations, type BetSize, CATEGORY, CATEGORY_NAMES, COMBOS, COMBO_CARDS, COMBO_LANES, DECK, type Estimate, NodeKind, PLATFORM, PRECISION_BYTES, type PerPlayer, type Precision, type Progress, RANKS, type RaiseSizes, type ResolvedBoard, SUITS, type Solution, type SolveOptions, type SolveRun, type Solver, type Spot, type SpotConfig, SpotTooLargeError, type StrategyView, type SubgameBetting, type WarmStartReport, activeCombos, cardOf, categoryOf, comboIndex, createRun, defineSpot, evaluate, evaluateCards, formatCard, formatCards, formatCombo, makeRegretStore, makeSumStore, parseCard, parseCards, parseRange, predictCrossing, rangeWeight, rankOf, simdAvailable, solve, suitLanes, suitOf };