cascading-reel 0.0.28 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +162 -0
- package/dist/index.cjs.js +3 -3
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +8 -46
- package/dist/index.es.js +238 -263
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +3 -3
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# cascading-reel
|
|
2
|
+
|
|
3
|
+
A high-performance WebGL cascading reel animator for slot-style UIs on any `HTMLCanvasElement`.
|
|
4
|
+
|
|
5
|
+
- 3x3 reel grid with deterministic scripted outcomes.
|
|
6
|
+
- Queued spins with per-spin callbacks.
|
|
7
|
+
- Win highlight with electric border and particle burst.
|
|
8
|
+
- DPR-aware rendering for mobile and desktop.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
yarn add cascading-reel
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage (TypeScript)
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { CascadingReel } from 'cascading-reel';
|
|
20
|
+
|
|
21
|
+
const container = document.getElementById('reelWrap');
|
|
22
|
+
const canvas = document.getElementById('canvas');
|
|
23
|
+
const button = document.getElementById('spinBtn');
|
|
24
|
+
|
|
25
|
+
if (!container || !canvas || !button) {
|
|
26
|
+
throw new Error('Demo DOM is not ready');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const reel = new CascadingReel({
|
|
30
|
+
container: container as HTMLDivElement,
|
|
31
|
+
canvas: canvas as HTMLCanvasElement,
|
|
32
|
+
button: button as HTMLButtonElement,
|
|
33
|
+
sprite: new URL('./assets/reel.webp', import.meta.url).href,
|
|
34
|
+
spriteElementsCount: 6,
|
|
35
|
+
initialSegments: [
|
|
36
|
+
[0, 1, 2],
|
|
37
|
+
[3, 0, 5],
|
|
38
|
+
[0, 1, 0],
|
|
39
|
+
],
|
|
40
|
+
queuedSpinStates: [
|
|
41
|
+
{
|
|
42
|
+
stopRows: [
|
|
43
|
+
[0, 4, 5],
|
|
44
|
+
[2, 1, 4],
|
|
45
|
+
[1, 3, 0],
|
|
46
|
+
],
|
|
47
|
+
finaleSequenceRows: [
|
|
48
|
+
[
|
|
49
|
+
[1, 1, 0],
|
|
50
|
+
[0, 1, 2],
|
|
51
|
+
[4, 5, 1],
|
|
52
|
+
],
|
|
53
|
+
],
|
|
54
|
+
highlightWin: true,
|
|
55
|
+
callback: () => console.log('spin complete'),
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
await reel.init();
|
|
61
|
+
reel.spin();
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Usage (Vue 3)
|
|
65
|
+
|
|
66
|
+
```vue
|
|
67
|
+
<script setup lang="ts">
|
|
68
|
+
import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue';
|
|
69
|
+
import { CascadingReel } from 'cascading-reel';
|
|
70
|
+
|
|
71
|
+
const containerRef = ref<HTMLDivElement | null>(null);
|
|
72
|
+
const canvasRef = ref<HTMLCanvasElement | null>(null);
|
|
73
|
+
const buttonRef = ref<HTMLButtonElement | null>(null);
|
|
74
|
+
const reel = shallowRef<CascadingReel | null>(null);
|
|
75
|
+
|
|
76
|
+
onMounted(async () => {
|
|
77
|
+
if (!containerRef.value || !canvasRef.value) return;
|
|
78
|
+
reel.value = new CascadingReel({
|
|
79
|
+
container: containerRef.value,
|
|
80
|
+
canvas: canvasRef.value,
|
|
81
|
+
button: buttonRef.value ?? undefined,
|
|
82
|
+
sprite: new URL('./assets/reel.webp', import.meta.url).href,
|
|
83
|
+
spriteElementsCount: 6,
|
|
84
|
+
particleColor: 'rainbow',
|
|
85
|
+
});
|
|
86
|
+
await reel.value.init();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
onBeforeUnmount(() => {
|
|
90
|
+
reel.value?.destroy();
|
|
91
|
+
reel.value = null;
|
|
92
|
+
});
|
|
93
|
+
</script>
|
|
94
|
+
|
|
95
|
+
<template>
|
|
96
|
+
<button ref="buttonRef">Spin</button>
|
|
97
|
+
<div ref="containerRef">
|
|
98
|
+
<canvas ref="canvasRef"></canvas>
|
|
99
|
+
</div>
|
|
100
|
+
</template>
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## HTML Layout
|
|
104
|
+
|
|
105
|
+
```html
|
|
106
|
+
<button id="spinBtn">Spin</button>
|
|
107
|
+
<div id="reelWrap">
|
|
108
|
+
<canvas id="canvas"></canvas>
|
|
109
|
+
</div>
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Call `reel.spin()` to consume the next item from `queuedSpinStates`.
|
|
113
|
+
|
|
114
|
+
## SpinState
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
type SpinState = {
|
|
118
|
+
stopGrid?: number[][];
|
|
119
|
+
stopRows?: number[][];
|
|
120
|
+
finaleSequence?: number[][][];
|
|
121
|
+
finaleSequenceRows?: number[][][];
|
|
122
|
+
highlightWin?: boolean;
|
|
123
|
+
callback?: () => void;
|
|
124
|
+
};
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
- Use `stopRows` for row-major input (`[row][col]`).
|
|
128
|
+
- Use `stopGrid` for column-major input (`[col][row]`).
|
|
129
|
+
- `finaleSequenceRows` and `finaleSequence` follow the same row/column conventions.
|
|
130
|
+
|
|
131
|
+
## Options
|
|
132
|
+
|
|
133
|
+
| Option | Type | Default | Description |
|
|
134
|
+
|:--|:--|:--:|:--|
|
|
135
|
+
| `canvas` | `HTMLCanvasElement` | — | Canvas for rendering. |
|
|
136
|
+
| `container` | `HTMLElement` | — | Element used for responsive sizing. |
|
|
137
|
+
| `button` | `HTMLButtonElement` | — | Optional spin button. |
|
|
138
|
+
| `sprite` | `string` | — | Sprite sheet URL. |
|
|
139
|
+
| `spriteElementsCount` | `number` | `6` | Number of symbols in the sprite sheet. |
|
|
140
|
+
| `initialSegments` | `number[][]` | randomized | Initial 3x3 state in rows format. |
|
|
141
|
+
| `highlightInitialWinningCells` | `boolean` | `true` | Show initial highlight before first spin. |
|
|
142
|
+
| `queuedSpinStates` | `SpinState[]` | `[]` | Predefined queue consumed by `spin()`. |
|
|
143
|
+
| `particleColor` | `'rainbow' \| [number, number, number]` | `[255, 235, 110]` | Win particle color mode or solid RGB color. |
|
|
144
|
+
|
|
145
|
+
## Methods
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
await reel.init();
|
|
149
|
+
reel.spin();
|
|
150
|
+
reel.destroy();
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Sprite Format
|
|
154
|
+
|
|
155
|
+
- Single vertical sprite sheet.
|
|
156
|
+
- Every symbol frame is square.
|
|
157
|
+
- Total texture height equals `spriteElementsCount * frameWidth` (square-frame assumption).
|
|
158
|
+
- `PNG` and `WebP` with transparency are supported.
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
MIT
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=6,f=3,d=3,X=[.04,0,-.04],A={columnStaggerMs:76,fallMs:800,outroOverlapMs:88,outroRowGapMs:14,rowBaseSpacingRatio:.05,incomingAlphaRampMs:34,fixedStepMs:1e3/120,maxCatchUpStepsPerFrame:6};A.outroRowGapMs;A.rowBaseSpacingRatio;const L=1800,V=.15,I=720,D=34,y=[255,235,110];A.columnStaggerMs;A.fallMs;A.outroOverlapMs;const Y=200;function x(s,t,i){return s<t?t:s>i?i:s}function $(s){return Math.floor(Math.random()*s)}function E(s,t){return(s%t+t)%t}function O(s){return x(Math.round(s),0,255)}function F(s){const t=[];for(let i=0;i<f;i+=1){const e=[];for(let n=0;n<d;n+=1)e.push($(s));t.push(e)}return t}function B(s){const t=new Map;for(let r=0;r<f;r+=1)for(let o=0;o<d;o+=1){const h=s[r][o];t.set(h,(t.get(h)??0)+1)}let i=s[0][0],e=-1;for(const[r,o]of t.entries())o>e&&(e=o,i=r);const n=[];for(let r=0;r<f;r+=1)for(let o=0;o<d;o+=1)s[r][o]===i&&n.push({col:r,row:o});return n}function S(){return Array.from({length:f},()=>Array.from({length:d},()=>0))}function P(s,t){for(let i=0;i<f;i+=1)for(let e=0;e<d;e+=1)s[i][e]=t}class K{rafId=null;step=null;start(t){this.rafId===null&&(this.step=t,this.rafId=requestAnimationFrame(this.tick))}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.step=null}isRunning(){return this.rafId!==null}tick=t=>{if(!this.step){this.stop();return}if(this.step(t)===!1){this.stop();return}this.rafId!==null&&(this.rafId=requestAnimationFrame(this.tick))}}function Q(s){const t=x(s,0,1);return t*t*t*(t*(t*6-15)+10)}function G(s,t){if(s.endMs<=s.startMs)return{value:s.to,t:1,done:!0};const i=x((t-s.startMs)/(s.endMs-s.startMs),0,1),e=Q(i);return{value:s.from+(s.to-s.from)*e,t:i,done:i>=1}}function j(s,t,i,e){const n=[0,0,0];let r=0;for(let o=d-1;o>=0;o-=1){if(s[o]===0){n[o]=0;continue}n[o]=r;const h=Math.floor(t*e);r+=h+i}return n}function Z(s){const i=s.height-s.boardY+s.cellH+2,e=[i,i,i];return{columnStaggerMs:s.motionProfile.columnStaggerMs,fallMs:s.motionProfile.fallMs,incomingAlphaRampMs:s.motionProfile.incomingAlphaRampMs,outgoingDistance:i,incomingFromOffsets:[-s.cellH,-s.cellH*2,-s.cellH*3],rowStartDelays:j(e,s.motionProfile.fallMs,s.motionProfile.outroRowGapMs,s.motionProfile.rowBaseSpacingRatio),incomingStartShift:Math.max(0,s.motionProfile.fallMs-s.motionProfile.outroOverlapMs)}}function H(s){let t=!0,i=!0;for(let e=0;e<s.scriptedOutgoingOffsets.length;e+=1){const n=s.elapsedMs-e*s.motionPlan.columnStaggerMs;for(let r=0;r<d;r+=1){const o=n-s.motionPlan.rowStartDelays[r];if(o<=0){s.scriptedOutgoingOffsets[e][r]=0,s.scriptedIncomingOffsets[e][r]=s.motionPlan.incomingFromOffsets[r],s.scriptedIncomingAlpha[e][r]=0,s.scriptedIncomingVisibility[e][r]="hidden",t=!1,i=!1;continue}const h=G({startMs:0,endMs:s.motionPlan.fallMs,from:0,to:s.motionPlan.outgoingDistance},o);s.scriptedOutgoingOffsets[e][r]=h.value,s.scriptedIncomingVisibility[e][r]=h.done?"entering":"exiting",h.done||(t=!1);const u=o-s.motionPlan.incomingStartShift;if(u<=0){s.scriptedIncomingOffsets[e][r]=s.motionPlan.incomingFromOffsets[r],s.scriptedIncomingAlpha[e][r]=0,s.scriptedIncomingVisibility[e][r]="hidden",i=!1;continue}const c=G({startMs:0,endMs:s.motionPlan.fallMs,from:s.motionPlan.incomingFromOffsets[r],to:0},u);s.scriptedIncomingOffsets[e][r]=c.value,s.scriptedIncomingAlpha[e][r]=x(u/Math.max(1,s.motionPlan.incomingAlphaRampMs),0,1),s.scriptedIncomingVisibility[e][r]=c.done?"active":"entering",c.done||(i=!1)}}return{allOutgoingDone:t,allIncomingDone:i}}function J(s){if(s==="rainbow")return{mode:"rainbow",rgb:y};const t=s??y;return{mode:"solid",rgb:[O(t[0]),O(t[1]),O(t[2])]}}function C(s){if(s.length!==d)throw new Error(`rows must contain ${d} rows`);for(let t=0;t<d;t+=1)if(!Array.isArray(s[t])||s[t].length!==f)throw new Error(`rows[${t}] must contain ${f} columns`);return[[s[0][0],s[1][0],s[2][0]],[s[0][1],s[1][1],s[2][1]],[s[0][2],s[1][2],s[2][2]]]}function v(s,t){if(s.length!==f)throw new Error(`stopGrid must contain ${f} columns`);const i=[];for(let e=0;e<f;e+=1){const n=s[e];if(!Array.isArray(n)||n.length!==d)throw new Error(`stopGrid[${e}] must contain ${d} rows`);i[e]=[E(n[0],t),E(n[1],t),E(n[2],t)]}return i}function tt(s,t){return v(C(s),t)}function it(s){return{stopGrid:s.stopGrid?.map(t=>[...t]),stopRows:s.stopRows?.map(t=>[...t]),finaleSequence:s.finaleSequence?.map(t=>t.map(i=>[...i])),finaleSequenceRows:s.finaleSequenceRows?.map(t=>t.map(i=>[...i])),highlightWin:s.highlightWin,callback:s.callback}}class et{queue;constructor(t){this.queue=(t??[]).map(i=>it(i))}hasPending(){return this.queue.length>0}consume(){return this.queue.length===0?null:this.queue.shift()??null}}function st(){return{isSpinning:!1,hasStartedFirstSpin:!1,queueFinished:!1,shouldHighlightCurrentSpin:!1,activeSpinState:null,phase:"idle",winFlashStartedAt:0,outroStartedAt:0,idleStartedAt:0,preSpinStartedAt:0,winEffectsEnvelope:1}}function rt(s,t){s.hasStartedFirstSpin=!0,s.isSpinning=!0,s.phase="outro",s.outroStartedAt=t.startedAt,s.activeSpinState=t.activeSpinState,s.shouldHighlightCurrentSpin=t.shouldHighlightCurrentSpin}function nt(s,t,i){s.phase="idle",s.idleStartedAt=i,s.isSpinning=!1,s.shouldHighlightCurrentSpin=!1,s.queueFinished=!t,s.activeSpinState=null}function U(s,t){s.winFlashStartedAt=t,s.phase="winFlash"}function ot(s){s.isSpinning=!1,s.queueFinished=!0}const ht=`
|
|
2
2
|
attribute vec2 a_pos;
|
|
3
3
|
uniform vec2 u_resolution;
|
|
4
4
|
uniform mediump vec4 u_destRect;
|
|
@@ -20,7 +20,7 @@ void main() {
|
|
|
20
20
|
gl_Position = vec4(clip, 0.0, 1.0);
|
|
21
21
|
v_uv = local;
|
|
22
22
|
}
|
|
23
|
-
`,
|
|
23
|
+
`,lt=`
|
|
24
24
|
precision mediump float;
|
|
25
25
|
|
|
26
26
|
uniform sampler2D u_texture;
|
|
@@ -126,5 +126,5 @@ void main() {
|
|
|
126
126
|
gl_FragColor = u_color;
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
-
`;class dt{canvas;spriteImage;spriteElementsCount;gl;program;uniforms;quadBuffer;texture;viewportW=1;viewportH=1;spriteWidth;spriteHeight;spriteSegmentHeight;constructor(t){this.canvas=t.canvas,this.spriteImage=t.spriteImage,this.spriteElementsCount=Math.max(1,t.spriteElementsCount),this.spriteWidth=this.spriteImage.width,this.spriteHeight=this.spriteImage.height,this.spriteSegmentHeight=this.spriteHeight/this.spriteElementsCount;const i=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1})??this.canvas.getContext("webgl",{alpha:!0,antialias:!1});if(!i)throw new Error("WebGL context is not available");this.gl=i;const e=this.createShader(this.gl.VERTEX_SHADER,ut),r=this.createShader(this.gl.FRAGMENT_SHADER,ct);this.program=this.createProgram(e,r),this.gl.deleteShader(e),this.gl.deleteShader(r);const n=this.gl.createBuffer();if(!n)throw new Error("Failed to create WebGL quad buffer");this.quadBuffer=n,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW);const o=this.gl.createTexture();if(!o)throw new Error("Failed to create WebGL texture");this.texture=o,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,0),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.spriteImage),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.useProgram(this.program);const h=this.gl.getAttribLocation(this.program,"a_pos");this.gl.enableVertexAttribArray(h),this.gl.vertexAttribPointer(h,2,this.gl.FLOAT,!1,8,0),this.uniforms={resolution:this.gl.getUniformLocation(this.program,"u_resolution"),destRect:this.gl.getUniformLocation(this.program,"u_destRect"),srcRect:this.gl.getUniformLocation(this.program,"u_srcRect"),color:this.gl.getUniformLocation(this.program,"u_color"),useTexture:this.gl.getUniformLocation(this.program,"u_useTexture"),shapeMode:this.gl.getUniformLocation(this.program,"u_shapeMode"),texture:this.gl.getUniformLocation(this.program,"u_texture"),time:this.gl.getUniformLocation(this.program,"u_time"),borderPx:this.gl.getUniformLocation(this.program,"u_borderPx"),borderInsetPx:this.gl.getUniformLocation(this.program,"u_borderInsetPx"),cornerRadiusPx:this.gl.getUniformLocation(this.program,"u_cornerRadiusPx"),noiseAmp:this.gl.getUniformLocation(this.program,"u_noiseAmp"),pulseStrength:this.gl.getUniformLocation(this.program,"u_pulseStrength")},this.gl.uniform1i(this.uniforms.texture,0),this.gl.uniform1f(this.uniforms.time,0),this.gl.uniform1f(this.uniforms.borderPx,1),this.gl.uniform1f(this.uniforms.borderInsetPx,0),this.gl.uniform1f(this.uniforms.cornerRadiusPx,0),this.gl.uniform1f(this.uniforms.noiseAmp,0),this.gl.uniform1f(this.uniforms.pulseStrength,0),this.gl.clearColor(0,0,0,0),this.gl.enable(this.gl.BLEND),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA)}resize(t,i){this.viewportW=Math.max(1,Math.floor(t)),this.viewportH=Math.max(1,Math.floor(i)),this.gl.viewport(0,0,this.viewportW,this.viewportH)}beginFrame(){this.gl.useProgram(this.program),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.uniform2f(this.uniforms.resolution,this.viewportW,this.viewportH),this.gl.uniform1f(this.uniforms.shapeMode,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}drawSprite(t,i,e,r,n,o=1){const u=_(t,this.spriteElementsCount)*this.spriteSegmentHeight,c=u+this.spriteSegmentHeight,l=.5,p=l/this.spriteWidth,g=1-l/this.spriteWidth,m=1-(c-l)/this.spriteHeight,A=1-(u+l)/this.spriteHeight;this.gl.uniform4f(this.uniforms.destRect,i,e,r,n),this.gl.uniform4f(this.uniforms.srcRect,p,m,g,A),this.gl.uniform4f(this.uniforms.color,1,1,1,o),this.gl.uniform1f(this.uniforms.shapeMode,0),this.gl.uniform1f(this.uniforms.useTexture,1),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}drawSolidRect(t,i,e,r,n){this.gl.uniform4f(this.uniforms.destRect,t,i,e,r),this.gl.uniform4f(this.uniforms.srcRect,0,0,1,1),this.gl.uniform4f(this.uniforms.color,n[0],n[1],n[2],n[3]),this.gl.uniform1f(this.uniforms.shapeMode,0),this.gl.uniform1f(this.uniforms.useTexture,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}drawSoftCircle(t,i,e,r){const n=e*2;this.gl.uniform4f(this.uniforms.destRect,t-e,i-e,n,n),this.gl.uniform4f(this.uniforms.srcRect,0,0,1,1),this.gl.uniform4f(this.uniforms.color,r[0],r[1],r[2],r[3]),this.gl.uniform1f(this.uniforms.useTexture,0),this.gl.uniform1f(this.uniforms.shapeMode,1),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1f(this.uniforms.shapeMode,0)}drawElectricBorder(t){this.gl.uniform4f(this.uniforms.destRect,t.x,t.y,t.width,t.height),this.gl.uniform4f(this.uniforms.srcRect,0,0,1,1),this.gl.uniform4f(this.uniforms.color,t.rgba[0],t.rgba[1],t.rgba[2],t.rgba[3]),this.gl.uniform1f(this.uniforms.useTexture,0),this.gl.uniform1f(this.uniforms.shapeMode,2),this.gl.uniform1f(this.uniforms.time,t.timeMs*.001),this.gl.uniform1f(this.uniforms.borderPx,Math.max(.5,t.borderThicknessPx)),this.gl.uniform1f(this.uniforms.borderInsetPx,Math.max(0,t.borderInsetPx)),this.gl.uniform1f(this.uniforms.cornerRadiusPx,Math.max(0,t.cornerRadiusPx)),this.gl.uniform1f(this.uniforms.noiseAmp,Math.max(0,t.noiseAmplitudePx)),this.gl.uniform1f(this.uniforms.pulseStrength,Math.max(0,t.pulseStrength)),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1f(this.uniforms.shapeMode,0)}beginAdditiveBlend(){this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE)}endAdditiveBlend(){this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA)}dispose(){this.gl.deleteTexture(this.texture),this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteProgram(this.program)}createShader(t,i){const e=this.gl.createShader(t);if(!e)throw new Error("Failed to create WebGL shader");if(this.gl.shaderSource(e,i),this.gl.compileShader(e),!this.gl.getShaderParameter(e,this.gl.COMPILE_STATUS)){const r=this.gl.getShaderInfoLog(e)??"unknown error";throw this.gl.deleteShader(e),new Error(`WebGL shader compile failed: ${r}`)}return e}createProgram(t,i){const e=this.gl.createProgram();if(!e)throw new Error("Failed to create WebGL program");if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){const r=this.gl.getProgramInfoLog(e)??"unknown error";throw this.gl.deleteProgram(e),new Error(`WebGL program link failed: ${r}`)}return e}}class a{static RAINBOW_HUE_BUCKETS=24;static PARTICLE_GLOBAL_ALPHA=.9;static PARTICLE_MAX_DISTANCE=.72;static PARTICLE_BASE_RADIUS=.028;canvas;container;button;spinQueueController;spriteUrl;spriteElementsCount;highlightInitialWinningCells;particleColorRgb;particleColorMode;motionProfile;pixelSnapY;isCoarsePointerDevice;spriteImage=null;webglRenderer=null;rafLoop=new j;runtime=ot();width=0;height=0;cellW=0;cellH=0;boardX=0;boardY=0;scriptedCascadeQueue=[];scriptedOutgoingGrid=null;scriptedPendingGrid=null;scriptedOutroStartedAt=0;scriptedOutroElapsedMs=0;outroMotionPlan=null;scriptedOutgoingOffsets=S();scriptedOutgoingOffsetsPrev=S();scriptedIncomingOffsets=S();scriptedIncomingOffsetsPrev=S();scriptedIncomingAlpha=S();scriptedIncomingAlphaPrev=S();scriptedIncomingVisibility=a.createVisibilityGrid("hidden");scriptedIncomingVisibilityPrev=a.createVisibilityGrid("hidden");winningCells=[];winningCellKeys=new Set;grid;particlesPerCell=y;lastRafTime=0;initialHighlightRequestedAt=0;simulationLastNow=0;simulationAccumulatorMs=0;outroInterpolationAlpha=1;isOutroPipelineWarmedUp=!1;isGpuPipelineWarmedUp=!1;perfWindowStartedAt=0;perfFrameCount=0;perfOver20MsCount=0;perfDtSamples=[];mobileDprCap=2;mobilePerfGoodWindows=0;mobilePerfBadWindows=0;static PERF_WINDOW_MS=1500;static MOBILE_DPR_CAP_MIN=1.25;static MOBILE_DPR_CAP_MAX=1.5;static MOBILE_DPR_STEP_DOWN=.1;static MOBILE_DPR_STEP_UP=.05;static DPR_QUANT_STEP=.25;static MAX_CANVAS_AREA_PX_COARSE=900*900;static MAX_CANVAS_AREA_PX_FINE=1400*1400;static PRE_SPIN_MS=150;static WIN_EFFECTS_ENVELOPE_TAU_MS=120;static MAX_FRAME_DELTA_MS=100;static WIN_BORDER_ALPHA=.72;static WIN_BORDER_INSET_RATIO=.08;static particleSeedsCache=new Map;constructor(t){this.canvas=t.canvas,this.container=t.container,this.button=t.button,this.spriteUrl=t.sprite,this.spriteElementsCount=Math.max(1,t.spriteElementsCount??z),this.highlightInitialWinningCells=t.highlightInitialWinningCells!==!1,this.spinQueueController=new nt(t.queuedSpinStates),this.particleColorRgb=it(t.particleColorRgb),this.particleColorMode=et(t.particleColorMode),this.motionProfile=V(t.motionProfile??X),this.pixelSnapY=t.pixelSnapY??this.motionProfile.pixelSnapY,this.isCoarsePointerDevice=a.detectCoarsePointerDevice(),this.mobileDprCap=this.isCoarsePointerDevice?a.MOBILE_DPR_CAP_MAX:2,this.grid=t.initialSegments?st(t.initialSegments,this.spriteElementsCount):D(this.spriteElementsCount)}async init(){if(this.bindEvents(),this.resize(),await this.loadSpriteIfProvided(),!this.spriteImage)throw new Error("sprite is required for WebGL renderer");this.webglRenderer=new dt({canvas:this.canvas,spriteImage:this.spriteImage,spriteElementsCount:this.spriteElementsCount}),this.webglRenderer.resize(this.width,this.height),this.warmUpOutroPipeline(),this.warmUpGpuPipeline(),this.applyInitialHighlightIfNeeded(),requestAnimationFrame(t=>{this.render(t),this.startLoop()})}destroy(){this.unbindEvents(),this.rafLoop.stop(),this.simulationLastNow=0,this.simulationAccumulatorMs=0,at(this.runtime),this.webglRenderer?.dispose(),this.webglRenderer=null,this.clearWinningCells()}spin(){if(this.dismissHighlightIfActive(),this.runtime.isSpinning||this.runtime.queueFinished)return;if(!this.spinQueueController.hasPending()){this.runtime.queueFinished=!0,this.button&&(this.button.disabled=!0);return}const t=this.spinQueueController.consume(),i=t?.highlightWin===!0;this.runtime.isSpinning=!0,this.runtime.phase="preSpin",this.runtime.preSpinStartedAt=performance.now(),this.runtime.activeSpinState=t,this.runtime.shouldHighlightCurrentSpin=i,this.runtime.hasStartedFirstSpin=!0,this.simulationLastNow=0,this.simulationAccumulatorMs=0,this.button&&(this.button.disabled=!0),this.startLoop()}bindEvents(){window.addEventListener("resize",this.resize),document.addEventListener("visibilitychange",this.onVisibilityChange),this.button?.addEventListener("click",this.onSpinClick)}unbindEvents(){window.removeEventListener("resize",this.resize),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.button?.removeEventListener("click",this.onSpinClick)}onVisibilityChange=()=>{this.lastRafTime=0,this.simulationLastNow=0,this.simulationAccumulatorMs=0,this.resetPerfWindow()};onSpinClick=()=>{this.runtime.isSpinning&&this.runtime.phase!=="winFlash"||this.spin()};getNextGrid(t){return t?O(t,this.spriteElementsCount):D(this.spriteElementsCount)}update(t){if(this.runtime.isSpinning){if(this.runtime.phase==="preSpin"){if(t-this.runtime.preSpinStartedAt<a.PRE_SPIN_MS)return;ht(this.runtime,{activeSpinState:this.runtime.activeSpinState,shouldHighlightCurrentSpin:this.runtime.shouldHighlightCurrentSpin,startedAt:t}),this.runtime.preSpinStartedAt=0;const i=this.runtime.activeSpinState?.finaleSequenceRows?this.runtime.activeSpinState.finaleSequenceRows.map(n=>v(n)):this.runtime.activeSpinState?.finaleSequence??[];this.scriptedCascadeQueue=i.map(n=>n.map(o=>[...o])),this.clearWinningCells();const e=this.runtime.activeSpinState?.stopRows?v(this.runtime.activeSpinState.stopRows):this.runtime.activeSpinState?.stopGrid,r=this.getNextGrid(e);this.startOutroTransition(r,t)}this.runtime.phase}}stepScriptedOutro(t){if(!this.scriptedOutgoingGrid||!this.scriptedPendingGrid){this.finishSpinWithUi();return}this.outroMotionPlan||(this.outroMotionPlan=this.createOutroMotionPlan()),this.scriptedOutroElapsedMs+=t;const{allOutgoingDone:i,allIncomingDone:e}=G({elapsedMs:this.scriptedOutroElapsedMs,scriptedOutgoingOffsets:this.scriptedOutgoingOffsets,scriptedIncomingOffsets:this.scriptedIncomingOffsets,scriptedIncomingAlpha:this.scriptedIncomingAlpha,scriptedIncomingVisibility:this.scriptedIncomingVisibility,motionPlan:this.outroMotionPlan});if(!(!i||!e)&&(this.grid=this.scriptedPendingGrid,this.scriptedOutgoingGrid=null,this.scriptedPendingGrid=null,this.outroMotionPlan=null,this.clearWinningCells(),this.resetOutroBuffers(1,"active"),!this.tryStartScriptedCascade(this.scriptedOutroStartedAt+this.scriptedOutroElapsedMs))){if(!this.runtime.shouldHighlightCurrentSpin){this.finishSpinWithUi();return}this.setWinningCells(F(this.grid)),U(this.runtime,this.scriptedOutroStartedAt+this.scriptedOutroElapsedMs),this.runtime.activeSpinState?.callback?.(),this.button&&this.runtime.shouldHighlightCurrentSpin&&this.spinQueueController.hasPending()&&(this.button.disabled=!1)}}tryStartScriptedCascade(t){if(this.scriptedCascadeQueue.length===0)return!1;const i=this.scriptedCascadeQueue.shift();return i?(this.startOutroTransition(O(i,this.spriteElementsCount),t),!0):!1}startOutroTransition(t,i){this.scriptedOutgoingGrid=this.grid.map(e=>[...e]),this.scriptedPendingGrid=t.map(e=>[...e]),this.outroMotionPlan=this.createOutroMotionPlan(),this.resetOutroBuffers(0,"hidden"),this.clearWinningCells(),this.runtime.phase="outro",this.scriptedOutroStartedAt=i,this.scriptedOutroElapsedMs=0,this.outroInterpolationAlpha=1}finishSpinWithUi(t=!1){const i=this.runtime.activeSpinState,e=t?void 0:i?.callback,r=this.spinQueueController.hasPending();lt(this.runtime,r,performance.now()),this.button&&(this.button.disabled=this.runtime.queueFinished),e?.()}dismissHighlightIfActive(){this.runtime.phase==="winFlash"&&this.finishSpinWithUi(!0)}applyInitialHighlightIfNeeded(){this.highlightInitialWinningCells&&(this.setWinningCells(F(this.grid)),this.initialHighlightRequestedAt=performance.now())}warmUpOutroPipeline(){if(this.isOutroPipelineWarmedUp)return;const t=this.createOutroMotionPlan(),i=S(),e=S(),r=S(),n=a.createVisibilityGrid("hidden"),o=Math.max(...t.rowStartDelays),h=(f-1)*t.columnStaggerMs,u=[0,this.motionProfile.fixedStepMs,t.incomingStartShift+this.motionProfile.fixedStepMs,t.fallMs+o+h+this.motionProfile.fixedStepMs];for(const c of u)G({elapsedMs:c,scriptedOutgoingOffsets:i,scriptedIncomingOffsets:e,scriptedIncomingAlpha:r,scriptedIncomingVisibility:n,motionPlan:t});this.isOutroPipelineWarmedUp=!0}createOutroMotionPlan(){const t=tt({height:this.height,boardY:this.boardY,cellH:this.cellH,motionProfile:this.motionProfile});if(!this.isCoarsePointerDevice)return t;const i=1e3/60;return{...t,columnStaggerMs:this.quantizeMs(t.columnStaggerMs,i),incomingStartShift:this.quantizeMs(t.incomingStartShift,i),rowStartDelays:[this.quantizeMs(t.rowStartDelays[0],i),this.quantizeMs(t.rowStartDelays[1],i),this.quantizeMs(t.rowStartDelays[2],i)]}}quantizeMs(t,i){return t<=0?0:Math.max(1,Math.round(t/i))*i}warmUpGpuPipeline(){if(this.isGpuPipelineWarmedUp)return;const t=this.webglRenderer;if(!t)return;const i=Math.max(8,this.cellW*.2),e=Math.max(8,this.cellH*.2),r=this.boardX+2,n=this.boardY+2;t.beginFrame(),t.drawSprite(0,r,n,i,e,1),t.drawSolidRect(r+i+2,n,i,e,[1,1,1,.35]),t.beginAdditiveBlend(),t.drawSoftCircle(r+i*.5,n+e*.5,Math.max(2,i*.25),[1,.9,.4,.4]),t.endAdditiveBlend(),this.isGpuPipelineWarmedUp=!0}trackOutroPerf(t,i){if(this.runtime.phase!=="outro"){this.resetPerfWindow();return}this.perfWindowStartedAt<=0&&(this.perfWindowStartedAt=i),this.perfFrameCount+=1,t>20&&(this.perfOver20MsCount+=1),this.perfDtSamples.push(t),!(i-this.perfWindowStartedAt<a.PERF_WINDOW_MS)&&(this.flushPerfWindow(),this.perfWindowStartedAt=i)}resetPerfWindow(){this.perfWindowStartedAt=0,this.perfFrameCount=0,this.perfOver20MsCount=0,this.perfDtSamples.length=0}flushPerfWindow(){if(this.perfFrameCount===0)return;const t=[...this.perfDtSamples].sort((r,n)=>r-n),i=Math.max(0,Math.min(t.length-1,Math.floor(t.length*.95))),e=t[i];this.adjustMobileDprCap(e,this.perfOver20MsCount,this.perfFrameCount),this.perfFrameCount=0,this.perfOver20MsCount=0,this.perfDtSamples.length=0}adjustMobileDprCap(t,i,e){if(!this.isCoarsePointerDevice||e<=0)return;const r=i/e,n=t>19||r>.03,o=t<=17.5&&i===0;let h=this.mobileDprCap;n?(this.mobilePerfBadWindows+=1,this.mobilePerfGoodWindows=0,this.mobilePerfBadWindows>=2&&(h=Math.max(a.MOBILE_DPR_CAP_MIN,this.mobileDprCap-a.MOBILE_DPR_STEP_DOWN),this.mobilePerfBadWindows=0)):o?(this.mobilePerfGoodWindows+=1,this.mobilePerfBadWindows=0,this.mobilePerfGoodWindows>=4&&(h=Math.min(a.MOBILE_DPR_CAP_MAX,this.mobileDprCap+a.MOBILE_DPR_STEP_UP),this.mobilePerfGoodWindows=0)):(this.mobilePerfGoodWindows=0,this.mobilePerfBadWindows=0),!(Math.abs(h-this.mobileDprCap)<.001)&&(this.mobileDprCap=h,this.resize())}render(t){if(!this.webglRenderer)return;this.initialHighlightRequestedAt>0&&t-this.initialHighlightRequestedAt>=K&&(U(this.runtime,this.initialHighlightRequestedAt),this.runtime.winEffectsEnvelope=1,this.initialHighlightRequestedAt=0,this.button&&(this.button.disabled=!1));const i=this.runtime.phase==="preSpin"?0:this.runtime.phase==="winFlash"?1:0;if(this.lastRafTime>0){const h=Math.min(t-this.lastRafTime,50);this.trackOutroPerf(h,t);const u=1-Math.exp(-h/a.WIN_EFFECTS_ENVELOPE_TAU_MS);this.runtime.winEffectsEnvelope+=(i-this.runtime.winEffectsEnvelope)*u}else this.resetPerfWindow();this.lastRafTime=t,this.webglRenderer.beginFrame();const e=this.runtime.phase==="winFlash"||this.runtime.phase==="preSpin"||this.initialHighlightRequestedAt>0&&this.winningCells.length>0;this.runtime.phase==="outro"&&this.scriptedOutgoingGrid&&this.scriptedPendingGrid?(this.drawGridInterpolated(this.scriptedOutgoingGrid,this.scriptedOutgoingOffsetsPrev,this.scriptedOutgoingOffsets,this.outroInterpolationAlpha,e),this.drawGridInterpolated(this.scriptedPendingGrid,this.scriptedIncomingOffsetsPrev,this.scriptedIncomingOffsets,this.outroInterpolationAlpha,e,this.scriptedIncomingAlphaPrev,this.scriptedIncomingAlpha,this.scriptedIncomingVisibility)):this.drawGrid(this.grid,null,e);const r=this.initialHighlightRequestedAt>0?"winFlash":this.runtime.phase,n=this.initialHighlightRequestedAt>0?this.initialHighlightRequestedAt:this.runtime.winFlashStartedAt,o=this.initialHighlightRequestedAt>0?1:this.runtime.winEffectsEnvelope;this.drawWinningEffects({now:t,phase:r,winFlashStartedAt:n,winEffectsEnvelope:o})}isWinningCell=(t,i)=>this.winningCellKeys.has(`${t}:${i}`);getRowCompactOffset(t){return(k[t]??0)*this.cellH}applyPixelSnapY(t){const i=this.isCoarsePointerDevice&&this.pixelSnapY==="none"?"half":this.pixelSnapY;return i==="integer"?Math.round(t):i==="half"?Math.round(t*2)/2:t}drawGrid(t,i,e){this.drawGridWithSampler({grid:t,skipWinningCells:e,sampleOffsetY:(r,n)=>i?i[r][n]:0,sampleAlpha:()=>1,isVisible:()=>!0})}drawGridInterpolated(t,i,e,r,n,o,h,u){this.drawGridWithSampler({grid:t,skipWinningCells:n,sampleOffsetY:(c,l)=>i[c][l]+(e[c][l]-i[c][l])*r,sampleAlpha:(c,l)=>o&&h?o[c][l]+(h[c][l]-o[c][l])*r:1,isVisible:(c,l)=>!u||u[c][l]!=="hidden"})}drawGridWithSampler(t){const i=this.webglRenderer;if(i)for(let e=0;e<f;e+=1){const r=this.boardX+e*this.cellW;for(let n=0;n<d;n+=1){if(t.skipWinningCells&&this.isWinningCell(e,n)||!t.isVisible(e,n))continue;const o=t.sampleOffsetY(e,n),h=this.applyPixelSnapY(this.boardY+n*this.cellH+o+this.getRowCompactOffset(n));if(h>this.height||h+this.cellH<0)continue;const u=t.sampleAlpha(e,n);u<=0||i.drawSprite(t.grid[e][n],r,h,this.cellW,this.cellH,u)}}}drawWinningEffects(t){const i=this.webglRenderer;if(!i||this.winningCells.length===0||t.phase!=="winFlash"&&t.phase!=="preSpin")return;const e=Math.max(0,Math.min(1,t.winEffectsEnvelope)),r=Math.max(0,t.now-t.winFlashStartedAt),n=r%W/W,o=1+Math.sin(n*Math.PI*2)*Y*e,h=Math.max(1,this.cellW*a.WIN_BORDER_INSET_RATIO),u=Math.max(1,this.cellW*.022),c=this.runtime.phase==="winFlash"&&this.runtime.shouldHighlightCurrentSpin&&this.runtime.hasStartedFirstSpin;for(const l of this.winningCells){const p=this.boardX+l.col*this.cellW,g=this.boardY+l.row*this.cellH+this.getRowCompactOffset(l.row),m=this.grid[l.col][l.row],A=a.WIN_BORDER_ALPHA*e,R=this.particleColorMode==="rainbow"?a.hslToRgb01((r*.2+l.col*36+l.row*22)%360,.96,.64):[this.particleColorRgb[0]/255,this.particleColorRgb[1]/255,this.particleColorRgb[2]/255],x=this.cellW*o,w=this.cellH*o,b=(this.cellW-x)*.5,H=(this.cellH-w)*.5;i.drawSprite(m,p+b,g+H,x,w,1);const N=p+h,q=g+h,T=this.cellW-h*2,L=this.cellH-h*2;T<=u*2||L<=u*2||(this.drawElectricBorder({renderer:i,cell:l,x:N,y:q,w:T,h:L,borderThickness:u,borderColor:R,alpha:A,elapsed:r,envelope:e}),c&&this.drawCellParticleBurst({renderer:i,cell:l,centerX:p+this.cellW*.5,centerY:g+this.cellH*.5,elapsed:r,envelope:e}))}}drawCellParticleBurst(t){const i=Math.min(this.cellW,this.cellH)*a.PARTICLE_MAX_DISTANCE,e=Math.min(this.cellW,this.cellH)*a.PARTICLE_BASE_RADIUS,r=a.getParticleSeeds(t.cell.col,t.cell.row),n=[this.particleColorRgb[0]/255,this.particleColorRgb[1]/255,this.particleColorRgb[2]/255];t.renderer.beginAdditiveBlend();for(let o=0;o<this.particlesPerCell;o+=1){const h=r[o],u=h.phaseOffset*I,c=t.elapsed-u;if(c<0)continue;const l=c%I/I,p=h.seedA*Math.PI*2,g=i*l*(.35+h.seedB*.65),m=t.centerX+Math.cos(p)*g,A=t.centerY+Math.sin(p)*g,R=.7+.9*Math.max(0,Math.sin((t.elapsed*.012+h.twinkleSeed*2)*Math.PI*2)),x=Math.max(1,e*(.55+h.seedC*.6)*(1-l*.5)),w=Math.max(0,Math.min(1,(.9+R*.2)*a.PARTICLE_GLOBAL_ALPHA*t.envelope));if(w<=0)continue;const b=this.particleColorMode==="rainbow"?a.getRainbowParticleColor(t.elapsed,t.cell.col,t.cell.row,h.seedA):n;t.renderer.drawSoftCircle(m,A,x,[b[0],b[1],b[2],w])}t.renderer.endAdditiveBlend()}drawElectricBorder(t){const i=Math.max(0,Math.min(1,t.alpha*t.envelope)),e=t.borderThickness*1.8,r=t.elapsed+t.cell.col*170+t.cell.row*290;t.renderer.beginAdditiveBlend(),t.renderer.drawElectricBorder({x:t.x-e,y:t.y-e,width:t.w+e*2,height:t.h+e*2,rgba:[t.borderColor[0],t.borderColor[1],t.borderColor[2],i*.55],timeMs:r,borderThicknessPx:Math.max(.8,t.borderThickness*1.1),borderInsetPx:e*.85,cornerRadiusPx:Math.max(2,t.borderThickness*2.5),noiseAmplitudePx:Math.max(.15,t.borderThickness*.6),pulseStrength:.9}),t.renderer.drawElectricBorder({x:t.x-e*.5,y:t.y-e*.5,width:t.w+e,height:t.h+e,rgba:[t.borderColor[0],t.borderColor[1],t.borderColor[2],i*.9],timeMs:r*1.03,borderThicknessPx:Math.max(.7,t.borderThickness*.8),borderInsetPx:e*.5,cornerRadiusPx:Math.max(1.5,t.borderThickness*1.7),noiseAmplitudePx:Math.max(.12,t.borderThickness*.42),pulseStrength:1.25}),t.renderer.endAdditiveBlend()}static hslToRgb01(t,i,e){const r=(t%360+360)%360,n=Math.max(0,Math.min(1,i)),o=Math.max(0,Math.min(1,e)),h=(1-Math.abs(2*o-1))*n,u=r/60,c=h*(1-Math.abs(u%2-1));let l=0,p=0,g=0;u>=0&&u<1?(l=h,p=c):u<2?(l=c,p=h):u<3?(p=h,g=c):u<4?(p=c,g=h):u<5?(l=c,g=h):(l=h,g=c);const m=o-h*.5;return[l+m,p+m,g+m]}static getRainbowParticleColor(t,i,e,r){const n=(r*360+t*.24+i*38+e*22)%360,o=360/a.RAINBOW_HUE_BUCKETS,h=Math.floor(n/o)*o;return a.hslToRgb01(h,.98,.64)}static detectCoarsePointerDevice(){if(typeof window>"u")return!1;const t=typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,i=typeof navigator<"u"&&typeof navigator.maxTouchPoints=="number"?navigator.maxTouchPoints:0;return t||i>0}quantizeDprCap(t){const i=a.DPR_QUANT_STEP;return Math.max(1,Math.round(t/i)*i)}static hash01(t,i,e,r){const n=Math.sin(t*127.1+i*311.7+e*74.7+r*19.3)*43758.5453;return n-Math.floor(n)}static getParticleSeeds(t,i){const e=`${t},${i}`,r=a.particleSeedsCache.get(e);if(r)return r;const n=[];for(let o=0;o<y;o+=1)n.push({seedA:a.hash01(t,i,o,1),seedB:a.hash01(t,i,o,2),seedC:a.hash01(t,i,o,3),phaseOffset:a.hash01(t,i,o,4),twinkleSeed:a.hash01(t,i,o,5)});return a.particleSeedsCache.set(e,n),n}clearWinningCells(){this.winningCells=[],this.winningCellKeys.clear()}setWinningCells(t){this.winningCells=t,this.winningCellKeys.clear();for(const i of t)this.winningCellKeys.add(`${i.col}:${i.row}`)}resize=()=>{const t=this.container.getBoundingClientRect(),i=Math.max(300,Math.floor(t.width)),e=Math.max(1,i*i),r=this.isCoarsePointerDevice?a.MAX_CANVAS_AREA_PX_COARSE:a.MAX_CANVAS_AREA_PX_FINE,n=Math.max(1,Math.sqrt(r/e)),o=this.isCoarsePointerDevice?this.mobileDprCap:2,h=this.quantizeDprCap(Math.min(o,n)),u=Math.max(1,Math.min(window.devicePixelRatio||1,h)),c=Math.max(300,Math.floor(i*u));this.width=c,this.height=c;const l=Math.floor(Math.min(this.width/f,this.height/d));this.cellW=l,this.cellH=l,this.boardX=Math.floor((this.width-this.cellW*f)/2),this.boardY=Math.floor((this.height-this.cellH*d)/2),this.canvas.width=this.width,this.canvas.height=this.height,this.webglRenderer?.resize(this.width,this.height)};async loadSpriteIfProvided(){if(!this.spriteUrl)return;const t=new Image;t.decoding="async",t.src=this.spriteUrl;try{await t.decode(),this.spriteImage=t}catch{this.spriteImage=null}}advanceSimulation(t){if(this.simulationLastNow<=0){this.simulationLastNow=t,this.update(t);return}const i=Math.max(0,Math.min(t-this.simulationLastNow,a.MAX_FRAME_DELTA_MS));if(this.simulationLastNow=t,this.update(t),this.runtime.phase!=="outro"){this.outroInterpolationAlpha=1;return}this.simulationAccumulatorMs+=i;const e=this.motionProfile.fixedStepMs;let r=0;for(;this.simulationAccumulatorMs>=e&&r<this.motionProfile.maxCatchUpStepsPerFrame&&this.runtime.phase==="outro";)this.snapshotOutroState(),this.stepScriptedOutro(e),this.simulationAccumulatorMs-=e,r+=1;if(this.runtime.phase!=="outro"){this.outroInterpolationAlpha=1;return}this.outroInterpolationAlpha=Math.max(0,Math.min(1,this.simulationAccumulatorMs/e))}snapshotOutroState(){this.copyOffsets(this.scriptedOutgoingOffsetsPrev,this.scriptedOutgoingOffsets),this.copyOffsets(this.scriptedIncomingOffsetsPrev,this.scriptedIncomingOffsets),this.copyOffsets(this.scriptedIncomingAlphaPrev,this.scriptedIncomingAlpha),this.copyVisibility(this.scriptedIncomingVisibilityPrev,this.scriptedIncomingVisibility)}copyOffsets(t,i){for(let e=0;e<f;e+=1)for(let r=0;r<d;r+=1)t[e][r]=i[e][r]}copyVisibility(t,i){for(let e=0;e<f;e+=1)for(let r=0;r<d;r+=1)t[e][r]=i[e][r]}resetOutroBuffers(t,i){P(this.scriptedOutgoingOffsets,0),P(this.scriptedIncomingOffsets,0),P(this.scriptedOutgoingOffsetsPrev,0),P(this.scriptedIncomingOffsetsPrev,0),P(this.scriptedIncomingAlpha,t),P(this.scriptedIncomingAlphaPrev,t),this.fillVisibilityGrid(this.scriptedIncomingVisibility,i),this.fillVisibilityGrid(this.scriptedIncomingVisibilityPrev,i)}static createVisibilityGrid(t){return Array.from({length:f},()=>Array.from({length:d},()=>t))}fillVisibilityGrid(t,i){for(let e=0;e<f;e+=1)for(let r=0;r<d;r+=1)t[e][r]=i}startLoop(){this.rafLoop.isRunning()||this.rafLoop.start(t=>(this.advanceSimulation(t),this.render(t),this.shouldKeepAnimating()))}shouldKeepAnimating(){return this.runtime.isSpinning||this.initialHighlightRequestedAt>0?!0:this.runtime.winEffectsEnvelope>.001}}exports.CascadingReel=a;
|
|
129
|
+
`;class at{canvas;spriteImage;spriteElementsCount;gl;program;uniforms;quadBuffer;texture;viewportW=1;viewportH=1;spriteWidth;spriteHeight;spriteSegmentHeight;constructor(t){this.canvas=t.canvas,this.spriteImage=t.spriteImage,this.spriteElementsCount=Math.max(1,t.spriteElementsCount),this.spriteWidth=this.spriteImage.width,this.spriteHeight=this.spriteImage.height,this.spriteSegmentHeight=this.spriteHeight/this.spriteElementsCount;const i=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1})??this.canvas.getContext("webgl",{alpha:!0,antialias:!1});if(!i)throw new Error("WebGL context is not available");this.gl=i;const e=this.createShader(this.gl.VERTEX_SHADER,ht),n=this.createShader(this.gl.FRAGMENT_SHADER,lt);this.program=this.createProgram(e,n),this.gl.deleteShader(e),this.gl.deleteShader(n);const r=this.gl.createBuffer();if(!r)throw new Error("Failed to create WebGL quad buffer");this.quadBuffer=r,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),this.gl.STATIC_DRAW);const o=this.gl.createTexture();if(!o)throw new Error("Failed to create WebGL texture");this.texture=o,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,0),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.spriteImage),this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.useProgram(this.program);const h=this.gl.getAttribLocation(this.program,"a_pos");this.gl.enableVertexAttribArray(h),this.gl.vertexAttribPointer(h,2,this.gl.FLOAT,!1,8,0),this.uniforms={resolution:this.gl.getUniformLocation(this.program,"u_resolution"),destRect:this.gl.getUniformLocation(this.program,"u_destRect"),srcRect:this.gl.getUniformLocation(this.program,"u_srcRect"),color:this.gl.getUniformLocation(this.program,"u_color"),useTexture:this.gl.getUniformLocation(this.program,"u_useTexture"),shapeMode:this.gl.getUniformLocation(this.program,"u_shapeMode"),texture:this.gl.getUniformLocation(this.program,"u_texture"),time:this.gl.getUniformLocation(this.program,"u_time"),borderPx:this.gl.getUniformLocation(this.program,"u_borderPx"),borderInsetPx:this.gl.getUniformLocation(this.program,"u_borderInsetPx"),cornerRadiusPx:this.gl.getUniformLocation(this.program,"u_cornerRadiusPx"),noiseAmp:this.gl.getUniformLocation(this.program,"u_noiseAmp"),pulseStrength:this.gl.getUniformLocation(this.program,"u_pulseStrength")},this.gl.uniform1i(this.uniforms.texture,0),this.gl.uniform1f(this.uniforms.time,0),this.gl.uniform1f(this.uniforms.borderPx,1),this.gl.uniform1f(this.uniforms.borderInsetPx,0),this.gl.uniform1f(this.uniforms.cornerRadiusPx,0),this.gl.uniform1f(this.uniforms.noiseAmp,0),this.gl.uniform1f(this.uniforms.pulseStrength,0),this.gl.clearColor(0,0,0,0),this.gl.enable(this.gl.BLEND),this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA)}resize(t,i){this.viewportW=Math.max(1,Math.floor(t)),this.viewportH=Math.max(1,Math.floor(i)),this.gl.viewport(0,0,this.viewportW,this.viewportH)}beginFrame(){this.gl.useProgram(this.program),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.quadBuffer),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.uniform2f(this.uniforms.resolution,this.viewportW,this.viewportH),this.gl.uniform1f(this.uniforms.shapeMode,0),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}drawSprite(t,i,e,n,r,o=1){const u=E(t,this.spriteElementsCount)*this.spriteSegmentHeight,c=u+this.spriteSegmentHeight,a=.5,p=a/this.spriteWidth,g=1-a/this.spriteWidth,m=1-(c-a)/this.spriteHeight,_=1-(u+a)/this.spriteHeight;this.gl.uniform4f(this.uniforms.destRect,i,e,n,r),this.gl.uniform4f(this.uniforms.srcRect,p,m,g,_),this.gl.uniform4f(this.uniforms.color,1,1,1,o),this.gl.uniform1f(this.uniforms.shapeMode,0),this.gl.uniform1f(this.uniforms.useTexture,1),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}drawSolidRect(t,i,e,n,r){this.gl.uniform4f(this.uniforms.destRect,t,i,e,n),this.gl.uniform4f(this.uniforms.srcRect,0,0,1,1),this.gl.uniform4f(this.uniforms.color,r[0],r[1],r[2],r[3]),this.gl.uniform1f(this.uniforms.shapeMode,0),this.gl.uniform1f(this.uniforms.useTexture,0),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}drawSoftCircle(t,i,e,n){const r=e*2;this.gl.uniform4f(this.uniforms.destRect,t-e,i-e,r,r),this.gl.uniform4f(this.uniforms.srcRect,0,0,1,1),this.gl.uniform4f(this.uniforms.color,n[0],n[1],n[2],n[3]),this.gl.uniform1f(this.uniforms.useTexture,0),this.gl.uniform1f(this.uniforms.shapeMode,1),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1f(this.uniforms.shapeMode,0)}drawElectricBorder(t){this.gl.uniform4f(this.uniforms.destRect,t.x,t.y,t.width,t.height),this.gl.uniform4f(this.uniforms.srcRect,0,0,1,1),this.gl.uniform4f(this.uniforms.color,t.rgba[0],t.rgba[1],t.rgba[2],t.rgba[3]),this.gl.uniform1f(this.uniforms.useTexture,0),this.gl.uniform1f(this.uniforms.shapeMode,2),this.gl.uniform1f(this.uniforms.time,t.timeMs*.001),this.gl.uniform1f(this.uniforms.borderPx,Math.max(.5,t.borderThicknessPx)),this.gl.uniform1f(this.uniforms.borderInsetPx,Math.max(0,t.borderInsetPx)),this.gl.uniform1f(this.uniforms.cornerRadiusPx,Math.max(0,t.cornerRadiusPx)),this.gl.uniform1f(this.uniforms.noiseAmp,Math.max(0,t.noiseAmplitudePx)),this.gl.uniform1f(this.uniforms.pulseStrength,Math.max(0,t.pulseStrength)),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1f(this.uniforms.shapeMode,0)}beginAdditiveBlend(){this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE)}endAdditiveBlend(){this.gl.blendFunc(this.gl.ONE,this.gl.ONE_MINUS_SRC_ALPHA)}dispose(){this.gl.deleteTexture(this.texture),this.gl.deleteBuffer(this.quadBuffer),this.gl.deleteProgram(this.program)}createShader(t,i){const e=this.gl.createShader(t);if(!e)throw new Error("Failed to create WebGL shader");if(this.gl.shaderSource(e,i),this.gl.compileShader(e),!this.gl.getShaderParameter(e,this.gl.COMPILE_STATUS)){const n=this.gl.getShaderInfoLog(e)??"unknown error";throw this.gl.deleteShader(e),new Error(`WebGL shader compile failed: ${n}`)}return e}createProgram(t,i){const e=this.gl.createProgram();if(!e)throw new Error("Failed to create WebGL program");if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS)){const n=this.gl.getProgramInfoLog(e)??"unknown error";throw this.gl.deleteProgram(e),new Error(`WebGL program link failed: ${n}`)}return e}}class l{static RAINBOW_HUE_BUCKETS=24;static PARTICLE_GLOBAL_ALPHA=.9;static PARTICLE_MAX_DISTANCE=.72;static PARTICLE_BASE_RADIUS=.028;canvas;container;button;spinQueueController;spriteUrl;spriteElementsCount;highlightInitialWinningCells;particleColorRgb;particleColorMode;motionProfile;isCoarsePointerDevice;spriteImage=null;webglRenderer=null;rafLoop=new K;runtime=st();width=0;height=0;cellW=0;cellH=0;boardX=0;boardY=0;scriptedCascadeQueue=[];scriptedOutgoingGrid=null;scriptedPendingGrid=null;scriptedOutroStartedAt=0;scriptedOutroElapsedMs=0;outroMotionPlan=null;scriptedOutgoingOffsets=S();scriptedOutgoingOffsetsPrev=S();scriptedIncomingOffsets=S();scriptedIncomingOffsetsPrev=S();scriptedIncomingAlpha=S();scriptedIncomingAlphaPrev=S();scriptedIncomingVisibility=l.createVisibilityGrid("hidden");scriptedIncomingVisibilityPrev=l.createVisibilityGrid("hidden");winningCells=[];winningCellKeys=new Set;grid;particlesPerCell=D;lastRafTime=0;initialHighlightRequestedAt=0;simulationLastNow=0;simulationAccumulatorMs=0;outroInterpolationAlpha=1;isOutroPipelineWarmedUp=!1;isGpuPipelineWarmedUp=!1;perfWindowStartedAt=0;perfFrameCount=0;perfOver20MsCount=0;perfDtSamples=[];mobileDprCap=2;mobilePerfGoodWindows=0;mobilePerfBadWindows=0;static PERF_WINDOW_MS=1500;static PERF_BAD_P95_DT_MS=19;static PERF_GOOD_P95_DT_MS=17.5;static PERF_BAD_SLOW_RATIO=.03;static MOBILE_BAD_WINDOWS_TO_DECREASE_DPR=2;static MOBILE_GOOD_WINDOWS_TO_INCREASE_DPR=4;static MOBILE_DPR_CAP_MIN=1.25;static MOBILE_DPR_CAP_MAX=1.5;static MOBILE_DPR_STEP_DOWN=.1;static MOBILE_DPR_STEP_UP=.05;static DPR_QUANT_STEP=.25;static MAX_CANVAS_AREA_PX_COARSE=900*900;static MAX_CANVAS_AREA_PX_FINE=1400*1400;static PRE_SPIN_MS=150;static WIN_EFFECTS_ENVELOPE_TAU_MS=120;static MAX_FRAME_DELTA_MS=100;static WIN_BORDER_ALPHA=.72;static WIN_BORDER_INSET_RATIO=.08;static particleSeedsCache=new Map;constructor(t){this.canvas=t.canvas,this.container=t.container,this.button=t.button,this.spriteUrl=t.sprite,this.spriteElementsCount=Math.max(1,t.spriteElementsCount??k),this.highlightInitialWinningCells=t.highlightInitialWinningCells!==!1,this.spinQueueController=new et(t.queuedSpinStates);const i=J(t.particleColor);this.particleColorRgb=i.rgb,this.particleColorMode=i.mode,this.motionProfile=A,this.isCoarsePointerDevice=l.detectCoarsePointerDevice(),this.mobileDprCap=this.isCoarsePointerDevice?l.MOBILE_DPR_CAP_MAX:2,this.grid=t.initialSegments?tt(t.initialSegments,this.spriteElementsCount):F(this.spriteElementsCount)}async init(){if(this.bindEvents(),this.resize(),await this.loadSpriteIfProvided(),!this.spriteImage)throw new Error("sprite is required for WebGL renderer");this.webglRenderer=new at({canvas:this.canvas,spriteImage:this.spriteImage,spriteElementsCount:this.spriteElementsCount}),this.webglRenderer.resize(this.width,this.height),this.warmUpOutroPipeline(),this.warmUpGpuPipeline(),this.applyInitialHighlightIfNeeded(),requestAnimationFrame(t=>{this.render(t),this.startLoop()})}destroy(){this.unbindEvents(),this.rafLoop.stop(),this.simulationLastNow=0,this.simulationAccumulatorMs=0,ot(this.runtime),this.webglRenderer?.dispose(),this.webglRenderer=null,this.clearWinningCells()}spin(){if(this.dismissHighlightIfActive(),this.runtime.isSpinning||this.runtime.queueFinished)return;if(!this.spinQueueController.hasPending()){this.runtime.queueFinished=!0,this.button&&(this.button.disabled=!0);return}const t=this.spinQueueController.consume(),i=t?.highlightWin===!0;this.runtime.isSpinning=!0,this.runtime.phase="preSpin",this.runtime.preSpinStartedAt=performance.now(),this.runtime.activeSpinState=t,this.runtime.shouldHighlightCurrentSpin=i,this.runtime.hasStartedFirstSpin=!0,this.simulationLastNow=0,this.simulationAccumulatorMs=0,this.button&&(this.button.disabled=!0),this.startLoop()}bindEvents(){window.addEventListener("resize",this.resize),document.addEventListener("visibilitychange",this.onVisibilityChange),this.button?.addEventListener("click",this.onSpinClick)}unbindEvents(){window.removeEventListener("resize",this.resize),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.button?.removeEventListener("click",this.onSpinClick)}onVisibilityChange=()=>{this.lastRafTime=0,this.simulationLastNow=0,this.simulationAccumulatorMs=0,this.resetPerfWindow()};onSpinClick=()=>{this.runtime.isSpinning&&this.runtime.phase!=="winFlash"||this.spin()};getNextGrid(t){return t?v(t,this.spriteElementsCount):F(this.spriteElementsCount)}update(t){if(this.runtime.isSpinning){if(this.runtime.phase==="preSpin"){if(t-this.runtime.preSpinStartedAt<l.PRE_SPIN_MS)return;rt(this.runtime,{activeSpinState:this.runtime.activeSpinState,shouldHighlightCurrentSpin:this.runtime.shouldHighlightCurrentSpin,startedAt:t}),this.runtime.preSpinStartedAt=0;const i=this.runtime.activeSpinState?.finaleSequenceRows?this.runtime.activeSpinState.finaleSequenceRows.map(r=>C(r)):this.runtime.activeSpinState?.finaleSequence??[];this.scriptedCascadeQueue=i.map(r=>r.map(o=>[...o])),this.clearWinningCells();const e=this.runtime.activeSpinState?.stopRows?C(this.runtime.activeSpinState.stopRows):this.runtime.activeSpinState?.stopGrid,n=this.getNextGrid(e);this.startOutroTransition(n,t)}this.runtime.phase}}stepScriptedOutro(t){if(!this.scriptedOutgoingGrid||!this.scriptedPendingGrid){this.finishSpinWithUi();return}this.outroMotionPlan||(this.outroMotionPlan=this.createOutroMotionPlan()),this.scriptedOutroElapsedMs+=t;const{allOutgoingDone:i,allIncomingDone:e}=H({elapsedMs:this.scriptedOutroElapsedMs,scriptedOutgoingOffsets:this.scriptedOutgoingOffsets,scriptedIncomingOffsets:this.scriptedIncomingOffsets,scriptedIncomingAlpha:this.scriptedIncomingAlpha,scriptedIncomingVisibility:this.scriptedIncomingVisibility,motionPlan:this.outroMotionPlan});if(!(!i||!e)&&(this.grid=this.scriptedPendingGrid,this.scriptedOutgoingGrid=null,this.scriptedPendingGrid=null,this.outroMotionPlan=null,this.clearWinningCells(),this.resetOutroBuffers(1,"active"),!this.tryStartScriptedCascade(this.scriptedOutroStartedAt+this.scriptedOutroElapsedMs))){if(!this.runtime.shouldHighlightCurrentSpin){this.finishSpinWithUi();return}this.setWinningCells(B(this.grid)),U(this.runtime,this.scriptedOutroStartedAt+this.scriptedOutroElapsedMs),this.runtime.activeSpinState?.callback?.(),this.button&&this.runtime.shouldHighlightCurrentSpin&&this.spinQueueController.hasPending()&&(this.button.disabled=!1)}}tryStartScriptedCascade(t){if(this.scriptedCascadeQueue.length===0)return!1;const i=this.scriptedCascadeQueue.shift();return i?(this.startOutroTransition(v(i,this.spriteElementsCount),t),!0):!1}startOutroTransition(t,i){this.scriptedOutgoingGrid=this.grid.map(e=>[...e]),this.scriptedPendingGrid=t.map(e=>[...e]),this.outroMotionPlan=this.createOutroMotionPlan(),this.resetOutroBuffers(0,"hidden"),this.clearWinningCells(),this.runtime.phase="outro",this.scriptedOutroStartedAt=i,this.scriptedOutroElapsedMs=0,this.outroInterpolationAlpha=1}finishSpinWithUi(t=!1){const i=this.runtime.activeSpinState,e=t?void 0:i?.callback,n=this.spinQueueController.hasPending();nt(this.runtime,n,performance.now()),this.button&&(this.button.disabled=this.runtime.queueFinished),e?.()}dismissHighlightIfActive(){this.runtime.phase==="winFlash"&&this.finishSpinWithUi(!0)}applyInitialHighlightIfNeeded(){this.highlightInitialWinningCells&&(this.setWinningCells(B(this.grid)),this.initialHighlightRequestedAt=performance.now())}warmUpOutroPipeline(){if(this.isOutroPipelineWarmedUp)return;const t=this.createOutroMotionPlan(),i=S(),e=S(),n=S(),r=l.createVisibilityGrid("hidden"),o=Math.max(...t.rowStartDelays),h=(f-1)*t.columnStaggerMs,u=[0,this.motionProfile.fixedStepMs,t.incomingStartShift+this.motionProfile.fixedStepMs,t.fallMs+o+h+this.motionProfile.fixedStepMs];for(const c of u)H({elapsedMs:c,scriptedOutgoingOffsets:i,scriptedIncomingOffsets:e,scriptedIncomingAlpha:n,scriptedIncomingVisibility:r,motionPlan:t});this.isOutroPipelineWarmedUp=!0}createOutroMotionPlan(){const t=Z({height:this.height,boardY:this.boardY,cellH:this.cellH,motionProfile:this.motionProfile});if(!this.isCoarsePointerDevice)return t;const i=1e3/60;return{...t,columnStaggerMs:this.quantizeMs(t.columnStaggerMs,i),incomingStartShift:this.quantizeMs(t.incomingStartShift,i),rowStartDelays:[this.quantizeMs(t.rowStartDelays[0],i),this.quantizeMs(t.rowStartDelays[1],i),this.quantizeMs(t.rowStartDelays[2],i)]}}quantizeMs(t,i){return t<=0?0:Math.max(1,Math.round(t/i))*i}warmUpGpuPipeline(){if(this.isGpuPipelineWarmedUp)return;const t=this.webglRenderer;if(!t)return;const i=Math.max(8,this.cellW*.2),e=Math.max(8,this.cellH*.2),n=this.boardX+2,r=this.boardY+2;t.beginFrame(),t.drawSprite(0,n,r,i,e,1),t.drawSolidRect(n+i+2,r,i,e,[1,1,1,.35]),t.beginAdditiveBlend(),t.drawSoftCircle(n+i*.5,r+e*.5,Math.max(2,i*.25),[1,.9,.4,.4]),t.endAdditiveBlend(),this.isGpuPipelineWarmedUp=!0}trackOutroPerf(t,i){if(this.runtime.phase!=="outro"){this.resetPerfWindow();return}this.perfWindowStartedAt<=0&&(this.perfWindowStartedAt=i),this.perfFrameCount+=1,t>20&&(this.perfOver20MsCount+=1),this.perfDtSamples.push(t),!(i-this.perfWindowStartedAt<l.PERF_WINDOW_MS)&&(this.flushPerfWindow(),this.perfWindowStartedAt=i)}resetPerfWindow(){this.perfWindowStartedAt=0,this.perfFrameCount=0,this.perfOver20MsCount=0,this.perfDtSamples.length=0}flushPerfWindow(){if(this.perfFrameCount===0)return;const t=[...this.perfDtSamples].sort((n,r)=>n-r),i=Math.max(0,Math.min(t.length-1,Math.floor(t.length*.95))),e=t[i];this.adjustMobileDprCap(e,this.perfOver20MsCount,this.perfFrameCount),this.perfFrameCount=0,this.perfOver20MsCount=0,this.perfDtSamples.length=0}adjustMobileDprCap(t,i,e){if(!this.isCoarsePointerDevice||e<=0)return;const n=i/e,r=t>l.PERF_BAD_P95_DT_MS||n>l.PERF_BAD_SLOW_RATIO,o=t<=l.PERF_GOOD_P95_DT_MS&&i===0;let h=this.mobileDprCap;r?(this.mobilePerfBadWindows+=1,this.mobilePerfGoodWindows=0,this.mobilePerfBadWindows>=l.MOBILE_BAD_WINDOWS_TO_DECREASE_DPR&&(h=Math.max(l.MOBILE_DPR_CAP_MIN,this.mobileDprCap-l.MOBILE_DPR_STEP_DOWN),this.mobilePerfBadWindows=0)):o?(this.mobilePerfGoodWindows+=1,this.mobilePerfBadWindows=0,this.mobilePerfGoodWindows>=l.MOBILE_GOOD_WINDOWS_TO_INCREASE_DPR&&(h=Math.min(l.MOBILE_DPR_CAP_MAX,this.mobileDprCap+l.MOBILE_DPR_STEP_UP),this.mobilePerfGoodWindows=0)):(this.mobilePerfGoodWindows=0,this.mobilePerfBadWindows=0),!(Math.abs(h-this.mobileDprCap)<.001)&&(this.mobileDprCap=h,this.resize())}render(t){if(!this.webglRenderer)return;this.initialHighlightRequestedAt>0&&t-this.initialHighlightRequestedAt>=Y&&(U(this.runtime,this.initialHighlightRequestedAt),this.runtime.winEffectsEnvelope=1,this.initialHighlightRequestedAt=0,this.button&&(this.button.disabled=!1));const i=this.runtime.phase==="preSpin"?0:this.runtime.phase==="winFlash"?1:0;if(this.lastRafTime>0){const h=Math.min(t-this.lastRafTime,50);this.trackOutroPerf(h,t);const u=1-Math.exp(-h/l.WIN_EFFECTS_ENVELOPE_TAU_MS);this.runtime.winEffectsEnvelope+=(i-this.runtime.winEffectsEnvelope)*u}else this.resetPerfWindow();this.lastRafTime=t,this.webglRenderer.beginFrame();const e=this.runtime.phase==="winFlash"||this.runtime.phase==="preSpin"||this.initialHighlightRequestedAt>0&&this.winningCells.length>0;this.runtime.phase==="outro"&&this.scriptedOutgoingGrid&&this.scriptedPendingGrid?(this.drawGridInterpolated(this.scriptedOutgoingGrid,this.scriptedOutgoingOffsetsPrev,this.scriptedOutgoingOffsets,this.outroInterpolationAlpha,e),this.drawGridInterpolated(this.scriptedPendingGrid,this.scriptedIncomingOffsetsPrev,this.scriptedIncomingOffsets,this.outroInterpolationAlpha,e,this.scriptedIncomingAlphaPrev,this.scriptedIncomingAlpha,this.scriptedIncomingVisibility)):this.drawGrid(this.grid,null,e);const n=this.initialHighlightRequestedAt>0?"winFlash":this.runtime.phase,r=this.initialHighlightRequestedAt>0?this.initialHighlightRequestedAt:this.runtime.winFlashStartedAt,o=this.initialHighlightRequestedAt>0?1:this.runtime.winEffectsEnvelope;this.drawWinningEffects({now:t,phase:n,winFlashStartedAt:r,winEffectsEnvelope:o})}isWinningCell=(t,i)=>this.winningCellKeys.has(`${t}:${i}`);getRowCompactOffset(t){return(X[t]??0)*this.cellH}applyPixelSnapY(t){return this.isCoarsePointerDevice?Math.round(t*2)/2:t}drawGrid(t,i,e){this.drawGridWithSampler({grid:t,skipWinningCells:e,sampleOffsetY:(n,r)=>i?i[n][r]:0,sampleAlpha:()=>1,isVisible:()=>!0})}drawGridInterpolated(t,i,e,n,r,o,h,u){this.drawGridWithSampler({grid:t,skipWinningCells:r,sampleOffsetY:(c,a)=>i[c][a]+(e[c][a]-i[c][a])*n,sampleAlpha:(c,a)=>o&&h?o[c][a]+(h[c][a]-o[c][a])*n:1,isVisible:(c,a)=>!u||u[c][a]!=="hidden"})}drawGridWithSampler(t){const i=this.webglRenderer;if(i)for(let e=0;e<f;e+=1){const n=this.boardX+e*this.cellW;for(let r=0;r<d;r+=1){if(t.skipWinningCells&&this.isWinningCell(e,r)||!t.isVisible(e,r))continue;const o=t.sampleOffsetY(e,r),h=this.applyPixelSnapY(this.boardY+r*this.cellH+o+this.getRowCompactOffset(r));if(h>this.height||h+this.cellH<0)continue;const u=t.sampleAlpha(e,r);u<=0||i.drawSprite(t.grid[e][r],n,h,this.cellW,this.cellH,u)}}}drawWinningEffects(t){const i=this.webglRenderer;if(!i||this.winningCells.length===0||t.phase!=="winFlash"&&t.phase!=="preSpin")return;const e=Math.max(0,Math.min(1,t.winEffectsEnvelope)),n=Math.max(0,t.now-t.winFlashStartedAt),r=n%L/L,o=1+Math.sin(r*Math.PI*2)*V*e,h=Math.max(1,this.cellW*l.WIN_BORDER_INSET_RATIO),u=Math.max(1,this.cellW*.022),c=this.runtime.phase==="winFlash"&&this.runtime.shouldHighlightCurrentSpin&&this.runtime.hasStartedFirstSpin;for(const a of this.winningCells){const p=this.boardX+a.col*this.cellW,g=this.boardY+a.row*this.cellH+this.getRowCompactOffset(a.row),m=this.grid[a.col][a.row],_=l.WIN_BORDER_ALPHA*e,R=this.particleColorMode==="rainbow"?l.hslToRgb01((n*.2+a.col*36+a.row*22)%360,.96,.64):[this.particleColorRgb[0]/255,this.particleColorRgb[1]/255,this.particleColorRgb[2]/255],w=this.cellW*o,M=this.cellH*o,b=(this.cellW-w)*.5,N=(this.cellH-M)*.5;i.drawSprite(m,p+b,g+N,w,M,1);const q=p+h,z=g+h,T=this.cellW-h*2,W=this.cellH-h*2;T<=u*2||W<=u*2||(this.drawElectricBorder({renderer:i,cell:a,x:q,y:z,w:T,h:W,borderThickness:u,borderColor:R,alpha:_,elapsed:n,envelope:e}),c&&this.drawCellParticleBurst({renderer:i,cell:a,centerX:p+this.cellW*.5,centerY:g+this.cellH*.5,elapsed:n,envelope:e}))}}drawCellParticleBurst(t){const i=Math.min(this.cellW,this.cellH)*l.PARTICLE_MAX_DISTANCE,e=Math.min(this.cellW,this.cellH)*l.PARTICLE_BASE_RADIUS,n=l.getParticleSeeds(t.cell.col,t.cell.row),r=[this.particleColorRgb[0]/255,this.particleColorRgb[1]/255,this.particleColorRgb[2]/255];t.renderer.beginAdditiveBlend();for(let o=0;o<this.particlesPerCell;o+=1){const h=n[o],u=h.phaseOffset*I,c=t.elapsed-u;if(c<0)continue;const a=c%I/I,p=h.seedA*Math.PI*2,g=i*a*(.35+h.seedB*.65),m=t.centerX+Math.cos(p)*g,_=t.centerY+Math.sin(p)*g,R=.7+.9*Math.max(0,Math.sin((t.elapsed*.012+h.twinkleSeed*2)*Math.PI*2)),w=Math.max(1,e*(.55+h.seedC*.6)*(1-a*.5)),M=Math.max(0,Math.min(1,(.9+R*.2)*l.PARTICLE_GLOBAL_ALPHA*t.envelope));if(M<=0)continue;const b=this.particleColorMode==="rainbow"?l.getRainbowParticleColor(t.elapsed,t.cell.col,t.cell.row,h.seedA):r;t.renderer.drawSoftCircle(m,_,w,[b[0],b[1],b[2],M])}t.renderer.endAdditiveBlend()}drawElectricBorder(t){const i=Math.max(0,Math.min(1,t.alpha*t.envelope)),e=t.borderThickness*1.8,n=t.elapsed+t.cell.col*170+t.cell.row*290;t.renderer.beginAdditiveBlend(),t.renderer.drawElectricBorder({x:t.x-e,y:t.y-e,width:t.w+e*2,height:t.h+e*2,rgba:[t.borderColor[0],t.borderColor[1],t.borderColor[2],i*.55],timeMs:n,borderThicknessPx:Math.max(.8,t.borderThickness*1.1),borderInsetPx:e*.85,cornerRadiusPx:Math.max(2,t.borderThickness*2.5),noiseAmplitudePx:Math.max(.15,t.borderThickness*.6),pulseStrength:.9}),t.renderer.drawElectricBorder({x:t.x-e*.5,y:t.y-e*.5,width:t.w+e,height:t.h+e,rgba:[t.borderColor[0],t.borderColor[1],t.borderColor[2],i*.9],timeMs:n*1.03,borderThicknessPx:Math.max(.7,t.borderThickness*.8),borderInsetPx:e*.5,cornerRadiusPx:Math.max(1.5,t.borderThickness*1.7),noiseAmplitudePx:Math.max(.12,t.borderThickness*.42),pulseStrength:1.25}),t.renderer.endAdditiveBlend()}static hslToRgb01(t,i,e){const n=(t%360+360)%360,r=Math.max(0,Math.min(1,i)),o=Math.max(0,Math.min(1,e)),h=(1-Math.abs(2*o-1))*r,u=n/60,c=h*(1-Math.abs(u%2-1));let a=0,p=0,g=0;u>=0&&u<1?(a=h,p=c):u<2?(a=c,p=h):u<3?(p=h,g=c):u<4?(p=c,g=h):u<5?(a=c,g=h):(a=h,g=c);const m=o-h*.5;return[a+m,p+m,g+m]}static getRainbowParticleColor(t,i,e,n){const r=(n*360+t*.24+i*38+e*22)%360,o=360/l.RAINBOW_HUE_BUCKETS,h=Math.floor(r/o)*o;return l.hslToRgb01(h,.98,.64)}static detectCoarsePointerDevice(){if(typeof window>"u")return!1;const t=typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,i=typeof navigator<"u"&&typeof navigator.maxTouchPoints=="number"?navigator.maxTouchPoints:0;return t||i>0}quantizeDprCap(t){const i=l.DPR_QUANT_STEP;return Math.max(1,Math.round(t/i)*i)}static hash01(t,i,e,n){const r=Math.sin(t*127.1+i*311.7+e*74.7+n*19.3)*43758.5453;return r-Math.floor(r)}static getParticleSeeds(t,i){const e=`${t},${i}`,n=l.particleSeedsCache.get(e);if(n)return n;const r=[];for(let o=0;o<D;o+=1)r.push({seedA:l.hash01(t,i,o,1),seedB:l.hash01(t,i,o,2),seedC:l.hash01(t,i,o,3),phaseOffset:l.hash01(t,i,o,4),twinkleSeed:l.hash01(t,i,o,5)});return l.particleSeedsCache.set(e,r),r}clearWinningCells(){this.winningCells=[],this.winningCellKeys.clear()}setWinningCells(t){this.winningCells=t,this.winningCellKeys.clear();for(const i of t)this.winningCellKeys.add(`${i.col}:${i.row}`)}resize=()=>{const t=this.container.getBoundingClientRect(),i=Math.max(300,Math.floor(t.width)),e=Math.max(1,i*i),n=this.isCoarsePointerDevice?l.MAX_CANVAS_AREA_PX_COARSE:l.MAX_CANVAS_AREA_PX_FINE,r=Math.max(1,Math.sqrt(n/e)),o=this.isCoarsePointerDevice?this.mobileDprCap:2,h=this.quantizeDprCap(Math.min(o,r)),u=Math.max(1,Math.min(window.devicePixelRatio||1,h)),c=Math.max(300,Math.floor(i*u));this.width=c,this.height=c;const a=Math.floor(Math.min(this.width/f,this.height/d));this.cellW=a,this.cellH=a,this.boardX=Math.floor((this.width-this.cellW*f)/2),this.boardY=Math.floor((this.height-this.cellH*d)/2),this.canvas.width=this.width,this.canvas.height=this.height,this.webglRenderer?.resize(this.width,this.height)};async loadSpriteIfProvided(){if(!this.spriteUrl)return;const t=new Image;t.decoding="async",t.src=this.spriteUrl;try{await t.decode(),this.spriteImage=t}catch{this.spriteImage=null}}advanceSimulation(t){if(this.simulationLastNow<=0){this.simulationLastNow=t,this.update(t);return}const i=Math.max(0,Math.min(t-this.simulationLastNow,l.MAX_FRAME_DELTA_MS));if(this.simulationLastNow=t,this.update(t),this.runtime.phase!=="outro"){this.outroInterpolationAlpha=1;return}this.advanceOutroFixedStep(i)}advanceOutroFixedStep(t){this.simulationAccumulatorMs+=t;const i=this.motionProfile.fixedStepMs;let e=0;for(;this.simulationAccumulatorMs>=i&&e<this.motionProfile.maxCatchUpStepsPerFrame&&this.runtime.phase==="outro";)this.snapshotOutroState(),this.stepScriptedOutro(i),this.simulationAccumulatorMs-=i,e+=1;if(this.runtime.phase!=="outro"){this.outroInterpolationAlpha=1;return}this.outroInterpolationAlpha=Math.max(0,Math.min(1,this.simulationAccumulatorMs/i))}snapshotOutroState(){this.copyOffsets(this.scriptedOutgoingOffsetsPrev,this.scriptedOutgoingOffsets),this.copyOffsets(this.scriptedIncomingOffsetsPrev,this.scriptedIncomingOffsets),this.copyOffsets(this.scriptedIncomingAlphaPrev,this.scriptedIncomingAlpha),this.copyVisibility(this.scriptedIncomingVisibilityPrev,this.scriptedIncomingVisibility)}copyOffsets(t,i){for(let e=0;e<f;e+=1)for(let n=0;n<d;n+=1)t[e][n]=i[e][n]}copyVisibility(t,i){for(let e=0;e<f;e+=1)for(let n=0;n<d;n+=1)t[e][n]=i[e][n]}resetOutroBuffers(t,i){P(this.scriptedOutgoingOffsets,0),P(this.scriptedIncomingOffsets,0),P(this.scriptedOutgoingOffsetsPrev,0),P(this.scriptedIncomingOffsetsPrev,0),P(this.scriptedIncomingAlpha,t),P(this.scriptedIncomingAlphaPrev,t),this.fillVisibilityGrid(this.scriptedIncomingVisibility,i),this.fillVisibilityGrid(this.scriptedIncomingVisibilityPrev,i)}static createVisibilityGrid(t){return Array.from({length:f},()=>Array.from({length:d},()=>t))}fillVisibilityGrid(t,i){for(let e=0;e<f;e+=1)for(let n=0;n<d;n+=1)t[e][n]=i}startLoop(){this.rafLoop.isRunning()||this.rafLoop.start(t=>(this.advanceSimulation(t),this.render(t),this.shouldKeepAnimating()))}shouldKeepAnimating(){return this.runtime.isSpinning||this.initialHighlightRequestedAt>0?!0:this.runtime.winEffectsEnvelope>.001}}exports.CascadingReel=l;
|
|
130
130
|
//# sourceMappingURL=index.cjs.js.map
|