pixi-reels 0.0.0-dependabot-github-actions-github-codeql-action-4-35-4-20260514194131
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/CHANGELOG.md +260 -0
- package/CONTRIBUTING.md +85 -0
- package/LICENSE +28 -0
- package/README.md +168 -0
- package/dist/SpineSymbol-CfVrc5Pk.js +88 -0
- package/dist/SpineSymbol-CfVrc5Pk.js.map +1 -0
- package/dist/SpineSymbol-JA5PdEbT.cjs +2 -0
- package/dist/SpineSymbol-JA5PdEbT.cjs.map +1 -0
- package/dist/cascade/CascadeAnticipationPhase.d.ts +23 -0
- package/dist/cascade/CascadeAnticipationPhase.d.ts.map +1 -0
- package/dist/cascade/DropRecipes.d.ts +40 -0
- package/dist/cascade/DropRecipes.d.ts.map +1 -0
- package/dist/config/SpeedPresets.d.ts +49 -0
- package/dist/config/SpeedPresets.d.ts.map +1 -0
- package/dist/config/defaults.d.ts +12 -0
- package/dist/config/defaults.d.ts.map +1 -0
- package/dist/config/types.d.ts +296 -0
- package/dist/config/types.d.ts.map +1 -0
- package/dist/core/Reel.d.ts +339 -0
- package/dist/core/Reel.d.ts.map +1 -0
- package/dist/core/ReelMotion.d.ts +51 -0
- package/dist/core/ReelMotion.d.ts.map +1 -0
- package/dist/core/ReelSet.d.ts +509 -0
- package/dist/core/ReelSet.d.ts.map +1 -0
- package/dist/core/ReelSetBuilder.d.ts +282 -0
- package/dist/core/ReelSetBuilder.d.ts.map +1 -0
- package/dist/core/ReelViewport.d.ts +129 -0
- package/dist/core/ReelViewport.d.ts.map +1 -0
- package/dist/core/StopSequencer.d.ts +26 -0
- package/dist/core/StopSequencer.d.ts.map +1 -0
- package/dist/debug/debug.d.ts +129 -0
- package/dist/debug/debug.d.ts.map +1 -0
- package/dist/events/EventEmitter.d.ts +25 -0
- package/dist/events/EventEmitter.d.ts.map +1 -0
- package/dist/events/ReelEvents.d.ts +125 -0
- package/dist/events/ReelEvents.d.ts.map +1 -0
- package/dist/frame/ColumnTarget.d.ts +77 -0
- package/dist/frame/ColumnTarget.d.ts.map +1 -0
- package/dist/frame/FrameBuilder.d.ts +51 -0
- package/dist/frame/FrameBuilder.d.ts.map +1 -0
- package/dist/frame/OffsetCalculator.d.ts +19 -0
- package/dist/frame/OffsetCalculator.d.ts.map +1 -0
- package/dist/frame/RandomSymbolProvider.d.ts +27 -0
- package/dist/frame/RandomSymbolProvider.d.ts.map +1 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +70 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2571 -0
- package/dist/index.js.map +1 -0
- package/dist/pins/CellPin.d.ts +140 -0
- package/dist/pins/CellPin.d.ts.map +1 -0
- package/dist/pool/ObjectPool.d.ts +36 -0
- package/dist/pool/ObjectPool.d.ts.map +1 -0
- package/dist/speed/SpeedManager.d.ts +38 -0
- package/dist/speed/SpeedManager.d.ts.map +1 -0
- package/dist/spin/SpinController.d.ts +183 -0
- package/dist/spin/SpinController.d.ts.map +1 -0
- package/dist/spin/modes/CascadeMode.d.ts +16 -0
- package/dist/spin/modes/CascadeMode.d.ts.map +1 -0
- package/dist/spin/modes/ImmediateMode.d.ts +10 -0
- package/dist/spin/modes/ImmediateMode.d.ts.map +1 -0
- package/dist/spin/modes/SpinningMode.d.ts +18 -0
- package/dist/spin/modes/SpinningMode.d.ts.map +1 -0
- package/dist/spin/modes/StandardMode.d.ts +10 -0
- package/dist/spin/modes/StandardMode.d.ts.map +1 -0
- package/dist/spin/phases/AdjustPhase.d.ts +73 -0
- package/dist/spin/phases/AdjustPhase.d.ts.map +1 -0
- package/dist/spin/phases/AnticipationPhase.d.ts +24 -0
- package/dist/spin/phases/AnticipationPhase.d.ts.map +1 -0
- package/dist/spin/phases/DropStartPhase.d.ts +21 -0
- package/dist/spin/phases/DropStartPhase.d.ts.map +1 -0
- package/dist/spin/phases/DropStopPhase.d.ts +44 -0
- package/dist/spin/phases/DropStopPhase.d.ts.map +1 -0
- package/dist/spin/phases/PhaseFactory.d.ts +32 -0
- package/dist/spin/phases/PhaseFactory.d.ts.map +1 -0
- package/dist/spin/phases/ReelPhase.d.ts +39 -0
- package/dist/spin/phases/ReelPhase.d.ts.map +1 -0
- package/dist/spin/phases/SpinPhase.d.ts +25 -0
- package/dist/spin/phases/SpinPhase.d.ts.map +1 -0
- package/dist/spin/phases/StartPhase.d.ts +26 -0
- package/dist/spin/phases/StartPhase.d.ts.map +1 -0
- package/dist/spin/phases/StopPhase.d.ts +37 -0
- package/dist/spin/phases/StopPhase.d.ts.map +1 -0
- package/dist/spine/SpineReelSymbol.d.ts +130 -0
- package/dist/spine/SpineReelSymbol.d.ts.map +1 -0
- package/dist/spine/index.d.ts +5 -0
- package/dist/spine/index.d.ts.map +1 -0
- package/dist/spine.cjs +2 -0
- package/dist/spine.cjs.map +1 -0
- package/dist/spine.js +123 -0
- package/dist/spine.js.map +1 -0
- package/dist/spotlight/SymbolSpotlight.d.ts +70 -0
- package/dist/spotlight/SymbolSpotlight.d.ts.map +1 -0
- package/dist/symbols/AnimatedSpriteSymbol.d.ts +30 -0
- package/dist/symbols/AnimatedSpriteSymbol.d.ts.map +1 -0
- package/dist/symbols/ReelSymbol.d.ts +86 -0
- package/dist/symbols/ReelSymbol.d.ts.map +1 -0
- package/dist/symbols/SpineSymbol.d.ts +34 -0
- package/dist/symbols/SpineSymbol.d.ts.map +1 -0
- package/dist/symbols/SpriteSymbol.d.ts +29 -0
- package/dist/symbols/SpriteSymbol.d.ts.map +1 -0
- package/dist/symbols/SymbolFactory.d.ts +20 -0
- package/dist/symbols/SymbolFactory.d.ts.map +1 -0
- package/dist/symbols/SymbolRegistry.d.ts +25 -0
- package/dist/symbols/SymbolRegistry.d.ts.map +1 -0
- package/dist/testing/FakeTicker.d.ts +45 -0
- package/dist/testing/FakeTicker.d.ts.map +1 -0
- package/dist/testing/HeadlessSymbol.d.ts +28 -0
- package/dist/testing/HeadlessSymbol.d.ts.map +1 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/testHarness.d.ts +97 -0
- package/dist/testing/testHarness.d.ts.map +1 -0
- package/dist/utils/Disposable.d.ts +10 -0
- package/dist/utils/Disposable.d.ts.map +1 -0
- package/dist/utils/TickerRef.d.ts +30 -0
- package/dist/utils/TickerRef.d.ts.map +1 -0
- package/dist/utils/gsapRef.d.ts +14 -0
- package/dist/utils/gsapRef.d.ts.map +1 -0
- package/dist/wins/Win.d.ts +7 -0
- package/dist/wins/Win.d.ts.map +1 -0
- package/dist/wins/WinPresenter.d.ts +100 -0
- package/dist/wins/WinPresenter.d.ts.map +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/events/EventEmitter.ts","../src/core/ReelMotion.ts","../src/core/StopSequencer.ts","../src/spin/modes/StandardMode.ts","../src/core/Reel.ts","../src/core/ReelViewport.ts","../src/spin/phases/ReelPhase.ts","../src/utils/gsapRef.ts","../src/spin/phases/StartPhase.ts","../src/spin/phases/SpinPhase.ts","../src/spin/phases/StopPhase.ts","../src/spin/phases/AnticipationPhase.ts","../src/spin/phases/PhaseFactory.ts","../src/utils/TickerRef.ts","../src/frame/ColumnTarget.ts","../src/spin/SpinController.ts","../src/speed/SpeedManager.ts","../src/spotlight/SymbolSpotlight.ts","../src/pins/CellPin.ts","../src/core/ReelSet.ts","../src/config/defaults.ts","../src/config/SpeedPresets.ts","../src/symbols/SymbolRegistry.ts","../src/pool/ObjectPool.ts","../src/symbols/SymbolFactory.ts","../src/frame/RandomSymbolProvider.ts","../src/frame/FrameBuilder.ts","../src/frame/OffsetCalculator.ts","../src/spin/phases/DropStartPhase.ts","../src/spin/phases/DropStopPhase.ts","../src/spin/phases/AdjustPhase.ts","../src/core/ReelSetBuilder.ts","../src/symbols/SpriteSymbol.ts","../src/symbols/AnimatedSpriteSymbol.ts","../src/cascade/DropRecipes.ts","../src/cascade/CascadeAnticipationPhase.ts","../src/spin/modes/CascadeMode.ts","../src/spin/modes/ImmediateMode.ts","../src/wins/Win.ts","../src/wins/WinPresenter.ts","../src/debug/debug.ts","../src/testing/FakeTicker.ts","../src/testing/HeadlessSymbol.ts","../src/testing/testHarness.ts"],"sourcesContent":["type Listener = (...args: any[]) => void;\n\ninterface ListenerEntry {\n fn: Listener;\n context: unknown;\n once: boolean;\n}\n\n/**\n * Lightweight typed event emitter with zero dependencies.\n *\n * Usage:\n * ```ts\n * interface MyEvents {\n * 'foo': [x: number, y: string];\n * 'bar': [];\n * }\n * const emitter = new EventEmitter<MyEvents>();\n * emitter.on('foo', (x, y) => console.log(x, y));\n * emitter.emit('foo', 42, 'hello');\n * ```\n */\nexport class EventEmitter<TEvents extends Record<string, unknown[]>> {\n private _listeners = new Map<keyof TEvents, ListenerEntry[]>();\n\n on<K extends keyof TEvents>(\n event: K,\n fn: (...args: TEvents[K]) => void,\n context?: unknown,\n ): this {\n return this._add(event, fn as Listener, context, false);\n }\n\n once<K extends keyof TEvents>(\n event: K,\n fn: (...args: TEvents[K]) => void,\n context?: unknown,\n ): this {\n return this._add(event, fn as Listener, context, true);\n }\n\n off<K extends keyof TEvents>(\n event: K,\n fn?: (...args: TEvents[K]) => void,\n context?: unknown,\n ): this {\n const entries = this._listeners.get(event);\n if (!entries) return this;\n\n if (!fn) {\n this._listeners.delete(event);\n return this;\n }\n\n const filtered = entries.filter(\n (e) => e.fn !== fn || (context !== undefined && e.context !== context),\n );\n if (filtered.length === 0) {\n this._listeners.delete(event);\n } else {\n this._listeners.set(event, filtered);\n }\n return this;\n }\n\n emit<K extends keyof TEvents>(event: K, ...args: TEvents[K]): boolean {\n const entries = this._listeners.get(event);\n if (!entries || entries.length === 0) return false;\n\n // Snapshot to allow mutations during iteration\n const snapshot = entries.slice();\n for (const entry of snapshot) {\n if (entry.once) {\n this.off(event, entry.fn as any, entry.context);\n }\n entry.fn.apply(entry.context, args);\n }\n return true;\n }\n\n removeAllListeners(event?: keyof TEvents): this {\n if (event !== undefined) {\n this._listeners.delete(event);\n } else {\n this._listeners.clear();\n }\n return this;\n }\n\n listenerCount(event: keyof TEvents): number {\n return this._listeners.get(event)?.length ?? 0;\n }\n\n private _add(\n event: keyof TEvents,\n fn: Listener,\n context: unknown,\n once: boolean,\n ): this {\n let entries = this._listeners.get(event);\n if (!entries) {\n entries = [];\n this._listeners.set(event, entries);\n }\n entries.push({ fn, context, once });\n return this;\n }\n}\n","import type { ReelSymbol } from '../symbols/ReelSymbol.js';\n\n/**\n * The physics of one reel — move symbols down, wrap them around.\n *\n * Every frame, `ReelMotion.update(delta)` adds `delta` to each symbol's\n * Y coordinate. A symbol whose position falls off the bottom wraps back\n * to the top (and vice versa — reels can run upward). Each wrap fires\n * the `_onSymbolWrapped` callback so the owning `Reel` can ask the\n * `FrameBuilder` for the next identity to paint on it.\n *\n * Maintains the invariant that `_symbols[0]` is always the visually\n * topmost symbol and `_symbols[N-1]` is always the bottommost. On each\n * wrap, the wrapping symbol is moved to the front (or back) of the array\n * so the ordering stays consistent with the grid. `snapToGrid` and the\n * visible window selection rely on this.\n */\nexport class ReelMotion {\n private _symbolHeight: number;\n private _symbolGapY: number;\n private _slotHeight: number;\n private _minY: number;\n private _maxY: number;\n\n constructor(\n private _symbols: ReelSymbol[],\n symbolHeight: number,\n symbolGapY: number,\n private _bufferAbove: number,\n visibleRows: number,\n private _onSymbolWrapped: (symbol: ReelSymbol, arrayIndex: number, direction: 'up' | 'down') => void,\n ) {\n this._symbolHeight = symbolHeight;\n this._symbolGapY = symbolGapY;\n this._slotHeight = symbolHeight + symbolGapY;\n this._maxY = (visibleRows + 1) * this._slotHeight;\n this._minY = -(this._bufferAbove + 1) * this._slotHeight;\n }\n\n /**\n * Move all symbols by deltaY pixels (positive = downward).\n * At most one wrap per call (deltaY is capped at half a symbol by the\n * spinning mode, so a single symbol can cross the boundary per tick).\n */\n displace(deltaY: number): void {\n if (deltaY === 0) return;\n for (const symbol of this._symbols) {\n symbol.view.y += deltaY;\n }\n if (deltaY > 0) {\n this._wrapBottomToTop();\n } else {\n this._wrapTopToBottom();\n }\n }\n\n /** Snap all symbols to their correct grid positions (array index = visual row). */\n snapToGrid(): void {\n for (let i = 0; i < this._symbols.length; i++) {\n const targetY = (i - this._bufferAbove) * this._slotHeight;\n this._symbols[i].view.y = targetY;\n }\n }\n\n /** Position all symbols above the visible area (for cascade mode start). */\n setToTopPosition(): void {\n for (let i = 0; i < this._symbols.length; i++) {\n this._symbols[i].view.y = this._minY - (this._symbols.length - i) * this._slotHeight;\n }\n }\n\n /** Get the correct Y position for a symbol at a given row. */\n getRowY(row: number): number {\n return (row - this._bufferAbove) * this._slotHeight;\n }\n\n get slotHeight(): number {\n return this._slotHeight;\n }\n\n /**\n * Reshape the motion layer for a new visible-row count and cell height.\n * Recomputes wrap bounds and the slot height. Called by `Reel.reshape()`\n * during AdjustPhase on MultiWays slots. The symbol array is re-bound by\n * `Reel.reshape()` directly via the same array reference, so this method\n * doesn't take a new array.\n */\n reshape(symbolHeight: number, symbolGapY: number, bufferAbove: number, visibleRows: number): void {\n this._symbolHeight = symbolHeight;\n this._symbolGapY = symbolGapY;\n this._slotHeight = symbolHeight + symbolGapY;\n this._bufferAbove = bufferAbove;\n this._maxY = (visibleRows + 1) * this._slotHeight;\n this._minY = -(this._bufferAbove + 1) * this._slotHeight;\n }\n\n private _wrapBottomToTop(): void {\n const lastIdx = this._symbols.length - 1;\n const lastSymbol = this._symbols[lastIdx];\n if (lastSymbol.view.y < this._maxY) return;\n const firstSymbol = this._symbols[0];\n lastSymbol.view.y = firstSymbol.view.y - this._slotHeight;\n // Maintain array order: last symbol becomes the new first.\n this._symbols.pop();\n this._symbols.unshift(lastSymbol);\n this._onSymbolWrapped(lastSymbol, 0, 'up');\n }\n\n private _wrapTopToBottom(): void {\n const firstSymbol = this._symbols[0];\n if (firstSymbol.view.y >= this._minY) return;\n const lastSymbol = this._symbols[this._symbols.length - 1];\n firstSymbol.view.y = lastSymbol.view.y + this._slotHeight;\n // Maintain array order: first symbol becomes the new last.\n this._symbols.shift();\n this._symbols.push(firstSymbol);\n this._onSymbolWrapped(firstSymbol, this._symbols.length - 1, 'down');\n }\n}\n","/**\n * The \"what do I land on\" queue for one reel.\n *\n * When a reel enters its stop phase, the `SpinController` loads the\n * target frame (the exact list of symbol ids that should appear on\n * screen, top-to-bottom, including the off-screen buffers). As the reel\n * keeps scrolling downward during deceleration, every `ReelMotion` wrap\n * event asks this sequencer for the next symbol — and it hands them back\n * from the END of the frame first, because new symbols arrive at the\n * top of a reel scrolling downward.\n *\n * After the last symbol is consumed the reel lands, and what you see on\n * screen matches the loaded frame exactly.\n */\nexport class StopSequencer {\n private _frame: string[] = [];\n private _remaining: number = 0;\n\n /** Load a target frame in top-to-bottom order. */\n setFrame(frame: string[]): void {\n this._frame = [...frame];\n this._remaining = this._frame.length;\n }\n\n /** Deliver the next symbol (consumed from the end of the frame). */\n next(): string {\n if (this._remaining > 0) {\n this._remaining--;\n return this._frame[this._remaining];\n }\n return this._frame[0] ?? '';\n }\n\n get hasRemaining(): boolean {\n return this._remaining > 0;\n }\n\n get remaining(): number {\n return this._remaining;\n }\n\n reset(): void {\n this._frame = [];\n this._remaining = 0;\n }\n}\n","import type { SpinningMode } from './SpinningMode.js';\n\n/**\n * Standard top-to-bottom reel spinning.\n * Symbols scroll downward at constant speed, wrapping around.\n */\nexport class StandardMode implements SpinningMode {\n readonly name = 'standard';\n\n computeDeltaY(symbolHeight: number, speed: number, deltaMs: number): number {\n const raw = (symbolHeight * speed * deltaMs) / 1000;\n // Cap at half symbol height to prevent skipping\n return Math.min(raw, symbolHeight / 2);\n }\n}\n","import { Container } from 'pixi.js';\nimport type { Disposable } from '../utils/Disposable.js';\nimport { ReelSymbol } from '../symbols/ReelSymbol.js';\nimport type { SymbolFactory } from '../symbols/SymbolFactory.js';\nimport type { SymbolData } from '../config/types.js';\nimport { ReelMotion } from './ReelMotion.js';\nimport { StopSequencer } from './StopSequencer.js';\nimport { EventEmitter } from '../events/EventEmitter.js';\nimport type { ReelEvents } from '../events/ReelEvents.js';\nimport type { RandomSymbolProvider } from '../frame/RandomSymbolProvider.js';\nimport type { ReelViewport } from './ReelViewport.js';\nimport type { SpinningMode } from '../spin/modes/SpinningMode.js';\nimport { StandardMode } from '../spin/modes/StandardMode.js';\n\n/**\n * Internal placeholder for OCCUPIED cells inside a big-symbol block. Has\n * no animation, no rendering — its view is invisible. Not registered in\n * `SymbolFactory`; allocated directly by `Reel` and disposed with it.\n */\nclass OccupiedStub extends ReelSymbol {\n protected onActivate(): void { this.view.alpha = 0; this.view.visible = false; }\n protected onDeactivate(): void {}\n async playWin(): Promise<void> {}\n stopAnimation(): void {}\n resize(): void {}\n}\n\nexport interface ReelConfig {\n reelIndex: number;\n visibleRows: number;\n bufferAbove: number;\n bufferBelow: number;\n symbolWidth: number;\n symbolHeight: number;\n symbolGapX: number;\n symbolGapY: number;\n symbolsData: Record<string, SymbolData>;\n initialSymbols: string[];\n /**\n * Y offset of this reel relative to the viewport's top edge. Set by the\n * builder so jagged shapes (pyramids) align according to `reelAnchor`.\n * Default 0.\n */\n offsetY?: number;\n /**\n * Pixel height of this reel's box. Used for MultiWays cell-height\n * derivation (`reelHeight / visibleRows`). Defaults to\n * `visibleRows * symbolHeight`.\n */\n reelHeight?: number;\n /**\n * SPIN-time uniform cell height. During SPIN every reel uses this same\n * height. AdjustPhase later swaps to per-reel `reelHeight / visibleRows`.\n * Defaults to `symbolHeight`.\n */\n spinSymbolHeight?: number;\n}\n\n/**\n * Internal sentinel marking non-anchor cells of a big symbol's block.\n * Never crosses the public API — `getVisibleSymbols()` resolves it to the\n * anchor's id.\n */\nexport const OCCUPIED_SENTINEL = '__pixi_reels_occupied__';\n\n/**\n * One vertical column of a slot board.\n *\n * A `Reel` owns:\n * - the `ReelSymbol[]` currently on screen (a small buffer above the\n * visible rows + the visible rows + a small buffer below — so symbols\n * can fade in from off-screen cleanly)\n * - the `ReelMotion` that adds a Y delta each tick and wraps symbols\n * that scroll off the ends\n * - a `StopSequencer` — the queue of target symbols the reel still has\n * to land on before it can stop\n *\n * You generally do not touch a `Reel` directly. Drive the `ReelSet` and\n * let it fan out. Reels are exposed on `reelSet.reels` so you can read\n * the current grid (`reel.getSymbolAt(row)`) or listen to per-reel\n * events (`phase:enter`, `landed`, `symbol:created`, ...).\n */\nexport class Reel implements Disposable {\n public readonly container: Container;\n public readonly events: EventEmitter<ReelEvents>;\n public readonly reelIndex: number;\n\n /** Current symbols in order (top buffer → visible → bottom buffer). */\n public symbols: ReelSymbol[];\n\n /** Current spin speed (pixels per frame). Set by phases. */\n public speed: number = 0;\n\n /** Current spinning mode. */\n public spinningMode: SpinningMode = new StandardMode();\n\n public readonly motion: ReelMotion;\n public readonly stopSequencer: StopSequencer;\n\n private _symbolFactory: SymbolFactory;\n private _randomProvider: RandomSymbolProvider;\n private _viewport: ReelViewport;\n private _symbolsData: Record<string, SymbolData>;\n private _visibleRows: number;\n private _bufferAbove: number;\n private _symbolWidth: number;\n private _symbolHeight: number;\n private _offsetY: number;\n private _reelHeight: number;\n private _spinSymbolHeight: number;\n private _symbolGapY: number;\n private _symbolGapX: number;\n private _isDestroyed = false;\n private _isStopping = false;\n /**\n * Internal stub instances reused for OCCUPIED cells inside a big-symbol\n * block. Allocated on demand (one per concurrent OCCUPIED cell on this\n * reel), never pooled through `SymbolFactory`. The views are invisible —\n * the anchor symbol is sized up to cover the whole block.\n */\n private _occupiedStubs: OccupiedStub[] = [];\n /**\n * Per-row marker recording which rows are non-anchor cells of a big\n * symbol. Populated when frames are placed; consulted by `getVisibleSymbols`\n * and `getSymbolAt` so anchor identity propagates through the block.\n *\n * Indexed by visible-row 0..visibleRows-1. Each entry is `null` for a\n * normal cell, or `{ anchorRow }` for a cell occupied by another row's\n * anchor.\n */\n private _occupancy: Array<{ anchorRow: number } | null> = [];\n /**\n * Optional resolver for cross-reel OCCUPIED cells. Set by `ReelSet` so\n * `getVisibleSymbols()` returns the anchor's id even when the anchor\n * lives on a different reel (a 2×2 bonus straddles cols c, c+1).\n * Without it, cross-reel OCCUPIED cells return the OCCUPIED sentinel.\n */\n private _crossReelResolver: ((col: number, row: number) => string) | null = null;\n\n constructor(\n config: ReelConfig,\n symbolFactory: SymbolFactory,\n randomProvider: RandomSymbolProvider,\n viewport: ReelViewport,\n ) {\n this.reelIndex = config.reelIndex;\n this._symbolFactory = symbolFactory;\n this._randomProvider = randomProvider;\n this._viewport = viewport;\n this._symbolsData = config.symbolsData;\n this._visibleRows = config.visibleRows;\n this._bufferAbove = config.bufferAbove;\n this._symbolWidth = config.symbolWidth;\n this._symbolHeight = config.symbolHeight;\n this._offsetY = config.offsetY ?? 0;\n this._reelHeight = config.reelHeight ?? config.visibleRows * config.symbolHeight;\n this._spinSymbolHeight = config.spinSymbolHeight ?? config.symbolHeight;\n this._symbolGapY = config.symbolGapY;\n this._symbolGapX = config.symbolGapX;\n this._occupancy = new Array(config.visibleRows).fill(null);\n this.events = new EventEmitter<ReelEvents>();\n this.stopSequencer = new StopSequencer();\n\n // Create container positioned at the reel's X column. Sortable so that\n // per-symbol zIndex (set from symbolData.zIndex + visual row) controls\n // render order — bottom-row symbols render in front, and flagged \"big\"\n // symbols like wild/bonus can override to render above neighbors.\n this.container = new Container();\n this.container.sortableChildren = true;\n this.container.x = config.reelIndex * (config.symbolWidth + config.symbolGapX);\n this.container.y = this._offsetY;\n // Explicit zIndex so the reel's layer in `ReelViewport.maskedContainer`\n // (sortableChildren = true) is deterministic. Rightmost reel draws on\n // top by default — same visual order as insertion, but now set via\n // zIndex so callers can flip it for bottom-left diagonal overflow.\n this.container.zIndex = config.reelIndex;\n\n // Create initial symbols. Use spinSymbolHeight so during SPIN every reel\n // uses the same uniform cell height regardless of post-AdjustPhase shape.\n this.symbols = config.initialSymbols.map((symbolId, row) => {\n const symbol = symbolFactory.acquire(symbolId);\n symbol.resize(config.symbolWidth, this._spinSymbolHeight);\n return symbol;\n });\n\n // Create motion handler. SPIN-time slot height is `spinSymbolHeight`;\n // AdjustPhase reshapes motion to the per-reel cell height.\n this.motion = new ReelMotion(\n this.symbols,\n this._spinSymbolHeight,\n config.symbolGapY,\n config.bufferAbove,\n config.visibleRows,\n (symbol, row, direction) => this._onSymbolWrapped(symbol, row, direction),\n );\n\n // Position symbols on grid and add to containers\n this._setupSymbolPositions(config);\n }\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n get isStopping(): boolean {\n return this._isStopping;\n }\n\n set isStopping(value: boolean) {\n this._isStopping = value;\n }\n\n get bufferAbove(): number {\n return this._bufferAbove;\n }\n\n get bufferBelow(): number {\n return this.symbols.length - this._bufferAbove - this._visibleRows;\n }\n\n get visibleRows(): number {\n return this._visibleRows;\n }\n\n /** The symbol cell width (in pixels). Constant for the reel's lifetime. */\n get symbolWidth(): number {\n return this._symbolWidth;\n }\n\n /**\n * The symbol cell height (in pixels). Mutates on MultiWays reshape via\n * `reshape()`. During SPIN this still equals `spinSymbolHeight`; the\n * per-reel target value comes into effect when AdjustPhase commits the\n * reshape. For non-MultiWays slots this is constant for the reel's lifetime.\n */\n get symbolHeight(): number {\n return this._symbolHeight;\n }\n\n /** Pixel height of this reel's box. Set by builder, immutable. */\n get reelHeight(): number {\n return this._reelHeight;\n }\n\n /** Y offset of this reel relative to the viewport top. Set by builder, immutable. */\n get offsetY(): number {\n return this._offsetY;\n }\n\n /**\n * SPIN-time uniform cell height. All reels in a slot use this value during\n * the SPIN phase regardless of their per-reel `symbolHeight`. Frozen at\n * construction.\n */\n get spinSymbolHeight(): number {\n return this._spinSymbolHeight;\n }\n\n /** Update reel for one frame. Called by SpinController via ticker. */\n update(deltaMs: number): void {\n if (this.speed === 0) return;\n\n const deltaY = this.spinningMode.computeDeltaY(\n this.motion.slotHeight,\n this.speed,\n deltaMs,\n );\n\n if (deltaY !== 0) {\n this.motion.displace(deltaY);\n }\n }\n\n /** Set the target frame for stopping. */\n setStopFrame(frame: string[]): void {\n this.stopSequencer.setFrame(frame);\n }\n\n /**\n * Get visible symbol IDs (top to bottom, excluding buffers).\n *\n * Big-symbol cells resolve to the anchor's id — both **same-reel**\n * (the anchor lives on this reel) and **cross-reel** (the anchor is on\n * a leftward reel of a wider block). The cross-reel resolver is\n * injected by `ReelSet`; without it, cross-reel OCCUPIED cells would\n * return the OCCUPIED sentinel, which is the only difference vs.\n * `ReelSet.getVisibleGrid()`. With the resolver wired, the two are\n * equivalent for any reel — `reels.map(r => r.getVisibleSymbols())`\n * matches `reelSet.getVisibleGrid()`.\n */\n getVisibleSymbols(): string[] {\n const result: string[] = [];\n for (let row = 0; row < this._visibleRows; row++) {\n const occ = this._occupancy[row];\n if (occ) {\n const anchor = this.symbols[this._bufferAbove + occ.anchorRow];\n result.push(anchor.symbolId);\n } else {\n const id = this.symbols[this._bufferAbove + row].symbolId;\n if (id === OCCUPIED_SENTINEL && this._crossReelResolver) {\n result.push(this._crossReelResolver(this.reelIndex, row));\n } else {\n result.push(id);\n }\n }\n }\n return result;\n }\n\n /**\n * Internal: register a callback used to resolve cross-reel OCCUPIED\n * cells to the originating big-symbol's id. Wired by `ReelSet` so this\n * reel can answer \"what id is at (myCol, row)?\" even when the anchor is\n * on a different reel.\n *\n * @internal\n */\n setCrossReelResolver(resolver: ((col: number, row: number) => string) | null): void {\n this._crossReelResolver = resolver;\n }\n\n /**\n * Get symbol at a visible row (0-indexed from top visible).\n * For non-anchor cells of a big symbol, walks up to the anchor row and\n * returns the anchor symbol so animations target the actual visual.\n */\n getSymbolAt(visibleRow: number): ReelSymbol {\n const occ = this._occupancy[visibleRow];\n const anchorRow = occ ? occ.anchorRow : visibleRow;\n return this.symbols[this._bufferAbove + anchorRow];\n }\n\n /**\n * Anchor row for a visible row. Equals `visibleRow` for normal cells;\n * for non-anchor cells inside a big-symbol block, returns the row where\n * the anchor lives.\n *\n * @internal — used by `ReelSet.getSymbolFootprint` and the cross-reel\n * resolver wired in `ReelSet`'s constructor. Not intended for consumer\n * use; prefer `ReelSet.getSymbolFootprint(col, row)` which returns full\n * anchor + size info.\n */\n _getAnchorRow(visibleRow: number): number {\n const occ = this._occupancy[visibleRow];\n return occ ? occ.anchorRow : visibleRow;\n }\n\n /**\n * Record that the given visible row is the non-anchor cell of a big\n * symbol whose anchor lives at `anchorRow`. Pass `null` to clear the\n * occupancy mark.\n *\n * @internal — called by `_finalizeFrame` and the big-symbol coordinator.\n */\n _setOccupancy(visibleRow: number, anchorRow: number | null): void {\n if (anchorRow === null) {\n this._occupancy[visibleRow] = null;\n } else {\n this._occupancy[visibleRow] = { anchorRow };\n }\n }\n\n /** Notify all visible symbols that the reel has started spinning. */\n notifySpinStart(): void {\n for (let i = this._bufferAbove; i < this._bufferAbove + this._visibleRows; i++) {\n this.symbols[i].onReelSpinStart();\n }\n }\n\n /** Notify all visible symbols that the reel is about to stop (just before bounce). */\n notifySpinEnd(): void {\n for (let i = this._bufferAbove; i < this._bufferAbove + this._visibleRows; i++) {\n this.symbols[i].onReelSpinEnd();\n }\n }\n\n /** Notify all visible symbols that the reel has landed on its target. */\n notifyLanded(): void {\n for (let i = this._bufferAbove; i < this._bufferAbove + this._visibleRows; i++) {\n this.symbols[i].onReelLanded();\n }\n }\n\n /**\n * Snap all symbols to grid and finalize big-symbol layout. Called at the\n * end of every stop sequence.\n */\n snapToGrid(): void {\n this.motion.snapToGrid();\n this._finalizeFrame();\n this.refreshZIndex();\n }\n\n /**\n * Swap the symbol at a single visible row in-place, without restarting\n * the spin or rebuilding the rest of the strip.\n *\n * Useful for live presentation effects at rest — converting a wild\n * after a cascade pop, swapping to a sticky variant after a win —\n * without going through the full `placeSymbols` / `setResult` paths.\n *\n * The symbol's `zIndex`, parent (masked vs unmasked), and visual state\n * are reset by `_replaceSymbol` so callers don't need to follow up\n * with `refreshZIndex`. The motion layer is **not** snapped — call\n * `snapToGrid()` separately if you need to re-grid.\n *\n * Throws if:\n * - the reel is currently moving (`speed !== 0` or `isStopping`).\n * A mid-spin swap would be overwritten by the next wrap/stop frame\n * anyway; the fail-loud throw spares the caller the silent loss.\n * - `visibleRow` is out of `[0, visibleRows)`.\n * - `symbolId` is not registered.\n * - the row is a non-anchor cell of an existing big-symbol block.\n * - the row currently holds the anchor of a big-symbol block — big\n * blocks span multiple cells (and possibly reels) and require\n * `placeSymbols` + the cross-reel OCCUPIED coordinator.\n * - `symbolId` itself is a big symbol — same reason.\n *\n * Pin overlap is **not** detected at this layer (Reel doesn't see the\n * pin map). Use `ReelSet.setSymbolAt(col, row, id)` for the safe\n * caller-facing surface that also throws on pinned cells.\n */\n setSymbolAt(visibleRow: number, symbolId: string): void {\n if (this.speed !== 0 || this._isStopping) {\n throw new Error(\n `setSymbolAt: cannot swap mid-spin (speed=${this.speed}, isStopping=${this._isStopping}). ` +\n `Wait for the spin to land before calling, or use the result grid via setResult().`,\n );\n }\n if (!Number.isInteger(visibleRow) || visibleRow < 0 || visibleRow >= this._visibleRows) {\n throw new Error(\n `setSymbolAt: visibleRow ${visibleRow} is out of range [0, ${this._visibleRows}).`,\n );\n }\n if (!Object.prototype.hasOwnProperty.call(this._symbolsData, symbolId)) {\n throw new Error(\n `setSymbolAt: symbolId '${symbolId}' is not registered. Register it via builder.symbols(...).`,\n );\n }\n const occ = this._occupancy[visibleRow];\n if (occ) {\n throw new Error(\n `setSymbolAt: visible row ${visibleRow} is a non-anchor cell of a big symbol (anchor at row ${occ.anchorRow}). ` +\n `Use placeSymbols to rebuild the frame.`,\n );\n }\n const arrayIndex = this._bufferAbove + visibleRow;\n const oldSym = this.symbols[arrayIndex];\n const oldMeta = this._symbolsData[oldSym.symbolId];\n if (oldMeta?.size && (oldMeta.size.w > 1 || oldMeta.size.h > 1)) {\n throw new Error(\n `setSymbolAt: row ${visibleRow} currently holds the anchor of big symbol ` +\n `'${oldSym.symbolId}' (${oldMeta.size.w}x${oldMeta.size.h}). Big blocks span multiple ` +\n `cells (and possibly reels); use placeSymbols + the OCCUPIED coordinator instead.`,\n );\n }\n const newMeta = this._symbolsData[symbolId];\n if (newMeta?.size && (newMeta.size.w > 1 || newMeta.size.h > 1)) {\n throw new Error(\n `setSymbolAt: '${symbolId}' is a big symbol (${newMeta.size.w}x${newMeta.size.h}). ` +\n `Use placeSymbols + the OCCUPIED coordinator instead.`,\n );\n }\n this._replaceSymbol(arrayIndex, symbolId);\n }\n\n /**\n * Place symbols immediately at target positions (for skip/turbo).\n *\n * `symbolIds[0..n-1]` is the visible area. `symbolIds[n..]` (if present)\n * targets buffer-below slots. Buffer-above slots are addressed via\n * negative-index string properties: `symbolIds[-1]` is the slot closest to\n * the visible top row, `symbolIds[-bufferAbove]` the furthest above.\n * Unset slots are filled with random symbols, matching the previous\n * behaviour when only visible-area entries were provided.\n */\n placeSymbols(symbolIds: string[]): void {\n const totalSlots = this.symbols.length;\n const bufferAbove = this._bufferAbove;\n for (let i = 0; i < totalSlots; i++) {\n let targetId: string | undefined;\n if (i < bufferAbove) {\n // Buffer above: look up via negative-index string property.\n // i=0 → -bufferAbove (furthest); i=bufferAbove-1 → -1 (closest).\n const bufRow = i - bufferAbove;\n targetId = (symbolIds as Record<number, string | undefined>)[bufRow];\n } else {\n targetId = symbolIds[i - bufferAbove];\n }\n if (targetId === undefined) targetId = this._randomProvider.next(true);\n this._replaceSymbol(i, targetId);\n }\n this.motion.snapToGrid();\n this._finalizeFrame();\n this.refreshZIndex();\n }\n\n /**\n * @internal — MultiWays orchestration only.\n *\n * Commit a new visible-row count and per-reel cell height. Resizes every\n * existing symbol on the strip to the new cell height, rebuilds the\n * symbol array (extending or truncating buffers as needed), reshapes the\n * motion layer, and recomputes `_reelHeight` from the new geometry so\n * `reelHeight` stays consistent. Idempotent if the shape doesn't change.\n *\n * Only the engine should call this — `SpinController._applyReshape` is\n * the single source of truth for reshape orchestration. Direct external\n * calls are unsupported and may leave pin overlays, the cross-reel\n * resolver, and the parent `ReelSet`'s shape state out of sync. Use\n * `ReelSet.setShape()` instead, which gates this method on a MultiWays\n * slot and migrates pins atomically.\n */\n reshape(\n newVisibleRows: number,\n newSymbolHeight: number,\n bufferAbove: number,\n bufferBelow: number,\n ): void {\n const newTotal = bufferAbove + newVisibleRows + bufferBelow;\n\n // Grow: append additional symbols at the bottom buffer. New symbols are\n // parented based on `unmask` flag — same rule as `_replaceSymbol`.\n while (this.symbols.length < newTotal) {\n const id = this._randomProvider.next(true);\n const sym = this._symbolFactory.acquire(id);\n sym.resize(this._symbolWidth, newSymbolHeight);\n this._placeSymbolView(sym.view, sym.view.y, this._isUnmasked(id));\n this._parentForSymbolId(id).addChild(sym.view);\n this.symbols.push(sym);\n }\n\n // Shrink: release tail symbols.\n while (this.symbols.length > newTotal) {\n const sym = this.symbols.pop()!;\n if (sym instanceof OccupiedStub) {\n sym.view.parent?.removeChild(sym.view);\n } else {\n this._symbolFactory.release(sym);\n }\n }\n\n this._visibleRows = newVisibleRows;\n this._symbolHeight = newSymbolHeight;\n this._bufferAbove = bufferAbove;\n this._occupancy = new Array(newVisibleRows).fill(null);\n // Recompute pixel-box height from the new geometry. For MultiWays this\n // equals the fixed `multiways.reelPixelHeight` by construction (the cell\n // height is derived from it); for any non-MultiWays caller it matches\n // what the builder would have set at construction. Keeps `reelHeight`\n // from going stale across reshape.\n this._reelHeight =\n newVisibleRows * newSymbolHeight + (newVisibleRows - 1) * this._symbolGapY;\n\n // Resize every kept symbol to the new cell height.\n for (const sym of this.symbols) {\n if (sym instanceof OccupiedStub) continue;\n sym.resize(this._symbolWidth, newSymbolHeight);\n }\n\n // Update motion: new slot height + bounds.\n this.motion.reshape(newSymbolHeight, this._symbolGapY, bufferAbove, newVisibleRows);\n this.motion.snapToGrid();\n this.refreshZIndex();\n }\n\n /**\n * Compute the canonical zIndex for a single symbol view at a given\n * array index. Centralizes the formula used by both `refreshZIndex`\n * (full rescan) and the per-swap activate path (so newly placed\n * symbols land with their correct zIndex without the caller needing\n * to remember to call `refreshZIndex` afterwards).\n */\n private _computeSymbolZIndex(symbolId: string, index: number): number {\n const base = this._symbolsData[symbolId]?.zIndex ?? 0;\n return base * 100 + index;\n }\n\n /**\n * Recompute `zIndex` for every symbol in the reel.\n *\n * Formula: `symbolData.zIndex ?? 0` (scaled by 100 to leave room for row\n * ordering), plus the symbol's current array index — so bottom-row symbols\n * render in front of top-row symbols and any symbol with a higher\n * configured base zIndex (e.g. wild, bonus) renders above its neighbors.\n *\n * Called automatically after wraps, snaps, and direct placement. Also\n * called inline by `_replaceSymbol` for the single newly-placed symbol —\n * so consumers who swap one symbol at a time (via the public APIs that\n * funnel into `_replaceSymbol`) get correct layering for free, no\n * manual `refreshZIndex` required. Call it manually after mutating\n * `symbolsData.zIndex` at runtime.\n */\n refreshZIndex(): void {\n for (let i = 0; i < this.symbols.length; i++) {\n const symbol = this.symbols[i];\n if (symbol instanceof OccupiedStub) {\n symbol.view.zIndex = i;\n continue;\n }\n symbol.view.zIndex = this._computeSymbolZIndex(symbol.symbolId, i);\n }\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n for (const symbol of this.symbols) {\n if (symbol instanceof OccupiedStub) {\n symbol.destroy();\n } else {\n this._symbolFactory.release(symbol);\n }\n }\n for (const stub of this._occupiedStubs) {\n if (!stub.isDestroyed) stub.destroy();\n }\n this._occupiedStubs = [];\n this.symbols = [];\n this.events.removeAllListeners();\n this.container.destroy({ children: true });\n this._isDestroyed = true;\n this.events.emit('destroyed');\n }\n\n /**\n * Whether the symbol with this id has `unmask: true` in its data — i.e.\n * its view should be parented to `viewport.unmaskedContainer` to render\n * above the reel mask.\n */\n private _isUnmasked(symbolId: string): boolean {\n return !!this._symbolsData[symbolId]?.unmask;\n }\n\n /**\n * Pick the right parent container for a symbol view based on its\n * `unmask` flag. Unmasked symbols sit in `viewport.unmaskedContainer`\n * (above the reel mask); everything else lives in this reel's own\n * container (which is itself inside `viewport.maskedContainer`).\n */\n private _parentForSymbolId(symbolId: string): Container {\n return this._isUnmasked(symbolId)\n ? this._viewport.unmaskedContainer\n : this.container;\n }\n\n /**\n * Position a symbol view at a given reel-local Y, choosing X and any\n * parent-translation offset based on whether the symbol is unmasked.\n *\n * Unmasked views live in `viewport.unmaskedContainer` (at viewport\n * (0,0)), so we add `reel.container.x` and `reel.container.y` to keep\n * the at-rest cell position aligned with the reel column. Masked views\n * live in `this.container`, so reel-local coords map directly.\n */\n private _placeSymbolView(view: Container, reelLocalY: number, isUnmasked: boolean): void {\n if (isUnmasked) {\n view.x = this.container.x;\n view.y = this.container.y + reelLocalY;\n } else {\n view.x = 0;\n view.y = reelLocalY;\n }\n }\n\n /**\n * Convert a view's current y back to reel-local coords. The view may\n * be parented to either `this.container` (already reel-local) or\n * `viewport.unmaskedContainer` (viewport-local — needs the reel offset\n * subtracted).\n */\n private _toReelLocalY(view: Container): number {\n return view.parent === this._viewport.unmaskedContainer\n ? view.y - this.container.y\n : view.y;\n }\n\n private _setupSymbolPositions(config: ReelConfig): void {\n const slotH = this._spinSymbolHeight + config.symbolGapY;\n // Add the reel container to the viewport's masked area first so\n // `this.container.x/y` are in viewport coords if any initial symbol\n // has `unmask: true` and needs parent-translation.\n this._viewport.maskedContainer.addChild(this.container);\n\n for (let i = 0; i < this.symbols.length; i++) {\n const symbol = this.symbols[i];\n const y = (i - config.bufferAbove) * slotH;\n const unmasked = this._isUnmasked(symbol.symbolId);\n this._placeSymbolView(symbol.view, y, unmasked);\n this._parentForSymbolId(symbol.symbolId).addChild(symbol.view);\n }\n }\n\n private _onSymbolWrapped(symbol: ReelSymbol, row: number, direction: 'up' | 'down'): void {\n let newSymbolId: string;\n if (this._isStopping && this.stopSequencer.hasRemaining) {\n newSymbolId = this.stopSequencer.next();\n } else {\n newSymbolId = this._randomProvider.next();\n }\n\n this._replaceSymbol(this.symbols.indexOf(symbol), newSymbolId);\n // Array was rearranged by ReelMotion (pop+unshift or shift+push), so the\n // array index of every remaining symbol changed — refresh all zIndexes.\n this.refreshZIndex();\n }\n\n private _replaceSymbol(index: number, newSymbolId: string): void {\n const oldSymbol = this.symbols[index];\n const isOldStub = oldSymbol instanceof OccupiedStub;\n // The old symbol's `view.parent` is unsafe as a destination because\n // the shared symbol pool can recycle a view across reels (or the\n // spotlight may have promoted it above the mask). Always re-pick\n // the destination from `_parentForSymbolId(newSymbolId)` (or\n // `this.container` for OCCUPIED stubs, which never carry `unmask`).\n\n // Capture old Y in reel-local coords before releasing — old view may\n // have been parented to viewport.unmaskedContainer and need an offset\n // subtraction to be reused as the new symbol's reel-local Y.\n const reelLocalY = isOldStub\n ? oldSymbol.view.y\n : this._toReelLocalY(oldSymbol.view);\n\n // OCCUPIED: install a stub. Stubs are not pooled through SymbolFactory\n // and never carry an `unmask` flag — they always live in `this.container`.\n if (newSymbolId === OCCUPIED_SENTINEL) {\n if (isOldStub) {\n oldSymbol.view.alpha = 0;\n return;\n }\n this._symbolFactory.release(oldSymbol);\n const stub = this._acquireOccupiedStub();\n stub.view.y = reelLocalY;\n stub.view.x = 0;\n stub.view.alpha = 0;\n stub.view.visible = true;\n stub.view.scale.set(1, 1);\n stub.view.zIndex = index;\n // Stubs are never unmasked — always live in this reel's container.\n if (stub.view.parent !== this.container) this.container.addChild(stub.view);\n this.symbols[index] = stub;\n return;\n }\n\n // Replacing a stub with a real symbol: release stub back to internal\n // cache. The new symbol may be unmasked → choose parent + offset by id.\n if (isOldStub) {\n this._releaseOccupiedStub(oldSymbol);\n const newSymbol = this._symbolFactory.acquire(newSymbolId);\n const newIsUnmasked = this._isUnmasked(newSymbolId);\n newSymbol.resize(this._symbolWidth, this._symbolHeight);\n this._placeSymbolView(newSymbol.view, reelLocalY, newIsUnmasked);\n newSymbol.view.alpha = 1;\n newSymbol.view.scale.set(1, 1);\n newSymbol.view.zIndex = this._computeSymbolZIndex(newSymbolId, index);\n this._parentForSymbolId(newSymbolId).addChild(newSymbol.view);\n this.symbols[index] = newSymbol;\n this.events.emit('symbol:created', newSymbolId, index);\n return;\n }\n\n // Same id fast-path. Reset every mutable visual property (alpha, scale,\n // rotation, filters, zIndex) AND re-anchor the view to this reel's\n // container in case the pool moved it elsewhere since the last\n // activation (e.g. spotlight promotion above the mask).\n if (oldSymbol.symbolId === newSymbolId) {\n oldSymbol.view.alpha = 1;\n oldSymbol.view.scale.set(1, 1);\n oldSymbol.view.rotation = 0;\n oldSymbol.view.filters = null;\n oldSymbol.view.zIndex = this._computeSymbolZIndex(newSymbolId, index);\n // Same id → same unmask status; pick the right destination by id\n // so an unmasked symbol stays in `unmaskedContainer` post-spotlight.\n const target = this._parentForSymbolId(newSymbolId);\n if (oldSymbol.view.parent !== target) target.addChild(oldSymbol.view);\n // Reset Y in case spotlight or another mutator displaced it.\n this._placeSymbolView(oldSymbol.view, reelLocalY, this._isUnmasked(newSymbolId));\n return;\n }\n\n this._symbolFactory.release(oldSymbol);\n const newSymbol = this._symbolFactory.acquire(newSymbolId);\n const newIsUnmasked = this._isUnmasked(newSymbolId);\n newSymbol.resize(this._symbolWidth, this._symbolHeight);\n this._placeSymbolView(newSymbol.view, reelLocalY, newIsUnmasked);\n newSymbol.view.alpha = 1;\n newSymbol.view.scale.set(1, 1);\n newSymbol.view.zIndex = this._computeSymbolZIndex(newSymbolId, index);\n\n this._parentForSymbolId(newSymbolId).addChild(newSymbol.view);\n\n this.symbols[index] = newSymbol;\n this.events.emit('symbol:created', newSymbolId, index);\n }\n\n /**\n * Acquire an OCCUPIED stub. Reuses any free stub stored locally; allocates\n * a new one if none are available. Stubs are never returned to\n * `SymbolFactory`.\n */\n private _acquireOccupiedStub(): OccupiedStub {\n for (const stub of this._occupiedStubs) {\n if (!stub.view.parent) return stub;\n }\n const stub = new OccupiedStub();\n stub.activate(OCCUPIED_SENTINEL);\n this._occupiedStubs.push(stub);\n return stub;\n }\n\n private _releaseOccupiedStub(stub: ReelSymbol): void {\n stub.view.parent?.removeChild(stub.view);\n }\n\n /**\n * After the visible target frame has been placed, scan visible rows to\n * size big-symbol anchors and populate the OCCUPIED occupancy map.\n *\n * Called from `snapToGrid` and `placeSymbols` so it runs both for normal\n * stop landing AND for skip/turbo. For non-anchor rows of a block, the\n * anchor symbol is sized to span the block; the OCCUPIED stub at that\n * row stays invisible underneath.\n */\n private _finalizeFrame(): void {\n this._occupancy = new Array(this._visibleRows).fill(null);\n\n for (let row = 0; row < this._visibleRows; row++) {\n const sym = this.symbols[this._bufferAbove + row];\n if (sym instanceof OccupiedStub) continue;\n const meta = this._symbolsData[sym.symbolId];\n if (!meta?.size) continue;\n const w = meta.size.w;\n const h = meta.size.h;\n if (w === 1 && h === 1) continue;\n\n // Size the anchor to span the block PLUS inter-cell gaps. A 2x2\n // block on a (cellW=80, cellH=80, gapX=4, gapY=4) layout covers\n // 2*80 + 1*4 = 164px wide, not 160px. Without the gap, the anchor\n // leaves a thin uncovered strip at the gap row/col.\n const blockW = w * this._symbolWidth + (w - 1) * this._symbolGapX;\n const blockH = h * this._symbolHeight + (h - 1) * this._symbolGapY;\n sym.resize(blockW, blockH);\n for (let dy = 1; dy < h; dy++) {\n const occRow = row + dy;\n if (occRow < this._visibleRows) {\n this._occupancy[occRow] = { anchorRow: row };\n }\n }\n }\n }\n}\n","import { Container, Graphics } from 'pixi.js';\nimport type { Disposable } from '../utils/Disposable.js';\n\n/**\n * Bounding rectangle for one reel — what `MaskStrategy` builds the clip\n * geometry from. Local to ReelViewport (origin = viewport top-left).\n */\nexport interface ReelMaskRect {\n /** Left edge of the reel column (= reel.container.x). */\n x: number;\n /** Top edge of the reel box (= reel.offsetY). */\n y: number;\n /** Width of the reel column — equals one symbol cell wide. */\n width: number;\n /** Height of the reel box — equals reel.reelHeight. */\n height: number;\n}\n\n/**\n * Strategy for building the viewport's clip mask. Public — pass a custom\n * implementation to `ReelSetBuilder.maskStrategy(...)` to clip the reels\n * with any shape PixiJS Graphics can express (rounded frames, hex grids,\n * etc.). v1 ships two strategies:\n *\n * - {@link RectMaskStrategy} — one rect per reel (default). Good for\n * pyramid layouts; symbols never leak buffer rows above/below.\n * - {@link SharedRectMaskStrategy} — single bounding-box rect spanning\n * every reel's tallest extent. Big symbols spanning multiple reels\n * render correctly even when reels have horizontal gaps; cross-reel\n * overlap (e.g. a 2×2 bonus straddling reel 2 and 3 with `symbolGap.x>0`)\n * needs this strategy.\n */\nexport interface MaskStrategy {\n /** Build (or rebuild) the mask graphic. Returns the Graphics to use as the mask. */\n build(rects: ReelMaskRect[], totalWidth: number, totalHeight: number): Graphics;\n /** Update the mask when reel boxes resize (e.g. MultiWays reshape). */\n update(graphics: Graphics, rects: ReelMaskRect[], totalWidth: number, totalHeight: number): void;\n}\n\n/**\n * v1 default: a per-reel rectangular mask. Each reel is clipped to its own\n * `(offsetY, reelHeight)` box so pyramid shapes clip cleanly without\n * buffer-row peek above or below short reels.\n *\n * PixiJS masks support multiple shapes inside a single Graphics — the union\n * of every filled shape is the visible region. So drawing one rect per reel\n * gives the engine a jagged-but-rectangular mask without a custom shader.\n *\n * **Caveat:** if reels have a horizontal `symbolGap.x > 0`, a symbol that\n * extends across the gap (e.g. a 2×2 bonus on a non-zero-gap layout) will\n * be clipped between the columns. Use {@link SharedRectMaskStrategy} in\n * that case, or set `symbolGap: { x: 0, y: ... }`.\n *\n * If `rects` is empty (the builder hasn't supplied per-reel rects yet),\n * this falls back to a single bounding-box rect.\n */\nexport class RectMaskStrategy implements MaskStrategy {\n build(rects: ReelMaskRect[], totalWidth: number, totalHeight: number): Graphics {\n const g = new Graphics();\n this._draw(g, rects, totalWidth, totalHeight);\n return g;\n }\n\n update(g: Graphics, rects: ReelMaskRect[], totalWidth: number, totalHeight: number): void {\n g.clear();\n this._draw(g, rects, totalWidth, totalHeight);\n }\n\n private _draw(g: Graphics, rects: ReelMaskRect[], totalW: number, totalH: number): void {\n if (rects.length === 0) {\n g.rect(0, 0, totalW, totalH).fill({ color: 0xffffff });\n return;\n }\n for (const r of rects) {\n g.rect(r.x, r.y, r.width, r.height).fill({ color: 0xffffff });\n }\n }\n}\n\n/**\n * Single bounding-box mask covering every reel's tallest extent. Use this\n * when symbols need to overlap across reel boundaries — typical for slots\n * with big symbols that span multiple columns (a 2×2 bonus, a 3×3 giant)\n * AND a non-zero `symbolGap.x`. Per-reel rects would clip those symbols at\n * the column gaps; a single shared rect keeps them visible.\n *\n * Pyramid layouts using this strategy will show buffer rows above/below\n * short reels (the \"pyramid peek\" — covered by frame art in production).\n *\n * @example\n * builder.maskStrategy(new SharedRectMaskStrategy())\n */\nexport class SharedRectMaskStrategy implements MaskStrategy {\n build(rects: ReelMaskRect[], totalWidth: number, totalHeight: number): Graphics {\n const g = new Graphics();\n this._draw(g, rects, totalWidth, totalHeight);\n return g;\n }\n\n update(g: Graphics, rects: ReelMaskRect[], totalWidth: number, totalHeight: number): void {\n g.clear();\n this._draw(g, rects, totalWidth, totalHeight);\n }\n\n private _draw(g: Graphics, _rects: ReelMaskRect[], totalW: number, totalH: number): void {\n g.rect(0, 0, totalW, totalH).fill({ color: 0xffffff });\n }\n}\n\n/**\n * The clipping window + layering tricks for a reel set.\n *\n * The viewport is the \"looking-glass\" of the slot: a rectangle the size\n * of the visible grid with a PixiJS mask so symbols scrolling above or\n * below the visible rows are hidden. It also provides three stacking\n * layers so win animations can break out of the mask:\n *\n * - `maskedContainer` — the normal place for reels. Clipped to the\n * visible area so buffer rows never leak.\n * - `unmaskedContainer` — rendered on top of the mask. Use for a symbol\n * whose celebration animation expands beyond its cell (a big expanding\n * wild, a splash frame).\n * - `spotlightContainer` — above everything else. Win spotlight lifts\n * winning symbols here temporarily so dim overlay + bounce don't clip.\n *\n * `dimOverlay` is a semi-transparent rectangle the spotlight fades in\n * behind the promoted winners to visually push the losers into the\n * background.\n */\nexport class ReelViewport extends Container implements Disposable {\n public readonly maskedContainer: Container;\n public readonly unmaskedContainer: Container;\n public readonly spotlightContainer: Container;\n public readonly dimOverlay: Graphics;\n\n private _mask: Graphics;\n private _maskStrategy: MaskStrategy;\n private _maskWidth: number;\n private _maskHeight: number;\n private _maskRects: ReelMaskRect[] = [];\n private _isDestroyed = false;\n\n constructor(\n width: number,\n height: number,\n position: { x: number; y: number } = { x: 0, y: 0 },\n maskStrategy: MaskStrategy = new RectMaskStrategy(),\n ) {\n super();\n this.x = position.x;\n this.y = position.y;\n this._maskStrategy = maskStrategy;\n this._maskWidth = width;\n this._maskHeight = height;\n\n // Create mask graphic\n this._mask = this._maskStrategy.build(this._maskRects, width, height);\n\n // Masked container — main symbol area\n this.maskedContainer = new Container();\n this.maskedContainer.sortableChildren = true;\n this.maskedContainer.addChild(this._mask);\n this.maskedContainer.mask = this._mask;\n this.addChild(this.maskedContainer);\n\n // Unmasked container — for symbols with unmask flag\n this.unmaskedContainer = new Container();\n this.unmaskedContainer.sortableChildren = true;\n this.addChild(this.unmaskedContainer);\n\n // Dim overlay — for win animations\n this.dimOverlay = new Graphics();\n this.dimOverlay.rect(0, 0, width, height).fill({ color: 0x000000, alpha: 0.5 });\n this.dimOverlay.visible = false;\n this.addChild(this.dimOverlay);\n\n // Spotlight container — promoted symbols render above everything\n this.spotlightContainer = new Container();\n this.spotlightContainer.sortableChildren = true;\n this.addChild(this.spotlightContainer);\n }\n\n /** The viewport mask bounding box width (independent of children bounds). */\n get maskWidth(): number { return this._maskWidth; }\n /** The viewport mask bounding box height. */\n get maskHeight(): number { return this._maskHeight; }\n /** Per-reel mask rects last passed to the strategy. Used by debug overlays. */\n get maskRects(): readonly ReelMaskRect[] { return this._maskRects; }\n /** Internal mask Graphics. Exposed so debug helpers can recolor it. */\n get maskGraphics(): Graphics { return this._mask; }\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n /** Show the dim overlay with given opacity. */\n showDim(alpha: number = 0.5): void {\n this.dimOverlay.alpha = alpha;\n this.dimOverlay.visible = true;\n }\n\n /** Hide the dim overlay. */\n hideDim(): void {\n this.dimOverlay.visible = false;\n }\n\n /** Update mask size and per-reel rects. Used after pyramid/MultiWays shape changes. */\n updateMaskSize(width: number, height: number, rects: ReelMaskRect[] = []): void {\n this._maskWidth = width;\n this._maskHeight = height;\n this._maskRects = rects;\n this._maskStrategy.update(this._mask, this._maskRects, width, height);\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this._isDestroyed = true;\n super.destroy({ children: true });\n }\n}\n","import type { Reel } from '../../core/Reel.js';\nimport type { SpeedProfile } from '../../config/types.js';\n\n/**\n * Abstract base for reel spin phases.\n *\n * Each phase represents one stage of the spin lifecycle:\n * START → SPIN → ANTICIPATION → STOP.\n *\n * Phases are entered and exited by SpinController, and can be skipped\n * if marked as skippable and the user triggers skip/slam-stop.\n *\n * @typeParam TConfig - Phase-specific configuration type.\n */\nexport abstract class ReelPhase<TConfig = void> {\n abstract readonly name: string;\n abstract readonly skippable: boolean;\n\n protected _reel: Reel;\n protected _speed: SpeedProfile;\n protected _resolve: (() => void) | null = null;\n protected _isActive = false;\n\n constructor(reel: Reel, speed: SpeedProfile) {\n this._reel = reel;\n this._speed = speed;\n }\n\n get reel(): Reel {\n return this._reel;\n }\n\n get isActive(): boolean {\n return this._isActive;\n }\n\n /** Enter the phase. Returns a promise that resolves when the phase is complete. */\n async run(config: TConfig): Promise<void> {\n this._isActive = true;\n this._reel.events.emit('phase:enter', this.name);\n\n return new Promise<void>((resolve) => {\n this._resolve = () => {\n this._isActive = false;\n this._reel.events.emit('phase:exit', this.name);\n resolve();\n };\n this.onEnter(config);\n });\n }\n\n /** Skip the phase immediately (if skippable). */\n skip(): void {\n if (!this.skippable || !this._isActive) return;\n this.onSkip();\n this._complete();\n }\n\n /** Force-complete the phase regardless of skippable flag. */\n forceComplete(): void {\n if (!this._isActive) return;\n this.onSkip();\n this._complete();\n }\n\n /** Called each frame while the phase is active. */\n abstract update(deltaMs: number): void;\n\n /** Subclass: set up the phase (start tweens, set speed, etc). */\n protected abstract onEnter(config: TConfig): void;\n\n /** Subclass: clean up when skipped or force-completed. */\n protected abstract onSkip(): void;\n\n /** Call when the phase naturally completes. */\n protected _complete(): void {\n if (this._resolve) {\n const resolve = this._resolve;\n this._resolve = null;\n resolve();\n }\n }\n}\n","import { gsap as defaultGsap } from 'gsap';\n\n/**\n * The gsap instance every phase, motion tween, and cascade animation in\n * the engine reads from.\n *\n * **Why this indirection exists:** under tools that resolve modules through\n * symlinked workspaces (vite + a locally-linked pixi-reels, pnpm dev\n * setups, esbuild plugin chains), the gsap import inside the lib's\n * compiled `dist/index.js` and the gsap import in the consumer's source\n * can resolve to *different module instances* — each with its own root\n * timeline. The consumer drives one, the lib's tweens live on the other,\n * and reels stall at progress 0.\n *\n * The fix: every internal animation site reads gsap through `getGsap()`\n * instead of importing the `'gsap'` module directly. The builder method\n * `ReelSetBuilder.gsap(myGsap)` rebinds the singleton so the consumer's\n * gsap is the one the engine uses.\n *\n * Defaults to the gsap import resolved at lib-load time, so consumers\n * who don't hit the dual-instance trap don't have to do anything.\n */\nlet currentGsap: typeof defaultGsap = defaultGsap;\n\n/**\n * Replace the gsap instance the engine drives. Call this BEFORE\n * `ReelSetBuilder.build()` (the builder does this for you when you call\n * `.gsap(instance)`).\n *\n * Process-global: there's only one bound instance at a time. If you\n * build several ReelSets with different gsap instances, the last\n * `setGsap` call wins.\n */\nexport function setGsap(g: typeof defaultGsap): void {\n currentGsap = g;\n}\n\n/** The currently-bound gsap instance. */\nexport function getGsap(): typeof defaultGsap {\n return currentGsap;\n}\n","import type { gsap } from 'gsap';\nimport { getGsap } from '../../utils/gsapRef.js';\nimport { ReelPhase } from './ReelPhase.js';\nimport type { SpinningMode } from '../modes/SpinningMode.js';\n\nexport interface StartPhaseConfig {\n /** Spinning mode to set on enter. */\n spinningMode: SpinningMode;\n /** Delay before this reel starts (for staggered start). */\n delay?: number;\n}\n\n/**\n * Accelerates the reel from rest to full spin speed.\n *\n * Optionally performs a brief step-back (reel reverses a tiny amount) before\n * accelerating upward, giving the classic slot machine \"pull\" feel.\n */\nexport class StartPhase extends ReelPhase<StartPhaseConfig> {\n readonly name = 'start';\n readonly skippable = true;\n\n private _tween: gsap.core.Timeline | null = null;\n private _delayedCall: gsap.core.Tween | null = null;\n\n protected onEnter(config: StartPhaseConfig): void {\n const reel = this._reel;\n const speed = this._speed;\n const delay = config.delay ?? 0;\n\n reel.spinningMode = config.spinningMode;\n reel.speed = 0;\n\n if (delay > 0) {\n this._delayedCall = getGsap().delayedCall(delay / 1000, () => this._launch());\n } else {\n this._launch();\n }\n }\n\n private _launch(): void {\n this._delayedCall = null;\n const reel = this._reel;\n const speed = this._speed;\n const accelDuration = (speed.accelerationDuration ?? 300) / 1000;\n const accelEase = speed.accelerationEase ?? 'power2.in';\n\n this._tween = getGsap().timeline();\n\n // Step-back: brief reverse to give a \"pull\" before launch.\n if (speed.bounceDistance > 0) {\n this._tween.to(reel, {\n speed: -2,\n duration: 0.05,\n ease: 'power1.out',\n });\n }\n\n this._tween.to(reel, {\n speed: speed.spinSpeed,\n duration: accelDuration,\n ease: accelEase,\n onComplete: () => {\n reel.notifySpinStart();\n this._complete();\n },\n });\n }\n\n update(_deltaMs: number): void {\n // Motion is driven by reel.speed, updated by Reel.update()\n }\n\n protected onSkip(): void {\n this._kill();\n this._reel.speed = this._speed.spinSpeed;\n }\n\n private _kill(): void {\n if (this._delayedCall) {\n this._delayedCall.kill();\n this._delayedCall = null;\n }\n if (this._tween) {\n this._tween.kill();\n this._tween = null;\n }\n }\n}\n","import { ReelPhase } from './ReelPhase.js';\n\nexport interface SpinPhaseConfig {\n /** Minimum time to spin before allowing stop. Overrides speed profile if set. */\n minimumSpinTime?: number;\n}\n\n/**\n * Continuous spinning at constant speed.\n *\n * Runs until externally resolved (when setResult arrives). Tracks minimum\n * spin time via ticker accumulation so it behaves consistently when the tab\n * is hidden (no reliance on wall-clock performance.now()).\n */\nexport class SpinPhase extends ReelPhase<SpinPhaseConfig> {\n readonly name = 'spin';\n readonly skippable = false;\n\n private _elapsed = 0;\n private _minTime = 0;\n private _readyToStop = false;\n\n protected onEnter(config: SpinPhaseConfig): void {\n this._elapsed = 0;\n this._minTime = config.minimumSpinTime ?? this._speed.minimumSpinTime ?? 500;\n this._readyToStop = false;\n }\n\n update(deltaMs: number): void {\n this._elapsed += deltaMs;\n if (this._readyToStop && this._elapsed >= this._minTime) {\n this._complete();\n }\n }\n\n /** Signal that this phase should end (called by SpinController when result arrives). */\n resolve(): void {\n this._readyToStop = true;\n if (this._elapsed >= this._minTime) {\n this._complete();\n }\n }\n\n protected onSkip(): void {\n // SpinPhase is not skippable.\n }\n}\n","import type { gsap } from 'gsap';\nimport { getGsap } from '../../utils/gsapRef.js';\nimport { ReelPhase } from './ReelPhase.js';\n\nexport interface StopPhaseConfig {\n /** Target symbols for this reel (full frame including buffers, top-to-bottom). */\n targetFrame: string[];\n /** Delay before this reel starts stopping (for staggered stop). */\n delay?: number;\n}\n\n/**\n * Stops the reel on the target frame with a weighted, slot-machine feel.\n *\n * Sequence:\n * 1. Wait for the staggered delay.\n * 2. Keep spinning at full speed with `isStopping` flagged. The target frame\n * is loaded into the StopSequencer; each wrap event at the top of the\n * reel pulls the next frame symbol — so targets arrive in the visible\n * area naturally, carrying the full momentum of the spin.\n * 3. When the sequencer is exhausted, snap to grid and bounce:\n * - overshoot downward by `bounceDistance` with `power1.out`\n * - settle back upward with `power1.out`\n * Both legs share a duration for a symmetric, weighty landing.\n */\nexport class StopPhase extends ReelPhase<StopPhaseConfig> {\n readonly name = 'stop';\n readonly skippable = true;\n\n private _config: StopPhaseConfig | null = null;\n private _delayTween: gsap.core.Tween | null = null;\n private _bounceTween: gsap.core.Timeline | null = null;\n private _stage: 'delay' | 'spinning' | 'bouncing' | 'done' = 'delay';\n private _baseY = 0;\n\n protected onEnter(config: StopPhaseConfig): void {\n this._config = config;\n this._stage = 'delay';\n this._baseY = this._reel.container.y;\n\n const delay = (config.delay ?? 0) / 1000;\n if (delay > 0) {\n this._delayTween = getGsap().delayedCall(delay, () => this._beginSpinOut());\n } else {\n this._beginSpinOut();\n }\n }\n\n private _beginSpinOut(): void {\n if (!this._config) return;\n const reel = this._reel;\n const speed = this._speed;\n\n reel.setStopFrame(this._config.targetFrame);\n reel.isStopping = true;\n // Restore full spin speed — anticipation or other phases may have lowered\n // it. Weighty stops need full momentum through the final frame.\n reel.speed = speed.spinSpeed;\n\n this._stage = 'spinning';\n }\n\n update(_deltaMs: number): void {\n if (this._stage !== 'spinning') return;\n // Sequencer consumes one symbol per wrap via Reel._onSymbolWrapped.\n // When it's empty, the target frame is fully placed — time to land.\n if (!this._reel.stopSequencer.hasRemaining) {\n this._landAndBounce();\n }\n }\n\n private _landAndBounce(): void {\n const reel = this._reel;\n const speed = this._speed;\n\n reel.speed = 0;\n reel.isStopping = false;\n reel.snapToGrid();\n reel.notifySpinEnd();\n reel.notifyLanded();\n\n const bounceDistance = speed.bounceDistance;\n if (bounceDistance <= 0) {\n this._stage = 'done';\n this._complete();\n return;\n }\n\n const legDuration = (speed.bounceDuration ?? 600) / 2000; // half of total, in seconds\n this._stage = 'bouncing';\n this._bounceTween = getGsap().timeline();\n this._bounceTween.to(reel.container, {\n y: this._baseY + bounceDistance,\n duration: legDuration,\n ease: 'power1.out',\n });\n this._bounceTween.to(reel.container, {\n y: this._baseY,\n duration: legDuration,\n ease: 'power1.out',\n onComplete: () => {\n this._stage = 'done';\n this._complete();\n },\n });\n }\n\n protected onSkip(): void {\n this._killTweens();\n const reel = this._reel;\n reel.speed = 0;\n reel.isStopping = false;\n\n if (this._stage !== 'done' && this._config) {\n const bufferAbove = reel.bufferAbove;\n const visible = reel.visibleRows;\n reel.placeSymbols(this._config.targetFrame.slice(bufferAbove, bufferAbove + visible));\n }\n reel.snapToGrid();\n reel.container.y = this._baseY;\n this._stage = 'done';\n }\n\n private _killTweens(): void {\n if (this._delayTween) {\n this._delayTween.kill();\n this._delayTween = null;\n }\n if (this._bounceTween) {\n this._bounceTween.kill();\n this._bounceTween = null;\n }\n }\n}\n","import type { gsap } from 'gsap';\nimport { getGsap } from '../../utils/gsapRef.js';\nimport { ReelPhase } from './ReelPhase.js';\n\nexport interface AnticipationPhaseConfig {\n /** Duration override in ms. Uses speed profile anticipationDelay if not set. */\n duration?: number;\n /** Speed multiplier during anticipation. Default: 0.3 (30% of spin speed). */\n speedMultiplier?: number;\n}\n\n/**\n * Anticipation phase: slow-down tease before a reel stops.\n *\n * Decelerates to a fraction of spin speed, holds for a duration, then hands\n * off to StopPhase. StopPhase resets speed to full spin speed at the start\n * of its spin-out stage, so leaving speed low here is fine.\n */\nexport class AnticipationPhase extends ReelPhase<AnticipationPhaseConfig> {\n readonly name = 'anticipation';\n readonly skippable = true;\n\n private _tween: gsap.core.Timeline | null = null;\n\n protected onEnter(config: AnticipationPhaseConfig): void {\n const reel = this._reel;\n const speed = this._speed;\n const duration = (config.duration ?? speed.anticipationDelay) / 1000;\n const targetSpeed = speed.spinSpeed * (config.speedMultiplier ?? 0.3);\n\n if (duration <= 0) {\n this._complete();\n return;\n }\n\n this._tween = getGsap().timeline();\n\n this._tween.to(reel, {\n speed: targetSpeed,\n duration: duration * 0.35,\n ease: 'power2.out',\n });\n this._tween.to({}, { duration: duration * 0.65, onComplete: () => this._complete() });\n }\n\n update(_deltaMs: number): void {\n // Driven by GSAP tweens\n }\n\n protected onSkip(): void {\n this._kill();\n this._reel.speed = this._speed.spinSpeed;\n }\n\n private _kill(): void {\n if (this._tween) {\n this._tween.kill();\n this._tween = null;\n }\n }\n}\n","import type { Reel } from '../../core/Reel.js';\nimport type { SpeedProfile } from '../../config/types.js';\nimport { ReelPhase } from './ReelPhase.js';\nimport { StartPhase } from './StartPhase.js';\nimport { SpinPhase } from './SpinPhase.js';\nimport { StopPhase } from './StopPhase.js';\nimport { AnticipationPhase } from './AnticipationPhase.js';\n\ntype PhaseConstructor<T extends ReelPhase<any> = ReelPhase<any>> =\n new (reel: Reel, speed: SpeedProfile) => T;\n\ntype PhaseCreatorFn<T extends ReelPhase<any> = ReelPhase<any>> =\n (reel: Reel, speed: SpeedProfile) => T;\n\n/**\n * Factory for creating reel phase instances.\n *\n * Ships with all four default phases pre-registered.\n * Users can override any phase by registering a custom constructor or factory function.\n * Use registerFactory() when the phase needs extra construction-time config\n * (e.g. cascade drop settings baked in via closure).\n */\nexport class PhaseFactory {\n private _registry = new Map<string, PhaseCreatorFn>();\n\n constructor() {\n this._registry.set('start', (r, s) => new StartPhase(r, s));\n this._registry.set('spin', (r, s) => new SpinPhase(r, s));\n this._registry.set('stop', (r, s) => new StopPhase(r, s));\n this._registry.set('anticipation', (r, s) => new AnticipationPhase(r, s));\n }\n\n /** Register or override a phase type by constructor. */\n register<T extends ReelPhase<any>>(name: string, PhaseClass: PhaseConstructor<T>): void {\n this._registry.set(name, (r, s) => new PhaseClass(r, s));\n }\n\n /**\n * Register or override a phase type by factory function.\n * Use this when the phase needs extra args at construction time.\n *\n * @example\n * factory.registerFactory('stop', (reel, speed) => new DropStopPhase(reel, speed, dropConfig));\n */\n registerFactory<T extends ReelPhase<any>>(\n name: string,\n factory: PhaseCreatorFn<T>,\n ): void {\n this._registry.set(name, factory);\n }\n\n /** Create a phase instance for a reel. */\n create<T extends ReelPhase<any> = ReelPhase<any>>(\n name: string,\n reel: Reel,\n speed: SpeedProfile,\n ): T {\n const creator = this._registry.get(name);\n if (!creator) {\n throw new Error(\n `Phase '${name}' not registered. Available: ${[...this._registry.keys()].join(', ')}`,\n );\n }\n return creator(reel, speed) as T;\n }\n\n has(name: string): boolean {\n return this._registry.has(name);\n }\n}\n","import type { Ticker } from 'pixi.js';\nimport type { Disposable } from './Disposable.js';\n\ntype TickerCallback = (ticker: Ticker) => void;\n\n/**\n * Safe wrapper around PixiJS Ticker subscriptions.\n *\n * Solves the #1 memory leak in the original library: dangling ticker callbacks.\n * When `destroy()` is called, ALL registered callbacks are automatically\n * removed from the ticker.\n *\n * Usage:\n * ```ts\n * const ref = new TickerRef(app.ticker);\n * ref.add((ticker) => reel.update(ticker));\n * // Later:\n * ref.destroy(); // all callbacks removed\n * ```\n */\nexport class TickerRef implements Disposable {\n private _callbacks: TickerCallback[] = [];\n private _isDestroyed = false;\n\n constructor(private _ticker: Ticker) {}\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n add(fn: TickerCallback): void {\n if (this._isDestroyed) return;\n this._callbacks.push(fn);\n this._ticker.add(fn);\n }\n\n remove(fn: TickerCallback): void {\n const idx = this._callbacks.indexOf(fn);\n if (idx !== -1) {\n this._callbacks.splice(idx, 1);\n this._ticker.remove(fn);\n }\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n for (const fn of this._callbacks) {\n this._ticker.remove(fn);\n }\n this._callbacks.length = 0;\n this._isDestroyed = true;\n }\n}\n","/**\n * Per-reel target shape for `ReelSet.setResult`. The explicit alternative to\n * the legacy `string[]` form where buffer-above slots are stored as\n * negative-index string properties (`arr[-1]`, `arr[-2]`).\n *\n * Both forms are accepted by `setResult`. The explicit form is easier to\n * type-check, serialize across worker/network boundaries, and read in code\n * reviews — internally the engine normalizes one to the other.\n */\nexport interface ColumnTarget {\n /** Visible-area target symbols, indexed `0 … visibleRows-1`. */\n visible: string[];\n /**\n * Buffer-above target symbols. `bufferAbove[0]` is the slot closest to the\n * visible top row; `bufferAbove[bufferAboveCount-1]` is the furthest above.\n * Equivalent to legacy `frame[col][-1] … frame[col][-bufferAboveCount]`.\n */\n bufferAbove?: (string | undefined)[];\n /**\n * Buffer-below target symbols. `bufferBelow[0]` is the slot closest to the\n * visible bottom row; later indices go further below.\n * Equivalent to legacy `frame[col][visibleRows] … frame[col][visibleRows + n - 1]`.\n */\n bufferBelow?: (string | undefined)[];\n}\n\n/**\n * True when `grid` is the explicit `ColumnTarget[]` form. False for the\n * legacy `string[][]` form. Discriminated by whether the first column is an\n * array (legacy) or a plain object (explicit).\n */\nexport function isColumnTargetGrid(\n grid: string[][] | ColumnTarget[],\n): grid is ColumnTarget[] {\n return grid.length > 0 && !Array.isArray(grid[0]);\n}\n\n/**\n * Clone a per-reel target grid while preserving negative-index slots used by\n * buffer-above targeting.\n *\n * **CONTRIBUTOR NOTE — do not replace with plain spread.**\n *\n * The legacy public API supports `frame[col][-1] = 'COIN'` for targeting\n * the cell just above the visible window. JavaScript stores that as a\n * string property `\"-1\"` on the array object. Standard spread (`[...col]`),\n * `structuredClone`, `JSON.stringify`, `Array.from`, and `postMessage`\n * **all silently drop** those non-numeric properties. Any code path that\n * needs to clone a result grid in the engine **must** route through this\n * helper, or buffer-above targeting will silently break end-to-end and the\n * integration tests in `tests/integration/setResult-bufferAbove.test.ts`\n * will fail. See `tests/unit/ColumnTarget.test.ts` for the canary.\n *\n * Two existing call sites depend on this:\n * - `ReelSet._applyPinsToGrid`\n * - `SpinController._coordinateBigSymbols`\n *\n * If you add a third clone site, use this helper there too.\n */\nexport function cloneTargetGrid(grid: string[][], bufferAbove: number): string[][] {\n return grid.map((col) => cloneColumn(col, bufferAbove));\n}\n\n/** Single-column form of {@link cloneTargetGrid}. Same contributor rules. */\nexport function cloneColumn(col: string[], bufferAbove: number): string[] {\n const out = [...col];\n for (let i = 1; i <= bufferAbove; i++) {\n const v = (col as Record<number, string | undefined>)[-i];\n if (v !== undefined) (out as Record<number, string>)[-i] = v;\n }\n return out;\n}\n\n/**\n * Convert a `ColumnTarget` to the legacy `string[]` form, materializing\n * `bufferAbove` entries as negative-index slots and `bufferBelow` entries as\n * indices `>= visible.length`. This is what the rest of the pipeline (the\n * `FrameBuilder` target-placement middleware, big-symbol coordinator, pins)\n * already understands.\n */\nexport function columnTargetToArray(target: ColumnTarget): string[] {\n const arr: string[] = [...target.visible];\n if (target.bufferBelow) {\n for (let i = 0; i < target.bufferBelow.length; i++) {\n const v = target.bufferBelow[i];\n if (v !== undefined) arr[target.visible.length + i] = v;\n }\n }\n if (target.bufferAbove) {\n for (let i = 0; i < target.bufferAbove.length; i++) {\n const v = target.bufferAbove[i];\n if (v !== undefined) (arr as Record<number, string>)[-1 - i] = v;\n }\n }\n return arr;\n}\n\n/**\n * Normalize either input form into the legacy `string[][]` shape the\n * pipeline runs on. Cheap when the input is already `string[][]` — returns\n * it unchanged. Otherwise materializes one `string[]` per column.\n *\n * Throws with a readable message if the columns are a mix of the two\n * shapes (e.g. `[ ['a','b'], { visible: ['c','d'] } ]`). TypeScript blocks\n * this at compile time, but a JS caller bypassing types would otherwise\n * crash later with a confusing `[...col]`-not-iterable error inside the\n * pipeline; we fail loudly at the entry point instead.\n */\nexport function toLegacyTargetGrid(\n grid: string[][] | ColumnTarget[],\n): string[][] {\n if (grid.length === 0) return grid as string[][];\n const firstIsArray = Array.isArray(grid[0]);\n for (let i = 1; i < grid.length; i++) {\n if (Array.isArray(grid[i]) !== firstIsArray) {\n const a = firstIsArray ? 'string[]' : 'ColumnTarget';\n const b = Array.isArray(grid[i]) ? 'string[]' : 'ColumnTarget';\n throw new Error(\n `setResult/initialFrame: mixed input shapes — column 0 is ${a} ` +\n `but column ${i} is ${b}. Use one shape consistently for all reels.`,\n );\n }\n }\n if (firstIsArray) return grid as string[][];\n return (grid as ColumnTarget[]).map(columnTargetToArray);\n}\n","import type { Ticker } from 'pixi.js';\nimport type { Reel } from '../core/Reel.js';\nimport type { SpeedProfile, SpinOptions, SymbolData } from '../config/types.js';\nimport type { SpeedManager } from '../speed/SpeedManager.js';\nimport type { FrameBuilder } from '../frame/FrameBuilder.js';\nimport type { SpinResult } from '../events/ReelEvents.js';\nimport { EventEmitter } from '../events/EventEmitter.js';\nimport type { ReelSetEvents } from '../events/ReelEvents.js';\nimport { PhaseFactory } from './phases/PhaseFactory.js';\nimport type { SpinPhase } from './phases/SpinPhase.js';\nimport type { ReelPhase } from './phases/ReelPhase.js';\nimport type { StartPhaseConfig } from './phases/StartPhase.js';\nimport type { StopPhaseConfig } from './phases/StopPhase.js';\nimport type { AnticipationPhaseConfig } from './phases/AnticipationPhase.js';\nimport type { AdjustPhaseConfig } from './phases/AdjustPhase.js';\nimport type { SpinningMode } from './modes/SpinningMode.js';\nimport { StandardMode } from './modes/StandardMode.js';\nimport type { Disposable } from '../utils/Disposable.js';\nimport { TickerRef } from '../utils/TickerRef.js';\nimport { OCCUPIED_SENTINEL } from '../core/Reel.js';\nimport type { CellPin } from '../pins/CellPin.js';\nimport { cloneTargetGrid } from '../frame/ColumnTarget.js';\n\n/**\n * MultiWays/big-symbol coordination hook injected by `ReelSet` into\n * `SpinController`. All callbacks are no-ops (and `isMultiWaysSlot=false`)\n * for non-MultiWays slots, so the standard chain is unchanged.\n */\nexport interface SpinControllerHooks {\n isMultiWaysSlot: boolean;\n symbolsData: Record<string, SymbolData>;\n /** Read pending MultiWays shape. Returns null when no shape is pending. */\n peekTargetShape(): number[] | null;\n /** Clear pending shape after AdjustPhase runs. */\n clearTargetShape(): void;\n /** Reel pixel-box height for MultiWays cell-height derivation. */\n multiwaysReelPixelHeight: number;\n symbolGapY: number;\n /** Reel-scoped pin lookup. Used to build AdjustPhase tween descriptors. */\n getPinsOnReel(reelIndex: number): CellPin[];\n /**\n * Migrate pins on a reel to a new visible-row count, returning the\n * resulting moves. Mutates the pin map directly inside ReelSet.\n */\n migratePinsForReel(reelIndex: number, newRows: number): {\n pin: CellPin;\n fromRow: number;\n toRow: number;\n clamped: boolean;\n }[];\n /**\n * Reposition + resize every pin overlay on the given reel. Called after\n * AdjustPhase commits a MultiWays reshape so overlays move to their new\n * (post-migration) row at the new cell size.\n */\n refreshPinOverlaysForReel(reelIndex: number): void;\n /**\n * Build AdjustPhase pin-overlay tween descriptors for a reel — one per\n * active pin overlay. Captures pre-reshape (current) Y/size from the\n * overlay and computes post-reshape target. Called BEFORE the reshape\n * commits so the \"from\" state reflects what's actually on screen.\n */\n buildPinOverlayTweens(\n reelIndex: number,\n targetSymbolHeight: number,\n symbolGapY: number,\n ): import('./phases/AdjustPhase.js').PinOverlayTween[];\n}\n\n/**\n * The conductor of a spin.\n *\n * A reel set has many moving parts; the `SpinController` is the single\n * brain that drives them in time. On `spin()` it walks every reel through\n * its phase state machine (`StartPhase` → `SpinPhase` → optional\n * `AnticipationPhase` → `StopPhase`), applies the per-reel staggered\n * delays from the `SpeedProfile`, and resolves a promise when the last\n * reel lands (or the spin is skipped).\n *\n * It does not draw anything — drawing lives on `Reel` and `ReelSymbol`.\n * It does not decide outcomes — that's `setResult(grid)` coming in from\n * your game code. Its one job is timing.\n *\n * Every interesting moment fires on the event bus:\n * `spin:start`, `spin:allStarted`, `spin:stopping`, `spin:reelLanded`,\n * `spin:allLanded`, `spin:complete`, `skip:requested`, `skip:completed`.\n */\nexport class SpinController implements Disposable {\n private _reels: Reel[];\n private _speedManager: SpeedManager;\n private _frameBuilder: FrameBuilder;\n private _phaseFactory: PhaseFactory;\n private _events: EventEmitter<ReelSetEvents>;\n private _tickerRef: TickerRef;\n private _spinningMode: SpinningMode;\n private _defaultSpinMode: 'standard' | 'cascade';\n private _currentSpinMode: 'standard' | 'cascade' = 'standard';\n private _hooks: SpinControllerHooks;\n\n private _isSpinning = false;\n private _spinStartTime = 0;\n private _resultSymbols: string[][] | null = null;\n private _anticipationReels: number[] = [];\n private _stopDelayOverride: number[] | null = null;\n private _activePhases: Map<number, ReelPhase<any>> = new Map();\n private _landedReels = new Set<number>();\n /**\n * Reels held for the current spin (per `SpinOptions.holdReels`). Held\n * reels skip START / SPIN / STOP and stay on their current symbols.\n * Cleared at the start of every spin.\n */\n private _heldReels = new Set<number>();\n private _wasSkipped = false;\n private _skipPending = false;\n private _isDestroyed = false;\n private _currentSpinResolve: ((result: SpinResult) => void) | null = null;\n /** Incremented on each new spin. If a callback sees a stale generation, it no-ops. */\n private _spinGeneration = 0;\n\n constructor(\n reels: Reel[],\n speedManager: SpeedManager,\n frameBuilder: FrameBuilder,\n phaseFactory: PhaseFactory,\n events: EventEmitter<ReelSetEvents>,\n ticker: Ticker,\n spinningMode?: SpinningMode,\n defaultSpinMode: 'standard' | 'cascade' = 'standard',\n hooks?: SpinControllerHooks,\n ) {\n this._reels = reels;\n this._speedManager = speedManager;\n this._frameBuilder = frameBuilder;\n this._phaseFactory = phaseFactory;\n this._events = events;\n this._tickerRef = new TickerRef(ticker);\n this._spinningMode = spinningMode ?? new StandardMode();\n this._defaultSpinMode = defaultSpinMode;\n this._hooks = hooks ?? {\n isMultiWaysSlot: false,\n symbolsData: {},\n peekTargetShape: () => null,\n clearTargetShape: () => {},\n multiwaysReelPixelHeight: 0,\n symbolGapY: 0,\n getPinsOnReel: () => [],\n migratePinsForReel: () => [],\n refreshPinOverlaysForReel: () => {},\n buildPinOverlayTweens: () => [],\n };\n\n this._tickerRef.add((ticker) => this._onTick(ticker));\n }\n\n get isSpinning(): boolean {\n return this._isSpinning;\n }\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n async spin(options?: SpinOptions): Promise<SpinResult> {\n if (this._isSpinning) {\n throw new Error('Cannot start a new spin while one is in progress.');\n }\n\n const mode = options?.mode ?? this._defaultSpinMode;\n if (mode === 'cascade' && !this._phaseFactory.has('dropStart')) {\n throw new Error(\n \"spin({ mode: 'cascade' }) requires .cascade(...) on the builder.\",\n );\n }\n this._currentSpinMode = mode;\n\n this._isSpinning = true;\n this._wasSkipped = false;\n this._skipPending = false;\n this._spinStartTime = performance.now();\n this._resultSymbols = null;\n this._anticipationReels = [];\n this._stopDelayOverride = null;\n this._landedReels.clear();\n this._activePhases.clear();\n this._heldReels = this._normalizeHoldReels(options?.holdReels);\n this._spinGeneration++;\n\n const generation = this._spinGeneration;\n const speed = this._speedManager.active;\n\n this._events.emit('spin:start');\n\n const resultPromise = new Promise<SpinResult>((resolve) => {\n this._currentSpinResolve = resolve;\n });\n\n // Degenerate case: every reel held → resolve next microtask with the\n // current visible grid. Spin emitted, but no animation runs.\n if (this._heldReels.size === this._reels.length) {\n Promise.resolve().then(() => {\n if (generation !== this._spinGeneration) return;\n this._finishSpin();\n });\n return resultPromise;\n }\n\n for (let i = 0; i < this._reels.length; i++) {\n if (this._heldReels.has(i)) continue;\n this._startReel(i, speed, generation);\n }\n\n return resultPromise;\n }\n\n /**\n * Filter `holdReels` down to a clean Set: drop out-of-range, drop\n * duplicates, drop non-integer entries. Returning a normalized set\n * makes every internal call site safe to read without re-validating.\n */\n private _normalizeHoldReels(input: number[] | undefined): Set<number> {\n const out = new Set<number>();\n if (!input) return out;\n for (const i of input) {\n if (Number.isInteger(i) && i >= 0 && i < this._reels.length) {\n out.add(i);\n }\n }\n return out;\n }\n\n setResult(symbols: string[][]): void {\n if (!this._isSpinning) return;\n // Fail-fast: validate big-symbol block fit so setResult throws at the\n // call site rather than later inside skip()/_tryBeginStopSequence().\n const visibleRowsForReel = (i: number): number => {\n const pendingShape = this._hooks.peekTargetShape();\n return pendingShape ? pendingShape[i] : this._reels[i].visibleRows;\n };\n this._coordinateBigSymbols(symbols, visibleRowsForReel);\n this._resultSymbols = symbols;\n this._tryBeginStopSequence();\n if (this._skipPending) {\n this._skipPending = false;\n this.skip();\n }\n }\n\n setAnticipation(reelIndices: number[]): void {\n // Held reels never reach AnticipationPhase, but filter here too so the\n // public API is forgiving — callers can pass a flat list without\n // tracking which indices are held this spin.\n this._anticipationReels = reelIndices.filter((i) => !this._heldReels.has(i));\n }\n\n /**\n * Override the per-reel stop delay (in ms). Pass one value per reel.\n * When set, these replace the staggered `reelIndex * speed.stopDelay`\n * pattern for the current spin. Cleared at the start of each new spin.\n */\n setStopDelays(delays: number[]): void {\n this._stopDelayOverride = [...delays];\n }\n\n /**\n * Slam-stop safe before `setResult()` arrives. Queues until a result is\n * set, then fires `skip()`. Otherwise equivalent to `skip()`.\n */\n requestSkip(): void {\n if (!this._isSpinning) return;\n if (this._resultSymbols) {\n this.skip();\n return;\n }\n this._skipPending = true;\n }\n\n skip(): void {\n if (!this._isSpinning) return;\n\n this._wasSkipped = true;\n this._events.emit('skip:requested');\n\n for (const [, phase] of this._activePhases) {\n phase.forceComplete();\n }\n this._activePhases.clear();\n\n this._spinGeneration++;\n\n if (this._resultSymbols) {\n // MultiWays skip: apply pending shape and big-symbol coordinator before\n // placement so reels land at the new shape with OCCUPIED sentinels.\n const pendingShape = this._hooks.peekTargetShape();\n const visibleRowsForReel = (i: number): number =>\n pendingShape ? pendingShape[i] : this._reels[i].visibleRows;\n const decorated = this._coordinateBigSymbols(this._resultSymbols, visibleRowsForReel);\n\n for (let i = 0; i < this._reels.length; i++) {\n if (this._landedReels.has(i)) continue;\n if (this._heldReels.has(i)) continue;\n const reel = this._reels[i];\n reel.speed = 0;\n reel.isStopping = false;\n\n if (this._hooks.isMultiWaysSlot && pendingShape) {\n // Pin migration already ran at setShape() time; reshape via the\n // shared helper that both paths use. No tween — skip is instant.\n //\n // Edge case: pins exist but the shape didn't change (`pendingShape`\n // is null). We don't refresh overlays here because they're about\n // to be destroyed in `_onSpinLanded` anyway — the cell symbols at\n // the pinned coords land via `placeSymbols(decorated[i])` below\n // and overlay the same id, so the player sees the right thing.\n // `pinMigrationDuration` doesn't apply on skip by design (slam\n // stop is meant to land *now*, not run a tween on the way there).\n this._applyReshape(i, pendingShape[i]);\n }\n\n reel.placeSymbols(decorated[i]);\n reel.notifySpinEnd();\n reel.notifyLanded();\n this._markLanded(i);\n }\n } else {\n for (let i = 0; i < this._reels.length; i++) {\n if (this._landedReels.has(i)) continue;\n if (this._heldReels.has(i)) continue;\n const reel = this._reels[i];\n reel.speed = 0;\n reel.isStopping = false;\n reel.snapToGrid();\n reel.notifySpinEnd();\n reel.notifyLanded();\n this._markLanded(i);\n }\n }\n\n this._events.emit('skip:completed');\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this._tickerRef.destroy();\n this._activePhases.clear();\n this._isDestroyed = true;\n }\n\n /**\n * Compute the target cell height for a reel given a target row count.\n * MultiWays slots derive cell height from the fixed `multiwaysReelPixelHeight`;\n * non-MultiWays slots return the reel's current `symbolHeight` unchanged.\n */\n private _targetCellHeightFor(reel: Reel, targetRows: number): number {\n if (this._hooks.multiwaysReelPixelHeight <= 0) return reel.symbolHeight;\n return (this._hooks.multiwaysReelPixelHeight - (targetRows - 1) * this._hooks.symbolGapY) / targetRows;\n }\n\n /**\n * Commit a reshape on one reel: emit `adjust:start`, call `reel.reshape()`,\n * refresh pin overlays, emit `adjust:complete`. Returns whether work was\n * actually done.\n *\n * **The single source of truth** for reshape orchestration — both the\n * normal AdjustPhase path AND the skip path call this. Avoids the\n * \"two parallel implementations\" bug magnet that previously had each\n * path duplicating the same compute-target-height + reshape + refresh +\n * emit-events logic.\n *\n * Pin migration already happened at `setShape()` time, so this method\n * only handles geometry + overlays.\n */\n private _applyReshape(reelIndex: number, targetRows: number): boolean {\n const reel = this._reels[reelIndex];\n const targetCellH = this._targetCellHeightFor(reel, targetRows);\n const fromRows = reel.visibleRows;\n\n if (targetRows === fromRows && targetCellH === reel.symbolHeight) {\n return false;\n }\n\n this._events.emit('adjust:start', { reelIndex, fromRows, toRows: targetRows });\n reel.reshape(targetRows, targetCellH, reel.bufferAbove, reel.bufferBelow);\n this._hooks.refreshPinOverlaysForReel(reelIndex);\n this._events.emit('adjust:complete', { reelIndex });\n return true;\n }\n\n // ── Internal ──────────────────────────────────────────\n\n private async _startReel(reelIndex: number, speed: SpeedProfile, generation: number): Promise<void> {\n if (generation !== this._spinGeneration) return;\n\n const reel = this._reels[reelIndex];\n\n const phaseKeys = this._currentSpinMode === 'cascade'\n ? { start: 'dropStart', stop: 'dropStop' }\n : { start: 'start', stop: 'stop' };\n\n // START → SPIN: chain via phase.run() promises (no busy-polling).\n const startPhase = this._phaseFactory.create<any>(phaseKeys.start, reel, speed);\n this._activePhases.set(reelIndex, startPhase);\n await startPhase.run({\n spinningMode: this._spinningMode,\n delay: reelIndex * speed.spinDelay,\n } as StartPhaseConfig);\n\n if (generation !== this._spinGeneration) return;\n\n const spinPhase = this._phaseFactory.create<SpinPhase>('spin', reel, speed);\n this._activePhases.set(reelIndex, spinPhase);\n const spinDone = spinPhase.run({});\n\n let allSpinning = true;\n for (let i = 0; i < this._reels.length; i++) {\n // Held reels never enter the phase chain; they don't gate\n // `spin:allStarted` or the stop-sequence start.\n if (this._heldReels.has(i)) continue;\n const phase = this._activePhases.get(i);\n if (!phase || phase.name !== 'spin') { allSpinning = false; break; }\n }\n if (allSpinning) {\n this._events.emit('spin:allStarted');\n this._tryBeginStopSequence();\n }\n\n await spinDone;\n if (generation !== this._spinGeneration) return;\n\n // MultiWays: AdjustPhase commits the new shape and migrates pins between\n // SpinPhase and StopPhase. Inserted only when builder.multiways() was\n // called — non-MultiWays slots skip this entirely.\n if (this._hooks.isMultiWaysSlot && this._phaseFactory.has('adjust')) {\n await this._runAdjustForReel(reel, reelIndex, speed, generation);\n if (generation !== this._spinGeneration) return;\n }\n\n // SpinPhase resolved (result arrived). Run ANTICIPATION (if requested) then STOP.\n const stopDelay = this._stopDelayFor(reelIndex, speed);\n const targetFrame = this._frameFor(reelIndex);\n\n if (this._anticipationReels.includes(reelIndex) && speed.anticipationDelay > 0) {\n this._events.emit('spin:stopping', reelIndex);\n const anticipationPhase = this._phaseFactory.create<any>('anticipation', reel, speed);\n this._activePhases.set(reelIndex, anticipationPhase);\n await anticipationPhase.run({} as AnticipationPhaseConfig);\n if (generation !== this._spinGeneration) return;\n } else {\n this._events.emit('spin:stopping', reelIndex);\n }\n\n const stopPhase = this._phaseFactory.create<any>(phaseKeys.stop, reel, speed);\n this._activePhases.set(reelIndex, stopPhase);\n await stopPhase.run({ targetFrame, delay: stopDelay } as StopPhaseConfig);\n if (generation !== this._spinGeneration) return;\n\n this._markLanded(reelIndex);\n }\n\n /**\n * MultiWays AdjustPhase orchestration: pull the pending shape, migrate\n * pins to their new rows, build pin-overlay tween descriptors, run the\n * phase. Emits `adjust:start` on entry and `adjust:complete` on exit.\n *\n * **Skips entirely** when there's no shape change AND no pin overlay on\n * this reel — no phase instance is constructed and no `adjust:*` events\n * fire. A spin where most reels have no work shouldn't pay for a phase\n * boundary or spam the event bus.\n */\n private async _runAdjustForReel(\n reel: Reel,\n reelIndex: number,\n speed: SpeedProfile,\n generation: number,\n ): Promise<void> {\n const targetShape = this._hooks.peekTargetShape();\n const targetRows = targetShape ? targetShape[reelIndex] : reel.visibleRows;\n const targetCellH = this._targetCellHeightFor(reel, targetRows);\n\n // Build tween descriptors BEFORE the reshape commits — they capture\n // each overlay's current on-screen pose as the tween's `from` state.\n const pinOverlays = this._hooks.buildPinOverlayTweens(\n reelIndex,\n targetCellH,\n this._hooks.symbolGapY,\n );\n\n // Commit the reshape via the shared helper (events + reel.reshape +\n // overlay refresh). Skip if no work and no overlays to tween.\n const reshapeHappened = this._applyReshape(reelIndex, targetRows);\n if (!reshapeHappened && pinOverlays.length === 0) {\n return;\n }\n\n // Run AdjustPhase purely as a tween phase — the geometry is already\n // committed. Phase only animates the pin overlays from their captured\n // pre-reshape pose to the new cell positions.\n if (pinOverlays.length === 0) {\n return;\n }\n const adjust = this._phaseFactory.create<any>('adjust', reel, speed);\n this._activePhases.set(reelIndex, adjust);\n await adjust.run({ pinOverlays } satisfies AdjustPhaseConfig);\n }\n\n private _stopDelayFor(reelIndex: number, speed: SpeedProfile): number {\n if (this._stopDelayOverride) {\n return this._stopDelayOverride[reelIndex] ?? 0;\n }\n return reelIndex * speed.stopDelay;\n }\n\n private _cachedFrames: string[][] | null = null;\n\n private _frameFor(reelIndex: number): string[] {\n if (!this._cachedFrames) return [];\n return this._cachedFrames[reelIndex];\n }\n\n private _tryBeginStopSequence(): void {\n if (!this._resultSymbols) return;\n\n for (let i = 0; i < this._reels.length; i++) {\n // Held reels never enter a phase chain — don't gate the stop\n // sequence on them.\n if (this._heldReels.has(i)) continue;\n const phase = this._activePhases.get(i);\n if (!phase || phase.name !== 'spin') return;\n }\n\n // For MultiWays, the per-reel target row count is whatever AdjustPhase\n // will reshape to. For frame-building purposes we need to send the\n // correct number of visible rows per reel. Pull the pending shape; if\n // unset, fall back to current reel.visibleRows.\n const pendingShape = this._hooks.peekTargetShape();\n const visibleRowsForReel = (i: number): number =>\n pendingShape ? pendingShape[i] : this._reels[i].visibleRows;\n\n // Big symbols: paint cross-reel OCCUPIED sentinels into the result grid\n // BEFORE per-reel frame building. The coordinator validates block fit\n // and rewrites cells; per-reel FrameBuilder then sees the sentinels and\n // RandomFillMiddleware skips them. Non-big-symbol slots are zero-cost.\n const decorated = this._coordinateBigSymbols(this._resultSymbols, visibleRowsForReel);\n\n // Build and cache frames using each reel's actual buffer/visible config.\n // Reels may differ in buffer size; build each independently. Held reels\n // get an empty placeholder — their entry is never read because no\n // StopPhase ever fires for them.\n const frames: string[][] = [];\n for (let i = 0; i < this._reels.length; i++) {\n if (this._heldReels.has(i)) {\n frames.push([]);\n continue;\n }\n const reel = this._reels[i];\n const rows = visibleRowsForReel(i);\n frames.push(\n this._frameBuilder.build(\n i,\n rows,\n reel.bufferAbove,\n reel.bufferBelow,\n decorated[i],\n ),\n );\n }\n this._cachedFrames = frames;\n\n // Resolve all non-held SpinPhases; each reel's _startReel awaits its own\n // spinDone, then independently runs ANTICIPATION/STOP. Held reels have\n // no SpinPhase to resolve.\n for (let i = 0; i < this._reels.length; i++) {\n if (this._heldReels.has(i)) continue;\n const spinPhase = this._activePhases.get(i) as SpinPhase;\n if (spinPhase?.resolve) spinPhase.resolve();\n }\n }\n\n /**\n * Big symbols cross-reel coordinator. Walks the result grid, locates big\n * symbols (those with `SymbolData.size.w * size.h > 1`), validates that\n * the block fits within reel bounds, and paints OCCUPIED sentinels into\n * the non-anchor cells so per-reel FrameBuilder leaves them alone.\n *\n * Pure: returns a new grid; does not mutate the input. Zero-overhead for\n * slots with no big symbols (the loop runs but never matches metadata).\n *\n * IMPORTANT: clones via `cloneTargetGrid`, not `grid.map(col => [...col])`.\n * Plain spread drops the negative-index string properties that carry\n * buffer-above targets — every downstream consumer (FrameBuilder,\n * placeSymbols) expects them to survive into `decorated[col]`. See the\n * helper's TSDoc for the full contract.\n */\n private _coordinateBigSymbols(\n grid: string[][],\n visibleRowsForReel: (i: number) => number,\n ): string[][] {\n const out = cloneTargetGrid(grid, this._reels[0]?.bufferAbove ?? 0);\n const symData = this._hooks.symbolsData;\n\n for (let col = 0; col < out.length; col++) {\n const rows = visibleRowsForReel(col);\n for (let row = 0; row < rows && row < out[col].length; row++) {\n const id = out[col][row];\n const meta = symData[id];\n if (!meta?.size) continue;\n const w = meta.size.w;\n const h = meta.size.h;\n if (w === 1 && h === 1) continue;\n\n // Validate block fit on this reel and across columns to the right.\n if (row + h > rows) {\n throw new Error(\n `big symbol '${id}' (${w}x${h}) at (col=${col}, row=${row}) ` +\n `exceeds reel ${col} height ${rows}.`,\n );\n }\n if (col + w > out.length) {\n throw new Error(\n `big symbol '${id}' (${w}x${h}) at (col=${col}, row=${row}) ` +\n `exceeds reel count ${out.length}.`,\n );\n }\n for (let dx = 0; dx < w; dx++) {\n const targetReel = col + dx;\n const targetRows = visibleRowsForReel(targetReel);\n if (row + h > targetRows) {\n throw new Error(\n `big symbol '${id}' (${w}x${h}) at (col=${col}, row=${row}) ` +\n `exceeds reel ${targetReel} height ${targetRows}.`,\n );\n }\n }\n\n // Paint OCCUPIED across the block (skip the anchor itself at dx=0,dy=0).\n for (let dy = 0; dy < h; dy++) {\n for (let dx = 0; dx < w; dx++) {\n if (dx === 0 && dy === 0) continue;\n out[col + dx][row + dy] = OCCUPIED_SENTINEL;\n }\n }\n }\n }\n return out;\n }\n\n private _markLanded(reelIndex: number): void {\n if (this._landedReels.has(reelIndex)) return;\n this._landedReels.add(reelIndex);\n\n const reel = this._reels[reelIndex];\n const symbols = reel.getVisibleSymbols();\n reel.events.emit('landed', symbols);\n this._events.emit('spin:reelLanded', reelIndex, symbols);\n\n // All NON-HELD reels accounted for → finish. Held reels never\n // _markLanded, but their slots count toward `reels.length`, so we\n // compare against the count that was supposed to actually animate.\n if (this._landedReels.size === this._reels.length - this._heldReels.size) {\n this._finishSpin();\n }\n }\n\n private _finishSpin(): void {\n const result: SpinResult = {\n symbols: this._reels.map((r) => r.getVisibleSymbols()),\n wasSkipped: this._wasSkipped,\n duration: performance.now() - this._spinStartTime,\n };\n\n this._isSpinning = false;\n this._activePhases.clear();\n this._cachedFrames = null;\n // MultiWays: the target shape was applied this spin; clear it so the next\n // spin starts fresh. Non-MultiWays: this is a no-op.\n this._hooks.clearTargetShape();\n\n this._events.emit('spin:allLanded', result);\n this._events.emit('spin:complete', result);\n\n if (this._currentSpinResolve) {\n this._currentSpinResolve(result);\n this._currentSpinResolve = null;\n }\n }\n\n private _onTick(ticker: Ticker): void {\n if (!this._isSpinning) return;\n\n const deltaMs = ticker.deltaMS;\n for (const reel of this._reels) {\n reel.update(deltaMs);\n }\n for (const phase of this._activePhases.values()) {\n if (phase.isActive) {\n phase.update(deltaMs);\n }\n }\n }\n}\n","import type { SpeedProfile } from '../config/types.js';\n\n/**\n * The tempo of your reels, as named presets.\n *\n * A `SpeedProfile` is a bundle of timings — how long the wind-up takes,\n * how fast the reel scrolls at full speed, how deep the landing bounce\n * is, which GSAP easing drives each transition. `SpeedManager` holds\n * those profiles by name and tracks which one is active.\n *\n * Built-in profiles: `normal` (default), `turbo`, `superTurbo`. Add your\n * own via `reelSet.speed.addProfile('cinematic', {...})`. Switch at\n * runtime with `reelSet.setSpeed('turbo')`.\n *\n * Speed changes take effect on the next spin — mid-spin switching\n * is deliberately not supported to keep animation state simple.\n */\nexport class SpeedManager {\n private _profiles = new Map<string, SpeedProfile>();\n private _activeName: string;\n private _active: SpeedProfile;\n\n constructor(profiles: Map<string, SpeedProfile>, initialSpeed: string) {\n for (const [name, profile] of profiles) {\n this._profiles.set(name, profile);\n }\n const initial = this._profiles.get(initialSpeed);\n if (!initial) {\n throw new Error(\n `Speed profile '${initialSpeed}' not found. Available: ${[...this._profiles.keys()].join(', ')}`,\n );\n }\n this._activeName = initialSpeed;\n this._active = initial;\n }\n\n /** The currently active speed profile. */\n get active(): Readonly<SpeedProfile> {\n return this._active;\n }\n\n /** Name of the currently active speed profile. */\n get activeName(): string {\n return this._activeName;\n }\n\n /** Switch to a different named speed profile. */\n set(name: string): { previous: SpeedProfile; current: SpeedProfile } {\n const profile = this._profiles.get(name);\n if (!profile) {\n throw new Error(\n `Speed profile '${name}' not found. Available: ${[...this._profiles.keys()].join(', ')}`,\n );\n }\n const previous = this._active;\n this._activeName = name;\n this._active = profile;\n return { previous, current: profile };\n }\n\n /** Add or replace a speed profile. */\n addProfile(name: string, profile: SpeedProfile): void {\n this._profiles.set(name, profile);\n }\n\n /** Get a profile by name, or undefined if not found. */\n getProfile(name: string): SpeedProfile | undefined {\n return this._profiles.get(name);\n }\n\n /** All registered profile names. */\n get profileNames(): string[] {\n return [...this._profiles.keys()];\n }\n}\n","import type { Reel } from '../core/Reel.js';\nimport type { ReelViewport } from '../core/ReelViewport.js';\nimport type { SymbolPosition } from '../events/ReelEvents.js';\nimport type { ReelSymbol } from '../symbols/ReelSymbol.js';\nimport type { Disposable } from '../utils/Disposable.js';\n\nexport interface SpotlightOptions {\n /** Opacity of the dim overlay (0-1). Default: 0.5. */\n dimAmount?: number;\n /** Whether to play win animation on spotlighted symbols. Default: true. */\n playWinAnimation?: boolean;\n /** Whether to re-parent symbols above the mask. Default: true. */\n promoteAboveMask?: boolean;\n}\n\nexport interface WinLine {\n positions: SymbolPosition[];\n}\n\nexport interface CycleOptions extends SpotlightOptions {\n /** Milliseconds to display each win line. Default: 2000. */\n displayDuration?: number;\n /** Milliseconds between lines. Default: 300. */\n gapDuration?: number;\n /** Number of cycles (-1 for infinite). Default: 1. */\n cycles?: number;\n}\n\ninterface PromotedSymbol {\n symbol: ReelSymbol;\n originalParent: any;\n position: SymbolPosition;\n}\n\n/**\n * The \"we just won\" visual primitive.\n *\n * The spotlight is what turns a landed grid into a celebration. Given a\n * list of winning cell positions, it:\n *\n * 1. Fades in the dim overlay behind everything (everything that is\n * not winning visually sinks into the background).\n * 2. Re-parents each winning `ReelSymbol` into the viewport's\n * spotlight layer so its animation isn't clipped by the reel mask.\n * 3. Calls `playWin()` on each winner (your symbol class's one-shot).\n * 4. When you call `hide()` or the cycle ends, it puts every symbol\n * back where it came from and removes the dim overlay.\n *\n * Two modes:\n * - `show(positions, options)` — one-shot. Cell highlight + promote +\n * play win. Returns when the animation fully ends.\n * - `cycle(lines, options)` — iterate multiple win lines with a\n * configurable per-line duration and gap, optionally repeating.\n *\n * Win detection is NOT part of this. pixi-reels never computes wins —\n * your server / game code decides which cells are winners and passes\n * them here. See [ADR 007](../../docs/adr/007-scope.md).\n */\nexport class SymbolSpotlight implements Disposable {\n private _reels: Reel[];\n private _viewport: ReelViewport;\n private _promoted: PromotedSymbol[] = [];\n private _isActive = false;\n private _isDestroyed = false;\n private _cycleAbort: AbortController | null = null;\n\n constructor(reels: Reel[], viewport: ReelViewport) {\n this._reels = reels;\n this._viewport = viewport;\n }\n\n get isActive(): boolean {\n return this._isActive;\n }\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n /** Show spotlight on specific positions. */\n async show(positions: SymbolPosition[], options: SpotlightOptions = {}): Promise<void> {\n this.hide(); // Clear any existing spotlight\n\n const {\n dimAmount = 0.5,\n playWinAnimation = true,\n promoteAboveMask = true,\n } = options;\n\n this._isActive = true;\n\n // Show dim overlay\n this._viewport.showDim(dimAmount);\n\n // Promote symbols\n const winPromises: Promise<void>[] = [];\n\n const seen = new Set<string>();\n for (const pos of positions) {\n const reel = this._reels[pos.reelIndex];\n if (!reel) continue;\n\n const symbol = reel.getSymbolAt(pos.rowIndex);\n if (!symbol) continue;\n\n // Avoid promoting the same physical symbol twice (e.g. a 2×2 big\n // symbol's anchor cell + its OCCUPIED cells all resolve to one symbol).\n const key = `${pos.reelIndex}:${reel._getAnchorRow(pos.rowIndex)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n\n // Track for hide() only when we're actually moving the view —\n // otherwise the entry's `originalParent` would become stale if the\n // shared symbol pool recycles this instance into a different reel\n // before the next hide(), and `hide()` would reparent it back to a\n // reel that no longer owns it (leaving a hole on the new owner).\n if (promoteAboveMask) {\n const originalParent = symbol.view.parent;\n this._promoted.push({ symbol, originalParent, position: pos });\n const globalPos = symbol.view.getGlobalPosition();\n this._viewport.spotlightContainer.addChild(symbol.view);\n const localPos = this._viewport.spotlightContainer.toLocal(globalPos);\n symbol.view.x = localPos.x;\n symbol.view.y = localPos.y;\n }\n\n if (playWinAnimation) {\n winPromises.push(symbol.playWin());\n }\n }\n\n if (winPromises.length > 0) {\n await Promise.all(winPromises);\n }\n }\n\n /** Hide the spotlight and return symbols to their original positions. */\n hide(): void {\n // Cancel any running cycle\n if (this._cycleAbort) {\n this._cycleAbort.abort();\n this._cycleAbort = null;\n }\n\n // Return promoted symbols. Skip any whose view has been moved out of\n // the spotlight container — that means the shared symbol pool has\n // recycled them into another reel since show(), and reparenting back\n // to `originalParent` would steal them from their new owner.\n for (const { symbol, originalParent } of this._promoted) {\n if (symbol.view.parent !== this._viewport.spotlightContainer) continue;\n if (originalParent) {\n const globalPos = symbol.view.getGlobalPosition();\n originalParent.addChild(symbol.view);\n const localPos = originalParent.toLocal(globalPos);\n symbol.view.x = localPos.x;\n symbol.view.y = localPos.y;\n }\n symbol.stopAnimation();\n }\n this._promoted = [];\n\n // Hide dim overlay\n this._viewport.hideDim();\n this._isActive = false;\n }\n\n /**\n * Cycle through win lines, showing each for a duration.\n * Returns when all cycles complete or when hide() is called.\n */\n async cycle(winLines: WinLine[], options: CycleOptions = {}): Promise<void> {\n const {\n displayDuration = 2000,\n gapDuration = 300,\n cycles = 1,\n } = options;\n\n if (winLines.length === 0) return;\n\n this._cycleAbort = new AbortController();\n const signal = this._cycleAbort.signal;\n\n let cycleCount = 0;\n while (cycles === -1 || cycleCount < cycles) {\n for (const line of winLines) {\n if (signal.aborted) return;\n await this.show(line.positions, options);\n await this._wait(displayDuration, signal);\n if (signal.aborted) return;\n this.hide();\n await this._wait(gapDuration, signal);\n }\n cycleCount++;\n }\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this.hide();\n this._isDestroyed = true;\n }\n\n private _wait(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal.addEventListener('abort', () => {\n clearTimeout(timer);\n resolve();\n }, { once: true });\n });\n }\n}\n","/**\n * A claim on a grid cell.\n *\n * A `CellPin` occupies a `{col, row}` position on the reel grid. It is\n * applied as a forced stop target when `setResult()` is called, so the\n * reel lands on the pinned symbol regardless of what the server sent for\n * that cell. It persists across spins according to its `turns` field.\n *\n * Pins unify every \"stays put\" mechanic in the library:\n *\n * - Sticky wild → `pin(col, row, 'wild', { turns: 3 })`\n * - Expanding wild → `pin(col, row, 'wild', { turns: 'eval' })`\n * - Hold & Win coin → `pin(col, row, 'coin', { turns: 'permanent', payload: { value: 50 } })`\n * - Multiplier wild → `pin(col, row, 'wild', { turns: 'permanent', payload: { multiplier: 3 } })`\n * - Sticky-win respin → `pin(col, row, symbolId, { turns: respinsLeft })`\n *\n * Movement (walking wild, trailing wild) is done via `reelSet.movePin()`\n * in a separate slice; state-only pins ship first.\n */\n/**\n * How a pin behaves when a MultiWays reshape changes the row count of its\n * reel. Non-MultiWays slots never reshape, so this value is irrelevant\n * there.\n *\n * - **`'origin'`** (default) — the pin migrates to `min(originRow, newRows - 1)`\n * on every reshape. Clamps when the shape is too small; **restores to\n * the origin** when the shape grows back. Prevents wander — a pin at\n * `originRow=3` clamped to row 2 on a 3-row shape returns to row 3 on\n * a later 5-row shape. The right default for sticky wilds, trailing\n * wilds, and any \"this position has meaning\" mechanic.\n *\n * - **`'frozen'`** — the pin stays at its current row if the new shape\n * fits, otherwise clamps to the last visible row AND **updates\n * `originRow` to the clamped position** so it never restores. Use when\n * the pin's row should be locked to wherever it is now, regardless of\n * future shape changes (e.g. a walking-wild on MultiWays where the\n * wild's \"current row\" IS the source of truth — restoring to a\n * pre-walk row would undo the walk).\n */\nexport type PinMigration = 'origin' | 'frozen';\n\nexport interface CellPin {\n /** Column (reel index) this pin is anchored to. */\n readonly col: number;\n /** Row (0 = top visible row) this pin is anchored to. */\n readonly row: number;\n /** Symbol id this pin forces onto its cell. */\n readonly symbolId: string;\n /**\n * Original row at pin creation. The pin migrates back toward this value\n * across MultiWays reshapes when `migration === 'origin'` (the default).\n * For `migration === 'frozen'` this is updated on every clamp so the\n * pin never restores to a higher row.\n *\n * Non-MultiWays: equals `row` and never changes.\n */\n readonly originRow: number;\n /**\n * Migration policy across MultiWays reshapes. Default `'origin'` —\n * see {@link PinMigration} for semantics.\n */\n readonly migration: PinMigration;\n /**\n * Lifetime of the pin:\n * - number → counts down after each completed spin; removed at 0\n * - 'eval' → valid for one spin only; cleared at the next spin start\n * - 'permanent' → persists until `unpin()` is called explicitly\n */\n readonly turns: number | 'eval' | 'permanent';\n /** Optional per-instance data: multiplier, value, tier — game-specific. */\n payload?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Options accepted by `reelSet.pin()`.\n *\n * **Calling `pin()` mid-reshape** (from a `shape:changed`, `pin:migrated`, or\n * `adjust:start` event handler) is allowed and well-defined: the new pin is\n * placed at the cell you pass, and `originRow` defaults to the **post-reshape**\n * row (i.e. whatever `row` is *now*, on the new shape). If you want the pin\n * to remember a different origin, pass `originRow` explicitly. The pin\n * participates in the next migration cycle like any other pin.\n */\nexport interface CellPinOptions {\n /** Defaults to 'permanent'. */\n turns?: number | 'eval' | 'permanent';\n /** Arbitrary per-instance data. */\n payload?: Record<string, unknown>;\n /**\n * Original row for MultiWays pin migration. Defaults to the row at pin\n * placement. With `migration === 'origin'` (default), the pin's `row`\n * migrates back toward this value when the shape grows enough to fit\n * it; with `migration === 'frozen'` this gets overwritten on every\n * clamp so the pin doesn't restore.\n */\n originRow?: number;\n /**\n * MultiWays migration policy. Default `'origin'` — clamp + restore.\n * Set to `'frozen'` for \"lock at current row, never restore\" semantics.\n * See {@link PinMigration}.\n */\n migration?: PinMigration;\n}\n\n/** Reason a pin expired. Fired with `pin:expired`. */\nexport type PinExpireReason = 'turns' | 'explicit' | 'eval';\n\n/** A grid coordinate. */\nexport interface CellCoord {\n col: number;\n row: number;\n}\n\n/** Options for `reelSet.movePin()` — flight animation tuning + lifecycle hooks. */\nexport interface MovePinOptions {\n /** Animation duration in milliseconds. Default 400. */\n duration?: number;\n /** GSAP easing string. Default 'power2.inOut'. */\n easing?: string;\n /**\n * Symbol id to use as the filler at the vacated cell. When omitted, the\n * engine picks a random symbol from its frame builder's random provider.\n */\n backfill?: string;\n /**\n * Fires after the flight symbol is acquired, positioned at `from`, and\n * added to the viewport — but before the tween begins. Use this hook to\n * drive animation state on the flight instance. For example: cast to\n * your `SpineSymbol` subclass and switch to a `run` animation for the\n * duration of the flight.\n *\n * `flight` is the pooled `ReelSymbol` instance. The type is `unknown` so\n * this module stays free of circular imports; cast in the caller.\n */\n onFlightCreated?: (flight: unknown) => void;\n /**\n * Fires after the tween completes, before the flight symbol is released\n * back to the pool. Use this hook to play a landing animation or return\n * a Spine symbol to `idle` before its instance is recycled.\n */\n onFlightCompleted?: (flight: unknown) => void;\n}\n\n/** Map key used internally and exposed by `reelSet.pins`. */\nexport function pinKey(col: number, row: number): string {\n return `${col}:${row}`;\n}\n","import { Container } from 'pixi.js';\nimport type { Disposable } from '../utils/Disposable.js';\nimport type { ReelSetInternalConfig, CellBounds, SymbolData, SpinOptions } from '../config/types.js';\nimport { EventEmitter } from '../events/EventEmitter.js';\nimport type { ReelSetEvents, SpinResult, } from '../events/ReelEvents.js';\nimport { Reel, } from './Reel.js';\nimport { ReelViewport } from './ReelViewport.js';\nimport { SpinController } from '../spin/SpinController.js';\nimport { SpeedManager } from '../speed/SpeedManager.js';\nimport { SymbolSpotlight, } from '../spotlight/SymbolSpotlight.js';\nimport type { SymbolFactory } from '../symbols/SymbolFactory.js';\nimport type { ReelSymbol } from '../symbols/ReelSymbol.js';\nimport type { FrameBuilder } from '../frame/FrameBuilder.js';\nimport type { PhaseFactory } from '../spin/phases/PhaseFactory.js';\nimport type { SpinningMode } from '../spin/modes/SpinningMode.js';\nimport type { CellPin, CellPinOptions, PinExpireReason, MovePinOptions, CellCoord } from '../pins/CellPin.js';\nimport { pinKey } from '../pins/CellPin.js';\nimport { getGsap } from '../utils/gsapRef.js';\nimport type { FrameMiddleware } from '../frame/FrameBuilder.js';\nimport type { ColumnTarget } from '../frame/ColumnTarget.js';\nimport { cloneTargetGrid, toLegacyTargetGrid } from '../frame/ColumnTarget.js';\n\nexport interface ReelSetParams {\n config: ReelSetInternalConfig;\n reels: Reel[];\n viewport: ReelViewport;\n symbolFactory: SymbolFactory;\n frameBuilder: FrameBuilder;\n phaseFactory: PhaseFactory;\n spinningMode: SpinningMode;\n defaultSpinMode: 'standard' | 'cascade';\n}\n\n/**\n * The runtime-mutable frame-builder pipeline exposed on `reelSet.frame`.\n * Matches `FrameBuilder.use/remove` — the internal machinery that already\n * exists; this is the ergonomic surface.\n */\nexport interface FrameAPI {\n /** Add a middleware. Sorted by `priority` on next frame build. */\n use(middleware: FrameMiddleware): void;\n /** Remove a middleware by `name`. No-op if absent. */\n remove(name: string): void;\n /** Current middleware list in registration order. */\n readonly middleware: ReadonlyArray<FrameMiddleware>;\n}\n\n/**\n * The whole slot board as one object.\n *\n * A `ReelSet` is a PixiJS `Container` that owns every reel, the spin\n * controller, the speed manager, and the win spotlight. You `addChild` it\n * to your stage and then drive it from the four public verbs below:\n *\n * - `spin()` — start the reels moving, returns a promise that resolves\n * when every reel has landed (or been slam-stopped)\n * - `setResult(grid)` — tell the reels what to land on; the spin\n * controller consumes this and each reel queues its target symbols\n * - `setAnticipation(reelIndices)` — slow the given reels before they\n * stop, for \"will the third scatter land?\" tension\n * - `skip()` — land immediately; useful for slam-stop UX\n *\n * Everything else is subsystems: `speed`, `spotlight`, `events`, `viewport`.\n * Construction goes through {@link ReelSetBuilder}, never `new ReelSet()`\n * directly — the builder enforces that every required piece is wired.\n *\n * ```ts\n * const reelSet = new ReelSetBuilder()\n * .reels(5).visibleSymbols(3).symbolSize(140, 140)\n * .symbols((r) => r.register('cherry', SpriteSymbol, { textures }))\n * .ticker(app.ticker)\n * .build();\n * app.stage.addChild(reelSet);\n *\n * const spin = reelSet.spin();\n * reelSet.setResult(await server.spin());\n * await spin;\n * ```\n *\n * Teardown cascades: one `reelSet.destroy()` disposes every child.\n */\nexport class ReelSet extends Container implements Disposable {\n /**\n * zIndex applied to pin overlays so they render above the reel strip.\n *\n * **The library's z-index budget**, for reference if you author symbols\n * that need to layer above defaults:\n *\n * | Layer | zIndex | Source |\n * |---|---|---|\n * | 1×1 symbol, default | `0 * 100 + arrayIndex` (~0–10) | `symbolData.zIndex ?? 0` |\n * | 1×1 symbol, elevated (`zIndex: 1` on `symbolData`) | `1 * 100 + arrayIndex` (~100) | `symbolData.zIndex` |\n * | Big-symbol anchor, default registration | `5 * 100 + arrayIndex` (~500) | recipe convention |\n * | Pin overlay (sticky/expanding wild during spin) | `10000` | `PIN_OVERLAY_Z_INDEX` |\n *\n * The 100× multiplier on `symbolData.zIndex` leaves room for per-row\n * stacking inside a layer (bottom rows render in front of top rows on\n * the same layer). The 10000 ceiling on pin overlays is set very high\n * so a consumer who sets `symbolData.zIndex: 50` (= 5000) still sits\n * below pins. If you need to stack ABOVE pin overlays — e.g. a win-\n * presenter symbol promotion — re-parent the symbol to\n * `viewport.spotlightContainer`, which is its own DisplayObject layer\n * above pin overlays.\n */\n private static readonly PIN_OVERLAY_Z_INDEX = 10000;\n\n private _events = new EventEmitter<ReelSetEvents>();\n private _reels: Reel[];\n private _viewport: ReelViewport;\n private _spinController: SpinController;\n private _speedManager: SpeedManager;\n private _spotlight: SymbolSpotlight;\n private _symbolFactory: SymbolFactory;\n private _frameBuilder: FrameBuilder;\n private _frameAPI: FrameAPI;\n private _isDestroyed = false;\n private _pins = new Map<string, CellPin>();\n /**\n * Visual overlays rendered above the reel viewport while a spin is in\n * motion. Each overlay is a pooled ReelSymbol sitting in the viewport's\n * unmaskedContainer at the pin's cell position — it keeps the pinned\n * symbol visible while the underlying reel scrolls. Created on\n * spin:start, destroyed on spin:allLanded. The pin is co-stored so\n * _destroyPinOverlay always has it available even after the pin is\n * removed from `_pins` (e.g. during unpin()).\n */\n private _pinOverlays = new Map<string, { pin: CellPin; overlay: ReelSymbol }>();\n\n /**\n * MultiWays: target row counts for the next AdjustPhase. Recorded by\n * `setShape()`, consumed by `SpinController` when it builds AdjustPhase\n * configs. `null` means \"no shape change pending\".\n */\n private _targetShape: number[] | null = null;\n\n /**\n * True once `setResult()` has been called for the current spin. Reset on\n * every `spin:start`. Used to enforce the contract that `setShape()`\n * must be called BEFORE `setResult()` — calling it after corrupts the\n * cached frames (pins were applied at their pre-migration rows; a later\n * setShape would migrate them but the frames are already built).\n */\n private _resultSetForCurrentSpin = false;\n\n /** Set at construction by the builder when `.multiways(...)` was called. */\n private _isMultiWaysSlot: boolean;\n private _multiwaysMinRows = 0;\n private _multiwaysMaxRows = 0;\n private _multiwaysReelPixelHeight = 0;\n\n /** Resolved per-symbol metadata (size, zIndex, etc). */\n private _symbolsData: Record<string, SymbolData>;\n\n /** Horizontal symbol gap (px). Used by `getBlockBounds` for big symbols. */\n private _configGapX: number;\n\n constructor(params: ReelSetParams) {\n super();\n\n this._reels = params.reels;\n this._viewport = params.viewport;\n this._symbolFactory = params.symbolFactory;\n this._frameBuilder = params.frameBuilder;\n this._symbolsData = params.config.symbols;\n this._configGapX = params.config.grid.symbolGap.x;\n this._isMultiWaysSlot = !!params.config.grid.multiways;\n if (params.config.grid.multiways) {\n this._multiwaysMinRows = params.config.grid.multiways.minRows;\n this._multiwaysMaxRows = params.config.grid.multiways.maxRows;\n this._multiwaysReelPixelHeight = params.config.grid.multiways.reelPixelHeight;\n }\n\n // Wire each reel's cross-reel resolver so `Reel.getVisibleSymbols()`\n // returns the anchor's id even when the OCCUPIED cell's anchor lives\n // on a different reel. Without this, per-reel surface returns the\n // sentinel for cross-reel cells — making it inconsistent with\n // `ReelSet.getVisibleGrid()`.\n for (const reel of this._reels) {\n reel.setCrossReelResolver((col, row) => {\n const fp = this.getSymbolFootprint(col, row);\n const anchorReel = this._reels[fp.anchor.col];\n // Anchor row is on its OWN reel — read its symbolId directly to\n // avoid recursing back through this resolver.\n return anchorReel.symbols[anchorReel.bufferAbove + fp.anchor.row].symbolId;\n });\n }\n\n const fb = this._frameBuilder;\n this._frameAPI = {\n use(mw: FrameMiddleware): void { fb.use(mw); },\n remove(name: string): void { fb.remove(name); },\n get middleware(): ReadonlyArray<FrameMiddleware> { return fb.middleware; },\n };\n\n // Speed manager\n this._speedManager = new SpeedManager(\n params.config.speeds,\n params.config.initialSpeed,\n );\n\n // Spin controller\n this._spinController = new SpinController(\n params.reels,\n this._speedManager,\n params.frameBuilder,\n params.phaseFactory,\n this._events,\n params.config.ticker,\n params.spinningMode,\n params.defaultSpinMode,\n {\n isMultiWaysSlot: this._isMultiWaysSlot,\n symbolsData: this._symbolsData,\n peekTargetShape: () => this._peekTargetShape(),\n clearTargetShape: () => this._clearTargetShape(),\n multiwaysReelPixelHeight: this._multiwaysReelPixelHeight,\n symbolGapY: params.config.grid.symbolGap.y,\n getPinsOnReel: (reelIndex) => this._pinsOnReel(reelIndex),\n migratePinsForReel: (reelIndex, newRows) => this._migratePinsForReel(reelIndex, newRows),\n refreshPinOverlaysForReel: (reelIndex) => this.refreshPinOverlaysForReel(reelIndex),\n buildPinOverlayTweens: (reelIndex, targetSymbolHeight, symbolGapY) =>\n this._buildPinOverlayTweens(reelIndex, targetSymbolHeight, symbolGapY),\n },\n );\n\n // Spotlight\n this._spotlight = new SymbolSpotlight(params.reels, params.viewport);\n\n // Add viewport to display\n this.addChild(this._viewport);\n\n // Pin lifecycle: decrement numeric turns when the spin lands; clear 'eval'\n // pins when the next spin starts.\n this._events.on('spin:allLanded', () => this._onSpinLanded());\n this._events.on('spin:start', () => this._onSpinStart());\n }\n\n // ─── Event system ──────────────────────────────────────────\n // Uses a dedicated emitter to avoid collision with PixiJS Container events.\n\n /** The event emitter for reel-specific events. */\n get events(): EventEmitter<ReelSetEvents> {\n return this._events;\n }\n\n // ─── Spin API ─────────────────────────────────────────────\n\n /**\n * Start spinning. Returns a promise that resolves when all (non-held)\n * reels land.\n *\n * Pass `{ holdReels: [i, ...] }` to keep specific columns frozen for\n * this spin — they skip START / SPIN / STOP entirely and stay on\n * whatever symbols they're currently showing. The use cases are\n * Hold & Win respins, sticky / expanding wilds, and \"the trigger\n * column stays in place\" bonus rounds.\n *\n * Pass `{ mode: 'standard' | 'cascade' }` to override the builder-time\n * default for a single spin (e.g. classic strip-spin on the first round,\n * drop-in on the cascade waves). `'cascade'` requires `.cascade(...)`\n * on the builder.\n *\n * @example\n * // Plain spin — every reel animates.\n * await reelSet.spin();\n *\n * @example\n * // Hold reels 0 and 4; only the middle three reroll.\n * const spin = reelSet.spin({ holdReels: [0, 4] });\n * reelSet.setResult(serverGrid); // entries at 0/4 are ignored\n * await spin;\n *\n * @example\n * // Per-spin cascade override.\n * await reelSet.spin({ mode: 'cascade' });\n *\n * See {@link SpinOptions} for the full contract (event behaviour,\n * setResult interaction, setAnticipation filtering).\n */\n async spin(options?: SpinOptions): Promise<SpinResult> {\n return this._spinController.spin(options);\n }\n\n /**\n * Set the target result symbols. Triggers the stop sequence.\n *\n * Two input shapes are accepted:\n *\n * 1. **Legacy `string[][]`** — one column per reel, row-indexed. Set\n * `frame[col][-1]` (or `[-2]`, etc.) to target a buffer-above slot,\n * `frame[col][visibleRows]` for buffer-below.\n * 2. **Explicit `ColumnTarget[]`** — `{ visible, bufferAbove?, bufferBelow? }`\n * per column. Preferred for code that crosses worker/network boundaries,\n * structuredClones, or JSON-serializes (the legacy form's negative-index\n * slots don't survive standard cloning; the explicit form does).\n *\n * If any pins are active (`reelSet.pin(...)`), their symbols are overlaid\n * onto the result before it reaches the stop sequencer — so pinned cells\n * always land on the pin's `symbolId` regardless of what the server sent.\n */\n setResult(symbols: string[][] | ColumnTarget[]): void {\n const grid = toLegacyTargetGrid(symbols);\n const withPins = this._applyPinsToGrid(grid);\n this._resultSetForCurrentSpin = true;\n this._spinController.setResult(withPins);\n }\n\n /** Set which reels should show anticipation before stopping. */\n setAnticipation(reelIndices: number[]): void {\n this._spinController.setAnticipation(reelIndices);\n }\n\n /**\n * Override the per-reel stop delay for the current spin (in ms).\n * Pass one value per reel. Cleared at the start of each new spin.\n *\n * @example\n * // Stagger the last two reels more than the default for dramatic effect:\n * reelSet.setStopDelays([0, 140, 280, 600, 1100]);\n */\n setStopDelays(delays: number[]): void {\n this._spinController.setStopDelays(delays);\n }\n\n /** Skip/slam-stop: immediately land all reels on target. */\n skip(): void {\n this._spinController.skip();\n }\n\n /** Slam-stop safe before `setResult()` arrives — queues until then. */\n requestSkip(): void {\n this._spinController.requestSkip();\n }\n\n /**\n * Swap the symbol at a single grid cell in-place, at rest.\n *\n * Caller-facing wrapper over `Reel.setSymbolAt` that ALSO refuses\n * pinned cells (since `Reel` itself can't see the pin map). Use this\n * for live presentation effects — sticky-after-win, mid-feature\n * rewrites — without going through `setResult()`.\n *\n * Throws (in addition to the per-reel guards documented on\n * `Reel.setSymbolAt`) if `(col, row)` currently has an active pin.\n * Use `unpin(col, row)` first if you intentionally want to overwrite it.\n *\n * @example\n * await reelSet.spin(); // landed\n * reelSet.setSymbolAt(2, 1, 'wild'); // swap centre cell to wild\n */\n setSymbolAt(col: number, row: number, symbolId: string): void {\n if (col < 0 || col >= this._reels.length) {\n throw new RangeError(`setSymbolAt: col ${col} out of range [0, ${this._reels.length})`);\n }\n if (this._pins.has(pinKey(col, row))) {\n throw new Error(\n `setSymbolAt: cell (${col}, ${row}) has an active pin. Call unpin(col, row) ` +\n `first if you intend to overwrite it.`,\n );\n }\n this._reels[col].setSymbolAt(row, symbolId);\n }\n\n /**\n * Set the drop order for cascade drop-in mechanics.\n *\n * A convenience wrapper over setStopDelays() for common patterns.\n * The stagger step defaults to the active speed profile's stopDelay\n * (or 150 ms if stopDelay is 0).\n *\n * Call this before or after setResult() — both work.\n *\n * @example\n * reelSet.setDropOrder('ltr'); // left-to-right\n * reelSet.setDropOrder('rtl'); // right-to-left\n * reelSet.setDropOrder('all'); // all columns simultaneously\n * reelSet.setDropOrder([0, 0, 200, 200, 400]); // custom per-reel delays\n */\n setDropOrder(order: 'ltr' | 'rtl' | 'all' | number[], stepMs?: number): void {\n if (Array.isArray(order)) {\n this._spinController.setStopDelays(order);\n return;\n }\n\n const n = this._reels.length;\n const step = stepMs ?? Math.max(this._speedManager.active.stopDelay, 150);\n let delays: number[];\n\n if (order === 'all') {\n delays = new Array(n).fill(0);\n } else if (order === 'ltr') {\n delays = Array.from({ length: n }, (_, i) => i * step);\n } else {\n delays = Array.from({ length: n }, (_, i) => (n - 1 - i) * step);\n }\n\n this._spinController.setStopDelays(delays);\n }\n\n get isSpinning(): boolean {\n return this._spinController.isSpinning;\n }\n\n /** Whether this slot was built with `.multiways(...)`. */\n get isMultiWaysSlot(): boolean {\n return this._isMultiWaysSlot;\n }\n\n // ─── MultiWays API ─────────────────────────────────────────\n\n /**\n * MultiWays: record the row count each reel should land on this spin. The\n * AdjustPhase between SPIN and STOP will reshape reels (resize symbols,\n * reshape motion) before the stop sequence runs.\n *\n * Must be called between `spin()` and `setResult()`. The shape stays in\n * effect for the current spin only — call again on every spin.\n *\n * Throws if:\n * - this slot was not built with `.multiways(...)`\n * - `rowsPerReel.length !== reelCount`\n * - any entry falls outside `[multiways.minRows, multiways.maxRows]`\n */\n setShape(rowsPerReel: number[]): void {\n if (!this._isMultiWaysSlot) {\n throw new Error('setShape(): slot was not built with .multiways(...) — call ReelSetBuilder.multiways() first.');\n }\n if (this._resultSetForCurrentSpin) {\n throw new Error(\n 'setShape(): must be called BEFORE setResult() in the current spin. ' +\n 'Calling setShape after setResult corrupts the cached frames (pins were ' +\n 'overlaid at their pre-migration rows). Reorder: spin() → setShape() → setResult().',\n );\n }\n if (rowsPerReel.length !== this._reels.length) {\n throw new Error(\n `setShape(): rowsPerReel length ${rowsPerReel.length} must equal reelCount ${this._reels.length}.`,\n );\n }\n for (let i = 0; i < rowsPerReel.length; i++) {\n const r = rowsPerReel[i];\n if (r < this._multiwaysMinRows || r > this._multiwaysMaxRows) {\n throw new Error(\n `setShape(): rowsPerReel[${i}] = ${r} out of range [${this._multiwaysMinRows}, ${this._multiwaysMaxRows}].`,\n );\n }\n }\n // Fast-path: if the requested shape matches the current shape per-reel,\n // there's nothing to do. Avoids spurious `shape:changed` events and\n // pointless migration loops in defensive callers that always invoke\n // `setShape` per spin even when the shape didn't actually change.\n let isUnchanged = true;\n for (let i = 0; i < this._reels.length; i++) {\n if (this._reels[i].visibleRows !== rowsPerReel[i]) {\n isUnchanged = false;\n break;\n }\n }\n if (isUnchanged) {\n return;\n }\n\n this._targetShape = [...rowsPerReel];\n this._events.emit('shape:changed', [...rowsPerReel]);\n\n // Migrate pins to their post-reshape rows EAGERLY — before any\n // `setResult` overlay or frame build runs. Otherwise a pin at row=4\n // on a 7-row reel is silently dropped when setResult overlays it onto\n // a 3-row grid (row 4 is out of bounds for the new shape).\n //\n // AdjustPhase later commits the geometry; the pin map is already at\n // the post-migration rows by then, so AdjustPhase only needs to\n // refresh overlays + tween (when implemented).\n for (let i = 0; i < this._reels.length; i++) {\n this._migratePinsForReel(i, rowsPerReel[i]);\n }\n }\n\n /**\n * Internal: read the pending MultiWays target shape (does not clear).\n * Used by `SpinController` via the hooks interface. Not part of the\n * public API — call `setShape()` to change shape.\n *\n * @internal\n */\n private _peekTargetShape(): number[] | null {\n return this._targetShape;\n }\n\n /**\n * Internal: clear the pending MultiWays target shape after the spin lands.\n *\n * @internal\n */\n private _clearTargetShape(): void {\n this._targetShape = null;\n }\n\n /**\n * Resolved grid, with all OCCUPIED cells (same-reel and cross-reel)\n * replaced by their anchor's symbol id. A 2×2 bonus reads as four\n * `'bonus'` cells.\n *\n * Equivalent to `reelSet.reels.map(r => r.getVisibleSymbols())` because\n * each reel has a cross-reel resolver wired in by ReelSet's constructor —\n * the per-reel surface and the grid surface are the same.\n */\n getVisibleGrid(): string[][] {\n return this._reels.map((r) => r.getVisibleSymbols());\n }\n\n /**\n * Footprint of the symbol at `(col, row)`.\n *\n * - 1×1 symbols: `{ anchor: { col, row }, size: { w: 1, h: 1 } }`.\n * - Big symbols: returns the anchor cell and block size.\n * - OCCUPIED cells: resolves transparently to the anchor.\n *\n * Useful for win presenters that need to highlight a whole NxM block.\n */\n getSymbolFootprint(\n col: number,\n row: number,\n ): { anchor: { col: number; row: number }; size: { w: number; h: number } } {\n if (col < 0 || col >= this._reels.length) {\n throw new RangeError(`getSymbolFootprint: col ${col} out of range [0, ${this._reels.length})`);\n }\n const reel = this._reels[col];\n if (row < 0 || row >= reel.visibleRows) {\n throw new RangeError(`getSymbolFootprint: row ${row} out of range [0, ${reel.visibleRows})`);\n }\n\n // Resolve OCCUPIED → anchor row on this reel. Cross-reel OCCUPIED\n // requires walking left to find the anchoring column with size.w > col.\n const anchorRow = reel._getAnchorRow(row);\n const anchorSym = reel.getSymbolAt(row);\n const meta = this._symbolsData[anchorSym.symbolId];\n const size = meta?.size && (meta.size.w > 1 || meta.size.h > 1)\n ? meta.size\n : { w: 1, h: 1 };\n\n // Resolve cross-reel anchor column: if the anchor symbol on THIS reel\n // is itself an OCCUPIED stub painted by a big symbol on a leftward\n // reel, walk left until we find a column where the row matches a big\n // symbol whose width covers our column.\n let anchorCol = col;\n for (let c = col - 1; c >= 0; c--) {\n const leftReel = this._reels[c];\n if (anchorRow >= leftReel.visibleRows) break;\n const leftAnchorRow = leftReel._getAnchorRow(anchorRow);\n const leftSym = leftReel.getSymbolAt(anchorRow);\n const leftMeta = this._symbolsData[leftSym.symbolId];\n if (leftMeta?.size && leftMeta.size.w > col - c) {\n anchorCol = c;\n return {\n anchor: { col: anchorCol, row: leftAnchorRow },\n size: leftMeta.size,\n };\n }\n }\n\n return { anchor: { col: anchorCol, row: anchorRow }, size };\n }\n\n /**\n * Pixel rectangle covering a big symbol's whole `N×M` block, in\n * ReelSet-local coordinates. Returns the anchor cell's bounds for 1×1\n * symbols. Pass any cell of a block — anchor or non-anchor — and you\n * get the same rect.\n *\n * Useful for win presenters drawing an outline around a whole bonus, or\n * any overlay aligned to the visible footprint of a big symbol:\n *\n * ```ts\n * const rect = reelSet.getBlockBounds(2, 1);\n * gfx.rect(rect.x, rect.y, rect.width, rect.height)\n * .stroke({ color: 0xff6b35, width: 4 });\n * reelSet.addChild(gfx);\n * ```\n *\n * For 1×1 cells this is equivalent to `getCellBounds(col, row)`. For\n * big-symbol cells it multiplies width/height by the block size and\n * starts from the anchor cell's bounds.\n */\n getBlockBounds(col: number, row: number): CellBounds {\n const fp = this.getSymbolFootprint(col, row);\n const anchorBounds = this.getCellBounds(fp.anchor.col, fp.anchor.row);\n // Block covers w * cellWidth + (w-1) * gapX horizontally — the\n // (w-1) inter-cell gaps are part of the block's visible footprint.\n // Same vertically for cellHeight + gapY.\n const reel = this._reels[fp.anchor.col];\n const gapX = this._configGapX;\n const slotH = reel.motion.slotHeight;\n const cellW = anchorBounds.width;\n const cellH = anchorBounds.height;\n const gapY = slotH - cellH;\n return {\n x: anchorBounds.x,\n y: anchorBounds.y,\n width: fp.size.w * cellW + (fp.size.w - 1) * gapX,\n height: fp.size.h * cellH + (fp.size.h - 1) * gapY,\n };\n }\n\n // ─── Speed API ────────────────────────────────────────────\n\n /** Speed profile manager. */\n get speed(): SpeedManager {\n return this._speedManager;\n }\n\n /** Change speed and emit event. */\n setSpeed(name: string): void {\n const { previous, current } = this._speedManager.set(name);\n this._events.emit('speed:changed', current, previous);\n }\n\n // ─── Spotlight API ────────────────────────────────────────\n\n get spotlight(): SymbolSpotlight {\n return this._spotlight;\n }\n\n // ─── Reel access ──────────────────────────────────────────\n\n /** Get all reels. */\n get reels(): readonly Reel[] {\n return this._reels;\n }\n\n /** Get a reel by index. */\n getReel(index: number): Reel {\n return this._reels[index];\n }\n\n /**\n * Returns the bounding box of a visible grid cell in ReelSet-local\n * coordinates (i.e. relative to this Container, before any parent\n * transforms). Row 0 is the top visible row.\n *\n * Use this to place payline graphics, hit areas, or debug overlays\n * that must align with a specific symbol cell:\n *\n * ```ts\n * const b = reelSet.getCellBounds(2, 1);\n * gfx.rect(b.x, b.y, b.width, b.height).stroke({ color: 0xff6b35 });\n * reelSet.addChild(gfx);\n * ```\n *\n * To convert to stage / global coordinates use PixiJS:\n * ```ts\n * const global = reelSet.toGlobal({ x: b.x, y: b.y });\n * ```\n */\n getCellBounds(col: number, row: number): CellBounds {\n if (col < 0 || col >= this._reels.length) {\n throw new RangeError(`getCellBounds: col ${col} out of range [0, ${this._reels.length})`);\n }\n const reel = this._reels[col];\n if (row < 0 || row >= reel.visibleRows) {\n throw new RangeError(`getCellBounds: row ${row} out of range [0, ${reel.visibleRows})`);\n }\n return {\n x: this._viewport.x + reel.container.x,\n y: this._viewport.y + reel.offsetY + row * reel.motion.slotHeight,\n width: reel.symbolWidth,\n height: reel.symbolHeight,\n };\n }\n\n /** Get the viewport. */\n get viewport(): ReelViewport {\n return this._viewport;\n }\n\n // ─── Pins (persistent cell claims) ────────────────────────\n //\n // A `CellPin` claims a grid cell: the strip cannot overwrite it, and\n // `setResult()` overlays the pin's symbolId at that cell before the\n // stop sequence runs. Pins persist across spins according to their\n // `turns` field. See `CellPin` for the full semantics.\n\n /**\n * Pin a symbol to a grid cell. Applied immediately if the reel is idle;\n * applied at the next `setResult()` otherwise. Fires `pin:placed`.\n *\n * Passing the same `(col, row)` replaces the previous pin — the old one\n * is replaced silently (no `pin:expired` fires for replacement).\n *\n * @example\n * // Sticky wild for 3 spins\n * reelSet.pin(2, 1, 'wild', { turns: 3 })\n *\n * // Hold & Win coin with a payout value\n * reelSet.pin(col, row, 'coin', { turns: 'permanent', payload: { value: 50 } })\n *\n * // Expanding wild — fill column for the current spin's evaluation only\n * for (let r = 0; r < 3; r++) reelSet.pin(2, r, 'wild', { turns: 'eval' })\n */\n pin(col: number, row: number, symbolId: string, options?: CellPinOptions): CellPin {\n if (col < 0 || col >= this._reels.length) {\n throw new Error(`pin(): col ${col} out of range [0, ${this._reels.length})`);\n }\n const reel = this._reels[col];\n if (row < 0 || row >= reel.visibleRows) {\n throw new Error(`pin(): row ${row} out of range [0, ${reel.visibleRows})`);\n }\n\n const pin: CellPin = {\n col,\n row,\n originRow: options?.originRow ?? row,\n migration: options?.migration ?? 'origin',\n symbolId,\n turns: options?.turns ?? 'permanent',\n payload: options?.payload,\n };\n\n const key = pinKey(col, row);\n // If we're replacing an existing pin, drop its overlay so a fresh one\n // with the new symbolId can be created.\n if (this._pins.has(key)) {\n this._destroyPinOverlay(key);\n }\n this._pins.set(key, pin);\n\n if (!this._spinController.isSpinning) {\n // Reel is idle: apply the pin visually on the reel itself so\n // `getVisibleSymbols()` matches what `pins` reports.\n this._applyPinVisually(col, row, symbolId);\n } else {\n // Mid-spin: create an overlay so the pinned symbol is visible\n // immediately even while the reel scrolls.\n this._ensurePinOverlay(pin);\n }\n\n this._events.emit('pin:placed', pin);\n return pin;\n }\n\n /**\n * Remove a pin at `(col, row)`. If no pin exists at that cell, this is a\n * no-op. Fires `pin:expired` with reason `'explicit'`.\n */\n unpin(col: number, row: number): void {\n const key = pinKey(col, row);\n const pin = this._pins.get(key);\n if (!pin) return;\n this._pins.delete(key);\n this._destroyPinOverlay(key);\n this._events.emit('pin:expired', pin, 'explicit');\n }\n\n /**\n * All active pins, keyed by `\"col:row\"`.\n *\n * Reads are safe at any time — during a spin the map reflects pins that\n * will apply to the NEXT `setResult()`, not the one already in flight.\n */\n get pins(): ReadonlyMap<string, CellPin> {\n return this._pins;\n }\n\n /** Convenience: get the pin at `(col, row)` or `undefined`. */\n getPin(col: number, row: number): CellPin | undefined {\n return this._pins.get(pinKey(col, row));\n }\n\n /**\n * Move an existing pin from one cell to another. Animates a flight symbol\n * between the two cells, updates pin state atomically, and resolves when\n * the animation completes.\n *\n * This is the engine-native replacement for ghost sprites in walking-wild\n * recipes. The flight symbol is a pooled `ReelSymbol` acquired from the\n * factory, parented briefly to the viewport's `unmaskedContainer` so it\n * can travel across reel boundaries without being clipped.\n *\n * Constraints:\n * - Only callable at rest (throws if `isSpinning === true`).\n * - `to` must be within the grid; no pin may already exist there.\n * - Calling with `from === to` is a no-op that still fires `pin:moved`.\n *\n * @example\n * // Walking wild — move the pinned wild one column left each spin\n * reelSet.events.on('spin:complete', async () => {\n * for (const pin of [...reelSet.pins.values()]) {\n * if (pin.col > 0) {\n * await reelSet.movePin(\n * { col: pin.col, row: pin.row },\n * { col: pin.col - 1, row: pin.row },\n * );\n * } else {\n * reelSet.unpin(pin.col, pin.row);\n * }\n * }\n * });\n */\n async movePin(\n from: CellCoord,\n to: CellCoord,\n opts?: MovePinOptions,\n ): Promise<void> {\n if (this._spinController.isSpinning) {\n throw new Error('movePin(): cannot move pin while spinning');\n }\n\n const fromKey = pinKey(from.col, from.row);\n const pin = this._pins.get(fromKey);\n if (!pin) {\n throw new Error(\n `movePin(): no pin at (${from.col}, ${from.row})`,\n );\n }\n\n // Validate `to` bounds (same rules as pin()).\n if (to.col < 0 || to.col >= this._reels.length) {\n throw new Error(\n `movePin(): to col ${to.col} out of range [0, ${this._reels.length})`,\n );\n }\n const toReel = this._reels[to.col];\n if (to.row < 0 || to.row >= toReel.visibleRows) {\n throw new Error(\n `movePin(): to row ${to.row} out of range [0, ${toReel.visibleRows})`,\n );\n }\n\n // No-op self-move: still fire the event so callers can treat it uniformly.\n if (from.col === to.col && from.row === to.row) {\n this._events.emit('pin:moved', pin, { col: from.col, row: from.row });\n return;\n }\n\n const toKey = pinKey(to.col, to.row);\n if (this._pins.has(toKey)) {\n throw new Error(\n `movePin(): a pin already exists at (${to.col}, ${to.row})`,\n );\n }\n\n // Update pin state first (atomic). The map now reflects the new position\n // immediately — any subsequent spin sees the pin at `to`.\n this._pins.delete(fromKey);\n const movedPin: CellPin = { ...pin, col: to.col, row: to.row, originRow: to.row };\n this._pins.set(toKey, movedPin);\n\n // An overlay at the old cell (from a prior spin-interrupted state)\n // is no longer accurate — drop it; the flight symbol takes over.\n this._destroyPinOverlay(fromKey);\n\n // Gather viewport-local coordinates for both cells. The flight symbol\n // will be parented to `viewport.unmaskedContainer`, whose local space\n // matches `maskedContainer` (both sit at (0,0) inside viewport) — so\n // `reel.container.x + symbol.view.x/y` gives us the right offset.\n const fromReel = this._reels[from.col];\n const fromCellY = fromReel.getSymbolAt(from.row).view.y;\n const toCellY = toReel.getSymbolAt(to.row).view.y;\n const fromX = fromReel.container.x;\n const toX = toReel.container.x;\n\n // Backfill the vacated cell with a filler. Takes effect immediately —\n // the vacated cell visually swaps to the backfill while the flight\n // symbol is still in motion.\n const backfill =\n opts?.backfill ?? this._frameBuilder.randomProvider.next(false);\n const fromVisible = fromReel.getVisibleSymbols();\n fromVisible[from.row] = backfill;\n fromReel.placeSymbols(fromVisible);\n\n // Spawn the flight symbol on the unmasked container so it renders above\n // the reels and can cross column boundaries.\n const flight = this._symbolFactory.acquire(pin.symbolId);\n flight.resize(fromReel.symbolWidth, fromReel.symbolHeight);\n flight.view.x = fromX;\n flight.view.y = fromCellY;\n this._viewport.unmaskedContainer.addChild(flight.view);\n\n // onFlightCreated hook — fires after the flight symbol is in place but\n // before the tween begins. This is where consumers switch a Spine\n // symbol onto a `run` animation for the flight duration.\n try {\n opts?.onFlightCreated?.(flight);\n } catch { /* caller bug — don't let a hook kill the animation */ }\n\n // Tween.\n const duration = (opts?.duration ?? 400) / 1000;\n const easing = opts?.easing ?? 'power2.inOut';\n await new Promise<void>((resolve) => {\n getGsap().to(flight.view, {\n x: toX,\n y: toCellY,\n duration,\n ease: easing,\n onComplete: () => resolve(),\n });\n });\n\n // onFlightCompleted hook — fires before releasing the flight symbol,\n // so consumers can return a Spine to `idle` or play a landing animation.\n try {\n opts?.onFlightCompleted?.(flight);\n } catch { /* ignore */ }\n\n // Apply the pin visually at the destination cell.\n const toVisible = toReel.getVisibleSymbols();\n toVisible[to.row] = pin.symbolId;\n toReel.placeSymbols(toVisible);\n\n // Release the flight symbol.\n this._viewport.unmaskedContainer.removeChild(flight.view);\n this._symbolFactory.release(flight);\n\n this._events.emit('pin:moved', movedPin, {\n col: from.col,\n row: from.row,\n });\n }\n\n // ─── Frame pipeline (strip generation) ────────────────────\n //\n // Exposes the runtime-mutable FrameBuilder middleware pipeline on ReelSet\n // so recipes can add/remove frame middleware after build — the entry\n // point for mode-specific strip changes (feature weights, mystery\n // injection, positional overrides) without a full rebuild.\n //\n // The internal machinery was already present on FrameBuilder; this is\n // pure exposure — no behaviour change for recipes that don't call it.\n\n /**\n * Runtime-mutable middleware pipeline for symbol-frame generation.\n *\n * @example\n * // Feature entry — swap to a middleware that injects more wilds\n * reelSet.frame.use(moreWildsMiddleware);\n *\n * // Feature exit\n * reelSet.frame.remove('more-wilds');\n */\n get frame(): FrameAPI {\n return this._frameAPI;\n }\n\n // ─── Lifecycle ────────────────────────────────────────────\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this._isDestroyed = true;\n\n this._spotlight.destroy();\n this._spinController.destroy();\n\n for (const reel of this._reels) {\n reel.destroy();\n }\n\n this._destroyAllPinOverlays();\n this._symbolFactory.destroy();\n this._viewport.destroy();\n this._pins.clear();\n this._events.emit('destroyed');\n this._events.removeAllListeners();\n\n super.destroy({ children: true });\n }\n\n // ─── Pin internals ────────────────────────────────────────\n\n /**\n * Return a deep copy of `symbols` with active pins overlaid. Pure — does\n * not mutate the input. When there are no pins, returns the input as-is\n * (fast path; identical behaviour to pre-pin code).\n *\n * IMPORTANT: clones via `cloneTargetGrid`, not `symbols.map(col => [...col])`.\n * Spread drops the negative-index string properties that carry buffer-above\n * targets (`col[-1] = 'COIN'`). If you refactor this method, keep the\n * helper. See `cloneTargetGrid`'s TSDoc for the full contract.\n */\n private _applyPinsToGrid(symbols: string[][]): string[][] {\n if (this._pins.size === 0) return symbols;\n\n const cloned = cloneTargetGrid(symbols, this._reels[0]?.bufferAbove ?? 0);\n for (const pin of this._pins.values()) {\n if (pin.col < cloned.length && pin.row < cloned[pin.col].length) {\n cloned[pin.col][pin.row] = pin.symbolId;\n }\n }\n return cloned;\n }\n\n /** Pins on a given reel, in row order. Used by AdjustPhase migration. */\n private _pinsOnReel(reelIndex: number): CellPin[] {\n const result: CellPin[] = [];\n for (const pin of this._pins.values()) {\n if (pin.col === reelIndex) result.push(pin);\n }\n return result;\n }\n\n /**\n * MultiWays: relocate pins on a reel for a new visible-row count. The new\n * row is computed as `min(originRow, newRows - 1)` — clamped only when\n * the origin no longer fits. Returns the migrated pins so AdjustPhase\n * can build tween descriptors. Mutates the pins map in place.\n */\n private _migratePinsForReel(reelIndex: number, newRows: number): {\n pin: CellPin;\n fromRow: number;\n toRow: number;\n clamped: boolean;\n }[] {\n const migrations: {\n pin: CellPin;\n fromRow: number;\n toRow: number;\n clamped: boolean;\n }[] = [];\n\n const reelPins = this._pinsOnReel(reelIndex);\n for (const pin of reelPins) {\n const fromRow = pin.row;\n\n // Compute target row based on migration policy.\n // 'origin' → clamp to min(originRow, newRows - 1). Restores on grow.\n // 'frozen' → stay at current row if it fits, else clamp to last\n // visible row AND update originRow so future grows\n // don't restore. \"Lock at current position\" semantics.\n let target: number;\n let clamped: boolean;\n let nextOriginRow = pin.originRow;\n if (pin.migration === 'frozen') {\n if (fromRow < newRows) {\n target = fromRow;\n clamped = false;\n } else {\n target = newRows - 1;\n clamped = true;\n nextOriginRow = target; // freeze the new row as the new \"origin\"\n }\n } else {\n // 'origin' (default)\n target = Math.min(pin.originRow, newRows - 1);\n clamped = target !== pin.originRow;\n }\n\n if (target === fromRow && nextOriginRow === pin.originRow) continue;\n\n const fromKey = pinKey(pin.col, fromRow);\n const toKey = pinKey(pin.col, target);\n\n this._pins.delete(fromKey);\n const moved: CellPin = { ...pin, row: target, originRow: nextOriginRow };\n this._pins.set(toKey, moved);\n\n // Keep overlay map keyed by the new cell.\n const overlayEntry = this._pinOverlays.get(fromKey);\n if (overlayEntry) {\n this._pinOverlays.delete(fromKey);\n this._pinOverlays.set(toKey, { pin: moved, overlay: overlayEntry.overlay });\n }\n\n migrations.push({ pin: moved, fromRow, toRow: target, clamped });\n this._events.emit('pin:migrated', moved, {\n fromRow,\n toRow: target,\n clamped,\n reelIndex,\n });\n }\n return migrations;\n }\n\n /**\n * Apply a pin to the idle reel's visible display immediately. Used when\n * `pin()` is called while no spin is in flight — the grid updates right\n * away so `getVisibleSymbols()` reflects the pin.\n */\n private _applyPinVisually(col: number, row: number, symbolId: string): void {\n const reel = this._reels[col];\n const current = reel.getVisibleSymbols();\n if (current[row] === symbolId) return; // already there\n current[row] = symbolId;\n reel.placeSymbols(current);\n }\n\n /**\n * Fires on `spin:allLanded`. Destroys visual pin overlays (the actual reel\n * cells now show the pinned symbols via setResult overlay), then\n * decrements numeric-turns pins and expires pins that hit zero.\n */\n private _onSpinLanded(): void {\n // Overlays are only needed during spin motion — destroy them all.\n this._destroyAllPinOverlays();\n\n if (this._pins.size === 0) return;\n\n const expired: CellPin[] = [];\n for (const pin of this._pins.values()) {\n if (typeof pin.turns === 'number') {\n // turns is readonly on the public interface; the engine owns the\n // mutation here — cast to the mutable internal representation.\n (pin as { turns: number }).turns -= 1;\n if (pin.turns <= 0) expired.push(pin);\n }\n }\n\n for (const pin of expired) {\n this._pins.delete(pinKey(pin.col, pin.row));\n this._events.emit('pin:expired', pin, 'turns' as PinExpireReason);\n }\n }\n\n /**\n * Fires on `spin:start`. Clears every `'eval'` pin from the previous spin,\n * then creates a visual overlay for every remaining pin so its symbol\n * stays visible while the reel scrolls underneath.\n */\n private _onSpinStart(): void {\n // Fresh spin — setResult hasn't been called yet, so setShape() is\n // allowed again until setResult() flips this back.\n this._resultSetForCurrentSpin = false;\n\n if (this._pins.size > 0) {\n const expired: CellPin[] = [];\n for (const pin of this._pins.values()) {\n if (pin.turns === 'eval') expired.push(pin);\n }\n\n for (const pin of expired) {\n this._pins.delete(pinKey(pin.col, pin.row));\n this._events.emit('pin:expired', pin, 'eval' as PinExpireReason);\n }\n }\n\n // Create overlays for all remaining pins. The overlay is what the player\n // sees during the spin motion phase — the underlying reel cell scrolls\n // normally but is visually covered.\n for (const pin of this._pins.values()) {\n this._ensurePinOverlay(pin);\n }\n }\n\n /**\n * Create an overlay ReelSymbol for a pin in the viewport's unmasked\n * container. No-op if one already exists at that cell. Fires\n * `pin:overlayCreated` after the overlay is positioned and added to the\n * display list — that's the hook consumers use to drive animation state\n * (e.g. setting a Spine track).\n */\n private _ensurePinOverlay(pin: CellPin): void {\n const key = pinKey(pin.col, pin.row);\n if (this._pinOverlays.has(key)) return;\n\n const reel = this._reels[pin.col];\n const overlay = this._symbolFactory.acquire(pin.symbolId);\n overlay.resize(reel.symbolWidth, reel.symbolHeight);\n // Viewport.unmaskedContainer sits at (0,0) inside the viewport — same\n // local space as maskedContainer. Reel x lives on the reel container;\n // symbol-view y is reel-local; pyramid layouts add `reel.container.y`\n // (the per-reel offsetY) so overlays line up with the actual cell.\n overlay.view.x = reel.container.x;\n overlay.view.y = reel.container.y + reel.getSymbolAt(pin.row).view.y;\n overlay.view.zIndex = ReelSet.PIN_OVERLAY_Z_INDEX;\n this._viewport.unmaskedContainer.addChild(overlay.view);\n this._pinOverlays.set(key, { pin, overlay });\n this._events.emit('pin:overlayCreated', pin, overlay);\n }\n\n /**\n * Reposition + resize every pin overlay on the given reel.\n *\n * The engine calls this automatically after every MultiWays AdjustPhase\n * reshape (and from the skip path), so applications that just use\n * `setShape()` / `setResult()` never need to invoke it. **Call it\n * yourself only if** you mutate `Reel.symbolWidth`, `Reel.symbolHeight`,\n * or a pin's row outside the normal MultiWays flow — e.g. a custom\n * mid-spin layout swap that bypasses `AdjustPhase`.\n *\n * No-op for reels with no active pin overlays.\n */\n refreshPinOverlaysForReel(reelIndex: number): void {\n const reel = this._reels[reelIndex];\n for (const [, entry] of this._pinOverlays) {\n if (entry.pin.col !== reelIndex) continue;\n const { pin, overlay } = entry;\n overlay.resize(reel.symbolWidth, reel.symbolHeight);\n overlay.view.x = reel.container.x;\n overlay.view.y = reel.container.y + pin.row * reel.motion.slotHeight;\n }\n }\n\n /**\n * Internal: build AdjustPhase pin-overlay tween descriptors for a reel.\n * Captures the overlays' CURRENT on-screen Y + size as the tween's\n * `from` state, then computes the post-reshape `to` state from the\n * pin's already-migrated row + the upcoming cell height. Called BEFORE\n * AdjustPhase commits the reshape, so the snapshot reflects what the\n * player actually sees.\n */\n private _buildPinOverlayTweens(\n reelIndex: number,\n targetSymbolHeight: number,\n symbolGapY: number,\n ): import('../spin/phases/AdjustPhase.js').PinOverlayTween[] {\n const reel = this._reels[reelIndex];\n const out: import('../spin/phases/AdjustPhase.js').PinOverlayTween[] = [];\n const newSlot = targetSymbolHeight + symbolGapY;\n for (const [, entry] of this._pinOverlays) {\n if (entry.pin.col !== reelIndex) continue;\n const { pin, overlay } = entry;\n out.push({\n symbol: overlay,\n cellWidth: reel.symbolWidth,\n oldCellHeight: reel.symbolHeight,\n newCellHeight: targetSymbolHeight,\n fromY: overlay.view.y,\n toY: reel.container.y + pin.row * newSlot,\n x: reel.container.x,\n });\n }\n return out;\n }\n\n /**\n * Destroy a single pin's overlay, if present. Fires\n * `pin:overlayDestroyed` BEFORE the overlay is released to the pool, so\n * consumers can stop animations / remove listeners on a still-valid\n * instance.\n */\n private _destroyPinOverlay(key: string): void {\n const entry = this._pinOverlays.get(key);\n if (!entry) return;\n const { pin, overlay } = entry;\n this._events.emit('pin:overlayDestroyed', pin, overlay);\n this._viewport.unmaskedContainer.removeChild(overlay.view);\n this._symbolFactory.release(overlay);\n this._pinOverlays.delete(key);\n }\n\n /** Destroy every active pin overlay. Called on spin land and on destroy. */\n private _destroyAllPinOverlays(): void {\n const keys = [...this._pinOverlays.keys()];\n for (const key of keys) this._destroyPinOverlay(key);\n }\n}\n","/** Default values applied when not explicitly set by the builder. */\nexport const DEFAULTS = {\n bufferSymbols: 1 as number,\n symbolGap: { x: 0 as number, y: 0 as number },\n initialSpeed: 'normal' as string,\n maxPoolPerKey: 20 as number,\n zIndexStep: 100 as number,\n};\n","import type { SpeedProfile } from './types.js';\n\n/**\n * Built-in speed profiles covering common slot game needs.\n *\n * Bounce values are tuned for the typical 120–200px symbol range. For larger\n * or smaller symbols, register a custom profile or override `bounceDistance`.\n * `bounceDuration` is the total time for the two-leg bounce (down then back).\n */\nexport const SpeedPresets = {\n NORMAL: {\n name: 'normal',\n spinDelay: 100,\n spinSpeed: 30,\n stopDelay: 140,\n anticipationDelay: 450,\n bounceDistance: 56,\n bounceDuration: 600,\n accelerationEase: 'power2.in',\n decelerationEase: 'power2.out',\n accelerationDuration: 300,\n minimumSpinTime: 500,\n },\n TURBO: {\n name: 'turbo',\n spinDelay: 30,\n spinSpeed: 50,\n stopDelay: 0,\n anticipationDelay: 250,\n bounceDistance: 42,\n bounceDuration: 200,\n accelerationEase: 'power2.in',\n decelerationEase: 'power2.out',\n accelerationDuration: 200,\n minimumSpinTime: 300,\n },\n SUPER_TURBO: {\n name: 'superTurbo',\n spinDelay: 0,\n spinSpeed: 80,\n stopDelay: 0,\n anticipationDelay: 0,\n bounceDistance: 14,\n bounceDuration: 120,\n accelerationEase: 'power1.in',\n decelerationEase: 'power1.out',\n accelerationDuration: 50,\n minimumSpinTime: 100,\n },\n} as const satisfies Record<string, SpeedProfile>;\n","import type { ReelSymbol } from './ReelSymbol.js';\n\ntype SymbolConstructor<T extends ReelSymbol = ReelSymbol> = new (options: any) => T;\n\ninterface RegistryEntry {\n SymbolClass: SymbolConstructor;\n options: any;\n}\n\n/**\n * Registry that maps symbolIds to their constructors and options.\n *\n * Used by the builder and SymbolFactory to create symbols on demand.\n */\nexport class SymbolRegistry {\n private _entries = new Map<string, RegistryEntry>();\n\n /**\n * Register a symbol type.\n *\n * ```ts\n * registry.register('cherry', SpriteSymbol, { textures: { cherry: tex } });\n * ```\n */\n register<T extends ReelSymbol>(\n symbolId: string,\n SymbolClass: new (options: any) => T,\n options: T extends { constructor: (options: infer O) => any } ? O : any,\n ): void {\n if (this._entries.has(symbolId)) {\n throw new Error(`Symbol '${symbolId}' is already registered.`);\n }\n this._entries.set(symbolId, { SymbolClass, options });\n }\n\n /** Create a new symbol instance for the given symbolId. */\n create(symbolId: string): ReelSymbol {\n const entry = this._entries.get(symbolId);\n if (!entry) {\n throw new Error(\n `Symbol '${symbolId}' is not registered. Available: ${[...this._entries.keys()].join(', ')}`,\n );\n }\n const symbol = new entry.SymbolClass(entry.options);\n symbol.activate(symbolId);\n return symbol;\n }\n\n has(symbolId: string): boolean {\n return this._entries.has(symbolId);\n }\n\n get symbolIds(): string[] {\n return [...this._entries.keys()];\n }\n\n get size(): number {\n return this._entries.size;\n }\n}\n","import type { Disposable } from '../utils/Disposable.js';\n\n/**\n * Generic object pool for reusing expensive-to-create objects.\n *\n * Reduces GC pressure by recycling objects instead of creating/destroying them each frame.\n * Used internally for ReelSymbol instances and available to game code for trails, particles, etc.\n *\n * @typeParam T - The type of object to pool.\n */\nexport class ObjectPool<T> implements Disposable {\n private _pools = new Map<string, T[]>();\n private _isDestroyed = false;\n\n constructor(\n private _factory: (key: string) => T,\n private _reset?: (item: T) => void,\n private _dispose?: (item: T) => void,\n private _maxPerKey: number = 20,\n ) {}\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n /**\n * Get an object from the pool, or create a new one if the pool is empty.\n */\n acquire(key: string): T {\n const pool = this._pools.get(key);\n if (pool && pool.length > 0) {\n const item = pool.pop()!;\n this._reset?.(item);\n return item;\n }\n return this._factory(key);\n }\n\n /**\n * Return an object to the pool for reuse.\n * If the pool is at capacity, the object is disposed instead.\n */\n release(key: string, item: T): void {\n let pool = this._pools.get(key);\n if (!pool) {\n pool = [];\n this._pools.set(key, pool);\n }\n if (pool.length >= this._maxPerKey) {\n this._dispose?.(item);\n return;\n }\n pool.push(item);\n }\n\n /** Get the number of pooled items for a key. */\n size(key: string): number {\n return this._pools.get(key)?.length ?? 0;\n }\n\n /** Get total pooled items across all keys. */\n get totalSize(): number {\n let total = 0;\n for (const pool of this._pools.values()) {\n total += pool.length;\n }\n return total;\n }\n\n /** Clear all pooled items, calling dispose on each. */\n clear(): void {\n if (this._dispose) {\n for (const pool of this._pools.values()) {\n for (const item of pool) {\n this._dispose(item);\n }\n }\n }\n this._pools.clear();\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this.clear();\n this._isDestroyed = true;\n }\n}\n","import type { ReelSymbol } from './ReelSymbol.js';\nimport type { SymbolRegistry } from './SymbolRegistry.js';\nimport { ObjectPool } from '../pool/ObjectPool.js';\n\n/**\n * Creates and pools ReelSymbol instances.\n *\n * Wraps SymbolRegistry for creation and ObjectPool for recycling.\n * Game code should not need to interact with this directly —\n * it's managed by Reel internally.\n */\nexport class SymbolFactory {\n private _pool: ObjectPool<ReelSymbol>;\n\n constructor(\n private _registry: SymbolRegistry,\n maxPoolPerKey: number = 20,\n ) {\n this._pool = new ObjectPool<ReelSymbol>(\n (key: string) => this._registry.create(key),\n (item: ReelSymbol) => item.reset(),\n (item: ReelSymbol) => item.destroy(),\n maxPoolPerKey,\n );\n }\n\n /** Get a symbol (from pool or newly created), activated with symbolId. */\n acquire(symbolId: string): ReelSymbol {\n const symbol = this._pool.acquire(symbolId);\n if (symbol.symbolId !== symbolId) {\n symbol.activate(symbolId);\n }\n return symbol;\n }\n\n /** Return a symbol to the pool. */\n release(symbol: ReelSymbol): void {\n const id = symbol.symbolId;\n symbol.deactivate();\n this._pool.release(id, symbol);\n }\n\n destroy(): void {\n this._pool.destroy();\n }\n}\n","import type { SymbolData } from '../config/types.js';\n\n/**\n * Weighted random symbol selector using binary search on cumulative weights.\n *\n * Supports exclusion lists for symbols that shouldn't appear during\n * spinning or in buffer areas.\n */\nexport class RandomSymbolProvider {\n private _symbols: string[];\n private _weights: number[];\n private _cumulativeWeights: number[] = [];\n private _totalWeight: number = 0;\n private _excludeSpinning = new Set<string>();\n private _excludeBuffer = new Set<string>();\n\n constructor(symbolsData: Record<string, SymbolData>) {\n this._symbols = Object.keys(symbolsData);\n this._weights = this._symbols.map((id) => symbolsData[id].weight);\n this._rebuildWeights();\n }\n\n /** Get a random symbol, optionally excluding buffer-only symbols. */\n next(useBufferExclusion: boolean = false): string {\n const exclude = useBufferExclusion\n ? new Set([...this._excludeSpinning, ...this._excludeBuffer])\n : this._excludeSpinning;\n\n if (exclude.size === 0) {\n return this._pickWeighted();\n }\n\n // Build filtered weights on the fly for exclusions\n let total = 0;\n const filtered: { id: string; cumWeight: number }[] = [];\n for (let i = 0; i < this._symbols.length; i++) {\n if (exclude.has(this._symbols[i])) continue;\n total += this._weights[i];\n filtered.push({ id: this._symbols[i], cumWeight: total });\n }\n\n if (total === 0 || filtered.length === 0) {\n // Fallback: return first non-excluded symbol\n for (const s of this._symbols) {\n if (!exclude.has(s)) return s;\n }\n return this._symbols[0];\n }\n\n const rand = Math.random() * total;\n // Binary search\n let lo = 0;\n let hi = filtered.length - 1;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (filtered[mid].cumWeight <= rand) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n return filtered[lo].id;\n }\n\n /** Set symbols to exclude during spinning. */\n setExcludeSpinning(symbolIds: string[]): void {\n this._excludeSpinning = new Set(symbolIds);\n }\n\n /** Set symbols to exclude from buffer (above/below) areas. */\n setExcludeBuffer(symbolIds: string[]): void {\n this._excludeBuffer = new Set(symbolIds);\n }\n\n /** Update weights at runtime (e.g., for different game modes). */\n updateWeights(symbolsData: Record<string, SymbolData>): void {\n this._symbols = Object.keys(symbolsData);\n this._weights = this._symbols.map((id) => symbolsData[id].weight);\n this._rebuildWeights();\n }\n\n private _rebuildWeights(): void {\n this._cumulativeWeights = [];\n this._totalWeight = 0;\n for (const w of this._weights) {\n this._totalWeight += w;\n this._cumulativeWeights.push(this._totalWeight);\n }\n }\n\n private _pickWeighted(): string {\n const rand = Math.random() * this._totalWeight;\n let lo = 0;\n let hi = this._cumulativeWeights.length - 1;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (this._cumulativeWeights[mid] <= rand) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n return this._symbols[lo];\n }\n}\n","import type { RandomSymbolProvider } from './RandomSymbolProvider.js';\n\n/** Context passed through the middleware pipeline. */\nexport interface FrameContext {\n /** Reel column index. */\n readonly reelIndex: number;\n /** Total visible rows. */\n readonly visibleRows: number;\n /** Buffer symbols above visible area. */\n readonly bufferAbove: number;\n /** Buffer symbols below visible area. */\n readonly bufferBelow: number;\n /** The symbol array being built (buffer + visible + buffer). Mutable by middleware. */\n symbols: string[];\n /** Target symbols from setResult() (visible rows only), if available. */\n readonly targetSymbols?: string[];\n /** Whether the reel is currently spinning. */\n readonly isSpinning: boolean;\n /** Arbitrary metadata middleware can use to communicate. */\n metadata: Record<string, unknown>;\n}\n\n/** Middleware that participates in frame building. */\nexport interface FrameMiddleware {\n readonly name: string;\n /** Lower priority runs first. */\n readonly priority: number;\n process(context: FrameContext, next: () => void): void;\n}\n\n/**\n * Builds symbol frames using a middleware pipeline.\n *\n * Built-in middleware handles random fill and target placement.\n * Users can inject custom middleware for features like multiplier encoding\n * or triple-prevention.\n */\nexport class FrameBuilder {\n private _middlewares: FrameMiddleware[] = [];\n private _sorted = false;\n\n constructor(private _randomProvider: RandomSymbolProvider) {\n // Add built-in middleware\n this.use(new RandomFillMiddleware(_randomProvider));\n this.use(new TargetPlacementMiddleware());\n }\n\n /** Add a middleware to the pipeline. */\n use(middleware: FrameMiddleware): this {\n this._middlewares.push(middleware);\n this._sorted = false;\n return this;\n }\n\n /** Remove a middleware by name. */\n remove(name: string): this {\n this._middlewares = this._middlewares.filter((m) => m.name !== name);\n return this;\n }\n\n /** Build a frame for a single reel. */\n build(\n reelIndex: number,\n visibleRows: number,\n bufferAbove: number,\n bufferBelow: number,\n targetSymbols?: string[],\n isSpinning: boolean = false,\n ): string[] {\n if (!this._sorted) {\n this._middlewares.sort((a, b) => a.priority - b.priority);\n this._sorted = true;\n }\n\n const totalSlots = bufferAbove + visibleRows + bufferBelow;\n const context: FrameContext = {\n reelIndex,\n visibleRows,\n bufferAbove,\n bufferBelow,\n symbols: new Array<string>(totalSlots).fill(''),\n targetSymbols,\n isSpinning,\n metadata: {},\n };\n\n // Run middleware chain\n let index = 0;\n const next = (): void => {\n if (index < this._middlewares.length) {\n const mw = this._middlewares[index++];\n mw.process(context, next);\n }\n };\n next();\n\n return context.symbols;\n }\n\n /** Build frames for all reels. */\n buildAll(\n reelCount: number,\n visibleRows: number,\n bufferAbove: number,\n bufferBelow: number,\n targetSymbols?: string[][],\n isSpinning: boolean = false,\n ): string[][] {\n return Array.from({ length: reelCount }, (_, reelIndex) =>\n this.build(\n reelIndex,\n visibleRows,\n bufferAbove,\n bufferBelow,\n targetSymbols?.[reelIndex],\n isSpinning,\n ),\n );\n }\n\n get randomProvider(): RandomSymbolProvider {\n return this._randomProvider;\n }\n\n get middleware(): ReadonlyArray<FrameMiddleware> {\n return this._middlewares;\n }\n}\n\n/** Fills empty symbol slots with random symbols. OCCUPIED cells are kept verbatim. */\nclass RandomFillMiddleware implements FrameMiddleware {\n readonly name = 'random-fill';\n readonly priority = 0;\n\n constructor(private _provider: RandomSymbolProvider) {}\n\n process(context: FrameContext, next: () => void): void {\n for (let i = 0; i < context.symbols.length; i++) {\n if (!context.symbols[i]) {\n const isBuffer =\n i < context.bufferAbove ||\n i >= context.bufferAbove + context.visibleRows;\n context.symbols[i] = this._provider.next(isBuffer);\n }\n }\n next();\n }\n}\n\n/** Places target symbols (from setResult) into the visible area. */\nclass TargetPlacementMiddleware implements FrameMiddleware {\n readonly name = 'target-placement';\n readonly priority = 10;\n\n process(context: FrameContext, next: () => void): void {\n if (context.targetSymbols) {\n for (let row = -context.bufferAbove; row < context.targetSymbols.length; row++) {\n const idx = context.bufferAbove + row;\n if (context.targetSymbols[row] && idx < context.symbols.length) {\n context.symbols[idx] = context.targetSymbols[row];\n }\n }\n }\n next();\n }\n}\n","import type { OffsetConfig, TrapezoidConfig } from '../config/types.js';\n\n/**\n * Computes X-position offsets for symbols to create visual effects\n * like trapezoid perspective.\n */\nexport class OffsetCalculator {\n private _offsets: number[][] = [];\n\n constructor(\n private _reelCount: number,\n private _totalRows: number,\n private _symbolWidth: number,\n private _config: OffsetConfig,\n ) {\n this._compute();\n }\n\n /** Get X offset for a specific reel and row. */\n getOffset(reelIndex: number, rowIndex: number): number {\n return this._offsets[reelIndex]?.[rowIndex] ?? 0;\n }\n\n /** Get all offsets as a 2D array [reelIndex][rowIndex]. */\n get offsets(): readonly (readonly number[])[] {\n return this._offsets;\n }\n\n private _compute(): void {\n if (this._config.mode === 'none') {\n this._offsets = Array.from({ length: this._reelCount }, () =>\n new Array(this._totalRows).fill(0),\n );\n return;\n }\n\n // Trapezoid mode\n const config = this._config as TrapezoidConfig;\n const centralIndex = (this._reelCount - 1) / 2;\n this._offsets = [];\n\n for (let reel = 0; reel < this._reelCount; reel++) {\n const relativePos =\n this._reelCount > 1\n ? (reel - centralIndex) / (this._reelCount / 2)\n : 0;\n\n const reelOffsets: number[] = [];\n for (let row = 0; row < this._totalRows; row++) {\n const rowNorm = this._totalRows > 1 ? row / (this._totalRows - 1) : 0.5;\n const topOffset = relativePos * config.widthDifference * config.topWidthFactor;\n const bottomOffset = relativePos * config.widthDifference * config.bottomWidthFactor;\n const offset = topOffset + (bottomOffset - topOffset) * rowNorm;\n reelOffsets.push(offset);\n }\n this._offsets.push(reelOffsets);\n }\n }\n}\n","import { ReelPhase } from './ReelPhase.js';\nimport type { SpinningMode } from '../modes/SpinningMode.js';\n\nexport interface DropStartPhaseConfig {\n spinningMode: SpinningMode;\n delay?: number;\n}\n\n/**\n * No-op start phase for cascade drop-in mechanics.\n *\n * The reel never accelerates — it stays at speed 0 throughout the wait.\n * Notifies symbols that the spin has started, then immediately completes\n * so the state machine advances to SpinPhase (stationary wait for result).\n */\nexport class DropStartPhase extends ReelPhase<DropStartPhaseConfig> {\n readonly name = 'start';\n readonly skippable = true;\n\n protected onEnter(config: DropStartPhaseConfig): void {\n this._reel.spinningMode = config.spinningMode;\n this._reel.speed = 0;\n this._reel.notifySpinStart();\n this._complete();\n }\n\n update(_deltaMs: number): void {}\n\n protected onSkip(): void {}\n}\n","import type { gsap } from 'gsap';\nimport type { Container } from 'pixi.js';\nimport { getGsap } from '../../utils/gsapRef.js';\nimport type { Reel } from '../../core/Reel.js';\nimport type { SpeedProfile } from '../../config/types.js';\nimport { ReelPhase } from './ReelPhase.js';\nimport type { CascadeDropConfig } from '../../cascade/DropRecipes.js';\n\nexport interface DropStopPhaseConfig {\n /** Full frame including buffers (top-to-bottom). */\n targetFrame: string[];\n /** Delay before this reel's symbols drop IN. Fall-out always starts immediately. */\n delay?: number;\n}\n\n/**\n * Drop-in stop phase for cascade slot mechanics.\n *\n * Two-stage animation per column:\n * 1. Fall-out — current symbols accelerate downward out of the viewport.\n * 2. Drop-in — new symbols fall in from above, row by row, with bounce.\n *\n * placeSymbols() is called only after the fall completes, so old and new\n * views are never the same object mid-animation (avoids pool identity conflicts).\n *\n * The cascade config is baked in at construction by ReelSetBuilder.cascade().\n * The per-spin config only carries targetFrame + delay, matching StopPhaseConfig\n * so SpinController needs no changes.\n */\nexport class DropStopPhase extends ReelPhase<DropStopPhaseConfig> {\n readonly name = 'stop';\n readonly skippable = true;\n\n private readonly _dropConfig: CascadeDropConfig;\n private _runConfig: DropStopPhaseConfig | null = null;\n private _delayTween: gsap.core.Tween | null = null;\n private _fallTween: gsap.core.Timeline | null = null;\n private _dropTween: gsap.core.Timeline | null = null;\n private _stage: 'falling' | 'waiting' | 'dropping' | 'done' = 'falling';\n /** Views of the symbols that are currently falling out. Used by onSkip to hide them. */\n private _fallingViews: Container[] = [];\n\n constructor(reel: Reel, speed: SpeedProfile, dropConfig: CascadeDropConfig) {\n super(reel, speed);\n this._dropConfig = dropConfig;\n }\n\n protected onEnter(config: DropStopPhaseConfig): void {\n this._runConfig = config;\n this._stage = 'falling';\n this._beginFall();\n }\n\n private _beginFall(): void {\n this._delayTween = null;\n\n const reel = this._reel;\n const { fromY, fallDuration = 300, fallRowDelay = 0 } = this._dropConfig;\n const cellHeight = reel.motion.slotHeight;\n const visibleRows = reel.visibleRows;\n const dropFromY = fromY ?? cellHeight * (visibleRows + reel.bufferAbove);\n const fallSec = fallDuration / 1000;\n const fallRowDelaySec = fallRowDelay / 1000;\n\n // Capture current visible symbol views BEFORE placeSymbols swaps identities.\n const views = Array.from({ length: visibleRows }, (_, i) => reel.getSymbolAt(i).view);\n const startYs = views.map((v) => v.y);\n this._fallingViews = views;\n this._stage = 'falling';\n\n if (fallSec <= 0) {\n this._beginDropIn(dropFromY);\n return;\n }\n\n this._fallTween = getGsap().timeline({\n onComplete: () => {\n this._fallTween = null;\n views.forEach((v) => { v.alpha = 0; });\n this._fallingViews = [];\n const dropInDelay = (this._runConfig?.delay ?? 0) / 1000;\n if (dropInDelay > 0) {\n this._stage = 'waiting';\n this._delayTween = getGsap().delayedCall(dropInDelay, () => this._beginDropIn(dropFromY));\n } else {\n this._beginDropIn(dropFromY);\n }\n },\n });\n\n // Stagger rows by fallRowDelay (symmetric with rowDelay for drop-in)\n views.forEach((v, i) => {\n this._fallTween!.to(v, { y: startYs[i] + dropFromY, duration: fallSec, ease: 'power2.in' }, i * fallRowDelaySec);\n });\n }\n\n private _beginDropIn(dropFromY: number): void {\n this._stage = 'dropping';\n\n const reel = this._reel;\n const { rowDelay = 0, easing = 'bounce.out', dropDuration = 600 } = this._dropConfig;\n const bufferAbove = reel.bufferAbove;\n const visibleRows = reel.visibleRows;\n const rowDelaySec = rowDelay / 1000;\n const dropSec = dropDuration / 1000;\n\n // Place new symbols — snapToGrid is called internally by placeSymbols\n reel.placeSymbols(this._runConfig!.targetFrame.slice(bufferAbove, bufferAbove + visibleRows));\n reel.notifySpinEnd();\n\n const newViews = Array.from({ length: visibleRows }, (_, i) => reel.getSymbolAt(i).view);\n const finalYs = newViews.map((v) => v.y);\n\n // Start new symbols above the viewport\n newViews.forEach((v) => { v.y -= dropFromY; });\n\n if (dropSec <= 0) {\n newViews.forEach((v, i) => { v.y = finalYs[i]; });\n this._stage = 'done';\n reel.notifyLanded();\n this._complete();\n return;\n }\n\n this._dropTween = getGsap().timeline({\n onComplete: () => {\n this._stage = 'done';\n reel.notifyLanded();\n this._complete();\n },\n });\n\n newViews.forEach((v, rowIndex) => {\n this._dropTween!.to(\n v,\n { y: finalYs[rowIndex], duration: dropSec, ease: easing },\n rowIndex * rowDelaySec,\n );\n });\n }\n\n update(_deltaMs: number): void {}\n\n protected onSkip(): void {\n this._killTweens();\n\n // If falling out, hide those orphaned views so they don't show at mid-fall position\n this._fallingViews.forEach((v) => { v.alpha = 0; });\n this._fallingViews = [];\n\n const reel = this._reel;\n const config = this._runConfig;\n\n if (config && this._stage !== 'done') {\n const bufferAbove = reel.bufferAbove;\n const visibleRows = reel.visibleRows;\n reel.placeSymbols(config.targetFrame.slice(bufferAbove, bufferAbove + visibleRows));\n }\n\n this._stage = 'done';\n }\n\n private _killTweens(): void {\n this._delayTween?.kill();\n this._delayTween = null;\n this._fallTween?.kill();\n this._fallTween = null;\n this._dropTween?.kill();\n this._dropTween = null;\n }\n}\n","import type { gsap } from 'gsap';\nimport { getGsap } from '../../utils/gsapRef.js';\nimport { ReelPhase } from './ReelPhase.js';\nimport type { Reel } from '../../core/Reel.js';\nimport type { SpeedProfile } from '../../config/types.js';\nimport type { ReelSymbol } from '../../symbols/ReelSymbol.js';\n\nexport interface AdjustPhaseConfig {\n /**\n * Pin overlays on this reel that need to tween from their pre-reshape\n * cell to the post-reshape cell. Populated by `SpinController` BEFORE\n * the reshape commits — `fromY` captures each overlay's on-screen Y at\n * the moment the snapshot was taken, `toY` is computed from the new\n * geometry.\n *\n * AdjustPhase no longer commits geometry — `SpinController._applyReshape`\n * does that synchronously before the phase runs. The phase's only job is\n * the tween.\n */\n pinOverlays: PinOverlayTween[];\n}\n\n/**\n * Descriptor for one pin overlay's animation across a MultiWays reshape.\n *\n * @internal — constructed by `SpinController.buildPinOverlayTweens`. Not\n * meant to be hand-built by consumers.\n */\nexport interface PinOverlayTween {\n /** The pin overlay symbol — its view is what we animate. */\n symbol: ReelSymbol;\n /** Width to resize to after the tween (cell width — usually unchanged). */\n cellWidth: number;\n /** Cell height before reshape (the overlay's current size). */\n oldCellHeight: number;\n /** Cell height after reshape. */\n newCellHeight: number;\n /** Pre-tween Y in viewport-local coords. */\n fromY: number;\n /** Post-tween target Y in viewport-local coords. */\n toY: number;\n /** Reel container X (unchanged across reshape). */\n x: number;\n}\n\n/**\n * Tween-only phase between SPIN and STOP for MultiWays slots.\n *\n * The geometry commit (resize symbols, reshape motion) happens in\n * `SpinController._applyReshape` before this phase runs. AdjustPhase only\n * tweens any pin overlays from their pre-reshape cell to the new cell —\n * cell symbols on the strip snap instantly because the reel is still\n * spinning at full speed when this phase runs (tweening cell scale would\n * fight the motion layer).\n *\n * Inserted into the phase chain ONLY when `builder.multiways(...)` is\n * called. Non-MultiWays slots never see this phase.\n *\n * Plays on top of whatever stop staggering you've configured; duration\n * is independent of `stopDelay`.\n */\nexport class AdjustPhase extends ReelPhase<AdjustPhaseConfig> {\n readonly name = 'adjust';\n readonly skippable = true;\n\n private _durationMs: number;\n private _ease: string;\n private _tween: gsap.core.Timeline | null = null;\n private _settle: (() => void) | null = null;\n\n constructor(\n reel: Reel,\n speed: SpeedProfile,\n opts: { durationMs: number; ease?: string },\n ) {\n super(reel, speed);\n this._durationMs = opts.durationMs;\n this._ease = opts.ease ?? 'power2.out';\n }\n\n protected onEnter(config: AdjustPhaseConfig): void {\n const overlays = config.pinOverlays;\n\n if (overlays.length === 0) {\n // SpinController shouldn't construct the phase in this case, but\n // defend in depth.\n this._complete();\n return;\n }\n\n if (this._durationMs <= 0) {\n // Instant snap path — match user's `pinMigrationDuration(0)`.\n this._snapPinOverlays(overlays);\n this._complete();\n return;\n }\n\n // Pose every overlay at its OLD cell visually so the tween starts\n // from where the player last saw it. The overlay's underlying view is\n // already at `newCellHeight` after the upstream reshape; we use\n // scale.y to make it look its old size during the tween.\n for (const o of overlays) {\n o.symbol.resize(o.cellWidth, o.newCellHeight);\n o.symbol.view.x = o.x;\n o.symbol.view.y = o.fromY;\n o.symbol.view.scale.y =\n o.newCellHeight > 0 ? o.oldCellHeight / o.newCellHeight : 1;\n o.symbol.view.scale.x = 1;\n }\n\n this._settle = () => {\n for (const o of overlays) {\n o.symbol.view.scale.set(1, 1);\n o.symbol.view.y = o.toY;\n o.symbol.view.x = o.x;\n }\n };\n\n const dur = this._durationMs / 1000;\n const ease = this._ease;\n this._tween = getGsap().timeline({\n onComplete: () => {\n this._settle?.();\n this._settle = null;\n this._tween = null;\n this._complete();\n },\n });\n\n for (const o of overlays) {\n this._tween.to(o.symbol.view, { y: o.toY, duration: dur, ease }, 0);\n this._tween.to(o.symbol.view.scale, { y: 1, duration: dur, ease }, 0);\n }\n }\n\n update(_deltaMs: number): void {\n // GSAP-driven; no per-frame work needed.\n }\n\n protected onSkip(): void {\n if (this._tween) {\n this._tween.progress(1);\n this._tween.kill();\n this._tween = null;\n }\n if (this._settle) {\n this._settle();\n this._settle = null;\n }\n }\n\n private _snapPinOverlays(overlays: PinOverlayTween[]): void {\n for (const o of overlays) {\n o.symbol.resize(o.cellWidth, o.newCellHeight);\n o.symbol.view.x = o.x;\n o.symbol.view.y = o.toY;\n o.symbol.view.scale.set(1, 1);\n }\n }\n}\n","import type { Ticker } from 'pixi.js';\nimport type { gsap } from 'gsap';\nimport { setGsap } from '../utils/gsapRef.js';\nimport type {\n SpeedProfile,\n SymbolData,\n OffsetConfig,\n ReelSetInternalConfig,\n MultiWaysConfig,\n ReelAnchor,\n} from '../config/types.js';\nimport type { ReelMaskRect, MaskStrategy } from './ReelViewport.js';\nimport { RectMaskStrategy, SharedRectMaskStrategy } from './ReelViewport.js';\nimport { DEFAULTS } from '../config/defaults.js';\nimport { SpeedPresets } from '../config/SpeedPresets.js';\nimport { ReelSet, type ReelSetParams } from './ReelSet.js';\nimport { Reel, type ReelConfig } from './Reel.js';\nimport { ReelViewport } from './ReelViewport.js';\nimport { SymbolRegistry } from '../symbols/SymbolRegistry.js';\nimport { SymbolFactory } from '../symbols/SymbolFactory.js';\nimport { RandomSymbolProvider } from '../frame/RandomSymbolProvider.js';\nimport { FrameBuilder } from '../frame/FrameBuilder.js';\nimport { OffsetCalculator } from '../frame/OffsetCalculator.js';\nimport { PhaseFactory } from '../spin/phases/PhaseFactory.js';\nimport type { SpinningMode } from '../spin/modes/SpinningMode.js';\nimport { StandardMode } from '../spin/modes/StandardMode.js';\nimport type { FrameMiddleware } from '../frame/FrameBuilder.js';\nimport type { ColumnTarget } from '../frame/ColumnTarget.js';\nimport { toLegacyTargetGrid } from '../frame/ColumnTarget.js';\nimport type { CascadeDropConfig } from '../cascade/DropRecipes.js';\nimport { DropStartPhase } from '../spin/phases/DropStartPhase.js';\nimport { DropStopPhase } from '../spin/phases/DropStopPhase.js';\nimport { AdjustPhase } from '../spin/phases/AdjustPhase.js';\n\n/**\n * The configurator you call before every reel set.\n *\n * `ReelSetBuilder` is a fluent, chainable builder: every call returns the\n * builder so you can string setup onto one expression. It exists for two\n * reasons — it hides the twenty-odd subsystems you'd otherwise have to\n * wire by hand, and its `.build()` step validates that every required\n * piece is present (throws at construction, not at first spin).\n *\n * Required calls (in any order): `.reels(n)`, `.visibleSymbols(n)`,\n * `.symbolSize(w, h)`, `.symbols((registry) => ...)`, `.ticker(app.ticker)`.\n * Optional: `.symbolGap()`, `.weights()`, `.symbolData()`, `.speed()`,\n * `.bufferSymbols()`, `.offset()`, `.frameMiddleware()`, `.phases()`,\n * `.spinningMode()`.\n *\n * Reduces ~100 lines of manual wiring to ~10 lines of configuration.\n *\n * ```ts\n * const reelSet = new ReelSetBuilder()\n * .reels(5)\n * .visibleSymbols(3)\n * .symbolSize(200, 200)\n * .symbols((r) => {\n * r.register('cherry', SpriteSymbol, { textures: { cherry: tex } });\n * })\n * .weights({ cherry: 20 })\n * .ticker(app.ticker)\n * .build();\n * ```\n */\nexport class ReelSetBuilder {\n private _reelCount?: number;\n private _visibleRows?: number;\n private _symbolWidth?: number;\n private _symbolHeight?: number;\n private _symbolGap = { ...DEFAULTS.symbolGap };\n private _bufferSymbols = DEFAULTS.bufferSymbols;\n private _symbolRegistry = new SymbolRegistry();\n private _weights: Record<string, number> = {};\n private _speeds = new Map<string, SpeedProfile>();\n private _initialSpeed = DEFAULTS.initialSpeed;\n private _offset: OffsetConfig = { mode: 'none' };\n private _ticker?: Ticker;\n private _spinningMode: SpinningMode = new StandardMode();\n private _phaseFactory = new PhaseFactory();\n private _middlewares: FrameMiddleware[] = [];\n private _initialFrame?: string[][];\n private _symbolDataOverrides: Record<string, Partial<SymbolData>> = {};\n private _cascadeDropConfig?: CascadeDropConfig;\n private _defaultSpinMode: 'standard' | 'cascade' = 'standard';\n /** Per-reel static row counts (jagged shapes like 3-5-5-5-3). */\n private _visibleRowsPerReel?: number[];\n /** Per-reel pixel-box heights — used for both pyramids and MultiWays. */\n private _reelPixelHeights?: number[];\n /** Vertical alignment of short reels inside the tallest reel's box. */\n private _reelAnchor: ReelAnchor = 'center';\n /** MultiWays configuration. Set by `.multiways(...)`. */\n private _multiways?: MultiWaysConfig;\n /** Per-reel AdjustPhase tween duration in ms (MultiWays only). */\n private _pinMigrationDuration: number | ((reelIndex: number) => number) = 200;\n /** GSAP easing string used by AdjustPhase. Default: 'power2.out'. */\n private _pinMigrationEase = 'power2.out';\n /** Mask strategy. Default: per-reel `RectMaskStrategy`. */\n private _maskStrategy: MaskStrategy = new RectMaskStrategy();\n /** True if the user explicitly set a mask strategy (no auto-pick override). */\n private _maskStrategyExplicit = false;\n\n /** Set number of reel columns. */\n reels(count: number): this {\n this._reelCount = count;\n return this;\n }\n\n /**\n * Number of visible rows per reel (uniform across all reels).\n * Mutually exclusive with `visibleRowsPerReel()` — calling both throws\n * at `build()`.\n *\n * @example\n * builder.reels(5).visibleRows(3) // classic 5x3\n */\n visibleRows(count: number): this {\n this._visibleRows = count;\n return this;\n }\n\n /**\n * Alias of {@link visibleRows} — kept for backwards compatibility with\n * the original API. New code should prefer `visibleRows(n)` so the\n * naming aligns with `visibleRowsPerReel([...])` (both are about rows;\n * the original name pre-dated jagged shapes).\n *\n * @deprecated Use `visibleRows(n)` instead.\n */\n visibleSymbols(count: number): this {\n return this.visibleRows(count);\n }\n\n /**\n * Per-reel static row counts. Length MUST equal `reels()`. Mutually\n * exclusive with `visibleRows()` / `visibleSymbols()` — calling both\n * throws at `build()`.\n *\n * @example\n * builder.reels(5).visibleRowsPerReel([3, 5, 5, 5, 3]) // pyramid\n */\n visibleRowsPerReel(rows: number[]): this {\n this._visibleRowsPerReel = [...rows];\n return this;\n }\n\n /**\n * Per-reel pixel-box heights. Length MUST equal `reels()`.\n *\n * - Pyramid: defaults to `visibleRowsPerReel[i] * symbolHeight`. Override\n * to make all reels the same height with different cell heights per\n * reel.\n * - MultiWays: every entry equals the same fixed reel height. Cell\n * height per reel is derived as `reelPixelHeight / visibleRows[i]`.\n *\n * Precedence: when both `reelPixelHeights` and `reelAnchor` are set,\n * `reelPixelHeights` wins — anchor is derived from the explicit boxes.\n */\n reelPixelHeights(heights: number[]): this {\n this._reelPixelHeights = [...heights];\n return this;\n }\n\n /** Vertical alignment of short reels inside the tallest reel's box. Default 'center'. */\n reelAnchor(anchor: ReelAnchor): this {\n this._reelAnchor = anchor;\n return this;\n }\n\n /**\n * Custom mask strategy for the viewport. Defaults to {@link RectMaskStrategy}\n * (one clip rect per reel — clean for pyramid + uniform layouts).\n *\n * Use {@link SharedRectMaskStrategy} when reels have horizontal gaps\n * AND symbols (typically big symbols) need to overlap across reel\n * boundaries — the per-reel default would clip them at the gaps.\n *\n * Or pass any custom `MaskStrategy` for non-rectangular masks (rounded\n * frames, hexagonal grids, etc.).\n *\n * @example\n * import { SharedRectMaskStrategy } from 'pixi-reels';\n * builder.maskStrategy(new SharedRectMaskStrategy())\n */\n maskStrategy(strategy: MaskStrategy): this {\n // TS catches `null`/`undefined` for typed callers, but plain-JS callers\n // get a confusing crash deep inside `ReelViewport` later. Throw here\n // with a name they can grep.\n if (\n strategy == null ||\n typeof strategy.build !== 'function' ||\n typeof strategy.update !== 'function'\n ) {\n throw new Error(\n 'maskStrategy(): expected a MaskStrategy with build(...) and update(...) methods ' +\n '(e.g. new RectMaskStrategy() or new SharedRectMaskStrategy()).',\n );\n }\n this._maskStrategy = strategy;\n this._maskStrategyExplicit = true;\n return this;\n }\n\n /**\n * Configure this slot as MultiWays: per-spin row variation. Pass minRows,\n * maxRows, and the fixed reel pixel height. After build, call\n * `reelSet.setShape(rowsPerReel)` mid-spin to set the next stop's shape.\n *\n * Mutually exclusive with big-symbol registration (`SymbolData.size`).\n * Mutually exclusive with cascade mode in v1.\n */\n multiways(config: MultiWaysConfig): this {\n this._multiways = { ...config };\n return this;\n }\n\n /**\n * AdjustPhase tween duration in ms (MultiWays only). Pass a number for a\n * uniform duration across reels, or a function `(reelIndex) => number`\n * for per-reel control. Default: 200. Pass `0` for an instant snap (no\n * tween).\n *\n * AdjustPhase plays on top of whatever stop staggering you've configured\n * — its duration is independent of `stopDelay`.\n */\n pinMigrationDuration(value: number | ((reelIndex: number) => number)): this {\n this._pinMigrationDuration = value;\n return this;\n }\n\n /**\n * GSAP easing string used by AdjustPhase tweens (MultiWays only).\n * Applied to both the cell-resize tween and any pin-overlay migration\n * tween. Defaults to `'power2.out'`. See gsap.com/docs/v3/Eases for\n * the full vocabulary.\n *\n * @example\n * builder.pinMigrationEase('back.out(1.4)') // pop-in feel\n * builder.pinMigrationEase('expo.inOut') // slow start + slow end\n */\n pinMigrationEase(ease: string): this {\n this._pinMigrationEase = ease;\n return this;\n }\n\n /** Set symbol dimensions in pixels. */\n symbolSize(width: number, height: number): this {\n this._symbolWidth = width;\n this._symbolHeight = height;\n return this;\n }\n\n /** Set gap between symbols. Default: { x: 0, y: 0 }. */\n symbolGap(x: number, y: number): this {\n this._symbolGap = { x, y };\n return this;\n }\n\n /**\n * Set number of buffer symbols above/below the visible area. Default: 1.\n *\n * Buffer rows are off-screen cells the reel keeps around the visible\n * window so symbols can fade/slide in cleanly. The motion layer's wrap\n * detection assumes at least one buffer row above and one below — the\n * minimum supported value is **1**. Passing `0` (or a negative number)\n * is clamped to `1` and a single console warning is printed; the\n * builder does not throw, so existing user code keeps running.\n */\n bufferSymbols(count: number): this {\n if (!Number.isFinite(count) || count < 1) {\n if (!ReelSetBuilder._bufferWarnedThisProcess) {\n ReelSetBuilder._bufferWarnedThisProcess = true;\n // eslint-disable-next-line no-console\n console.warn(\n `[pixi-reels] bufferSymbols(${count}) is below the minimum of 1; clamping to 1. ` +\n `The motion layer needs at least one buffer row above and below the visible window for wrap detection.`,\n );\n }\n this._bufferSymbols = 1;\n return this;\n }\n this._bufferSymbols = count;\n return this;\n }\n /** One-shot guard so we don't spam consoles when builders are constructed in a loop. */\n private static _bufferWarnedThisProcess = false;\n\n /** Configure symbols via a registry callback. */\n symbols(configurator: (registry: SymbolRegistry) => void): this {\n configurator(this._symbolRegistry);\n return this;\n }\n\n /** Set weights for random symbol generation. */\n weights(weights: Record<string, number>): this {\n this._weights = weights;\n return this;\n }\n\n /**\n * Per-symbol metadata overrides (zIndex, unmask, or a custom weight that\n * replaces the one from `weights()`). Merged into the final symbolsData map\n * — any field you don't specify falls back to the default.\n *\n * @example\n * .symbolData({\n * wild: { zIndex: 5 }, // render above neighbours\n * bonus: { zIndex: 10, unmask: true }, // render outside the reel mask\n * })\n */\n symbolData(overrides: Record<string, Partial<SymbolData>>): this {\n this._symbolDataOverrides = { ...this._symbolDataOverrides, ...overrides };\n return this;\n }\n\n /** Add a named speed profile. */\n speed(name: string, profile: SpeedProfile): this {\n this._speeds.set(name, profile);\n return this;\n }\n\n /** Set which speed profile to use initially. Default: 'normal'. */\n initialSpeed(name: string): this {\n this._initialSpeed = name;\n return this;\n }\n\n /** Set X-axis offset config (e.g., trapezoid perspective). Default: 'none'. */\n offsetConfig(config: OffsetConfig): this {\n this._offset = config;\n return this;\n }\n\n /** Set the PixiJS ticker for frame updates. */\n ticker(ticker: Ticker): this {\n this._ticker = ticker;\n return this;\n }\n\n /**\n * Inject the GSAP instance the engine should use for tweens.\n *\n * **When you need this:** if your app already imports `gsap` and your\n * bundler resolves `gsap` to a different module instance than the one\n * `pixi-reels` resolved (common with symlinked workspaces, npm-link, or\n * misconfigured `dedupe`), every tween you start on a target the engine\n * also tweens will fight a separate timeline. Symptoms: spotlights that\n * render but never finish, animations that double-fire, tweens that\n * silently drop on hidden tabs in only one of the two instances.\n *\n * Calling `.gsap(myGsap)` rebinds every internal phase, motion tween,\n * pin-flight tween, and SpriteSymbol win pulse to the GSAP you pass —\n * guaranteed to be the same instance that drives your own animations.\n *\n * Default: the `gsap` import resolved at the engine's own\n * `node_modules/gsap` path. If your app and the engine resolve to the\n * same instance (the common case in production bundles with proper\n * `dedupe`), you do NOT need to call this.\n *\n * Idempotent — calling again with the same instance is a no-op. Calling\n * with a different instance after `.build()` only affects tweens\n * started after the swap.\n *\n * @example\n * import { gsap } from 'gsap';\n * const reelSet = new ReelSetBuilder()\n * .reels(5).visibleRows(3).symbolSize(200, 200)\n * .symbols(...)\n * .ticker(app.ticker)\n * .gsap(gsap) // ensure engine and app share one instance\n * .build();\n */\n gsap(instance: typeof gsap): this {\n setGsap(instance);\n return this;\n }\n\n /** Set the spinning mode. Default: StandardMode. */\n spinningMode(mode: SpinningMode): this {\n this._spinningMode = mode;\n return this;\n }\n\n /** Add custom frame middleware. */\n frameMiddleware(middleware: FrameMiddleware): this {\n this._middlewares.push(middleware);\n return this;\n }\n\n /** Override default phases. */\n phases(configurator: (factory: PhaseFactory) => void): this {\n configurator(this._phaseFactory);\n return this;\n }\n\n /**\n * Enable cascade drop-in mechanics.\n *\n * Replaces the strip-spin + bounce stop cycle with a stationary wait\n * followed by symbols dropping in from above the viewport.\n *\n * Usage is identical to standard spin — `spin()` / `setResult()` / `await`.\n * Use `reelSet.setDropOrder()` to control which columns drop first.\n *\n * @example\n * import { DropRecipes } from 'pixi-reels';\n * builder.cascade(DropRecipes.cascadeDrop)\n */\n cascade(config: CascadeDropConfig): this {\n this._cascadeDropConfig = config;\n this._defaultSpinMode = 'cascade';\n return this;\n }\n\n /**\n * Set the initial symbol grid the reels show before the first spin.\n *\n * Two input shapes are accepted, mirroring `ReelSet.setResult`:\n *\n * 1. **Legacy `string[][]`** — one column per reel, row-indexed. Use\n * `frame[col][-1]` (or `[-2]`, etc.) to target buffer-above slots,\n * `frame[col][visibleRows]` for buffer-below.\n * 2. **Explicit `ColumnTarget[]`** — `{ visible, bufferAbove?, bufferBelow? }`\n * per column. Preferred when the seed comes from outside this process\n * (JSON config, worker message, server-rendered state) — the legacy\n * form's negative-index slots don't survive standard cloning, the\n * explicit form does.\n */\n initialFrame(frame: string[][] | ColumnTarget[]): this {\n this._initialFrame = toLegacyTargetGrid(frame);\n return this;\n }\n\n /** Build the ReelSet. Validates configuration and assembles all internal objects. */\n build(): ReelSet {\n this._validate();\n\n const reelCount = this._reelCount!;\n const symbolWidth = this._symbolWidth!;\n const symbolHeight = this._symbolHeight!;\n const bufferAbove = this._bufferSymbols;\n const bufferBelow = this._bufferSymbols;\n const ticker = this._ticker!;\n const isMultiWays = !!this._multiways;\n\n // Resolve per-reel row counts. MultiWays: every reel starts at maxRows.\n let visibleRowsPerReel: number[];\n if (isMultiWays) {\n visibleRowsPerReel = new Array(reelCount).fill(this._multiways!.maxRows);\n } else if (this._visibleRowsPerReel) {\n visibleRowsPerReel = this._visibleRowsPerReel;\n } else {\n const v = this._visibleRows!;\n visibleRowsPerReel = new Array(reelCount).fill(v);\n }\n\n // Resolve per-reel pixel-box heights. MultiWays: uniform reelPixelHeight.\n // Pyramid: defaults to visibleRowsPerReel[i] * symbolHeight.\n let reelPixelHeights: number[];\n if (isMultiWays) {\n reelPixelHeights = new Array(reelCount).fill(this._multiways!.reelPixelHeight);\n } else if (this._reelPixelHeights) {\n reelPixelHeights = this._reelPixelHeights;\n } else {\n reelPixelHeights = visibleRowsPerReel.map(\n (rows) => rows * symbolHeight + (rows - 1) * this._symbolGap.y,\n );\n }\n\n // Compute per-reel offsetY and target cell height.\n // SPIN-time uniform cell height equals the configured `symbolHeight`.\n const tallest = Math.max(...reelPixelHeights);\n const offsetsY = reelPixelHeights.map((h) => {\n switch (this._reelAnchor) {\n case 'top': return 0;\n case 'bottom': return tallest - h;\n case 'center':\n default: return (tallest - h) / 2;\n }\n });\n const perReelSymbolHeight: number[] = reelPixelHeights.map((h, i) => {\n const rows = visibleRowsPerReel[i];\n return (h - (rows - 1) * this._symbolGap.y) / rows;\n });\n // MultiWays uses uniform spinSymbolHeight = configured symbolHeight.\n // Pyramid: per-reel cell height. Uniform: same as symbolHeight.\n const spinSymbolHeight = symbolHeight;\n const initialSymbolHeight = isMultiWays\n ? new Array(reelCount).fill(spinSymbolHeight)\n : perReelSymbolHeight;\n\n // Apply default speed if none registered\n if (this._speeds.size === 0) {\n this._speeds.set('normal', SpeedPresets.NORMAL);\n }\n\n // Build symbols data from weights + per-symbol overrides\n const symbolsData: Record<string, SymbolData> = {};\n const symbolIds = this._symbolRegistry.symbolIds;\n for (const id of symbolIds) {\n const override = this._symbolDataOverrides[id] ?? {};\n symbolsData[id] = {\n weight: override.weight ?? this._weights[id] ?? 10,\n zIndex: override.zIndex ?? 1,\n unmask: override.unmask,\n size: override.size,\n };\n }\n\n // Build internal config\n const config: ReelSetInternalConfig = {\n grid: {\n reelCount,\n visibleRows: this._visibleRows ?? visibleRowsPerReel[0],\n symbolWidth,\n symbolHeight,\n symbolGap: { ...this._symbolGap },\n bufferSymbols: this._bufferSymbols,\n visibleRowsPerReel,\n reelPixelHeights,\n reelAnchor: this._reelAnchor,\n multiways: this._multiways,\n },\n symbols: symbolsData,\n speeds: this._speeds,\n initialSpeed: this._initialSpeed,\n offset: this._offset,\n ticker,\n };\n\n // Create subsystems\n const symbolFactory = new SymbolFactory(this._symbolRegistry);\n const randomProvider = new RandomSymbolProvider(symbolsData);\n const frameBuilder = new FrameBuilder(randomProvider);\n\n // Add custom middlewares\n for (const mw of this._middlewares) {\n frameBuilder.use(mw);\n }\n\n // Wire cascade drop-in phases under cascade-specific keys so the\n // standard 'start' / 'stop' phases stay available. The default spin\n // mode flips to 'cascade' when .cascade() was called, preserving\n // existing behaviour for callers that don't pass `spin({ mode })`.\n if (this._cascadeDropConfig) {\n const dropConfig = this._cascadeDropConfig;\n this._phaseFactory.register('dropStart', DropStartPhase);\n this._phaseFactory.registerFactory('dropStop', (reel, speed) => new DropStopPhase(reel, speed, dropConfig));\n }\n\n // MultiWays: wire AdjustPhase. Stay out of non-MultiWays chains entirely\n // so the default `start → spin → stop` flow is unchanged for them.\n if (isMultiWays) {\n const adjustDur = this._pinMigrationDuration;\n const pinMigrationEase = this._pinMigrationEase;\n this._phaseFactory.registerFactory('adjust', (reel, speed) => {\n const ms = typeof adjustDur === 'function' ? adjustDur(reel.reelIndex) : adjustDur;\n return new AdjustPhase(reel, speed, { durationMs: ms, ease: pinMigrationEase });\n });\n }\n\n // Create viewport — width covers all reels, height covers tallest box.\n const viewportWidth = reelCount * (symbolWidth + this._symbolGap.x) - this._symbolGap.x;\n const viewportHeight = tallest;\n\n // Auto-pick `SharedRectMaskStrategy` when the layout has horizontal\n // gaps AND any registered symbol needs to span across reel boundaries:\n //\n // - **big symbols** (footprint w > 1 or h > 1) — the per-reel mask\n // would clip cross-reel big symbols at every column gap (visible\n // vertical strips through the symbol), so we share a single mask.\n // - **unmasked symbols** (`SymbolData.unmask: true`) — these render\n // above the per-reel mask anyway, but neighboring (masked)\n // symbols still get clipped at the gap. Players see a\n // half-cropped neighbor next to the unmasked overlay. Sharing\n // one mask removes the gap stripe.\n //\n // Explicit `.maskStrategy(...)` calls always win.\n const hasBigSymbols = Object.values(symbolsData).some(\n (d) => d.size && (d.size.w > 1 || d.size.h > 1),\n );\n const hasUnmaskedSymbols = Object.values(symbolsData).some((d) => d.unmask);\n\n // Pyramid + unmask is not supported. `ReelMotion.snapToGrid()` and\n // `displace()` write reel-local Y to every symbol view — including\n // unmasked views that live in `viewport.unmaskedContainer`. On a\n // pyramid (any reel with offsetY != 0), the unmasked view's at-rest\n // Y is misset by `reel.container.y`. The activate path compensates,\n // but the next snap (landing/skip) re-breaks it. Fail at config time\n // rather than ship a layout the engine can't keep aligned.\n if (hasUnmaskedSymbols && offsetsY.some((y) => y !== 0)) {\n const pyramidIdx = offsetsY.findIndex((y) => y !== 0);\n throw new Error(\n `[pixi-reels] unmask + pyramid layout is not supported (reel ${pyramidIdx} ` +\n `has offsetY=${offsetsY[pyramidIdx]}). The motion layer writes reel-local ` +\n `Y to unmasked views, which mispositions them by reel.container.y on every ` +\n `snap. Use cell pins (reelSet.pin(...)) for above-mask overlays on pyramid ` +\n `slots, or remove the per-reel offset.`,\n );\n }\n\n if (\n !this._maskStrategyExplicit &&\n (hasBigSymbols || hasUnmaskedSymbols) &&\n this._symbolGap.x > 0\n ) {\n this._maskStrategy = new SharedRectMaskStrategy();\n // Heads-up so devs see the auto-pick in their console.\n const reason = hasBigSymbols\n ? 'big symbols are registered'\n : 'one or more symbols use `unmask: true`';\n // eslint-disable-next-line no-console\n console.info(\n `[pixi-reels] auto-selected SharedRectMaskStrategy because ${reason} ` +\n 'and symbolGap.x > 0. Pass .maskStrategy(...) explicitly to override.',\n );\n }\n const viewport = new ReelViewport(viewportWidth, viewportHeight, undefined, this._maskStrategy);\n\n // Create offset calculator (X-axis)\n const totalRowsForOffset = bufferAbove + Math.max(...visibleRowsPerReel) + bufferBelow;\n const offsetCalc = new OffsetCalculator(\n reelCount,\n totalRowsForOffset,\n symbolWidth,\n this._offset,\n );\n\n // Create reels with per-reel geometry.\n const reels: Reel[] = [];\n const maskRects: ReelMaskRect[] = [];\n for (let reelIndex = 0; reelIndex < reelCount; reelIndex++) {\n const rows = visibleRowsPerReel[reelIndex];\n const initialCellH = initialSymbolHeight[reelIndex];\n\n // Per-reel initial frame at its own visibleRows count.\n const initialFrame = this._initialFrame\n ? frameBuilder.build(reelIndex, rows, bufferAbove, bufferBelow, this._initialFrame[reelIndex])\n : frameBuilder.build(reelIndex, rows, bufferAbove, bufferBelow);\n\n const reelConfig: ReelConfig = {\n reelIndex,\n visibleRows: rows,\n bufferAbove,\n bufferBelow,\n symbolWidth,\n symbolHeight: initialCellH,\n symbolGapX: this._symbolGap.x,\n symbolGapY: this._symbolGap.y,\n symbolsData,\n initialSymbols: initialFrame,\n offsetY: offsetsY[reelIndex],\n reelHeight: reelPixelHeights[reelIndex],\n spinSymbolHeight,\n };\n\n const reel = new Reel(reelConfig, symbolFactory, randomProvider, viewport);\n reels.push(reel);\n maskRects.push({\n x: reelIndex * (symbolWidth + this._symbolGap.x),\n y: offsetsY[reelIndex],\n width: symbolWidth,\n height: reelPixelHeights[reelIndex],\n });\n }\n viewport.updateMaskSize(viewportWidth, viewportHeight, maskRects);\n\n // Build params\n const params: ReelSetParams = {\n config,\n reels,\n viewport,\n symbolFactory,\n frameBuilder,\n phaseFactory: this._phaseFactory,\n spinningMode: this._spinningMode,\n defaultSpinMode: this._defaultSpinMode,\n };\n\n return new ReelSet(params);\n }\n\n private _validate(): void {\n const errors: string[] = [];\n\n if (this._reelCount === undefined || this._reelCount <= 0) {\n errors.push('reels() must be called with a positive number.');\n }\n\n const hasShape = !!this._visibleRowsPerReel;\n const hasUniform = this._visibleRows !== undefined;\n const hasMega = !!this._multiways;\n\n if (!hasMega && !hasUniform && !hasShape) {\n errors.push('one of visibleRows(n) or visibleRowsPerReel([...]) or multiways({...}) must be called.');\n }\n if (hasUniform && hasShape) {\n errors.push('cannot call both visibleRows() and visibleRowsPerReel() — pick one.');\n }\n if (hasMega && hasShape) {\n errors.push('cannot combine multiways() with visibleRowsPerReel() — MultiWays shapes are server-driven.');\n }\n\n if (this._reelCount && hasShape && this._visibleRowsPerReel!.length !== this._reelCount) {\n errors.push(\n `visibleRowsPerReel length ${this._visibleRowsPerReel!.length} must equal reels(${this._reelCount}).`,\n );\n }\n if (hasShape) {\n for (let i = 0; i < this._visibleRowsPerReel!.length; i++) {\n if (this._visibleRowsPerReel![i] <= 0) {\n errors.push(`visibleRowsPerReel[${i}] = ${this._visibleRowsPerReel![i]} must be positive.`);\n break;\n }\n }\n }\n if (this._reelCount && this._reelPixelHeights && this._reelPixelHeights.length !== this._reelCount) {\n errors.push(\n `reelPixelHeights length ${this._reelPixelHeights.length} must equal reels(${this._reelCount}).`,\n );\n }\n\n if (hasMega) {\n const m = this._multiways!;\n if (m.minRows <= 0 || m.maxRows <= 0) {\n errors.push('multiways({minRows, maxRows}) must both be positive.');\n } else if (m.minRows > m.maxRows) {\n errors.push(`multiways: minRows ${m.minRows} cannot exceed maxRows ${m.maxRows}.`);\n }\n if (m.reelPixelHeight <= 0) {\n errors.push('multiways({reelPixelHeight}) must be positive.');\n }\n // multiways({reelPixelHeight}) sets a uniform reel-pixel height for\n // every reel; reelPixelHeights([...]) sets per-reel heights for\n // pyramid layouts. Setting both is ambiguous — fail loud.\n if (this._reelPixelHeights) {\n errors.push(\n 'cannot combine multiways({reelPixelHeight}) with reelPixelHeights([...]) — ' +\n 'multiways slots use a uniform reel pixel height. Drop reelPixelHeights() or ' +\n 'remove the multiways() configuration.',\n );\n }\n // Big symbols are mutually exclusive with MultiWays.\n for (const id of this._symbolRegistry.symbolIds) {\n const override = this._symbolDataOverrides[id] ?? {};\n if (override.size && (override.size.w > 1 || override.size.h > 1)) {\n errors.push(\n `big symbol '${id}' (size ${override.size.w}x${override.size.h}) cannot be ` +\n 'registered on a MultiWays slot. Drop multiways() or remove the size metadata.',\n );\n break;\n }\n }\n }\n\n // Big symbols (size > 1x1) are placed by the server at anchor cells\n // only — random fill skips them in v1 (a 2x2 with a non-zero weight\n // would silently never get picked, since RandomFillMiddleware can't\n // place blocks). Throw to surface the misunderstanding.\n for (const id of this._symbolRegistry.symbolIds) {\n const override = this._symbolDataOverrides[id] ?? {};\n const size = override.size;\n if (!size || (size.w === 1 && size.h === 1)) continue;\n const weight = override.weight ?? this._weights[id];\n if (weight !== undefined && weight > 0) {\n errors.push(\n `big symbol '${id}' (size ${size.w}x${size.h}) must have weight 0 — ` +\n 'big symbols are placed by the server at anchor cells only and never enter ' +\n 'random fill in v1. Set weight to 0 (or omit it) and place the symbol via setResult().',\n );\n }\n }\n\n if (this._visibleRows !== undefined && this._visibleRows <= 0) {\n errors.push('visibleRows() must be called with a positive number.');\n }\n if (this._symbolWidth === undefined || this._symbolHeight === undefined) {\n errors.push('symbolSize() must be called with width and height.');\n }\n if (this._symbolRegistry.size === 0) {\n errors.push('symbols() must register at least one symbol.');\n }\n if (!this._ticker) {\n errors.push('ticker() must be called with a PixiJS Ticker.');\n }\n if (this._speeds.size > 0 && !this._speeds.has(this._initialSpeed)) {\n errors.push(\n `initialSpeed '${this._initialSpeed}' does not match any registered speed profile. ` +\n `Available: ${[...this._speeds.keys()].join(', ')}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`ReelSetBuilder validation failed:\\n - ${errors.join('\\n - ')}`);\n }\n }\n}\n","import { Sprite, type Texture } from 'pixi.js';\nimport type { gsap } from 'gsap';\nimport { getGsap } from '../utils/gsapRef.js';\nimport { ReelSymbol } from './ReelSymbol.js';\n\nexport interface SpriteSymbolOptions {\n /** Map of symbolId → Texture. */\n textures: Record<string, Texture>;\n /** Anchor point. Default: { x: 0.5, y: 0.5 }. */\n anchor?: { x: number; y: number };\n}\n\n/**\n * Symbol implementation using a simple PixiJS Sprite.\n * Swaps texture on activate. Win animation is a scale pulse via GSAP.\n */\nexport class SpriteSymbol extends ReelSymbol {\n private _sprite: Sprite;\n private _textures: Record<string, Texture>;\n private _winTween: gsap.core.Tween | null = null;\n\n constructor(options: SpriteSymbolOptions) {\n super();\n this._textures = options.textures;\n const anchor = options.anchor ?? { x: 0, y: 0 };\n this._sprite = new Sprite();\n this._sprite.anchor.set(anchor.x, anchor.y);\n this.view.addChild(this._sprite);\n }\n\n protected onActivate(symbolId: string): void {\n const texture = this._textures[symbolId];\n if (texture) {\n this._sprite.texture = texture;\n }\n }\n\n protected onDeactivate(): void {\n this._killWinTween();\n this._sprite.scale.set(1, 1);\n }\n\n async playWin(): Promise<void> {\n this._killWinTween();\n return new Promise<void>((resolve) => {\n this._winTween = getGsap().to(this._sprite.scale, {\n x: 1.15,\n y: 1.15,\n duration: 0.15,\n yoyo: true,\n repeat: 1,\n ease: 'power2.inOut',\n onComplete: resolve,\n });\n });\n }\n\n stopAnimation(): void {\n this._killWinTween();\n this._sprite.scale.set(1, 1);\n }\n\n resize(width: number, height: number): void {\n this._sprite.width = width;\n this._sprite.height = height;\n }\n\n protected override onDestroy(): void {\n this._killWinTween();\n }\n\n private _killWinTween(): void {\n if (this._winTween) {\n this._winTween.kill();\n this._winTween = null;\n }\n }\n}\n","import { AnimatedSprite, type Texture } from 'pixi.js';\nimport { ReelSymbol } from './ReelSymbol.js';\n\nexport interface AnimatedSpriteSymbolOptions {\n /** Map of symbolId → array of frame textures. */\n frames: Record<string, Texture[]>;\n /** Playback speed (frames per second multiplier). Default: 1. */\n animationSpeed?: number;\n /** Anchor point. Default: { x: 0.5, y: 0.5 }. */\n anchor?: { x: number; y: number };\n}\n\n/**\n * Symbol implementation using PixiJS AnimatedSprite.\n * Swaps frame arrays on activate. Win animation plays the full sequence.\n */\nexport class AnimatedSpriteSymbol extends ReelSymbol {\n private _animSprite: AnimatedSprite;\n private _frames: Record<string, Texture[]>;\n private _animationSpeed: number;\n private _winResolve: (() => void) | null = null;\n\n constructor(options: AnimatedSpriteSymbolOptions) {\n super();\n this._frames = options.frames;\n this._animationSpeed = options.animationSpeed ?? 1;\n const anchor = options.anchor ?? { x: 0, y: 0 };\n\n // Start with the first available frame set\n const firstFrames = Object.values(this._frames)[0] ?? [];\n this._animSprite = new AnimatedSprite(firstFrames.length > 0 ? firstFrames : []);\n this._animSprite.anchor.set(anchor.x, anchor.y);\n this._animSprite.animationSpeed = this._animationSpeed;\n this._animSprite.loop = false;\n this.view.addChild(this._animSprite);\n }\n\n protected onActivate(symbolId: string): void {\n const frames = this._frames[symbolId];\n if (frames && frames.length > 0) {\n this._animSprite.textures = frames;\n this._animSprite.gotoAndStop(0);\n }\n }\n\n protected onDeactivate(): void {\n this._animSprite.stop();\n this._winResolve = null;\n }\n\n async playWin(): Promise<void> {\n return new Promise<void>((resolve) => {\n this._winResolve = resolve;\n this._animSprite.loop = false;\n this._animSprite.onComplete = () => {\n this._winResolve = null;\n this._animSprite.onComplete = undefined;\n // Return to frame 0 so the cell settles on its idle look instead\n // of holding the last frame of the win sequence (which for\n // generated pixel-art sequences often ends mid-action — muted,\n // shifted, or otherwise not the neutral base pose).\n this._animSprite.gotoAndStop(0);\n resolve();\n };\n this._animSprite.gotoAndPlay(0);\n });\n }\n\n stopAnimation(): void {\n this._animSprite.stop();\n this._animSprite.gotoAndStop(0);\n if (this._winResolve) {\n this._winResolve();\n this._winResolve = null;\n }\n }\n\n resize(width: number, height: number): void {\n this._animSprite.width = width;\n this._animSprite.height = height;\n // Position the sprite to match its anchor so it fills the cell.\n // Without this, an anchor of (0.5, 0.5) would render the sprite with\n // its centre at the cell's top-left corner — only the bottom-right\n // quadrant visible inside the mask.\n this._animSprite.x = width * this._animSprite.anchor.x;\n this._animSprite.y = height * this._animSprite.anchor.y;\n }\n}\n","/**\n * Configuration for cascade drop-in behavior.\n * Passed to ReelSetBuilder.cascade() to replace the default strip-spin mechanic.\n */\nexport interface CascadeDropConfig {\n /** Stagger between rows dropping in (ms). 0 = all rows arrive simultaneously. Default: 0. */\n rowDelay?: number;\n /** Stagger between rows falling out (ms). 0 = all rows fall simultaneously. Default: 0. */\n fallRowDelay?: number;\n /** Distance symbols travel (px) — both falling out and dropping in. Default: auto (full column height). */\n fromY?: number;\n /** GSAP easing for the drop-in animation. Default: 'bounce.out'. */\n easing?: string;\n /** Duration of each symbol's drop-in animation (ms). 0 = instant. Default: 600. */\n dropDuration?: number;\n /** Duration of each symbol's fall-out animation (ms). 0 = skip fall. Default: 300. */\n fallDuration?: number;\n}\n\n/**\n * Named presets for common cascade drop patterns.\n *\n * Pass one to ReelSetBuilder.cascade():\n * builder.cascade(DropRecipes.cascadeDrop)\n *\n * Control reel order per-spin with reelSet.setDropOrder():\n * reelSet.setDropOrder('ltr') // left-to-right stagger\n * reelSet.setDropOrder('rtl') // right-to-left stagger\n * reelSet.setDropOrder('all') // all columns simultaneously\n */\nexport const DropRecipes = {\n /** Old symbols fall out, then new ones drop in row by row with bounce. Classic cascade feel. */\n cascadeDrop: { rowDelay: 80, dropDuration: 600, fallDuration: 300, easing: 'bounce.out' } as CascadeDropConfig,\n\n /** Stiff landing — no bounce. Symbols fall out then drop in cleanly with a hard stop. */\n stiffDrop: { rowDelay: 60, dropDuration: 450, fallDuration: 280, easing: 'power3.out' } as CascadeDropConfig,\n\n /** Old symbols fall out, then all new symbols in a column drop simultaneously. Good for refills. */\n simultaneousDrop: { rowDelay: 0, dropDuration: 500, fallDuration: 300, easing: 'bounce.out' } as CascadeDropConfig,\n\n /** Instant placement — no fall, no drop animation. Equivalent to slam-stop. */\n slamDrop: { rowDelay: 0, dropDuration: 0, fallDuration: 0 } as CascadeDropConfig,\n} as const;\n","import type { gsap } from 'gsap';\nimport { getGsap } from '../utils/gsapRef.js';\nimport { ReelPhase } from '../spin/phases/ReelPhase.js';\n\n/**\n * Anticipation phase for cascade drop-in mechanics.\n *\n * The default AnticipationPhase slows a spinning reel — useless when\n * the reel is stationary. This phase shakes the column instead, giving\n * the player a clear \"something's about to drop here\" signal.\n *\n * Register it to replace the default for cascade games:\n * builder.phases(f => f.register('anticipation', CascadeAnticipationPhase))\n *\n * Duration is driven by speed.anticipationDelay (same as standard anticipation).\n */\nexport class CascadeAnticipationPhase extends ReelPhase<void> {\n readonly name = 'anticipation';\n readonly skippable = true;\n\n private _tween: gsap.core.Tween | null = null;\n private _baseX = 0;\n\n protected onEnter(): void {\n const duration = this._speed.anticipationDelay / 1000;\n\n if (duration <= 0) {\n this._complete();\n return;\n }\n\n this._baseX = this._reel.container.x;\n\n // ~12 shakes per second; round to fill duration exactly\n const halfPeriod = 0.04;\n const repeats = Math.round(duration / halfPeriod) - 1;\n\n this._tween = getGsap().to(this._reel.container, {\n x: this._baseX + 4,\n duration: halfPeriod,\n ease: 'power1.inOut',\n yoyo: true,\n repeat: repeats,\n onComplete: () => {\n this._reel.container.x = this._baseX;\n this._complete();\n },\n });\n }\n\n update(_deltaMs: number): void {}\n\n protected onSkip(): void {\n this._tween?.kill();\n this._tween = null;\n this._reel.container.x = this._baseX;\n }\n}\n","import type { SpinningMode } from './SpinningMode.js';\n\n/**\n * Cascade/tumble spinning mode.\n * Symbols fall from above with gravity-like acceleration,\n * used for tumble/avalanche mechanics.\n */\nexport class CascadeMode implements SpinningMode {\n readonly name = 'cascade';\n\n private _gravity: number;\n\n /**\n * @param gravity - Gravity acceleration factor. Default: 1.5.\n */\n constructor(gravity: number = 1.5) {\n this._gravity = gravity;\n }\n\n computeDeltaY(symbolHeight: number, speed: number, deltaMs: number): number {\n const raw = (symbolHeight * speed * this._gravity * deltaMs) / 1000;\n return Math.min(raw, symbolHeight);\n }\n}\n","import type { SpinningMode } from './SpinningMode.js';\n\n/**\n * Immediate placement mode for super-turbo skip.\n * Symbols snap to position instantly — no actual spinning animation.\n */\nexport class ImmediateMode implements SpinningMode {\n readonly name = 'immediate';\n\n computeDeltaY(_symbolHeight: number, _speed: number, _deltaMs: number): number {\n // No movement — placement is handled directly by the phase\n return 0;\n }\n}\n","import type { SymbolPosition, Win } from '../config/types.js';\n\nexport type { Win, SymbolPosition };\n\n/** Return a new array sorted by `value` descending (non-mutating). Missing values sort as 0. */\nexport function sortByValueDesc<T extends { value?: number }>(wins: readonly T[]): T[] {\n return [...wins].sort((a, b) => (b.value ?? 0) - (a.value ?? 0));\n}\n","import type { Win } from '../config/types.js';\nimport type { ReelSet } from '../core/ReelSet.js';\nimport type { SymbolPosition } from '../events/ReelEvents.js';\nimport type { ReelSymbol } from '../symbols/ReelSymbol.js';\nimport type { Disposable } from '../utils/Disposable.js';\nimport { sortByValueDesc } from './Win.js';\n\n/**\n * What to play on each cell being highlighted.\n *\n * - `'win'` — default. Calls `symbol.playWin()` (your subclass's hook).\n * - `string` — a named animation. If the symbol exposes a\n * `playAnimation(name)` method (e.g. SpineSymbol), it's invoked; else\n * it falls back to `playWin()`.\n * - `(symbol, cell, win) => Promise<void>` — drive the animation\n * yourself. Good for GSAP bounces, line-specific pulses, etc.\n */\nexport type WinSymbolAnim =\n | 'win'\n | string\n | ((symbol: ReelSymbol, cell: SymbolPosition, win: Win) => Promise<void>);\n\nexport interface WinPresenterOptions {\n /**\n * Fade non-winning symbols to this alpha while a win is active.\n * - `true` (default) → alpha 0.35\n * - number → that alpha\n * - `false` → don't touch non-winners\n *\n * Restored on `win:end`.\n */\n dimLosers?: boolean | { alpha?: number };\n /** See {@link WinSymbolAnim}. Default `'win'`. */\n symbolAnim?: WinSymbolAnim;\n /**\n * Delay between cells *within* a single win (ms).\n * - `0` (default) → all cells animate simultaneously\n * - `> 0` → cells start one after another in array order (e.g. a\n * left-to-right sweep across a payline's cells)\n */\n stagger?: number;\n /** Delay between successive wins in the sequence (ms). Default 400. */\n cycleGap?: number;\n /** Number of full cycles through the wins list. `-1` for infinite. Default 1. */\n cycles?: number;\n /** Sort wins by `value` descending before cycling. Default true. */\n sortByValue?: boolean;\n}\n\ninterface ResolvedOptions {\n dimAlpha: number | null;\n symbolAnim: WinSymbolAnim;\n stagger: number;\n cycleGap: number;\n cycles: number;\n sortByValue: boolean;\n}\n\n/**\n * Highlights winning cells on a reel set. One job: animate the symbols.\n *\n * The presenter doesn't draw lines, outlines, or any per-win visual — it\n * emits `win:start` / `win:group` / `win:symbol` / `win:end` events so\n * your code can hook anything it wants (polylines, Spine line rigs,\n * popup numbers, sound cues) by subscribing and using\n * `reelSet.getCellBounds(col, row)` to place graphics.\n *\n * Two knobs cover the common presentation modes:\n *\n * - `stagger: 0` → all cells in a win pulse together\n * - `stagger: 60` → cells start one after another — a left-to-right\n * sweep if you pass cells in reel order\n *\n * ```ts\n * const presenter = new WinPresenter(reelSet, { stagger: 80 });\n *\n * reelSet.events.on('spin:complete', async () => {\n * const wins = await server.wins(result); // your wins, your shape\n * await presenter.show(wins);\n * });\n * reelSet.events.on('spin:start', () => presenter.abort());\n * ```\n *\n * Cascades: drive `presenter.show([{ cells: winners }])` from\n * `runCascade`'s `onWinnersVanish` hook — cluster pops and payline hits\n * are the same shape to the presenter.\n */\nexport class WinPresenter implements Disposable {\n private _reelSet: ReelSet;\n private _options: ResolvedOptions;\n private _abort: AbortController | null = null;\n private _isActive = false;\n private _isDestroyed = false;\n\n constructor(reelSet: ReelSet, options: WinPresenterOptions = {}) {\n this._reelSet = reelSet;\n this._options = WinPresenter._resolve(options);\n }\n\n get isActive(): boolean {\n return this._isActive;\n }\n\n get isDestroyed(): boolean {\n return this._isDestroyed;\n }\n\n /**\n * Present the given wins. Cancels any in-flight sequence first.\n * Resolves when all cycles complete or when `abort()` is called.\n *\n * Empty input resolves immediately without firing any events.\n */\n async show(wins: readonly Win[]): Promise<void> {\n this.abort();\n if (this._isDestroyed) return;\n if (wins.length === 0) return;\n\n const ordered = this._options.sortByValue\n ? sortByValueDesc(wins)\n : [...wins];\n\n const abort = new AbortController();\n this._abort = abort;\n this._isActive = true;\n this._reelSet.events.emit('win:start', ordered);\n\n let loop = 0;\n try {\n while (this._options.cycles === -1 || loop < this._options.cycles) {\n for (const win of ordered) {\n if (abort.signal.aborted) return;\n await this._showOne(win, abort.signal);\n if (abort.signal.aborted) return;\n await this._wait(this._options.cycleGap, abort.signal);\n }\n loop++;\n }\n } finally {\n this._restoreAlpha();\n const wasAborted = abort.signal.aborted;\n if (this._abort === abort) this._abort = null;\n this._isActive = false;\n this._reelSet.events.emit('win:end', wasAborted ? 'aborted' : 'complete');\n }\n }\n\n /** Abort any in-flight `show()`. */\n abort(): void {\n if (this._abort) this._abort.abort();\n }\n\n destroy(): void {\n if (this._isDestroyed) return;\n this._isDestroyed = true;\n this.abort();\n }\n\n private async _showOne(win: Win, signal: AbortSignal): Promise<void> {\n const cells = [...win.cells];\n if (cells.length === 0) return;\n\n // Apply dim before firing win:group so listeners observe the live\n // visual state (e.g. a UI snapshot sees losers already faded).\n this._applyDim(cells);\n this._reelSet.events.emit('win:group', win, cells);\n\n const stagger = this._options.stagger;\n const animPromises: Promise<void>[] = [];\n\n for (let i = 0; i < cells.length; i++) {\n if (signal.aborted) break;\n if (i > 0 && stagger > 0) await this._wait(stagger, signal);\n if (signal.aborted) break;\n const cell = cells[i];\n const reel = this._reelSet.getReel(cell.reelIndex);\n if (!reel) continue;\n const symbol = reel.getSymbolAt(cell.rowIndex);\n if (!symbol) continue;\n this._reelSet.events.emit('win:symbol', symbol, cell, win);\n animPromises.push(this._playAnim(symbol, cell, win));\n }\n\n await Promise.all(animPromises);\n }\n\n private async _playAnim(\n symbol: ReelSymbol,\n cell: SymbolPosition,\n win: Win,\n ): Promise<void> {\n const anim = this._options.symbolAnim;\n if (typeof anim === 'function') return anim(symbol, cell, win);\n if (anim === 'win') return symbol.playWin();\n const withPlay = symbol as unknown as { playAnimation?: (name: string) => Promise<void> };\n if (typeof withPlay.playAnimation === 'function') return withPlay.playAnimation(anim);\n return symbol.playWin();\n }\n\n private _applyDim(winCells: readonly SymbolPosition[]): void {\n const alpha = this._options.dimAlpha;\n if (alpha === null) return;\n\n const winKeys = new Set<string>();\n for (const c of winCells) winKeys.add(`${c.reelIndex}:${c.rowIndex}`);\n\n const reels = this._reelSet.reels;\n for (let r = 0; r < reels.length; r++) {\n const reel = reels[r];\n for (let row = 0; row < reel.visibleRows; row++) {\n const view = reel.getSymbolAt(row).view;\n view.alpha = winKeys.has(`${r}:${row}`) ? 1 : alpha;\n }\n }\n }\n\n private _restoreAlpha(): void {\n const reels = this._reelSet.reels;\n for (const reel of reels) {\n for (let row = 0; row < reel.visibleRows; row++) {\n reel.getSymbolAt(row).view.alpha = 1;\n }\n }\n }\n\n private _wait(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve();\n const t = setTimeout(resolve, ms);\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(t);\n resolve();\n },\n { once: true },\n );\n });\n }\n\n private static _resolve(opts: WinPresenterOptions): ResolvedOptions {\n let dimAlpha: number | null;\n if (opts.dimLosers === false) {\n dimAlpha = null;\n } else if (typeof opts.dimLosers === 'object' && opts.dimLosers !== null) {\n dimAlpha = opts.dimLosers.alpha ?? 0.35;\n } else {\n dimAlpha = 0.35;\n }\n\n return {\n dimAlpha,\n symbolAnim: opts.symbolAnim ?? 'win',\n stagger: Math.max(0, opts.stagger ?? 0),\n cycleGap: opts.cycleGap ?? 400,\n cycles: opts.cycles ?? 1,\n sortByValue: opts.sortByValue ?? true,\n };\n }\n}\n","import { Graphics } from 'pixi.js';\nimport type { ReelSet } from '../core/ReelSet.js';\nimport type { Reel } from '../core/Reel.js';\n\n/**\n * Debug snapshot — plain JSON representation of the entire reel state.\n *\n * Designed for AI agents that cannot see the canvas.\n * Returns no PixiJS display objects, only serializable data.\n *\n * **Breaking note (since v0.3):** `visibleRows` is now `number[]` (one entry\n * per reel) so jagged shapes (pyramids, MultiWays) are representable. For\n * uniform slots every entry is the same value. Adapt downstream code that\n * deep-reads the snapshot.\n */\nexport interface DebugSnapshot {\n timestamp: number;\n isSpinning: boolean;\n currentSpeed: string;\n availableSpeeds: string[];\n spotlightActive: boolean;\n reelCount: number;\n visibleRows: number[];\n reels: DebugReelSnapshot[];\n grid: string[][];\n}\n\nexport interface DebugReelSnapshot {\n index: number;\n speed: number;\n isStopping: boolean;\n allSymbols: { row: number; symbolId: string; y: number }[];\n visibleSymbols: string[];\n}\n\n/**\n * Take a plain-JSON snapshot of the entire reel set state.\n *\n * This is the primary debugging tool for AI agents. The output is\n * a serializable object with no circular references, no PixiJS types.\n *\n * ```ts\n * const state = debugSnapshot(reelSet);\n * console.log(JSON.stringify(state, null, 2));\n * ```\n */\nexport function debugSnapshot(reelSet: ReelSet): DebugSnapshot {\n const reels = reelSet.reels;\n const reelSnapshots: DebugReelSnapshot[] = reels.map((reel: Reel, i: number) => ({\n index: i,\n speed: reel.speed,\n isStopping: reel.isStopping,\n allSymbols: reel.symbols.map((s, row) => ({\n row,\n symbolId: s.symbolId,\n y: Math.round(s.view.y),\n })),\n visibleSymbols: reel.getVisibleSymbols(),\n }));\n\n // Build the visual grid (what a player would see). Uses the ReelSet\n // resolver so cross-reel OCCUPIED cells of a big-symbol block render as\n // the anchor's id, not as the OCCUPIED sentinel.\n const grid: string[][] = reelSet.getVisibleGrid();\n\n return {\n timestamp: Date.now(),\n isSpinning: reelSet.isSpinning,\n currentSpeed: reelSet.speed.activeName,\n availableSpeeds: reelSet.speed.profileNames,\n spotlightActive: reelSet.spotlight.isActive,\n reelCount: reels.length,\n visibleRows: reels.map((r) => r.visibleRows),\n reels: reelSnapshots,\n grid,\n };\n}\n\n/**\n * Pretty-print the grid as an ASCII table.\n *\n * ```\n * ┌────────┬────────┬────────┬────────┬────────┐\n * │ cherry │ lemon │ bar │ seven │ cherry │\n * │ plum │ cherry │ wild │ lemon │ orange │\n * │ orange │ bell │ cherry │ plum │ bell │\n * └────────┴────────┴────────┴────────┴────────┘\n * ```\n */\nexport function debugGrid(reelSet: ReelSet): string {\n const snap = debugSnapshot(reelSet);\n const { grid, visibleRows } = snap;\n if (grid.length === 0) return '(empty grid)';\n\n const colWidth = 8;\n const maxRows = Math.max(...visibleRows);\n const pad = (s: string) => s.slice(0, colWidth).padEnd(colWidth);\n const empty = ' '.repeat(colWidth);\n\n const border = (left: string, mid: string, right: string) =>\n left + grid.map(() => '─'.repeat(colWidth)).join(mid) + right;\n\n const lines: string[] = [];\n lines.push(border('┌', '┬', '┐'));\n\n for (let row = 0; row < maxRows; row++) {\n const cells = grid.map((col, i) => (row < visibleRows[i] ? pad(col[row] ?? '?') : empty));\n lines.push('│' + cells.join('│') + '│');\n }\n\n lines.push(border('└', '┴', '┘'));\n return lines.join('\\n');\n}\n\n/**\n * One captured frame from `startRecording()` — a `DebugSnapshot` plus the\n * tag the recording was started with and the spin event that triggered\n * the capture.\n */\nexport interface RecordedFrame {\n /** Recording tag at the time of capture. Useful for grouping multiple sessions. */\n tag: string;\n /** Reel-set event that triggered the capture (`spin:start`, `spin:allLanded`, etc). */\n trigger: string;\n /** Snapshot of `debugSnapshot(reelSet)` at the moment of capture. */\n snapshot: DebugSnapshot;\n}\n\n/**\n * Default upper bound on `_recordedFrames` length. When the buffer fills,\n * the oldest entries are dropped (rolling window). Override per session\n * via `startRecording(reelSet, tag, { maxFrames })`. A long-running debug\n * session in a browser would otherwise grow the array forever.\n */\nconst DEFAULT_MAX_FRAMES = 1000;\n\n/** All captured frames across all recording sessions in this process. */\nconst _recordedFrames: RecordedFrame[] = [];\n\n/** Effective per-process cap. Updated when a session starts with a higher value. */\nlet _maxFrames = DEFAULT_MAX_FRAMES;\n\n/**\n * Per-recording-session state: which events to listen on and how to\n * detach them later. Keyed by the `ReelSet` so two reel sets in the\n * same page can each record independently.\n */\nconst _recorders = new WeakMap<ReelSet, () => void>();\n\n/** Options for {@link startRecording}. */\nexport interface StartRecordingOptions {\n /**\n * Maximum number of frames retained across the whole process. When the\n * buffer is full the oldest frames are dropped. Default 1000.\n */\n maxFrames?: number;\n}\n\n/**\n * Start recording the reel-set's frame state at every key spin event\n * (`spin:start`, `spin:reelLanded`, `spin:allLanded`, `spin:complete`).\n * Each event captures a `DebugSnapshot` and pushes it onto a process-\n * wide rolling log readable via {@link getFrames}.\n *\n * The `tag` is freeform — use it to label multiple recording sessions\n * so you can filter `getFrames(tag)` later. Call {@link stopRecording}\n * to detach the listeners (also fires automatically when the reel set\n * emits `'destroyed'`).\n *\n * Designed for AI agents and debug harnesses. Calling `startRecording`\n * twice on the same `reelSet` replaces the prior recording (the previous\n * tag's listeners are removed before the new ones attach).\n *\n * ```ts\n * import { startRecording, stopRecording, getFrames } from 'pixi-reels';\n *\n * startRecording(reelSet, 'spin-1');\n * await reelSet.spin();\n * stopRecording(reelSet);\n * const frames = getFrames('spin-1'); // every snapshot tagged 'spin-1'\n * ```\n */\nexport function startRecording(\n reelSet: ReelSet,\n tag = 'default',\n options: StartRecordingOptions = {},\n): void {\n // Detach any prior recorder on this reel set first.\n stopRecording(reelSet);\n\n if (options.maxFrames !== undefined && options.maxFrames > 0) {\n _maxFrames = options.maxFrames;\n }\n\n const capture = (trigger: string): void => {\n _recordedFrames.push({ tag, trigger, snapshot: debugSnapshot(reelSet) });\n // Rolling window: drop oldest when over cap.\n if (_recordedFrames.length > _maxFrames) {\n _recordedFrames.splice(0, _recordedFrames.length - _maxFrames);\n }\n };\n\n const onStart = () => capture('spin:start');\n const onReelLanded = () => capture('spin:reelLanded');\n const onAllLanded = () => capture('spin:allLanded');\n const onComplete = () => capture('spin:complete');\n // Auto-detach when the reel set is destroyed — otherwise listeners hang\n // off a dead emitter and the WeakMap entry can't drop until GC.\n const onDestroyed = () => stopRecording(reelSet);\n\n reelSet.events.on('spin:start', onStart);\n reelSet.events.on('spin:reelLanded', onReelLanded);\n reelSet.events.on('spin:allLanded', onAllLanded);\n reelSet.events.on('spin:complete', onComplete);\n reelSet.events.on('destroyed', onDestroyed);\n\n _recorders.set(reelSet, () => {\n reelSet.events.off('spin:start', onStart);\n reelSet.events.off('spin:reelLanded', onReelLanded);\n reelSet.events.off('spin:allLanded', onAllLanded);\n reelSet.events.off('spin:complete', onComplete);\n reelSet.events.off('destroyed', onDestroyed);\n });\n}\n\n/** Detach the recorder previously installed by {@link startRecording}. No-op if none. */\nexport function stopRecording(reelSet: ReelSet): void {\n const detach = _recorders.get(reelSet);\n if (detach) {\n detach();\n _recorders.delete(reelSet);\n }\n}\n\n/**\n * All recorded frames in capture order. When `tag` is provided, only\n * frames tagged with it are returned. Frames are not cleared between\n * recording sessions — call {@link clearFrames} to reset.\n */\nexport function getFrames(tag?: string): readonly RecordedFrame[] {\n if (tag === undefined) return _recordedFrames.slice();\n return _recordedFrames.filter((f) => f.tag === tag);\n}\n\n/** Empty the global recording log. */\nexport function clearFrames(): void {\n _recordedFrames.length = 0;\n}\n\n/**\n * Enable debug mode: attaches debug utilities to `window.__PIXI_REELS_DEBUG`.\n *\n * After calling this, an AI agent can run in the browser console:\n * ```js\n * __PIXI_REELS_DEBUG.snapshot() // full state JSON\n * __PIXI_REELS_DEBUG.grid() // ASCII grid\n * __PIXI_REELS_DEBUG.log() // console.log the grid\n * __PIXI_REELS_DEBUG.startRecording('myTag')\n * __PIXI_REELS_DEBUG.stopRecording()\n * __PIXI_REELS_DEBUG.getFrames('myTag')\n * ```\n */\nexport function enableDebug(reelSet: ReelSet): void {\n if (typeof window === 'undefined') return;\n\n let maskOverlay: Graphics | null = null;\n\n const debug = {\n reelSet,\n snapshot: () => debugSnapshot(reelSet),\n grid: () => debugGrid(reelSet),\n log: () => {\n const snap = debugSnapshot(reelSet);\n console.log(`[pixi-reels debug] spinning=${snap.isSpinning} speed=${snap.currentSpeed}`);\n console.log(debugGrid(reelSet));\n return snap;\n },\n /** Log every event as it happens */\n trace: () => {\n const events = [\n 'spin:start', 'spin:allStarted', 'spin:stopping',\n 'spin:reelLanded', 'spin:allLanded', 'spin:complete',\n 'skip:requested', 'skip:completed', 'speed:changed',\n 'spotlight:start', 'spotlight:end',\n 'shape:changed', 'adjust:start', 'adjust:complete',\n 'pin:placed', 'pin:moved', 'pin:expired', 'pin:migrated',\n 'destroyed',\n ] as const;\n for (const event of events) {\n reelSet.events.on(event as any, (...args: any[]) => {\n console.log(`[pixi-reels] ${event}`, ...args);\n });\n }\n console.log('[pixi-reels debug] tracing enabled for all events');\n },\n /** Start a frame-state recording session on this reel set. */\n startRecording: (tag = 'default', options?: StartRecordingOptions) =>\n startRecording(reelSet, tag, options),\n /** Stop a recording session — paired with `startRecording`. */\n stopRecording: () => stopRecording(reelSet),\n /** Pull recorded frames; pass `tag` to filter to one session. */\n getFrames: (tag?: string) => getFrames(tag),\n /** Empty the global recording log. */\n clearFrames: () => clearFrames(),\n /**\n * Toggle a debug overlay on the unmasked container that visualizes the\n * mask shape and per-reel boxes. Useful for spotting pyramid peek and\n * confirming MultiWays box geometry.\n */\n showMask: (enabled: boolean) => {\n if (enabled) {\n if (maskOverlay) return;\n const g = new Graphics();\n g.rect(0, 0, reelSet.viewport.maskWidth, reelSet.viewport.maskHeight)\n .fill({ color: 0xff0000, alpha: 0.15 });\n for (const rect of reelSet.viewport.maskRects) {\n g.rect(rect.x, rect.y, rect.width, rect.height)\n .stroke({ color: 0x00ff00, width: 2 });\n }\n reelSet.viewport.unmaskedContainer.addChild(g);\n maskOverlay = g;\n } else if (maskOverlay) {\n reelSet.viewport.unmaskedContainer.removeChild(maskOverlay);\n maskOverlay.destroy();\n maskOverlay = null;\n }\n },\n };\n\n (window as any).__PIXI_REELS_DEBUG = debug;\n console.log('[pixi-reels] Debug mode enabled. Use __PIXI_REELS_DEBUG.log() to inspect state.');\n}\n","import type { Ticker } from 'pixi.js';\n\ntype TickerCallback = (ticker: Ticker) => void;\n\n/**\n * Minimal drop-in replacement for `PIXI.Ticker` for tests.\n *\n * Exposes the exact surface `pixi-reels` uses internally (`add`, `remove`,\n * `deltaMS`) plus a manual `tick(deltaMs)` method so tests can advance time\n * deterministically without depending on requestAnimationFrame.\n *\n * ```ts\n * const ticker = new FakeTicker();\n * const reelSet = new ReelSetBuilder()\n * .ticker(ticker as unknown as PIXI.Ticker)\n * ...\n * .build();\n *\n * ticker.tick(16); // advance one frame\n * ticker.tickFor(500); // advance 500ms in 16ms frames\n * ```\n */\nexport class FakeTicker {\n public deltaMS = 16;\n public deltaTime = 1;\n public elapsedMS = 0;\n public lastTime = 0;\n public speed = 1;\n public started = false;\n public FPS = 60;\n public minFPS = 10;\n public maxFPS = 0;\n\n private _callbacks: TickerCallback[] = [];\n\n add(fn: TickerCallback): this {\n this._callbacks.push(fn);\n return this;\n }\n\n addOnce(fn: TickerCallback): this {\n const wrapped: TickerCallback = (t) => {\n this.remove(wrapped);\n fn(t);\n };\n return this.add(wrapped);\n }\n\n remove(fn: TickerCallback): this {\n const i = this._callbacks.indexOf(fn);\n if (i !== -1) this._callbacks.splice(i, 1);\n return this;\n }\n\n start(): this {\n this.started = true;\n return this;\n }\n\n stop(): this {\n this.started = false;\n return this;\n }\n\n destroy(): void {\n this._callbacks.length = 0;\n this.started = false;\n }\n\n /** Manually advance time by `deltaMs` milliseconds and fire all listeners. */\n tick(deltaMs = 16): void {\n this.deltaMS = deltaMs;\n this.deltaTime = deltaMs / (1000 / 60);\n this.elapsedMS += deltaMs;\n this.lastTime += deltaMs;\n const snapshot = this._callbacks.slice();\n for (const cb of snapshot) {\n cb(this as unknown as Ticker);\n }\n }\n\n /** Advance time by `totalMs`, chopped into `stepMs` frames. */\n tickFor(totalMs: number, stepMs = 16): void {\n let remaining = totalMs;\n while (remaining > 0) {\n const step = Math.min(stepMs, remaining);\n this.tick(step);\n remaining -= step;\n }\n }\n\n get listenerCount(): number {\n return this._callbacks.length;\n }\n}\n","import { ReelSymbol } from '../symbols/ReelSymbol.js';\n\n/**\n * A `ReelSymbol` implementation that does no rendering at all.\n *\n * It creates a `Container` for its `view` (so the Reel's child-tree logic works)\n * but never paints anything. This lets tests build a real `ReelSet` without a\n * renderer, textures, or assets.\n *\n * ```ts\n * builder.symbols((r) => {\n * for (const id of ['cherry', 'lemon', 'seven']) {\n * r.register(id, HeadlessSymbol, {});\n * }\n * });\n * ```\n */\nexport class HeadlessSymbol extends ReelSymbol {\n private _width = 0;\n private _height = 0;\n\n protected onActivate(_symbolId: string): void {\n // no-op\n }\n\n protected onDeactivate(): void {\n // no-op\n }\n\n async playWin(): Promise<void> {\n // resolve immediately\n }\n\n stopAnimation(): void {\n // no-op\n }\n\n resize(width: number, height: number): void {\n this._width = width;\n this._height = height;\n }\n\n get width(): number {\n return this._width;\n }\n\n get height(): number {\n return this._height;\n }\n}\n","import type { Ticker } from 'pixi.js';\nimport { ReelSetBuilder } from '../core/ReelSetBuilder.js';\nimport type { ReelSet } from '../core/ReelSet.js';\nimport type { SpinResult } from '../events/ReelEvents.js';\nimport type { ColumnTarget } from '../frame/ColumnTarget.js';\nimport { debugSnapshot, debugGrid } from '../debug/debug.js';\nimport { FakeTicker } from './FakeTicker.js';\nimport { HeadlessSymbol } from './HeadlessSymbol.js';\n\nexport interface TestReelSetOptions {\n reels?: number;\n /**\n * Visible row count.\n * - `number` → uniform rows.\n * - `number[]` → per-reel static shape (pyramid).\n *\n * Mutually exclusive with `multiways` (which always starts at `maxRows`).\n */\n visibleRows?: number | number[];\n /**\n * MultiWays configuration. Mutually exclusive with `visibleRows: number[]`.\n * The harness sets uniform `reelPixelHeight` and forwards `min/maxRows`.\n */\n multiways?: { minRows: number; maxRows: number; reelPixelHeight: number };\n symbolIds?: string[];\n weights?: Record<string, number>;\n /** Per-symbol overrides — useful for big-symbol size declarations in tests. */\n symbolData?: Record<string, Partial<import('../config/types.js').SymbolData>>;\n symbolSize?: { width: number; height: number };\n symbolGap?: { x: number; y: number };\n /** Number of symbols above + below the visible area. Defaults to the builder default. */\n bufferSymbols?: number;\n /** Initial symbol grid (any form `ReelSetBuilder.initialFrame` accepts). */\n initialFrame?: string[][] | ColumnTarget[];\n}\n\nexport interface TestReelSetHandle {\n reelSet: ReelSet;\n ticker: FakeTicker;\n /** Advance the ticker by `ms` milliseconds. */\n advance(ms: number, stepMs?: number): void;\n /** Run one full spin that lands on `grid`. Uses `skip()` for deterministic synchronous completion. */\n spinAndLand(grid: string[][]): Promise<SpinResult>;\n /** Destroy the reel set. */\n destroy(): void;\n}\n\n/**\n * Build a headless `ReelSet` wired to a `FakeTicker`. Ideal for mechanic tests.\n *\n * The returned `ReelSet` uses `HeadlessSymbol` for every registered symbol,\n * so no textures, renderer, or DOM are required.\n *\n * ```ts\n * const { reelSet, spinAndLand } = createTestReelSet({\n * reels: 5, visibleRows: 3,\n * symbolIds: ['cherry', 'seven', 'wild'],\n * });\n *\n * await spinAndLand([\n * ['cherry','cherry','cherry'],\n * ['seven','seven','seven'],\n * ['wild','wild','wild'],\n * ['cherry','cherry','cherry'],\n * ['seven','seven','seven'],\n * ]);\n * ```\n */\nexport function createTestReelSet(opts: TestReelSetOptions = {}): TestReelSetHandle {\n const reels = opts.reels ?? 5;\n const symbolIds = opts.symbolIds ?? ['a', 'b', 'c'];\n const weights = opts.weights ?? {};\n const size = opts.symbolSize ?? { width: 100, height: 100 };\n\n const ticker = new FakeTicker();\n\n const builder = new ReelSetBuilder()\n .reels(reels)\n .symbolSize(size.width, size.height)\n .ticker(ticker as unknown as Ticker)\n .symbols((registry) => {\n for (const id of symbolIds) {\n registry.register(id, HeadlessSymbol, {});\n }\n });\n\n if (opts.multiways) {\n builder.multiways(opts.multiways);\n } else if (Array.isArray(opts.visibleRows)) {\n builder.visibleRowsPerReel(opts.visibleRows);\n } else {\n builder.visibleSymbols(opts.visibleRows ?? 3);\n }\n\n if (opts.symbolGap) {\n builder.symbolGap(opts.symbolGap.x, opts.symbolGap.y);\n }\n\n if (Object.keys(weights).length > 0) {\n builder.weights(weights);\n }\n\n if (opts.symbolData) {\n builder.symbolData(opts.symbolData);\n }\n\n if (opts.bufferSymbols !== undefined) {\n builder.bufferSymbols(opts.bufferSymbols);\n }\n\n if (opts.initialFrame) {\n builder.initialFrame(opts.initialFrame as string[][]);\n }\n\n const reelSet = builder.build();\n\n return {\n reelSet,\n ticker,\n advance(ms: number, stepMs = 16) {\n ticker.tickFor(ms, stepMs);\n },\n async spinAndLand(grid: string[][]) {\n return spinAndLand(reelSet, grid);\n },\n destroy() {\n reelSet.destroy();\n ticker.destroy();\n },\n };\n}\n\n/**\n * Deterministically run a spin to a target grid.\n *\n * Internally: `spin() → setResult(grid) → skip()`. The `skip()` path bypasses\n * all async phases and directly places the symbols, so the returned promise\n * resolves on a microtask.\n */\nexport async function spinAndLand(reelSet: ReelSet, grid: string[][]): Promise<SpinResult> {\n const promise = reelSet.spin();\n reelSet.setResult(grid);\n reelSet.skip();\n return promise;\n}\n\n/** Record every occurrence of the given events in order for assertion. */\nexport function captureEvents(\n reelSet: ReelSet,\n names: Array<keyof import('../events/ReelEvents.js').ReelSetEvents>,\n): Array<{ event: string; args: unknown[] }> {\n const log: Array<{ event: string; args: unknown[] }> = [];\n for (const name of names) {\n reelSet.events.on(name, (...args: unknown[]) => {\n log.push({ event: name as string, args });\n });\n }\n return log;\n}\n\n/**\n * Assert that the current visible grid equals `expected`.\n *\n * Throws a readable error showing the full current grid on mismatch.\n */\nexport function expectGrid(reelSet: ReelSet, expected: string[][]): void {\n const actual = debugSnapshot(reelSet).grid;\n const mismatches: string[] = [];\n\n if (actual.length !== expected.length) {\n throw new Error(\n `Grid reel count mismatch: expected ${expected.length} got ${actual.length}\\n${debugGrid(reelSet)}`,\n );\n }\n\n for (let r = 0; r < expected.length; r++) {\n if (expected[r].length !== actual[r].length) {\n mismatches.push(\n ` reel ${r} row count: expected ${expected[r].length} got ${actual[r].length}`,\n );\n continue;\n }\n for (let row = 0; row < expected[r].length; row++) {\n if (expected[r][row] !== actual[r][row]) {\n mismatches.push(\n ` reel ${r} row ${row}: expected \"${expected[r][row]}\" got \"${actual[r][row]}\"`,\n );\n }\n }\n }\n\n if (mismatches.length > 0) {\n throw new Error(\n `Grid mismatch:\\n${mismatches.join('\\n')}\\n\\nCurrent grid:\\n${debugGrid(reelSet)}`,\n );\n }\n}\n\n/**\n * Count how many times a given symbol appears in the visible grid.\n * Handy for scatter/wild-count assertions.\n */\nexport function countSymbol(reelSet: ReelSet, symbolId: string): number {\n let n = 0;\n for (const col of debugSnapshot(reelSet).grid) {\n for (const s of col) if (s === symbolId) n++;\n }\n return n;\n}\n"],"mappings":"4JAsBA,IAAa,EAAb,KAAqE,CACnE,WAAqB,IAAI,IAEzB,GACE,EACA,EACA,EACM,CACN,OAAO,KAAK,KAAK,EAAO,EAAgB,EAAS,GAAM,CAGzD,KACE,EACA,EACA,EACM,CACN,OAAO,KAAK,KAAK,EAAO,EAAgB,EAAS,GAAK,CAGxD,IACE,EACA,EACA,EACM,CACN,IAAM,EAAU,KAAK,WAAW,IAAI,EAAM,CAC1C,GAAI,CAAC,EAAS,OAAO,KAErB,GAAI,CAAC,EAEH,OADA,KAAK,WAAW,OAAO,EAAM,CACtB,KAGT,IAAM,EAAW,EAAQ,OACtB,GAAM,EAAE,KAAO,GAAO,IAAY,IAAA,IAAa,EAAE,UAAY,EAC/D,CAMD,OALI,EAAS,SAAW,EACtB,KAAK,WAAW,OAAO,EAAM,CAE7B,KAAK,WAAW,IAAI,EAAO,EAAS,CAE/B,KAGT,KAA8B,EAAU,GAAG,EAA2B,CACpE,IAAM,EAAU,KAAK,WAAW,IAAI,EAAM,CAC1C,GAAI,CAAC,GAAW,EAAQ,SAAW,EAAG,MAAO,GAG7C,IAAM,EAAW,EAAQ,OAAO,CAChC,IAAK,IAAM,KAAS,EACd,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