@codexo/exojs 0.15.0 → 0.15.2

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/dist/esm/animation/Tween.d.ts.map +1 -1
  3. package/dist/esm/animation/Tween.js +6 -4
  4. package/dist/esm/animation/Tween.js.map +1 -1
  5. package/dist/esm/audio/AudioManager.d.ts.map +1 -1
  6. package/dist/esm/audio/AudioManager.js +14 -4
  7. package/dist/esm/audio/AudioManager.js.map +1 -1
  8. package/dist/esm/audio/Playable.d.ts +6 -1
  9. package/dist/esm/audio/Playable.d.ts.map +1 -1
  10. package/dist/esm/core/Application.d.ts.map +1 -1
  11. package/dist/esm/core/Application.js +2 -0
  12. package/dist/esm/core/Application.js.map +1 -1
  13. package/dist/esm/core/BuildInfo.js +2 -2
  14. package/dist/esm/core/SceneNode.d.ts +10 -1
  15. package/dist/esm/core/SceneNode.d.ts.map +1 -1
  16. package/dist/esm/core/SceneNode.js +10 -1
  17. package/dist/esm/core/SceneNode.js.map +1 -1
  18. package/dist/esm/debug/BoundingBoxesLayer.d.ts.map +1 -1
  19. package/dist/esm/debug/BoundingBoxesLayer.js +2 -1
  20. package/dist/esm/debug/BoundingBoxesLayer.js.map +1 -1
  21. package/dist/esm/debug/HitTestLayer.js +4 -4
  22. package/dist/esm/debug/HitTestLayer.js.map +1 -1
  23. package/dist/esm/debug/PerformanceLayer.js +1 -1
  24. package/dist/esm/debug/PerformanceLayer.js.map +1 -1
  25. package/dist/esm/debug/RenderPassInspectorLayer.js +2 -2
  26. package/dist/esm/debug/RenderPassInspectorLayer.js.map +1 -1
  27. package/dist/esm/input/InputManager.d.ts.map +1 -1
  28. package/dist/esm/input/InputManager.js +12 -3
  29. package/dist/esm/input/InputManager.js.map +1 -1
  30. package/dist/esm/math/AbstractVector.d.ts +4 -3
  31. package/dist/esm/math/AbstractVector.d.ts.map +1 -1
  32. package/dist/esm/math/AbstractVector.js +5 -4
  33. package/dist/esm/math/AbstractVector.js.map +1 -1
  34. package/dist/esm/math/ObservableVector.d.ts +2 -0
  35. package/dist/esm/math/ObservableVector.d.ts.map +1 -1
  36. package/dist/esm/math/ObservableVector.js +9 -0
  37. package/dist/esm/math/ObservableVector.js.map +1 -1
  38. package/dist/esm/math/Polygon.d.ts.map +1 -1
  39. package/dist/esm/math/Polygon.js +4 -1
  40. package/dist/esm/math/Polygon.js.map +1 -1
  41. package/dist/esm/math/collision-detection.d.ts.map +1 -1
  42. package/dist/esm/math/collision-detection.js +13 -13
  43. package/dist/esm/math/collision-detection.js.map +1 -1
  44. package/dist/esm/math/collision-primitives.d.ts +1 -1
  45. package/dist/esm/math/collision-primitives.d.ts.map +1 -1
  46. package/dist/esm/math/collision-primitives.js +4 -1
  47. package/dist/esm/math/collision-primitives.js.map +1 -1
  48. package/dist/esm/rendering/primitives/Graphics.d.ts +7 -0
  49. package/dist/esm/rendering/primitives/Graphics.d.ts.map +1 -1
  50. package/dist/esm/rendering/primitives/Graphics.js +20 -6
  51. package/dist/esm/rendering/primitives/Graphics.js.map +1 -1
  52. package/dist/esm/rendering/sprite/AnimatedSprite.d.ts +1 -0
  53. package/dist/esm/rendering/sprite/AnimatedSprite.d.ts.map +1 -1
  54. package/dist/esm/rendering/sprite/AnimatedSprite.js +18 -1
  55. package/dist/esm/rendering/sprite/AnimatedSprite.js.map +1 -1
  56. package/dist/esm/rendering/sprite/Sprite.d.ts.map +1 -1
  57. package/dist/esm/rendering/sprite/Sprite.js +8 -0
  58. package/dist/esm/rendering/sprite/Sprite.js.map +1 -1
  59. package/dist/esm/rendering/text/TextLayout.d.ts.map +1 -1
  60. package/dist/esm/rendering/text/TextLayout.js +2 -3
  61. package/dist/esm/rendering/text/TextLayout.js.map +1 -1
  62. package/dist/esm/resources/Loader.d.ts.map +1 -1
  63. package/dist/esm/resources/Loader.js +20 -3
  64. package/dist/esm/resources/Loader.js.map +1 -1
  65. package/dist/esm/resources/coreAssetBindings.d.ts +11 -0
  66. package/dist/esm/resources/coreAssetBindings.d.ts.map +1 -1
  67. package/dist/esm/resources/coreAssetBindings.js +10 -2
  68. package/dist/esm/resources/coreAssetBindings.js.map +1 -1
  69. package/dist/exo.debug.esm.js +1 -1
  70. package/dist/exo.debug.esm.js.map +1 -1
  71. package/dist/exo.esm.js +1 -1
  72. package/dist/exo.esm.js.map +1 -1
  73. package/dist/exo.iife.js +157 -46
  74. package/dist/exo.iife.js.map +1 -1
  75. package/dist/exo.iife.min.js +1 -1
  76. package/dist/exo.iife.min.js.map +1 -1
  77. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- var Exo=function(e){"use strict";const t=e=>{const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375};class i{static linear=e=>e;static quadIn=e=>e*e;static quadOut=e=>e*(2-e);static quadInOut=e=>e<.5?2*e*e:(4-2*e)*e-1;static cubicIn=e=>e*e*e;static cubicOut=e=>--e*e*e+1;static cubicInOut=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;static quartIn=e=>e*e*e*e;static quartOut=e=>1- --e*e*e*e;static quartInOut=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;static quintIn=e=>e*e*e*e*e;static quintOut=e=>1+--e*e*e*e*e;static quintInOut=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;static sineIn=e=>1-Math.cos(e*Math.PI/2);static sineOut=e=>Math.sin(e*Math.PI/2);static sineInOut=e=>-(Math.cos(Math.PI*e)-1)/2;static expoIn=e=>0===e?0:Math.pow(2,10*e-10);static expoOut=e=>1===e?1:1-Math.pow(2,-10*e);static expoInOut=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;static circIn=e=>1-Math.sqrt(1-Math.pow(e,2));static circOut=e=>Math.sqrt(1-Math.pow(e-1,2));static circInOut=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;static backIn=e=>{const t=1.70158;return 2.70158*e*e*e-t*e*e};static backOut=e=>{const t=1.70158;return 1+2.70158*Math.pow(e-1,3)+t*Math.pow(e-1,2)};static backInOut=e=>{const t=2.5949095;return e<.5?Math.pow(2*e,2)*(7.189819*e-t)/2:(Math.pow(2*e-2,2)*((t+1)*(2*e-2)+t)+2)/2};static bounceOut=t;static bounceIn=e=>1-t(1-e);static bounceInOut=e=>e<.5?(1-t(1-2*e))/2:(1+t(2*e-1))/2;static elasticIn=e=>{if(0===e)return 0;if(1===e)return 1;const t=2*Math.PI/3;return-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*t)};static elasticOut=e=>{if(0===e)return 0;if(1===e)return 1;const t=2*Math.PI/3;return Math.pow(2,-10*e)*Math.sin((10*e-.75)*t)+1};static elasticInOut=e=>{if(0===e)return 0;if(1===e)return 1;const t=2*Math.PI/4.5;return e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*t)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*t)/2+1}}var n,r;e.TweenState=void 0,(n=e.TweenState||(e.TweenState={})).Idle="idle",n.Active="active",n.Paused="paused",n.Complete="complete",n.Stopped="stopped";class s{_target;_state=e.TweenState.Idle;_properties={};_startValues=null;_duration=0;_delay=0;_easing=i.linear;_elapsed=0;_delayElapsed=0;_repeatCount=0;_repeatTotal=0;_yoyo=!1;_direction=1;_onStart=null;_onUpdate=null;_onComplete=null;_onRepeat=null;_chained=null;_manager=null;_startFired=!1;constructor(e){this._target=e}get target(){return this._target}get state(){return this._state}get progress(){if(0===this._duration)return 1;const e=Math.min(this._elapsed/this._duration,1),t=1===this._direction?e:1-e;return this._easing(t)}to(e,t){return this._properties={...e},this._duration=t,this._startValues=null,this}delay(e){return this._delay=e,this}easing(e){return this._easing=e,this}repeat(e){return this._repeatTotal=e,this}yoyo(e=!0){return this._yoyo=e,this}onStart(e){return this._onStart=e,this}onUpdate(e){return this._onUpdate=e,this}onComplete(e){return this._onComplete=e,this}onRepeat(e){return this._onRepeat=e,this}start(){return this._state=e.TweenState.Active,this._elapsed=0,this._delayElapsed=0,this._startValues=null,this._startFired=!1,this._direction=1,this._repeatCount=this._repeatTotal,this._manager?.add(this),this}pause(){return this._state===e.TweenState.Active&&(this._state=e.TweenState.Paused),this}resume(){return this._state===e.TweenState.Paused&&(this._state=e.TweenState.Active),this}stop(){return this._state!==e.TweenState.Active&&this._state!==e.TweenState.Paused||(this._state=e.TweenState.Stopped,this._manager?.remove(this)),this}chain(e){return this._chained=e,e}_attachManager(e){this._manager=e}update(t){if(this._state===e.TweenState.Active){if(this._delayElapsed<this._delay){if(this._delayElapsed+=t,this._delayElapsed<this._delay)return;const e=this._delayElapsed-this._delay;this._delayElapsed=this._delay,t=e}if(null===this._startValues&&this._captureStartValues(),this._startFired||(this._startFired=!0,this._onStart?.()),this._elapsed+=t,this._elapsed>=this._duration&&(this._elapsed=this._duration),this._applyProgress(),this._elapsed>=this._duration){if(-1===this._repeatCount||this._repeatCount>0){-1!==this._repeatCount&&this._repeatCount--,this._onRepeat?.(),this._yoyo&&(this._direction=1===this._direction?-1:1);const e=this._elapsed-this._duration;this._elapsed=e>0?Math.min(e,this._duration):0,e>0&&this._applyProgress()}else this._complete()}}}_captureStartValues(){const e={},t=Object.keys(this._properties);for(const i of t){const t=this._target[i];"number"==typeof t&&(e[String(i)]=t)}this._startValues=e}_applyProgress(){if(null===this._startValues)return;const e=0===this._duration?1:Math.min(this._elapsed/this._duration,1),t=1===this._direction?e:1-e,i=this._easing(t),n=Object.keys(this._startValues),r=this._properties;for(const e of n){const t=this._startValues[e],n=r[e];void 0!==t&&void 0!==n&&(this._target[e]=t+(n-t)*i)}this._onUpdate?.(i)}_complete(){this._elapsed=this._duration,this._applyProgress(),this._state=e.TweenState.Complete,this._manager?.remove(this),this._onComplete?.(),this._chained?.start()}}e.TweenSequencerState=void 0,(r=e.TweenSequencerState||(e.TweenSequencerState={})).Idle="idle",r.Active="active",r.Paused="paused",r.Complete="complete",r.Stopped="stopped";class o{_stages=[];_state=e.TweenSequencerState.Idle;_manager;_currentStageIndex=0;_direction=1;_repeatCount=0;_repeatTotal=0;_yoyo=!1;_delayElapsed=0;_onStartCb=null;_onCompleteCb=null;_startFired=!1;constructor(e){this._manager=e??null}get state(){return this._state}get progress(){const e=this._stages.length;return 0===e?1:Math.min(this._currentStageIndex/e,1)}then(e){const t=Array.isArray(e)?e:[e];return this._stages.push({type:"tweens",tweens:t}),this}wait(e){return this._stages.push({type:"delay",seconds:e}),this}repeat(e){return this._repeatTotal=e,this}yoyo(e=!0){return this._yoyo=e,this}onStart(e){return this._onStartCb=e,this}onComplete(e){return this._onCompleteCb=e,this}start(){return this._state=e.TweenSequencerState.Active,this._currentStageIndex=0,this._direction=1,this._repeatCount=this._repeatTotal,this._startFired=!1,this._manager?.addTicker(this),this._startCurrentStage(),this}pause(){return this._state===e.TweenSequencerState.Active&&(this._state=e.TweenSequencerState.Paused,this._pauseCurrentStageTweens()),this}resume(){return this._state===e.TweenSequencerState.Paused&&(this._state=e.TweenSequencerState.Active,this._resumeCurrentStageTweens()),this}stop(){return this._state!==e.TweenSequencerState.Active&&this._state!==e.TweenSequencerState.Paused||(this._state=e.TweenSequencerState.Stopped,this._stopCurrentStageTweens(),this._manager?.removeTicker(this)),this}update(t){if(this._state!==e.TweenSequencerState.Active)return;if(this._startFired||(this._startFired=!0,this._onStartCb?.()),0===this._stages.length)return void this._finish();const i=this._getActualStageIndex(),n=this._stages[i];if(void 0!==n)if("delay"===n.type)this._delayElapsed+=t,this._delayElapsed>=n.seconds&&this._advanceStage();else{if(null===this._manager)for(const i of n.tweens)i.state===e.TweenState.Active&&i.update(t);n.tweens.every(t=>t.state===e.TweenState.Complete||t.state===e.TweenState.Stopped)&&this._advanceStage()}}_getActualStageIndex(){return 1===this._direction?this._currentStageIndex:this._stages.length-1-this._currentStageIndex}_startCurrentStage(){const e=this._getActualStageIndex(),t=this._stages[e];if(void 0!==t&&(this._delayElapsed=0,"tweens"===t.type))for(const e of t.tweens)null!==this._manager&&this._manager.add(e),e.start()}_advanceStage(){if(this._currentStageIndex++,this._currentStageIndex>=this._stages.length){-1===this._repeatCount||this._repeatCount>0?(-1!==this._repeatCount&&this._repeatCount--,this._yoyo&&(this._direction=1===this._direction?-1:1),this._currentStageIndex=0,this._startCurrentStage()):this._finish()}else this._startCurrentStage()}_finish(){this._state=e.TweenSequencerState.Complete,this._manager?.removeTicker(this),this._onCompleteCb?.()}_getCurrentStageTweens(){if(0===this._stages.length)return[];const e=this._getActualStageIndex(),t=this._stages[e];return"tweens"===t?.type?t.tweens:[]}_pauseCurrentStageTweens(){for(const e of this._getCurrentStageTweens())e.pause()}_resumeCurrentStageTweens(){for(const e of this._getCurrentStageTweens())e.resume()}_stopCurrentStageTweens(){for(const e of this._getCurrentStageTweens())e.stop()}}class a{order=400;_tweens=[];_tickers=[];_destroyed=!1;create(e){const t=new s(e);return t._attachManager(this),this._tweens.push(t),t}sequence(e){const[t]=e;if(void 0===t)throw new Error("[ExoJS] TweenManager.sequence() requires at least one tween.");for(let t=0;t<e.length-1;t++){const i=e[t],n=e[t+1];void 0!==i&&void 0!==n&&i.chain(n)}for(const t of e)this.add(t);return t}createSequencer(){return new o(this)}add(e){return e._attachManager(this),this._tweens.includes(e)||this._tweens.push(e),this}remove(e){const t=this._tweens.indexOf(e);return-1!==t&&this._tweens.splice(t,1),this}addTicker(e){return this._tickers.includes(e)||this._tickers.push(e),this}removeTicker(e){const t=this._tickers.indexOf(e);return-1!==t&&this._tickers.splice(t,1),this}update(e){if(this._destroyed)return;const t=[...this._tweens];for(const i of t)i.update(e.seconds);const i=[...this._tickers];for(const t of i)t.update(e.seconds)}clear(){return this._tweens=[],this._tickers=[],this}destroy(){this.clear(),this._destroyed=!0}}let h=null;class l{_width;_height;constructor(e=0,t=0){this._width=e,this._height=t}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}set(e,t=e){return this._width=e,this._height=t,this}add(e,t=e){return this._width+=e,this._height+=t,this}subtract(e,t=e){return this._width-=e,this._height-=t,this}scale(e,t=e){return this._width*=e,this._height*=t,this}divide(e,t=e){return this._width/=e,this._height/=t,this}copy(e){return this._width=e.width,this._height=e.height,this}clone(){return new l(this._width,this._height)}equals({width:e,height:t}={}){return!(void 0!==e&&this.width!==e||void 0!==t&&this.height!==t)}destroy(){}static zero=new l(0,0);static get temp(){return null===h&&(h=new l),h}}let u=null,c=null;const d=()=>{if("undefined"==typeof document)throw new Error("Canvas operations require a document context.");return null===u&&(u=document.createElement("canvas")),u},_=e=>{e.preventDefault(),e.stopImmediatePropagation()},f="undefined"!=typeof indexedDB,p=()=>performance.now(),m=new ArrayBuffer(0),g=(e,t,i)=>{if(t<e.length&&i>0){const n=t+i>e.length?e.length-t:i,r=e.length-n;for(let i=t;i<r;i++)e[i]=e[i+n];e.length=r}return e},y=e=>{const t=e;return e instanceof HTMLImageElement?l.temp.set(e.naturalWidth,e.naturalHeight):e instanceof HTMLVideoElement?l.temp.set(e.videoWidth,e.videoHeight):e instanceof SVGElement?l.temp.copy(e.getBoundingClientRect()):"number"==typeof t.displayWidth&&"number"==typeof t.displayHeight?l.temp.set(t.displayWidth,t.displayHeight):"number"==typeof t.width&&"number"==typeof t.height?l.temp.set(t.width,t.height):l.zero},w=e=>{const{width:t,height:i}=y(e),n=d();return n.width=t,n.height=i,(()=>{if(null===c){const e=d().getContext("2d");if(!e)throw new Error("Could not create a 2D canvas context.");c=e}return c})().drawImage(e,0,0,t,i),n.toDataURL()};class x{_handlers=[];_dispatching=!1;_pendingRemoves=null;get count(){return this._handlers.length}has(e){return this._handlers.includes(e)}add(e){return this._handlers.includes(e)||this._handlers.push(e),this}once(e){const t=(...i)=>{this.remove(t),e(...i)};return this._handlers.push(t),this}remove(e){if(this._dispatching)(this._pendingRemoves??=[]).push(e);else{const t=this._handlers.indexOf(e);-1!==t&&g(this._handlers,t,1)}return this}clear(){return this._dispatching?this._pendingRemoves=[...this._handlers]:this._handlers.length=0,this}dispatch(...e){const t=this._handlers.length;if(!t)return this;this._dispatching=!0;for(let i=0;i<t&&!1!==this._handlers[i](...e);i++);if(this._dispatching=!1,null!==this._pendingRemoves){for(const e of this._pendingRemoves){const t=this._handlers.indexOf(e);-1!==t&&g(this._handlers,t,1)}this._pendingRemoves=null}return this}destroy(){this._handlers.length=0,this._pendingRemoves=null}}const v=["mousedown","touchstart","touchend","keydown"];let b=null,S=null,B=!1,C=!1,T=!1;const M=()=>"undefined"!=typeof document,P=()=>b,A=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===b&&(b=new AudioContext),b},E=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===S){const e=A();S=new OfflineAudioContext(1,2,e.sampleRate)}return S},R=()=>{const e=P();"running"!==e?.state||T||(T=!0,(()=>{if(B&&M()){for(const e of v)document.removeEventListener(e,F,!1);B=!1}})(),I.dispatch(e))},k=()=>{R()},D=()=>{const e=A();C||"function"!=typeof e.addEventListener||(e.addEventListener("statechange",k),C=!0),R(),T||(()=>{if(!B&&M()){for(const e of v)document.addEventListener(e,F,!1);B=!0}})()},F=()=>{const e=A();"running"!==e.state?e.resume().then(()=>{R()}):R()};const I=new class extends x{add(e){return super.add(e),D(),this}once(e){return super.once(e),D(),this}},L=()=>{const e=A();return D(),e},U=()=>{const e=P();return null!==e&&"running"===e.state},G=async e=>E().decodeAudioData(e),N=2*Math.PI,O=Math.PI/180,V=180/Math.PI;var z;!function(e){e[e.left=-1]="left",e[e.middle=0]="middle",e[e.right=1]="right"}(z||(z={}));const q=e=>{const t=e%360;return t<0?t+360:t},W=e=>e*O,Y=(e,t,i)=>Math.min(i,Math.max(t,e)),$=(e,t,i)=>(1-i)*e+i*t,X=e=>0!==e&&!(e&e-1),H=(e,t,i)=>e>=Math.min(t,i)&&e<=Math.max(t,i),j=(e,t,i,n)=>{const r=e-i,s=t-n;return Math.sqrt(r*r+s*s)},K=(e,t,i,n,r,s,o,a,h=[],l=20)=>{h.push(e,t);for(let u=1;u<=l;u++){const c=u/l,d=1-c,_=d*d,f=_*d,p=c*c,m=p*c;h.push(f*e+3*_*c*i+3*d*p*r+m*o,f*t+3*_*c*n+3*d*p*s+m*a)}return h},Q=(e,t,i,n,r,s,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push($($(e,i,l),$(i,r,l),l),$($(t,n,l),$(n,s,l),l))}return o},Z={tau:N,clamp:Y,sign:e=>e&&(e<0?-1:1),lerp:$,inRange:H,isPowerOfTwo:X,distance:j,trimRotation:q,degreesToRadians:W,radiansToDegrees:e=>e*V,bezierCurveTo:K,quadraticCurveTo:Q};class J{name;_parent;_volume;_muted;_pan;_effects=[];_setup=null;_scheduledStopId=null;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setupAudio(e)};constructor(e,t={}){if(!e||"string"!=typeof e)throw new Error("AudioBus requires a non-empty string name.");this.name=e,this._parent=t.parent??null,this._volume=Y(t.volume??1,0,2),this._muted=t.muted??!1,this._pan=Y(t.pan??0,-1,1),t.effects&&this._effects.push(...t.effects),U()?this._setupAudio(L()):I.add(this._onAudioContextReady)}get parent(){return this._parent}get volume(){return this._volume}set volume(e){const t=Y(e,0,2);this._volume!==t&&(this._volume=t,this._applyVolume())}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this._applyVolume())}get pan(){return this._pan}set pan(e){const t=Y(e,-1,1);this._pan!==t&&(this._pan=t,this._setup&&this._setup.panNode.pan.setTargetAtTime(t,this._setup.audioContext.currentTime,.01))}get inputNode(){return this._setup?.inputNode??null}addEffect(e){return this._effects.push(e),this._rebuildEffectChain(),this}removeEffect(e){const t=this._effects.indexOf(e);return-1!==t&&(this._effects.splice(t,1),this._rebuildEffectChain()),this}fadeIn(e){if(this._clearScheduledStop(),e<=0||!this._setup)return this;const t=this._setup.audioContext,i=this._setup.outputNode,n=this._muted?0:this._volume;return i.gain.cancelScheduledValues(t.currentTime),i.gain.setValueAtTime(0,t.currentTime),i.gain.linearRampToValueAtTime(n,t.currentTime+e/1e3),this}fadeOut(e,t={}){const i=t.stopAfter??!0;if(this._clearScheduledStop(),e<=0||!this._setup)return i&&(this.muted=!0),this;const n=this._setup.audioContext,r=this._setup.outputNode;return r.gain.cancelScheduledValues(n.currentTime),r.gain.setValueAtTime(r.gain.value,n.currentTime),r.gain.linearRampToValueAtTime(0,n.currentTime+e/1e3),i&&(this._scheduledStopId=setTimeout(()=>{this._scheduledStopId=null,this.muted=!0},e)),this}destroy(){I.remove(this._onAudioContextReady),this._clearScheduledStop();for(const e of this._effects)e.destroy();this._effects.length=0,this._setup&&(this._setup.inputNode.disconnect(),this._setup.outputNode.disconnect(),this._setup.panNode.disconnect(),this._setup=null)}_getInputNode(){return this._setup?.inputNode??null}_getOutputNode(){return this._setup?.outputNode??null}_setupAudio(e){const t=e.createGain(),i=e.createStereoPanner(),n=e.createGain();n.gain.setTargetAtTime(this._muted?0:this._volume,e.currentTime,.01),i.pan.setTargetAtTime(this._pan,e.currentTime,.01),this._setup={audioContext:e,inputNode:t,outputNode:n,panNode:i},this._rebuildEffectChain(),this._connectUpstream()}_connectUpstream(){if(this._setup)if(this._parent){const e=this._parent._getInputNode();e?this._setup.outputNode.connect(e):this._parent.onceSetup(()=>{if(this._setup&&this._parent){const e=this._parent._getInputNode();e&&this._setup.outputNode.connect(e)}})}else this._setup.outputNode.connect(this._setup.audioContext.destination)}onceSetup(e){this._setup?e():I.once(()=>{this._setup&&e()})}_rebuildEffectChain(){if(!this._setup)return;const{inputNode:e,panNode:t}=this._setup;e.disconnect();for(const e of this._effects)e.inputNode.disconnect(),e.outputNode.disconnect();t.disconnect();let i=e;for(const e of this._effects)i.connect(e.inputNode),i=e.outputNode;i.connect(t),t.connect(this._setup.outputNode)}_applyVolume(){if(!this._setup)return;const e=this._muted?0:this._volume;this._setup.outputNode.gain.setTargetAtTime(e,this._setup.audioContext.currentTime,.01)}_clearScheduledStop(){null!==this._scheduledStopId&&(clearTimeout(this._scheduledStopId),this._scheduledStopId=null)}}class ee{get ready(){return Promise.resolve()}}class te{get angle(){return Math.atan2(this.x,this.y)}set angle(e){const t=this.length;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(e){const t=this.angle;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(e){this.length=Math.sqrt(e)}set(e,t=e){return this.x=e,this.y=t,this}equals({x:e,y:t}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t)}add(e,t=e){return this.x+=e,this.y+=t,this}subtract(e,t=e){return this.x-=e,this.y-=t,this}multiply(e,t=e){return this.x*=e,this.y*=t,this}divide(e,t=e){return 0!==e&&0!==t&&(this.x/=e,this.y/=t),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(e){return this.set(this.x*e.a+this.y*e.b+e.x,this.x*e.c+this.y*e.d+e.y)}transformInverse(e){const t=e.a*e.d-e.b*e.c,i=this.x-e.x,n=this.y-e.y;return this.set((e.d*i-e.b*n)/t,(e.a*n-e.c*i)/t)}perp(){return this.set(-this.y,this.x)}rperp(){return this.set(this.y,-this.x)}min(){return Math.min(this.x,this.y)}max(){return Math.max(this.x,this.y)}dot(e,t){return this.x*e+this.y*t}cross(e){return this.x*e.y-this.y*e.x}distanceTo(e){return j(this.x,this.y,e.x,e.y)}}var ie;e.CollisionType=void 0,(ie=e.CollisionType||(e.CollisionType={}))[ie.Point=0]="Point",ie[ie.Line=1]="Line",ie[ie.Rectangle=2]="Rectangle",ie[ie.Circle=3]="Circle",ie[ie.Ellipse=4]="Ellipse",ie[ie.Polygon=5]="Polygon",ie[ie.SceneNode=6]="SceneNode";const ne=1e-10,re=(e,t=e)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(e,t)))),se=({x:e,y:t,rx:i,ry:n})=>{if(i<=0||n<=0)return[];const r=re(i,n),s=2*Math.PI/r,o=[];for(let a=0;a<r;a++){const r=a*s;o.push({x:e+Math.cos(r)*i,y:t+Math.sin(r)*n})}return o},oe=({x:e,y:t},{x:i,y:n},{x:r,y:s})=>e<=Math.max(i,r)+ne&&e>=Math.min(i,r)-ne&&t<=Math.max(n,s)+ne&&t>=Math.min(n,s)-ne,ae=({x:e,y:t},{x:i,y:n},{x:r,y:s})=>{const o=(n-t)*(r-i)-(i-e)*(s-n);return Math.abs(o)<=ne?0:o>0?1:2},he=(e,t,i,n)=>{const r=ae(e,t,i),s=ae(e,t,n),o=ae(i,n,e),a=ae(i,n,t);return r!==s&&o!==a||(!(0!==r||!oe(i,e,t))||(!(0!==s||!oe(n,e,t))||(!(0!==o||!oe(e,i,n))||!(0!==a||!oe(t,i,n)))))},le=({x:e,y:t},i)=>{const n=i.length;if(n<3)return!1;let r=!1;for(let s=0,o=n-1;s<n;o=s++){const n=i[o],a=i[s];a.y>t!=n.y>t&&e<(n.x-a.x)*((t-a.y)/(n.y-a.y))+a.x&&(r=!r)}return r},ue=(e,t)=>{if(0===e.length||0===t.length)return!1;for(let i=0;i<e.length;i++){const n=e[i],r=e[(i+1)%e.length];for(let e=0;e<t.length;e++){const i=t[e],s=t[(e+1)%t.length];if(he(n,r,i,s))return!0}}return le(e[0],t)||le(t[0],e)},ce=({x:e,y:t},{x:i,y:n},{x:r,y:s},o=.1)=>{const a=j(e,t,i,n),h=j(e,t,r,s),l=j(i,n,r,s);return a+h>=l-o&&a+h<=l+o},de=(e,t,i,n)=>{const r=(t.x-e.x)*(n.y-i.y)-(n.x-i.x)*(t.y-e.y);if(Math.abs(r)<=ne)return!1;const s=((n.x-i.x)*(e.y-i.y)-(n.y-i.y)*(e.x-i.x))/r,o=((t.x-e.x)*(e.y-i.y)-(t.y-e.y)*(e.x-i.x))/r;return s>=0&&s<=1&&o>=0&&o<=1},_e=(e,t)=>Math.sqrt(e*e+t*t),fe=(e,t,i,n)=>{const r=i*e+n*t;const s=(o=e)*o+(a=t)*a;var o,a;return r<0?z.left:r>s?z.right:z.middle};let pe=null;class me{min;max;constructor(e=0,t=e){this.min=e,this.max=t}set(e,t){return this.min=e,this.max=t,this}copy(e){return this.set(e.min,e.max)}clone(){return new me(this.min,this.max)}containsInterval(e){return e.min>this.min&&e.max<this.max}includes(e){return e<=this.max&&e>=this.min}overlaps(e){return!(this.min>e.max||e.min>this.max)}getOverlap(e){return this.max<e.max?this.max-e.min:e.max-this.min}destroy(){}static zero=new me(0,0);static get temp(){return null===pe&&(pe=new me),pe}}const ge=(e,t)=>{const i=e.getNormals(),n=t.getNormals(),r=new me,s=new me;for(const n of i)if(e.project(n,r),t.project(n,s),!r.overlaps(s))return!1;for(const i of n)if(e.project(i,r),t.project(i,s),!r.overlaps(s))return!1;return!0},ye=(e,t,i=0)=>(({x:e,y:t},{x:i,y:n},r=0)=>j(e,t,i,n)<=r)(e,t,i),we=(e,t,i=.1)=>ce(e,t.fromPosition,t.toPosition,i),xe=(e,t)=>(({x:e,y:t},{x:i,y:n,width:r,height:s})=>H(e,i,i+r)&&H(t,n,n+s))(e,t),ve=(e,t)=>(({x:e,y:t},{x:i,y:n,radius:r})=>r>0&&j(e,t,i,n)<=r)(e,t),be=(e,t)=>(({x:e,y:t},{x:i,y:n,rx:r,ry:s})=>{if(r<=0||s<=0)return!1;const o=(e-i)/r,a=(t-n)/s;return o*o+a*a<=1})(e,t),Se=(e,t)=>((e,{points:t})=>le(e,t))(e,t),Be=(e,t)=>de(e.fromPosition,e.toPosition,t.fromPosition,t.toPosition),Ce=(e,t)=>{const{x:i,y:n,width:r,height:s}=t,o={x:i,y:n},a={x:i+r,y:n},h={x:i,y:n+s},l={x:i+r,y:n+s};return de(e.fromPosition,e.toPosition,o,h)||de(e.fromPosition,e.toPosition,a,l)||de(e.fromPosition,e.toPosition,o,a)||de(e.fromPosition,e.toPosition,h,l)},Te=(e,t)=>{if(ve(e.fromPosition,t)||ve(e.toPosition,t))return!0;const{fromX:i,fromY:n,toX:r,toY:s}=e,{x:o,y:a,radius:h}=t,l=j(i,n,r,s);if(0===l)return!1;const u=((o-i)*(r-i)+(a-n)*(s-n))/(l*l),c=i+u*(r-i),d=n+u*(s-n);return!!ce({x:c,y:d},e.fromPosition,e.toPosition)&&j(c,d,o,a)<=h},Me=(e,t)=>{const{x:i,y:n,rx:r,ry:s}=t;if(r<=0||s<=0)return!1;const o=(e.fromX-i)/r,a=(e.fromY-n)/s,h=(e.toX-i)/r-o,l=(e.toY-n)/s-a,u=h*h+l*l,c=2*(o*h+a*l),d=o*o+a*a-1;if(d<=0)return!0;if(u<=Number.EPSILON)return!1;const _=c*c-4*u*d;if(_<0)return!1;const f=Math.sqrt(_),p=(-c-f)/(2*u),m=(-c+f)/(2*u);return p>=0&&p<=1||m>=0&&m<=1},Pe=(e,t)=>{const{x:i,y:n,points:r}=t,s=r.length;for(let t=0;t<s;t++){const o=r[t],a=r[(t+1)%s];if(de(e.fromPosition,e.toPosition,{x:o.x+i,y:o.y+n},{x:a.x+i,y:a.y+n}))return!0}return!1},Ae=(e,t)=>(({x:e,y:t,width:i,height:n},{x:r,y:s,width:o,height:a})=>!(r>e+i||s>t+n||e>r+o||t>s+a))(e,t),Ee=({x:e,y:t,width:i,height:n},{x:r,y:s,radius:o})=>{const a=Y(r,e,e+i),h=Y(s,t,t+n);return j(r,s,a,h)<=o},Re=(e,t)=>ue((({x:e,y:t,width:i,height:n})=>[{x:e,y:t},{x:e+i,y:t},{x:e+i,y:t+n},{x:e,y:t+n}])(e),se(t)),ke=(e,t)=>ge(e,t),De=({x:e,y:t,radius:i},{x:n,y:r,radius:s})=>j(e,t,n,r)<=i+s,Fe=(e,t)=>ue((({x:e,y:t,radius:i})=>{if(i<=0)return[];const n=re(i),r=2*Math.PI/n,s=[];for(let o=0;o<n;o++){const n=o*r;s.push({x:e+Math.cos(n)*i,y:t+Math.sin(n)*i})}return s})(e),se(t)),Ie=(e,t,i,n,r,s,o,a,h)=>{if(fe(a,h,r,s)!==z.left)return!1;return fe(n.x,n.y,e-i.x,t-i.y)===z.right&&_e(r,s)>o},Le=(e,t,i,n,r,s,o,a,h)=>{if(fe(a,h,r,s)!==z.right)return!1;return fe(n.x,n.y,e-i.x,t-i.y)===z.left&&_e(r,s)>o},Ue=(e,t,i,n,r)=>{const s=r,o=-n,a=_e(s,o);if(0===a)return!1;const h=(e*s+t*o)/a;return h>0&&Math.abs(h)>i},Ge=({x:e,y:t,radius:i},{x:n,y:r,points:s,edges:o})=>{const a=n-e,h=r-t,l=s.length;for(let e=0;e<l;e++){const t=s[e],n=a-t.x,r=h-t.y,u=0===e?l-1:e-1,c=(e+1)%l,d=o[e];if(Ie(a,h,s[u],o[u],n,r,i,d.x,d.y))return!1;if(Le(a,h,s[c],o[c],n,r,i,d.x,d.y))return!1;if(Ue(n,r,i,d.x,d.y))return!1}return!0},Ne=(e,t)=>ue(se(e),se(t)),Oe=(e,t)=>ue(se(e),(({x:e,y:t,points:i})=>i.map(({x:i,y:n})=>({x:i+e,y:n+t})))(t)),Ve=(e,t)=>ge(e,t),ze=(e,t)=>{if(t.left>e.right||t.top>e.bottom)return null;if(e.left>t.right||e.top>t.bottom)return null;const i=Math.min(e.right,t.right)-Math.max(e.left,t.left),n=Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top),r=e.left+.5*e.width,s=e.top+.5*e.height,o=t.left+.5*t.width,a=t.top+.5*t.height;let h,l,u;i<n?(u=i,h=o<r?-1:1,l=0):(u=n,h=0,l=a<s?-1:1);const c=new it(h,l),d=new it(h*u,l*u);return{shapeA:e,shapeB:t,overlap:u,shapeAinB:t.containsRect(e),shapeBinA:e.containsRect(t),projectionN:c,projectionV:d}},qe=(e,t)=>{const i=t.position.clone().subtract(e.x,e.y),n=i.length,r=e.radius+t.radius-n;if(r<0)return i.destroy(),null;const s=i.clone().normalize(),o=i.multiply(r);return{shapeA:e,shapeB:t,overlap:r,shapeAinB:e.radius<=t.radius&&n<=t.radius-e.radius,shapeBinA:t.radius<=e.radius&&n<=e.radius-t.radius,projectionN:s,projectionV:o}},We=(e,t,i=!1)=>{const n=e.radius,r=Math.max(t.left,Math.min(e.x,t.right)),s=Math.max(t.top,Math.min(e.y,t.bottom)),o=e.x-r,a=e.y-s,h=o*o+a*a;if(h>n*n)return null;const l=Math.sqrt(h),u=n-l,c=t.width/2,d=t.height/2,_=Math.min(c,d),f=Math.max(c,d),p=j(e.x,e.y,t.left+c,t.top+d),m=n<=_&&p<=_-n,g=f<=n&&p<=n-f;let y,w;if(l>0)y=o/l,w=a/l;else{const i=e.x-t.left,n=t.right-e.x,r=e.y-t.top,s=t.bottom-e.y;Math.min(i,n)<Math.min(r,s)?(y=i<n?-1:1,w=0):(y=0,w=r<s?-1:1)}const x=i?-y:y,v=i?-w:w,b=e.position.clone().set(x,v),S=e.position.clone().set(x*u,v*u);return{shapeA:i?t:e,shapeB:i?e:t,overlap:u,shapeAinB:i?g:m,shapeBinA:i?m:g,projectionN:b,projectionV:S}},Ye=(e,t,i=!1)=>{if(!Re(t,e))return null;const n=Math.max(t.left,Math.min(e.x,t.right)),r=Math.max(t.top,Math.min(e.y,t.bottom)),s=e.x-n,o=e.y-r,a=Math.sqrt(s*s+o*o);let h,l,u;if(a>0){h=s/a,l=o/a;u=1/Math.sqrt(h*h/(e.rx*e.rx)+l*l/(e.ry*e.ry))-a}else{const i=e.x-t.left,n=t.right-e.x,r=e.y-t.top,s=t.bottom-e.y,o=Math.min(i,n),a=Math.min(r,s);o<a?(h=i<n?-1:1,l=0,u=o+e.rx):(h=0,l=r<s?-1:1,u=a+e.ry)}const c=i?-h:h,d=i?-l:l,_=e.position.clone().set(c,d),f=e.position.clone().set(c*u,d*u);return{shapeA:i?t:e,shapeB:i?e:t,overlap:u,shapeAinB:!1,shapeBinA:!1,projectionN:_,projectionV:f}},$e=(e,t,i=!1)=>{if(!Fe(t,e))return null;const n=e.x-t.x,r=e.y-t.y,s=Math.sqrt(n*n+r*r);let o,a,h;if(s>0){o=n/s,a=r/s;h=1/Math.sqrt(o*o/(e.rx*e.rx)+a*a/(e.ry*e.ry))+t.radius-s}else e.rx<=e.ry?(o=1,a=0,h=e.rx+t.radius):(o=0,a=1,h=e.ry+t.radius);const l=i?-o:o,u=i?-a:a,c=e.position.clone().set(l,u),d=e.position.clone().set(l*h,u*h);return{shapeA:i?t:e,shapeB:i?e:t,overlap:h,shapeAinB:!1,shapeBinA:!1,projectionN:c,projectionV:d}},Xe=(e,t,i=!1)=>{const n=t.radius,r=e.points,s=t.x-e.x,o=t.y-e.y,a=t.position.clone().set(0,0),h=r.length;let l=!0,u=!0,c=1/0;for(let e=0;e<h;e++){const t=r[e],i=r[(e+1)%h],d=i.x-t.x,_=i.y-t.y,f=s-t.x,p=o-t.y,m=fe(d,_,f,p),g=_e(f,p);if(g>n&&(l=!1),m===z.left){const i=r[0===e?h-1:e-1],l=t.x-i.x,d=t.y-i.y,_=s-i.x,m=o-i.y;if(fe(l,d,_,m)===z.right){if(g>n)return a.destroy(),null;const e=n-g;Math.abs(e)<Math.abs(c)&&(c=e,a.set(f,p).normalize()),u=!1}}else if(m===z.right){const t=r[(e+2)%h],l=t.x-i.x,d=t.y-i.y,_=s-i.x,f=o-i.y,p=_e(_,f);if(fe(l,d,_,f)===z.left){if(p>n)return a.destroy(),null;const e=n-p;Math.abs(e)<Math.abs(c)&&(c=e,a.set(_,f).normalize()),u=!1}}else{const e=_,t=-d,i=_e(e,t),r=0===i?0:(f*e+p*t)/i;if(r>0&&Math.abs(r)>n)return a.destroy(),null;(r>=0||n-r<2*n)&&(u=!1);const s=n-r;Math.abs(s)<Math.abs(c)&&(c=s,a.set(e,t).normalize())}}const d=a.clone().multiply(c);return{shapeA:i?t:e,shapeB:i?e:t,overlap:c,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:d}},He=(e,t)=>{if(!Ne(e,t))return null;const i=e.x-t.x,n=e.y-t.y,r=Math.sqrt(i*i+n*n);let s,o,a;if(r>0){s=i/r,o=n/r;a=Math.sqrt((s*e.rx)**2+(o*e.ry)**2)+Math.sqrt((s*t.rx)**2+(o*t.ry)**2)-r}else e.rx<=e.ry?(s=1,o=0,a=e.rx+t.rx):(s=0,o=1,a=e.ry+t.ry);if(a<=0)return null;const h=e.position.clone().set(s,o),l=e.position.clone().set(s*a,o*a);return{shapeA:e,shapeB:t,overlap:a,shapeAinB:!1,shapeBinA:!1,projectionN:h,projectionV:l}},je=(e,t)=>{const i=e.getNormals(),n=t.getNormals(),r=(i[0]||n[0]).clone(),s=new me,o=new me;let a,h,l,u=1/0,c=!0,d=!0;for(const n of i){if(e.project(n,s),t.project(n,o),!s.overlaps(o))return r.destroy(),null;l=s.getOverlap(o),a=o.containsInterval(s),h=s.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(s.min-o.min),Math.abs(s.max-o.max))),l<u&&(u=l,r.copy(n))}for(const i of n){if(e.project(i,s),t.project(i,o),!s.overlaps(o))return r.destroy(),null;l=s.getOverlap(o),a=o.containsInterval(s),h=s.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(s.min-o.min),Math.abs(s.max-o.max))),l<u&&(u=l,r.copy(i))}const _=r.clone().multiply(u,u);return{shapeA:e,shapeB:t,overlap:u,shapeAinB:c,shapeBinA:d,projectionN:r,projectionV:_}},Ke={intersects:{circleCircle:De,circleEllipse:Fe,circlePoly:Ge,ellipseEllipse:Ne,ellipsePoly:Oe,lineCircle:Te,lineEllipse:Me,lineLine:Be,linePoly:Pe,lineRect:Ce,pointCircle:ve,pointEllipse:be,pointLine:we,pointPoint:ye,pointPoly:Se,pointRect:xe,polyPoly:Ve,rectCircle:Ee,rectEllipse:Re,rectPoly:ke,rectRect:Ae},resolve:{circleCircle:qe,circleRectangle:We,ellipseCircle:$e,ellipseEllipse:He,ellipseRectangle:Ye,polygonCircle:Xe,rectangleRectangle:ze}};class Qe extends te{_x;_y;_owner;_channel;constructor(e,t=0,i=0,n=0){super(),this._x=i,this._y=n,this._owner=e,this._channel=t}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._owner?._onObservableChange(this._channel))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._owner?._onObservableChange(this._channel))}set angle(e){const t=this.length;this.set(Math.cos(e)*t,Math.sin(e)*t)}set length(e){const t=this.angle;this.set(Math.cos(t)*e,Math.sin(t)*e)}set(e=this._x,t=this._y){return this._x===e&&this._y===t||(this._x=e,this._y=t,this._owner?._onObservableChange(this._channel)),this}add(e,t=e){return this.set(this._x+e,this._y+t)}subtract(e,t=e){return this.set(this._x-e,this._y-t)}scale(e,t=e){return this.set(this._x*e,this._y*t)}divide(e,t=e){return 0!==e&&0!==t?this.set(this._x/e,this._y/t):this}clone(){return new Qe(this._owner,this._channel,this._x,this._y)}copy(e){return this.set(e.x,e.y)}destroy(){this._owner=null}}let Ze=null;const Je=new Qe(null);class et{collisionType=e.CollisionType.Rectangle;_position;_size;_normals=null;_normalsDirty=!1;constructor(e=0,t=e,i=0,n=i){this._position=new Qe(this,0,e,t),this._size=new l(i,n)}_onObservableChange(){this._normalsDirty=!0}get position(){return this._position}set position(e){this._position.copy(e)}get x(){return this._position.x}set x(e){this._position.x=e,this._normalsDirty=!0}get y(){return this._position.y}set y(e){this._position.y=e,this._normalsDirty=!0}get size(){return this._size}set size(e){this._size.copy(e),this._normalsDirty=!0}get width(){return this._size.width}set width(e){this._size.width=e,this._normalsDirty=!0}get height(){return this._size.height}set height(e){this._size.height=e,this._normalsDirty=!0}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}setPosition(e,t){return this._position.set(e,t),this._normalsDirty=!0,this}setSize(e,t){return this._size.set(e,t),this._normalsDirty=!0,this}set(e,t,i,n){return this.setPosition(e,t),this.setSize(i,n),this}copy(e){return this.position=e.position,this.size=e.size,this}clone(){return new et(this.x,this.y,this.width,this.height)}equals({x:e,y:t,width:i,height:n}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t||void 0!==i&&this.width!==i||void 0!==n&&this.height!==n)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new it,new it,new it,new it])),this._normalsDirty=!1),this._normals}project(e,t=new me){const i=e.dot(this.left,this.top),n=e.dot(this.right,this.top),r=e.dot(this.right,this.bottom),s=e.dot(this.left,this.bottom);return t.set(Math.min(i,n,r,s),Math.max(i,n,r,s))}transform(e,t=this){const i=Je.set(this.left,this.top).transform(e);let n=i.x,r=i.x,s=i.y,o=i.y;return i.set(this.left,this.bottom).transform(e),n=Math.min(n,i.x),s=Math.min(s,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(e),n=Math.min(n,i.x),s=Math.min(s,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(e),n=Math.min(n,i.x),s=Math.min(s,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),t.set(n,s,r-n,o-s)}contains(e,t){return xe(Je.set(e,t),this)}containsRect(e){return H(e.left,this.left,this.right)&&H(e.right,this.left,this.right)&&H(e.top,this.top,this.bottom)&&H(e.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return t.isAlignedBox?Ae(this,t.getBounds()):ge(this,t);case e.CollisionType.Rectangle:return Ae(this,t);case e.CollisionType.Polygon:return ke(this,t);case e.CollisionType.Circle:return Ee(this,t);case e.CollisionType.Ellipse:return Re(this,t);case e.CollisionType.Line:return Ce(t,this);case e.CollisionType.Point:return xe(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return t.isAlignedBox?ze(this,t.getBounds()):je(this,t);case e.CollisionType.Rectangle:return ze(this,t);case e.CollisionType.Polygon:return je(this,t);case e.CollisionType.Circle:return We(t,this,!0);case e.CollisionType.Ellipse:return Ye(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(e){e[0].set(this.right-this.left,0).rperp().normalize(),e[1].set(0,this.bottom-this.top).rperp().normalize(),e[2].set(this.left-this.right,0).rperp().normalize(),e[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===Ze&&(Ze=new et),Ze}}let tt=null;class it extends te{collisionType=e.CollisionType.Point;x;y;constructor(e=0,t=0){super(),this.x=e,this.y=t}clone(){return new it(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return xe(this,t.getBounds());case e.CollisionType.Rectangle:return xe(this,t);case e.CollisionType.Polygon:return Se(this,t);case e.CollisionType.Circle:return ve(this,t);case e.CollisionType.Ellipse:return be(this,t);case e.CollisionType.Line:return we(this,t);case e.CollisionType.Point:return ye(this,t);default:return!1}}collidesWith(e){return null}getBounds(){return et.temp.set(this.x,this.y,0,0)}contains(e,t){return ye(it.temp.set(e,t),this)}getNormals(){return[this.clone().rperp().normalize()]}project(e,t=new me){return t}destroy(){}static get temp(){return null===tt&&(tt=new it),tt}static zero=new it(0,0);static one=new it(1,1);static add(e,t){return new it(e.x+t.x,e.y+t.y)}static subtract(e,t){return new it(e.x-t.x,e.y-t.y)}static multiply(e,t){return new it(e.x*t.x,e.y*t.y)}static divide(e,t){return new it(e.x/t.x,e.y/t.y)}}const nt={distanceModel:"linear",refDistance:50,maxDistance:1e3,rolloffFactor:1};class rt{_audioContext;_output;_manager;_bus;_volume;_ended=!1;_stopTimer=null;onEnd=new x;_spatialConfig;_panner=null;_position=null;_followNode=null;_spatialRegistered=!1;_effects=[];constructor(e){this._audioContext=e.audioContext,this._output=e.output,this._bus=e.bus,this._manager=e.manager,this._volume=Y(e.volume,0,1),this._spatialConfig={...nt,...e.spatial},this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01),!1!==e.autoConnect&&this._connectOutput()}get ended(){return this._ended}get output(){return this._output}get volume(){return this._volume}set volume(e){this._volume=Y(e,0,1),this._ended||this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01)}get bus(){return this._bus}set bus(e){e!==this._bus&&(this._ended?this._bus=e:(this._tail().disconnect(),this._bus=e,this._connectOutput()))}addEffect(e){return this._ended||(this._effects.push(e),this._rebuildEffectChain()),this}removeEffect(e){const t=this._effects.indexOf(e);return-1!==t&&(this._effects.splice(t,1),e.outputNode.disconnect(),this._rebuildEffectChain()),this}fade(e,t){if(this._ended)return;const i=Y(e,0,1);this._volume=i;const n=this._audioContext,r=this._output;t<=0?r.gain.setTargetAtTime(i,n.currentTime,.01):(r.gain.cancelScheduledValues(n.currentTime),r.gain.setValueAtTime(r.gain.value,n.currentTime),r.gain.linearRampToValueAtTime(i,n.currentTime+t/1e3))}stop(e){if(!this._ended){if(void 0!==e&&e>0){const t=this._audioContext,i=this._output;return i.gain.cancelScheduledValues(t.currentTime),i.gain.setValueAtTime(i.gain.value,t.currentTime),i.gain.linearRampToValueAtTime(0,t.currentTime+e/1e3),this._clearStopTimer(),void(this._stopTimer=setTimeout(()=>{this._stopTimer=null,this._finish()},e))}this._finish()}}get position(){return this._position}set position(e){this._ended||(null!==e?(null===this._position?this._position=new it(e.x,e.y):this._position.set(e.x,e.y),this._ensurePanner(),this._tickSpatial()):null!==this._position&&(this._position.destroy(),this._position=null))}follow(e){this._ended||(this._followNode=e,null!==e&&(this._ensurePanner(),this._tickSpatial()))}_tickSpatial(){if(null===this._panner||this._ended)return;let e,t;if(null!==this._followNode){const i=this._followNode.getGlobalTransform();e=i.x,t=i.y}else{if(null===this._position)return;e=this._position.x,t=this._position.y}const i=this._panner,n=this._audioContext.currentTime;i.positionX?(i.positionX.setValueAtTime(e,n),i.positionY.setValueAtTime(t,n),i.positionZ.setValueAtTime(0,n)):i.setPosition&&i.setPosition(e,t,0)}_tail(){const e=this._effects[this._effects.length-1];return void 0!==e?e.outputNode:this._output}_connectOutput(){this._connectTail(this._tail())}_connectTail(e){const t=this._bus._getInputNode();null===t?(e.connect(this._audioContext.destination),this._bus.onceSetup(()=>{if(this._ended)return;const e=this._bus._getInputNode();if(null!==e){const t=this._tail();t.disconnect(),t.connect(e)}})):e.connect(t)}_rebuildEffectChain(){if(this._ended)return;this._output.disconnect();for(const e of this._effects)e.outputNode.disconnect();let e=this._output;for(const t of this._effects)e.connect(t.inputNode),e=t.outputNode;this._connectTail(e)}_clearStopTimer(){null!==this._stopTimer&&(clearTimeout(this._stopTimer),this._stopTimer=null)}_ensurePanner(){if(null!==this._panner||this._ended)return;const e=this._audioContext.createPanner();e.panningModel="equalpower",e.distanceModel=this._spatialConfig.distanceModel,e.refDistance=this._spatialConfig.refDistance,e.maxDistance=this._spatialConfig.maxDistance,e.rolloffFactor=this._spatialConfig.rolloffFactor,this._routeThroughPanner(e),this._panner=e,this._spatialRegistered||(this._spatialRegistered=!0,this._manager._registerSpatial(this))}_finish(){if(!this._ended){this._ended=!0,this._clearStopTimer(),this._teardownSource(),this._panner?.disconnect(),this._output.disconnect();for(const e of this._effects)e.outputNode.disconnect();this._effects.length=0,null!==this._position&&(this._position.destroy(),this._position=null),this._followNode=null,this.onEnd.dispatch(),this.onEnd.destroy()}}}class st extends rt{_oscillator;_envelopeGain;_envelope;_frequency;_type;_detune;_playbackRate=1;constructor(e){super(e);const t=this._audioContext,i=t.currentTime;this._frequency=e.frequency,this._type=e.type,this._detune=e.detune,this._envelope=e.envelope,this._envelopeGain=t.createGain(),this._envelopeGain.connect(this._output);const n=t.createOscillator();n.type=e.type,n.frequency.value=e.frequency,n.detune.value=e.detune,n.connect(this._envelopeGain),n.onended=()=>this._finish(),this._envelope?this._envelope.trigger(this._envelopeGain.gain,i):this._envelopeGain.gain.value=1,n.start(i),this._oscillator=n}get frequency(){return this._frequency}set frequency(e){this._frequency=e,this._ended||this._oscillator.frequency.setTargetAtTime(e,this._audioContext.currentTime,.01)}get type(){return this._type}set type(e){this._type=e,this._ended||(this._oscillator.type=e)}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e}get detune(){return this._detune}set detune(e){this._detune=e,this._ended||this._oscillator.detune.setTargetAtTime(e,this._audioContext.currentTime,.01)}stop(e){if(!this._ended)if(void 0!==e&&e>0)super.stop(e);else{if(this._envelope){const e=this._audioContext.currentTime;this._envelope.release(this._envelopeGain.gain,e);const t=e+this._envelope.releaseMs/1e3;try{this._oscillator.stop(t)}catch{}return}super.stop()}}_routeThroughPanner(e){this._envelopeGain.disconnect(),this._envelopeGain.connect(e),e.connect(this._output)}_teardownSource(){this._oscillator.onended=null;try{this._oscillator.stop(0)}catch{}this._oscillator.disconnect(),this._envelopeGain.disconnect()}}class ot{onEnd=new x;_bus;_output=null;constructor(e){this._bus=e}get ended(){return!0}get output(){return this._output??=L().createGain()}get volume(){return 0}set volume(e){}get bus(){return this._bus}set bus(e){}fade(e,t){}stop(e){}addEffect(e){return this}removeEffect(e){return this}}class at extends rt{_buffer;_window;_source;_loop;_playbackRate;_detune;_offsetAtStart;_startedAt;constructor(e){super(e),this._buffer=e.buffer,this._window=e.window,this._loop=e.loop,this._playbackRate=e.playbackRate,this._detune=e.detune,this._offsetAtStart=e.offset,this._startedAt=this._audioContext.currentTime,this._source=this._startSource(e.offset)}get duration(){return this._window.end-this._window.base}get time(){if(this._ended)return 0;const e=this.duration,t=(this._audioContext.currentTime-this._startedAt)*this._playbackRate;let i=this._offsetAtStart-this._window.base+t;return this._loop&&e>0&&(i%=e,i<0&&(i+=e)),Y(i,0,e)}set time(e){this.seek(e)}seek(e){if(this._ended)return;const t=this._window.base+Y(e,0,this.duration);this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect(),this._source=this._startSource(t),this._offsetAtStart=t,this._startedAt=this._audioContext.currentTime}get loop(){return this._loop}set loop(e){this._loop===e||this._ended?this._loop=e:(this._loop=e,this._source.loop=e,e&&(this._source.loopStart=this._window.loopStart,this._source.loopEnd=this._window.loopEnd))}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Y(e,.1,20);if(this._playbackRate===t||this._ended)return void(this._playbackRate=t);const i=this.time;this._playbackRate=t,this._offsetAtStart=this._window.base+i,this._startedAt=this._audioContext.currentTime,this._source.playbackRate.setTargetAtTime(t,this._audioContext.currentTime,.01)}get detune(){return this._detune}set detune(e){this._detune=e,this._ended||this._source.detune.setTargetAtTime(e,this._audioContext.currentTime,.01)}_routeThroughPanner(e){this._source.disconnect(),this._source.connect(e),e.connect(this._output)}_teardownSource(){this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect()}_startSource(e){const t=this._audioContext.createBufferSource();t.buffer=this._buffer,t.loop=this._loop,t.playbackRate.value=this._playbackRate,t.detune.value=this._detune,this._loop&&(t.loopStart=this._window.loopStart,t.loopEnd=this._window.loopEnd),t.connect(this._panner??this._output),t.onended=()=>this._finish();const i=this._loop?void 0:this._window.end-e;return!this._loop&&void 0!==i&&i>0?t.start(0,e,i):t.start(0,e),t}}var ht;e.SoundPoolStrategy=void 0,(ht=e.SoundPoolStrategy||(e.SoundPoolStrategy={})).FirstInFirstOut="fifo",ht.LeastRecentlyUsed="lru",ht.LowestPriority="priority";class lt{_audioBuffer;_sprites=new Map;_clipStart=0;_clipEnd=0;volume;loop;playbackRate;muted;_poolSize;_poolStrategy;_priority;_position=null;_velocity=null;_distanceModel="linear";_refDistance=50;_maxDistance=1e3;_rolloffFactor=1;_activeVoices=[];get audioBuffer(){return this._audioBuffer}get duration(){return this._clipEnd-this._clipStart}get poolSize(){return this._poolSize}set poolSize(e){this.setPoolSize(e)}get poolStrategy(){return this._poolStrategy}set poolStrategy(e){this._poolStrategy=e}get priority(){return this._priority}set priority(e){this._priority=e}get position(){return this._position}set position(e){null!==e?null===this._position?this._position=new it(e.x,e.y):this._position.set(e.x,e.y):null!==this._position&&(this._position.destroy(),this._position=null)}get velocity(){return this._velocity}set velocity(e){null===e?null!==this._velocity&&(this._velocity.destroy(),this._velocity=null):null===this._velocity?this._velocity=new it(e.x,e.y):this._velocity.set(e.x,e.y)}get distanceModel(){return this._distanceModel}set distanceModel(e){this._distanceModel=e}get refDistance(){return this._refDistance}set refDistance(e){this._refDistance=Math.max(0,e)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance=Math.max(0,e)}get rolloffFactor(){return this._rolloffFactor}set rolloffFactor(e){this._rolloffFactor=Math.max(0,e)}constructor(t,i={}){this._audioBuffer=t,this._clipEnd=t.duration;const{poolSize:n,poolStrategy:r,priority:s,sprites:o,volume:a,loop:h,playbackRate:l,muted:u,distanceModel:c,refDistance:d,maxDistance:_,rolloffFactor:f}=i;this.volume=Y(a??1,0,1),this.loop=h??!1,this.playbackRate=Y(l??1,.1,20),this.muted=u??!1,this._poolSize=Math.max(1,Math.floor(n??8)),this._poolStrategy=r??e.SoundPoolStrategy.FirstInFirstOut,this._priority=s??0,void 0!==c&&(this._distanceModel=c),void 0!==d&&(this._refDistance=Math.max(0,d)),void 0!==_&&(this._maxDistance=Math.max(0,_)),void 0!==f&&(this._rolloffFactor=Math.max(0,f)),o&&this.setSprites(o)}setPoolSize(e){const t=Math.max(1,Math.floor(e));return this._poolSize===t||(this._poolSize=t,this._trimActiveVoices()),this}setSprites(e){this._sprites.clear();for(const[t,i]of Object.entries(e))this.defineSprite(t,i);return this}defineSprite(e,t){if(0===e.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=t.start,n=t.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${e}" has an invalid start time (${i}).`);if(!Number.isFinite(n)||n<=i)throw new Error(`Sound sprite "${e}" has an invalid end time (${n}).`);if(n>this.duration)throw new Error(`Sound sprite "${e}" ends at ${n}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(e,{start:i,end:n,loop:t.loop??!1}),this}hasSprite(e){return this._sprites.has(e)}removeSprite(e){return this._sprites.delete(e),this}clip(e,t){const i=Y(e,0,this._audioBuffer.duration),n=Y(i+t,i,this._audioBuffer.duration),r=new lt(this._audioBuffer,{volume:this.volume,loop:this.loop,playbackRate:this.playbackRate,muted:this.muted,poolSize:this._poolSize,poolStrategy:this._poolStrategy,priority:this._priority,distanceModel:this._distanceModel,refDistance:this._refDistance,maxDistance:this._maxDistance,rolloffFactor:this._rolloffFactor});return r._clipStart=i,r._clipEnd=n,r}_createVoice(e,t){const i=this._clipStart+Math.max(0,t.time??0);return i>=this._clipEnd?new ot(t.bus??e.sound):this._buildVoice(e,t,i,{base:this._clipStart,end:this._clipEnd,loopStart:this._clipStart,loopEnd:this._clipEnd})}_createSpriteVoice(e,t,i={}){const n=this._sprites.get(t);if(!n)throw new Error(`Sound sprite "${t}" is not defined.`);const r=Math.max(0,i.time??0),s=n.start+r;if(s>=n.end)throw new Error(`Sound sprite "${t}" offset (${r}s) exceeds clip duration (${n.end-n.start}s).`);const o=i.loop??n.loop;return this._buildVoice(e,{...i,loop:o},s,{base:n.start,end:n.end,loopStart:n.start,loopEnd:n.end})}_buildVoice(e,t,i,n){const r=t.loop??this.loop,s=Y(t.playbackRate??this.playbackRate,.1,20),o=t.detune??0,a=Y(t.muted?0:t.volume??(this.muted?0:this.volume),0,1),h=t.bus??e.sound;if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const e=this._pickEvictionVictim(),t=this._activeVoices[e];t&&(this._activeVoices.splice(e,1),t.voice.stop())}const l=L(),u=l.createGain(),c=new at({audioContext:l,output:u,bus:h,manager:e,volume:a,spatial:{distanceModel:this._distanceModel,refDistance:this._refDistance,maxDistance:this._maxDistance,rolloffFactor:this._rolloffFactor},buffer:this._audioBuffer,loop:r,playbackRate:s,detune:o,offset:i,window:n});null!==this._position&&(c.position=this._position);const d={voice:c,startedAt:l.currentTime,effectiveDuration:r?1/0:n.end-i};return c.onEnd.add(()=>{const e=this._activeVoices.indexOf(d);-1!==e&&this._activeVoices.splice(e,1)}),this._activeVoices.push(d),c}_stopAllVoices(){const e=[...this._activeVoices];this._activeVoices.length=0;for(const t of e)t.voice.stop()}destroy(){this._stopAllVoices(),this._sprites.clear(),null!==this._position&&(this._position.destroy(),this._position=null),null!==this._velocity&&(this._velocity.destroy(),this._velocity=null)}_pruneEndedVoices(){for(let e=this._activeVoices.length-1;e>=0;e--)!0===this._activeVoices[e]?.voice.ended&&this._activeVoices.splice(e,1)}_pickEvictionVictim(){switch(this._poolStrategy){case e.SoundPoolStrategy.LeastRecentlyUsed:return this._pickClosestToEnd();case e.SoundPoolStrategy.LowestPriority:case e.SoundPoolStrategy.FirstInFirstOut:default:return 0}}_pickClosestToEnd(){const e=U()?L().currentTime:0;let t=1/0,i=0;for(let n=0;n<this._activeVoices.length;n++){const r=this._activeVoices[n];if(void 0===r)continue;const s=e-r.startedAt,o=r.effectiveDuration-s;o<t&&(t=o,i=n)}return i}_trimActiveVoices(){for(;this._activeVoices.length>this._poolSize;){const e=this._pickEvictionVictim(),t=this._activeVoices[e];if(!t)break;this._activeVoices.splice(e,1),t.voice.stop()}}}class ut{frequency;type;detune;envelope;volume;muted;_poolSize;_poolStrategy;priority;_activeVoices=[];get poolSize(){return this._poolSize}set poolSize(e){this._poolSize=Math.max(1,Math.floor(e))}get poolStrategy(){return this._poolStrategy}set poolStrategy(e){this._poolStrategy=e}constructor(t={}){this.frequency=t.frequency??440,this.type=t.type??"sine",this.detune=t.detune??0,this.envelope=t.envelope??null,this.volume=Y(t.volume??1,0,1),this.muted=t.muted??!1,this._poolSize=Math.max(1,Math.floor(t.poolSize??8)),this._poolStrategy=t.poolStrategy??e.SoundPoolStrategy.FirstInFirstOut,this.priority=t.priority??0}setNote(e){return this.frequency=ut.midiToFrequency(e),this}static midiToFrequency(e){return 440*Math.pow(2,(e-69)/12)}_createVoice(e,t){const i=t.bus??e.sound;if(!U())return new ot(i);if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const e=this._pickEvictionVictim(),t=this._activeVoices[e];t&&(this._activeVoices.splice(e,1),t.voice.stop())}const n=L(),r=n.createGain(),s=t.detune??this.detune,o=Y(t.muted?0:t.volume??(this.muted?0:this.volume),0,1),a=new st({audioContext:n,output:r,bus:i,manager:e,volume:o,frequency:this.frequency,type:this.type,detune:s,envelope:this.envelope}),h={voice:a,startedAt:n.currentTime};return a.onEnd.add(()=>{const e=this._activeVoices.indexOf(h);-1!==e&&this._activeVoices.splice(e,1)}),this._activeVoices.push(h),a}stopAll(){const e=[...this._activeVoices];this._activeVoices.length=0;for(const t of e)t.voice.stop();return this}destroy(){this.stopAll()}_pruneEndedVoices(){for(let e=this._activeVoices.length-1;e>=0;e--)!0===this._activeVoices[e]?.voice.ended&&this._activeVoices.splice(e,1)}_pickEvictionVictim(){if(this._poolStrategy===e.SoundPoolStrategy.LeastRecentlyUsed){let e=0,t=1/0;for(let i=0;i<this._activeVoices.length;i++){const n=this._activeVoices[i];void 0!==n&&n.startedAt<t&&(t=n.startedAt,e=i)}return e}return 0}}class ct{_stream;constructor(e){this._stream=e}get stream(){return this._stream}static async open(e={}){if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("AudioInput.open: getUserMedia is not available in this environment.");const t={};void 0!==e.deviceId&&(t.deviceId=e.deviceId),void 0!==e.echoCancellation&&(t.echoCancellation=e.echoCancellation),void 0!==e.noiseSuppression&&(t.noiseSuppression=e.noiseSuppression),void 0!==e.autoGainControl&&(t.autoGainControl=e.autoGainControl);const i=await navigator.mediaDevices.getUserMedia({audio:!(Object.keys(t).length>0)||t});return new ct(i)}close(){for(const e of this._stream.getTracks())e.stop()}}class dt{position=new it(0,0);velocity=new it(0,0);target=null;_audioListener=null;_ctx=null;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(){U()?this._setup(L()):I.add(this._onAudioContextReady)}_tick(){if(null!==this.target&&this._readTargetPosition(),null!==this._audioListener&&null!==this._ctx){const e=this._ctx.currentTime,t=this._audioListener;t.positionX&&t.positionY&&t.positionZ?(t.positionX.setValueAtTime(this.position.x,e),t.positionY.setValueAtTime(this.position.y,e),t.positionZ.setValueAtTime(0,e)):t.setPosition&&t.setPosition(this.position.x,this.position.y,0)}}destroy(){I.remove(this._onAudioContextReady),this.position.destroy(),this.velocity.destroy(),this.target=null,this._audioListener=null,this._ctx=null}_readTargetPosition(){const e=this.target;if(null===e)return;const t=e;if("function"==typeof t.getGlobalTransform){const e=t.getGlobalTransform();return void this.position.set(e.x,e.y)}const i=e;if(void 0!==i.center&&"object"==typeof i.center)return void this.position.set(i.center.x,i.center.y);const n=e;this.position.set(n.x,n.y)}_setup(e){this._ctx=e,this._audioListener=e.listener;const t=e.currentTime,i=e.listener;i.forwardX&&i.forwardY&&i.forwardZ&&i.upX&&i.upY&&i.upZ?(i.forwardX.setValueAtTime(0,t),i.forwardY.setValueAtTime(0,t),i.forwardZ.setValueAtTime(-1,t),i.upX.setValueAtTime(0,t),i.upY.setValueAtTime(1,t),i.upZ.setValueAtTime(0,t)):i.setOrientation&&i.setOrientation(0,0,-1,0,1,0)}}class _t extends rt{_sourceNode;_stream;constructor(e){super({...e,autoConnect:!1}),this._sourceNode=e.sourceNode,this._stream=e.stream,this._sourceNode.connect(this._output)}routeTo(e){return this._ended||(this._tail().disconnect(),this._bus=e,this._connectOutput()),this}async record(e){const t=new MediaRecorder(this._stream),i=[];return t.addEventListener("dataavailable",e=>{e.data.size>0&&i.push(e.data)}),new Promise((n,r)=>{t.addEventListener("stop",()=>{(async()=>{try{const e=new Blob(i,{type:t.mimeType||"audio/webm"}),r=await G(await e.arrayBuffer());n(new lt(r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}})()}),t.addEventListener("error",()=>r(new Error("Recording failed."))),t.start(),setTimeout(()=>{"inactive"!==t.state&&t.stop()},Math.max(0,e))})}_routeThroughPanner(e){this._sourceNode.disconnect(),this._sourceNode.connect(e),e.connect(this._output)}_teardownSource(){this._sourceNode.disconnect()}}class ft{order=300;master;music;sound;listener;onUnlock=new x;_registered=new Map;_spatial=new Set;_muteOnHidden=!1;constructor(){this.master=new J("master",{parent:null}),this.music=new J("music",{parent:this.master}),this.sound=new J("sound",{parent:this.master}),this.listener=new dt,this._registered.set("master",this.master),this._registered.set("music",this.music),this._registered.set("sound",this.sound),I.add(()=>{this.onUnlock.dispatch()})}get muteOnHidden(){return this._muteOnHidden}set muteOnHidden(e){this._muteOnHidden=e}get locked(){return!U()}play(e,t){return e._createVoice(this,t??{})}open(e){const t=L(),i=t.createMediaStreamSource(e.stream),n=t.createGain();return new _t({audioContext:t,output:n,bus:this.sound,manager:this,volume:1,sourceNode:i,stream:e.stream})}update(e){this.listener._tick();for(const e of this._spatial)e.ended?this._spatial.delete(e):e._tickSpatial()}_registerSpatial(e){this._spatial.add(e)}_applyVisibility(e){this._muteOnHidden&&(this.master.muted=!e)}registerBus(e){if(this._registered.has(e.name))throw new Error(`Audio bus "${e.name}" is already registered.`);return this._registered.set(e.name,e),this}unregisterBus(e){if(e===this.master||e===this.music||e===this.sound)throw new Error(`Cannot unregister built-in bus "${e.name}".`);return this._registered.get(e.name)!==e||(this._registered.delete(e.name),e.destroy()),this}getBus(e){const t=this._registered.get(e);if(!t)throw new Error(`Audio bus "${e}" is not registered.`);return t}hasBus(e){return this._registered.has(e)}destroy(){this.listener.destroy(),this._spatial.clear();for(const e of this._registered.values())e.destroy();this._registered.clear()}}class pt extends rt{_element;_sourceNode;_detune=0;_onEnded=()=>this._finish();_unlockHandler=null;constructor(e){super(e),this._element=e.element,this._sourceNode=e.sourceNode,this._sourceNode.connect(this._output),this._element.loop=e.loop,this._element.playbackRate=e.playbackRate,void 0!==e.startTime&&(this._element.currentTime=Math.max(0,e.startTime)),this._element.addEventListener("ended",this._onEnded),this._startPlayback()}get duration(){return this._element.duration}get time(){return this._element.currentTime}set time(e){this.seek(e)}seek(e){this._ended||(this._element.currentTime=Math.max(0,e))}pause(){this._ended||this._element.pause()}resume(){this._ended||this._element.play()}get paused(){return this._element.paused}get loop(){return this._element.loop}set loop(e){this._element.loop=e}get playbackRate(){return this._element.playbackRate}set playbackRate(e){this._element.playbackRate=Y(e,.1,20)}get detune(){return this._detune}set detune(e){this._detune=e}_routeThroughPanner(e){this._sourceNode.disconnect(),this._sourceNode.connect(e),e.connect(this._output)}_teardownSource(){this._element.removeEventListener("ended",this._onEnded),this._clearUnlockHandler(),this._element.pause(),this._sourceNode.disconnect()}_startPlayback(){U()?this._element.play():(this._unlockHandler=()=>{this._clearUnlockHandler(),this._ended||this._element.play()},I.add(this._unlockHandler))}_clearUnlockHandler(){null!==this._unlockHandler&&(I.remove(this._unlockHandler),this._unlockHandler=null)}}class mt{_audioElement;volume;loop;playbackRate;muted;_sourceNode=null;_activeVoice=null;constructor(e,t){this._audioElement=e,this.volume=Y(t?.volume??1,0,1),this.loop=t?.loop??!1,this.playbackRate=Y(t?.playbackRate??1,.1,20),this.muted=t?.muted??!1,void 0!==t?.time&&(this._audioElement.currentTime=Math.max(0,t.time))}get audioElement(){return this._audioElement}get duration(){return this._audioElement.duration}_createVoice(e,t){const i=t.bus??e.music,n=L();null===this._activeVoice||this._activeVoice.ended||this._activeVoice.stop(),null===this._sourceNode?this._sourceNode=n.createMediaElementSource(this._audioElement):this._sourceNode.disconnect();const r=n.createGain(),s=t.loop??this.loop,o=Y(t.playbackRate??this.playbackRate,.1,20),a=Y(t.muted?0:t.volume??(this.muted?0:this.volume),0,1),h=new pt({audioContext:n,output:r,bus:i,manager:e,volume:a,element:this._audioElement,sourceNode:this._sourceNode,loop:s,playbackRate:o,...void 0!==t.time&&{startTime:t.time}});return this._activeVoice=h,h.onEnd.add(()=>{this._activeVoice===h&&(this._activeVoice=null)}),h}destroy(){null!==this._activeVoice&&(this._activeVoice.stop(),this._activeVoice=null),null!==this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=null)}}const gt=new WeakMap,yt=new WeakMap;async function wt(e,t,i){let n=gt.get(e);if(n||(n=new Set,gt.set(e,n)),n.has(t))return;let r=yt.get(e);r||(r=new Map,yt.set(e,r));const s=r.get(t);if(s)return s;const o=new Blob([i],{type:"application/javascript"}),a=URL.createObjectURL(o),h=e.audioWorklet.addModule(a).finally(()=>{URL.revokeObjectURL(a)}).then(()=>{n.add(t),r.delete(t)}).catch(e=>{throw r.delete(t),e});return r.set(t,h),h}const xt=Object.freeze({extensions:Object.freeze([]),renderers:Object.freeze([]),assets:Object.freeze([]),serializers:Object.freeze([])});function vt(e){if(0===e.length)return xt;const t=new Map,i=new Set,n=new Set,r=[],s=[];function o(e){const a=t.get(e.id);if(void 0!==a&&a!==e)throw new Error(`Extension "${e.id}" was provided by multiple descriptor objects.`);if(void 0===a&&t.set(e.id,e),!n.has(e)){if(i.has(e)){const t=[...r.slice(r.indexOf(e)),e].map(e=>e.id).join(" → ");throw new Error(`Extension dependency cycle detected: ${t}`)}i.add(e),r.push(e);for(const t of e.dependencies??[])o(t);r.pop(),i.delete(e),n.add(e),s.push(e)}}for(const t of e)o(t);const a=[],h=[],l=[];for(const e of s){if(e.renderers)for(const t of e.renderers)a.push(t);if(e.assets)for(const t of e.assets)h.push(t);if(e.serializers)for(const t of e.serializers)l.push(t)}return Object.freeze({extensions:Object.freeze(s),renderers:Object.freeze(a),assets:Object.freeze(h),serializers:Object.freeze(l)})}let bt,St=new Map;function Bt(e,t){const i=new Set;for(const n of t){if(0===n.targets.length)throw new Error("A RendererBinding must declare at least one target.");for(const e of n.targets){if(i.has(e))throw new Error(`Two bindings target the same drawable type ${e.name}. Remove one of the conflicting bindings.`);i.add(e)}const t=n.create(e);void 0!==t&&e.rendererRegistry.bindRenderer(n.targets,t)}}const Ct=e=>0|Y(e,0,255);class Tt{_r;_g;_b;_a;_rgba=null;_array=null;constructor(e=0,t=0,i=0,n=1){this._r=Ct(e),this._g=Ct(t),this._b=Ct(i),this._a=Y(n,0,1)}get r(){return this._r}set r(e){this._r=Ct(e),this._rgba=null}get g(){return this._g}set g(e){this._g=Ct(e),this._rgba=null}get b(){return this._b}set b(e){this._b=Ct(e),this._rgba=null}get a(){return this._a}set a(e){this._a=Y(e,0,1),this._rgba=null}set(e=this._r,t=this._g,i=this._b,n=this._a){return this._r=Ct(e),this._g=Ct(t),this._b=Ct(i),this._a=Y(n,0,1),this._rgba=null,this}copy(e){return this.set(e.r,e.g,e.b,e.a)}clone(){return new Tt(this._r,this._g,this._b,this._a)}equals({r:e,g:t,b:i,a:n}={}){return!(void 0!==e&&this.r!==e||void 0!==t&&this.g!==t||void 0!==i&&this.b!==i||void 0!==n&&this.a!==n)}toArray(e=!1){return this._array||(this._array=new Float32Array(4)),e?(this._array[0]=this._r/255,this._array[1]=this._g/255,this._array[2]=this._b/255,this._array[3]=this._a):(this._array[0]=this._r,this._array[1]=this._g,this._array[2]=this._b,this._array[3]=this._a),this._array}toString(e=!0){return`${e?"#":""}${(1<<24|this._r<<16|this._g<<8|this._b).toString(16).substr(1)}`}toRgba(){return null===this._rgba&&(this._rgba=(255*this._a<<24|this._b<<16|this._g<<8|this._r)>>>0),this._rgba}destroy(){this._array&&(this._array=null)}static aliceBlue=new Tt(240,248,255,1);static antiqueWhite=new Tt(250,235,215,1);static aqua=new Tt(0,255,255,1);static aquamarine=new Tt(127,255,212,1);static azure=new Tt(240,255,255,1);static beige=new Tt(245,245,220,1);static bisque=new Tt(255,228,196,1);static black=new Tt(0,0,0,1);static blanchedAlmond=new Tt(255,235,205,1);static blue=new Tt(0,0,255,1);static blueViolet=new Tt(138,43,226,1);static brown=new Tt(165,42,42,1);static burlyWood=new Tt(222,184,135,1);static cadetBlue=new Tt(95,158,160,1);static chartreuse=new Tt(127,255,0,1);static chocolate=new Tt(210,105,30,1);static coral=new Tt(255,127,80,1);static cornflowerBlue=new Tt(100,149,237,1);static cornsilk=new Tt(255,248,220,1);static crimson=new Tt(220,20,60,1);static cyan=new Tt(0,255,255,1);static darkBlue=new Tt(0,0,139,1);static darkCyan=new Tt(0,139,139,1);static darkGoldenrod=new Tt(184,134,11,1);static darkGray=new Tt(169,169,169,1);static darkGreen=new Tt(0,100,0,1);static darkKhaki=new Tt(189,183,107,1);static darkMagenta=new Tt(139,0,139,1);static darkOliveGreen=new Tt(85,107,47,1);static darkOrange=new Tt(255,140,0,1);static darkOrchid=new Tt(153,50,204,1);static darkRed=new Tt(139,0,0,1);static darkSalmon=new Tt(233,150,122,1);static darkSeaGreen=new Tt(143,188,139,1);static darkSlateBlue=new Tt(72,61,139,1);static darkSlateGray=new Tt(47,79,79,1);static darkTurquoise=new Tt(0,206,209,1);static darkViolet=new Tt(148,0,211,1);static deepPink=new Tt(255,20,147,1);static deepSkyBlue=new Tt(0,191,255,1);static dimGray=new Tt(105,105,105,1);static dodgerBlue=new Tt(30,144,255,1);static firebrick=new Tt(178,34,34,1);static floralWhite=new Tt(255,250,240,1);static forestGreen=new Tt(34,139,34,1);static fuchsia=new Tt(255,0,255,1);static gainsboro=new Tt(220,220,220,1);static ghostWhite=new Tt(248,248,255,1);static gold=new Tt(255,215,0,1);static goldenrod=new Tt(218,165,32,1);static gray=new Tt(128,128,128,1);static green=new Tt(0,128,0,1);static greenYellow=new Tt(173,255,47,1);static honeydew=new Tt(240,255,240,1);static hotPink=new Tt(255,105,180,1);static indianRed=new Tt(205,92,92,1);static indigo=new Tt(75,0,130,1);static ivory=new Tt(255,255,240,1);static khaki=new Tt(240,230,140,1);static lavender=new Tt(230,230,250,1);static lavenderBlush=new Tt(255,240,245,1);static lawnGreen=new Tt(124,252,0,1);static lemonChiffon=new Tt(255,250,205,1);static lightBlue=new Tt(173,216,230,1);static lightCoral=new Tt(240,128,128,1);static lightCyan=new Tt(224,255,255,1);static lightGoldenrodYellow=new Tt(250,250,210,1);static lightGray=new Tt(211,211,211,1);static lightGreen=new Tt(144,238,144,1);static lightPink=new Tt(255,182,193,1);static lightSalmon=new Tt(255,160,122,1);static lightSeaGreen=new Tt(32,178,170,1);static lightSkyBlue=new Tt(135,206,250,1);static lightSlateGray=new Tt(119,136,153,1);static lightSteelBlue=new Tt(176,196,222,1);static lightYellow=new Tt(255,255,224,1);static lime=new Tt(0,255,0,1);static limeGreen=new Tt(50,205,50,1);static linen=new Tt(250,240,230,1);static magenta=new Tt(255,0,255,1);static maroon=new Tt(128,0,0,1);static mediumAquamarine=new Tt(102,205,170,1);static mediumBlue=new Tt(0,0,205,1);static mediumOrchid=new Tt(186,85,211,1);static mediumPurple=new Tt(147,112,219,1);static mediumSeaGreen=new Tt(60,179,113,1);static mediumSlateBlue=new Tt(123,104,238,1);static mediumSpringGreen=new Tt(0,250,154,1);static mediumTurquoise=new Tt(72,209,204,1);static mediumVioletRed=new Tt(199,21,133,1);static midnightBlue=new Tt(25,25,112,1);static mintCream=new Tt(245,255,250,1);static mistyRose=new Tt(255,228,225,1);static moccasin=new Tt(255,228,181,1);static navajoWhite=new Tt(255,222,173,1);static navy=new Tt(0,0,128,1);static oldLace=new Tt(253,245,230,1);static olive=new Tt(128,128,0,1);static oliveDrab=new Tt(107,142,35,1);static orange=new Tt(255,165,0,1);static orangeRed=new Tt(255,69,0,1);static orchid=new Tt(218,112,214,1);static paleGoldenrod=new Tt(238,232,170,1);static paleGreen=new Tt(152,251,152,1);static paleTurquoise=new Tt(175,238,238,1);static paleVioletRed=new Tt(219,112,147,1);static papayaWhip=new Tt(255,239,213,1);static peachPuff=new Tt(255,218,185,1);static peru=new Tt(205,133,63,1);static pink=new Tt(255,192,203,1);static plum=new Tt(221,160,221,1);static powderBlue=new Tt(176,224,230,1);static purple=new Tt(128,0,128,1);static red=new Tt(255,0,0,1);static rosyBrown=new Tt(188,143,143,1);static royalBlue=new Tt(65,105,225,1);static saddleBrown=new Tt(139,69,19,1);static salmon=new Tt(250,128,114,1);static sandyBrown=new Tt(244,164,96,1);static seaGreen=new Tt(46,139,87,1);static seaShell=new Tt(255,245,238,1);static sienna=new Tt(160,82,45,1);static silver=new Tt(192,192,192,1);static skyBlue=new Tt(135,206,235,1);static slateBlue=new Tt(106,90,205,1);static slateGray=new Tt(112,128,144,1);static snow=new Tt(255,250,250,1);static springGreen=new Tt(0,255,127,1);static steelBlue=new Tt(70,130,180,1);static tan=new Tt(210,180,140,1);static teal=new Tt(0,128,128,1);static thistle=new Tt(216,191,216,1);static tomato=new Tt(255,99,71,1);static transparentBlack=new Tt(0,0,0,0);static transparentWhite=new Tt(255,255,255,0);static turquoise=new Tt(64,224,208,1);static violet=new Tt(238,130,238,1);static wheat=new Tt(245,222,179,1);static white=new Tt(255,255,255,1);static whiteSmoke=new Tt(245,245,245,1);static yellow=new Tt(255,255,0,1);static yellowGreen=new Tt(154,205,50,1)}class Mt{_value=0;get value(){return this._value}constructor(...e){e.length&&this.push(...e)}push(...e){for(const t of e)this._value|=t;return this}pop(e){const t=this.has(e);return this.remove(e),t}remove(...e){for(const t of e)this._value&=~t;return this}has(...e){return e.some(e=>0!==(this._value&e))}clear(){return this._value=0,this}destroy(){this.clear()}}let Pt=null;class At{a;b;x;c;d;y;e;f;z;_array=null;constructor(e=1,t=0,i=0,n=0,r=1,s=0,o=0,a=0,h=1){this.a=e,this.b=t,this.x=i,this.c=n,this.d=r,this.y=s,this.e=o,this.f=a,this.z=h}set(e=this.a,t=this.b,i=this.x,n=this.c,r=this.d,s=this.y,o=this.e,a=this.f,h=this.z){return this.a=e,this.b=t,this.x=i,this.c=n,this.d=r,this.y=s,this.e=o,this.f=a,this.z=h,this}copy(e){return this.a=e.a,this.b=e.b,this.x=e.x,this.c=e.c,this.d=e.d,this.y=e.y,this.e=e.e,this.f=e.f,this.z=e.z,this}clone(){return new At(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:e,b:t,x:i,c:n,d:r,y:s,e:o,f:a,z:h}={}){return!(void 0!==e&&this.a!==e||void 0!==t&&this.b!==t||void 0!==i&&this.x!==i||void 0!==n&&this.c!==n||void 0!==r&&this.d!==r||void 0!==s&&this.y!==s||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(e){return this.set(this.a*e.a+this.c*e.b+this.e*e.x,this.b*e.a+this.d*e.b+this.f*e.x,this.x*e.a+this.y*e.b+this.z*e.x,this.a*e.c+this.c*e.d+this.e*e.y,this.b*e.c+this.d*e.d+this.f*e.y,this.x*e.c+this.y*e.d+this.z*e.y,this.a*e.e+this.c*e.f+this.e*e.z,this.b*e.e+this.d*e.f+this.f*e.z,this.x*e.e+this.y*e.f+this.z*e.z)}getInverse(e=this){const t=this.a*(this.z*this.d-this.y*this.f)-this.b*(this.z*this.c-this.y*this.e)+this.x*(this.f*this.c-this.d*this.e);return 0===t?e.copy(At.identity):e.set((this.d*this.z-this.y*this.f)/t,(this.x*this.f-this.b*this.z)/t,(this.b*this.y-this.x*this.d)/t,(this.y*this.e-this.c*this.z)/t,(this.a*this.z-this.x*this.e)/t,(this.x*this.c-this.a*this.y)/t,(this.c*this.f-this.d*this.e)/t,(this.b*this.e-this.a*this.f)/t,(this.a*this.d-this.b*this.c)/t)}translate(e,t=e){return this.combine(At.temp.set(1,0,e,0,1,t,0,0,1))}rotate(e,t=0,i=t){const n=W(e),r=Math.cos(n),s=Math.sin(n);return this.combine(At.temp.set(r,-s,t*(1-r)+i*s,s,r,i*(1-r)-t*s,0,0,1))}scale(e,t=e,i=0,n=i){return this.combine(At.temp.set(e,0,i*(1-e),0,t,n*(1-t),0,0,1))}toArray(e=!1){const t=this._array||(this._array=new Float32Array(9));return e?(t[0]=this.a,t[1]=this.b,t[2]=this.x,t[3]=this.c,t[4]=this.d,t[5]=this.y,t[6]=this.e,t[7]=this.f,t[8]=this.z):(t[0]=this.a,t[1]=this.c,t[2]=this.e,t[3]=this.b,t[4]=this.d,t[5]=this.f,t[6]=this.x,t[7]=this.y,t[8]=this.z),t}destroy(){this._array&&(this._array=null)}static identity=new At(1,0,0,0,1,0,0,0,1);static get temp(){return null===Pt&&(Pt=new At),Pt}}let Et=null;class Rt{collisionType=e.CollisionType.Polygon;_position;_points=[];_edges=[];_cachedNormals=null;_normalsDirty=!0;constructor(e=[],t=0,i=0){this._position=new it(t,i),this.setPoints(e)}get position(){return this._position}set position(e){this._position.copy(e),this._normalsDirty=!0}get x(){return this._position.x}set x(e){this._position.x=e,this._normalsDirty=!0}get y(){return this._position.y}set y(e){this._position.y=e,this._normalsDirty=!0}get points(){return this._points}set points(e){this.setPoints(e)}get edges(){return this._edges}setPosition(e,t){return this._position.set(e,t),this._normalsDirty=!0,this}setPoints(e){const t=this._points.length,i=e.length,n=t-i,r=Math.min(t,i);for(let t=0;t<r;t++)this._points[t].copy(e[t]);if(n>0){for(const e of this._points.splice(i))e.destroy();for(const e of this._edges.splice(i))e.destroy();if(null!==this._cachedNormals&&this._cachedNormals.length>i){const e=this._cachedNormals.splice(i);for(const t of e)t.destroy()}}else if(n<0)for(let n=t;n<i;n++)this._points.push(e[n].clone()),this._edges.push(e[n].clone());for(let e=0;e<i;e++){const t=this._points[e],n=this._points[(e+1)%i];this._edges[e].set(n.x-t.x,n.y-t.y)}return this._normalsDirty=!0,this}set(e,t,i){return this._position.set(e,t),this.setPoints(i),this._normalsDirty=!0,this}copy(e){return this._position.copy(e.position),this.setPoints(e.points),this._normalsDirty=!0,this}clone(){return new Rt(this.points,this.x,this.y)}equals({x:e,y:t,points:i}={}){return(void 0===e||this.x===e)&&(void 0===t||this.y===t)&&(void 0===i||this.points.length===i.length&&this.points.every((e,t)=>e.equals(i[t])))}getBounds(){let e=1/0,t=1/0,i=-1/0,n=-1/0;for(const r of this._points)e=Math.min(r.x,e),t=Math.min(r.y,t),i=Math.max(r.x,i),n=Math.max(r.y,n);return new et(this.x+e,this.y+t,i-e,n-t)}getNormals(){if(this._normalsDirty){const e=this._points.length;for(null===this._cachedNormals&&(this._cachedNormals=[]);this._cachedNormals.length<e;)this._cachedNormals.push(new it);for(let t=0;t<e;t++)this._cachedNormals[t].copy(this._edges[t]).rperp().normalize();this._normalsDirty=!1}return this._cachedNormals}project(e,t=new me){const i=Math.sqrt(e.x*e.x+e.y*e.y)||1,n=e.x/i,r=e.y/i,s=this._points;let o=1/0,a=-1/0;for(let e=0;e<s.length;e++){const t=s[e],i=n*t.x+r*t.y;i<o&&(o=i),i>a&&(a=i)}return t.set(o,a)}contains(e,t){return Se(it.temp.set(e,t),this)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return ke(t.getBounds(),this);case e.CollisionType.Rectangle:return ke(t,this);case e.CollisionType.Polygon:return Ve(this,t);case e.CollisionType.Circle:return Ge(t,this);case e.CollisionType.Ellipse:return Oe(t,this);case e.CollisionType.Line:return Pe(t,this);case e.CollisionType.Point:return Se(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:case e.CollisionType.Rectangle:case e.CollisionType.Polygon:case e.CollisionType.Ellipse:return je(this,t);case e.CollisionType.Circle:return Xe(this,t);default:return null}}destroy(){for(const e of this._points)e.destroy();for(const e of this._edges)e.destroy();if(null!==this._cachedNormals){for(const e of this._cachedNormals)e.destroy();this._cachedNormals=null}this._position.destroy(),this._points.length=0,this._edges.length=0}static get temp(){return null===Et&&(Et=new Rt),Et}}class kt{_minX=1/0;_minY=1/0;_maxX=-1/0;_maxY=-1/0;_dirty=!0;_rect=new et;get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(e,t){return this._minX=Math.min(this._minX,e),this._minY=Math.min(this._minY,t),this._maxX=Math.max(this._maxX,e),this._maxY=Math.max(this._maxY,t),this._dirty=!0,this}addRect(e,t){return t&&(e=e.transform(t,et.temp)),this.addCoords(e.left,e.top).addCoords(e.right,e.bottom)}getRect(){return this._dirty&&(this._rect.set(this._minX,this._minY,this._maxX-this._minX,this._maxY-this._minY),this._dirty=!1),this._rect}reset(){return this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this}destroy(){this._rect.destroy()}}var Dt,Ft;!function(e){e[e.None=0]="None",e[e.Translation=1]="Translation",e[e.Rotation=2]="Rotation",e[e.Scaling=4]="Scaling",e[e.Origin=8]="Origin",e[e.Skew=32]="Skew",e[e.Transform=47]="Transform",e[e.TransformInverse=16]="TransformInverse",e[e.GlobalTransform=256]="GlobalTransform",e[e.BoundsRect=512]="BoundsRect"}(Dt||(Dt={})),function(e){e[e.Position=0]="Position",e[e.Scale=1]="Scale",e[e.Origin=2]="Origin",e[e.Anchor=3]="Anchor"}(Ft||(Ft={}));const It=[new it,new it,new it,new it];class Lt{collisionType=e.CollisionType.SceneNode;flags=new Mt(Dt.Transform|Dt.GlobalTransform|Dt.BoundsRect);_bounds=new kt;_transform=new At;_position=new Qe(this,Ft.Position,0,0);_scale=new Qe(this,Ft.Scale,1,1);_origin=new Qe(this,Ft.Origin,0,0);_rotation=0;_skewX=0;_skewY=0;_sin=0;_cos=1;_stage=null;_visible=!0;_globalTransform=new At;_localBounds=new et;_anchor=new Qe(this,Ft.Anchor,0,0);_parentNode=null;_zIndex=0;_cullable=!0;_cullArea=null;_orientedBounds=null;name=null;get position(){return this._position}set position(e){this._position.copy(e)}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get rotation(){return this._rotation}set rotation(e){this.setRotation(e)}get scale(){return this._scale}set scale(e){this._scale.copy(e)}get origin(){return this._origin}set origin(e){this._origin.copy(e)}get anchor(){return this._anchor}set anchor(e){this._anchor.copy(e)}get parent(){return this._parentNode}set parent(e){this._parentNode=e}get visible(){return this._visible}set visible(e){this._visible=e}get zIndex(){return this._zIndex}set zIndex(e){this._zIndex!==e&&(this._zIndex=e)}get cullable(){return this._cullable}set cullable(e){this._cullable=e}get cullArea(){return this._cullArea}set cullArea(e){this._cullArea=e}get skewX(){return this._skewX}set skewX(e){this._skewX!==e&&(this._skewX=e,this._setSkewDirty())}get skewY(){return this._skewY}set skewY(e){this._skewY!==e&&(this._skewY=e,this._setSkewDirty())}get isAlignedBox(){return this.rotation%90==0&&0===this._skewX&&0===this._skewY}setPosition(e,t=e){return this._position.set(e,t),this}setRotation(e){const t=q(e);return this._rotation!==t&&(this._rotation=t,this._setRotationDirty()),this}setScale(e,t=e){return this._scale.set(e,t),this}setSkew(e,t=e){return this.skewX=e,this.skewY=t,this}setOrigin(e,t=e){return this._origin.set(e,t),this}move(e,t){return this.setPosition(this.x+e,this.y+t)}rotate(e){return this.setRotation(this._rotation+e)}getTransform(){return this.flags.has(Dt.Transform)&&(this.updateTransform(),this.flags.remove(Dt.Transform)),this._transform}updateTransform(){if(this.flags.has(Dt.Rotation)){const e=W(this._rotation);this._cos=Math.cos(e),this._sin=Math.sin(e)}if(this.flags.has(Dt.Rotation|Dt.Scaling|Dt.Skew)){const{x:e,y:t}=this._scale;if(0!==this._skewX||0!==this._skewY){const i=Math.tan(W(this._skewX)),n=Math.tan(W(this._skewY));this._transform.a=e*this._cos+i*this._sin,this._transform.b=t*this._sin+n*this._cos,this._transform.c=-e*this._sin+i*this._cos,this._transform.d=-n*this._sin+t*this._cos}else this._transform.a=e*this._cos,this._transform.b=t*this._sin,this._transform.c=-e*this._sin,this._transform.d=t*this._cos}if(this._rotation||0!==this._skewX||0!==this._skewY){const{x:e,y:t}=this._origin;this._transform.x=e*-this._transform.a-t*this._transform.b+this._position.x,this._transform.y=e*-this._transform.c-t*this._transform.d+this._position.y}else this._transform.x=this._origin.x*-this._scale.x+this._position.x,this._transform.y=this._origin.y*-this._scale.y+this._position.y;return this}setAnchor(e,t=e){return this._anchor.set(e,t),this}getLocalBounds(){return this._localBounds}getBounds(){return this.flags.has(Dt.BoundsRect)&&(this.updateBounds(),this.flags.remove(Dt.BoundsRect)),this._bounds.getRect()}updateBounds(){return this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform()),this}updateParentTransform(){return this._parentNode&&this._parentNode.updateParentTransform(),this.updateTransform(),this}getGlobalTransform(){return this.flags.has(Dt.GlobalTransform)&&(this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this.flags.remove(Dt.GlobalTransform)),this._globalTransform}getNormals(){return this._isWorldAligned()?this.getBounds().getNormals():this._orientedBoundsPolygon().getNormals()}project(e,t=new me){return this._isWorldAligned()?this.getBounds().project(e,t):this._orientedBoundsPolygon().project(e,t)}_orientedBoundsPolygon(){const e=this.getLocalBounds(),t=this.getGlobalTransform();return It[0].set(e.left,e.top).transform(t),It[1].set(e.right,e.top).transform(t),It[2].set(e.right,e.bottom).transform(t),It[3].set(e.left,e.bottom).transform(t),(this._orientedBounds??=new Rt).setPoints(It)}_isWorldAligned(){const e=this.getGlobalTransform(),t=1e-9;return Math.abs(e.b)<t&&Math.abs(e.c)<t||Math.abs(e.a)<t&&Math.abs(e.d)<t}intersectsWith(t){if(this._isWorldAligned())return this.getBounds().intersectsWith(t);switch(t.collisionType){case e.CollisionType.SceneNode:case e.CollisionType.Rectangle:case e.CollisionType.Polygon:return ge(this,t);case e.CollisionType.Circle:return Ee(this.getBounds(),t);case e.CollisionType.Ellipse:return Re(this.getBounds(),t);case e.CollisionType.Line:return Ce(t,this.getBounds());case e.CollisionType.Point:return xe(t,this.getBounds());default:return!1}}collidesWith(t){if(this._isWorldAligned())return this.getBounds().collidesWith(t);switch(t.collisionType){case e.CollisionType.SceneNode:case e.CollisionType.Rectangle:case e.CollisionType.Polygon:case e.CollisionType.Circle:return je(this,t);default:return null}}contains(e,t){if(this._isWorldAligned())return this.getBounds().contains(e,t);const i=this.getGlobalTransform(),n=i.a*i.d-i.b*i.c;if(0===n)return!1;const r=e-i.x,s=t-i.y,o=(i.d*r-i.b*s)/n,a=(i.a*s-i.c*r)/n;return this.getLocalBounds().contains(o,a)}inView(e){if(!this._cullable)return!0;const t=this._cullArea??this.getBounds();return e.getBounds().intersectsWith(t)}destroy(){this._transform.destroy(),this._position.destroy(),this._scale.destroy(),this._origin.destroy(),this.flags.destroy(),this._globalTransform.destroy(),this._localBounds.destroy(),this._bounds.destroy(),this._anchor.destroy(),this._orientedBounds?.destroy()}_setStage(e){this._stage=e}_getStage(){return this._stage}_onObservableChange(e){switch(e){case Ft.Position:this._setPositionDirty();break;case Ft.Scale:this._setScalingDirty();break;case Ft.Origin:this._setOriginDirty();break;case Ft.Anchor:this._updateOrigin()}}_invalidateSubtreeTransform(){this.flags.push(Dt.GlobalTransform|Dt.BoundsRect),this._invalidateChildrenTransform()}_invalidateChildrenTransform(){}_invalidateBoundsCascade(){this.flags.push(Dt.BoundsRect),this._stage?.interaction._notifyBoundsInvalidated(this);let e=this._parentNode;for(;null!==e&&!e.flags.has(Dt.BoundsRect);)e.flags.push(Dt.BoundsRect),e._stage?.interaction._notifyBoundsInvalidated(e),e=e.parent}_setPositionDirty(){this.flags.push(Dt.Translation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setRotationDirty(){this.flags.push(Dt.Rotation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setScalingDirty(){this.flags.push(Dt.Scaling),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setOriginDirty(){this.flags.push(Dt.Origin),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setSkewDirty(){this.flags.push(Dt.Skew),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_updateOrigin(){const{x:e,y:t}=this._anchor,{width:i,height:n}=this.getBounds();this.setOrigin(i*e,n*t)}}var Ut;e.BlendModes=void 0,(Ut=e.BlendModes||(e.BlendModes={}))[Ut.Normal=0]="Normal",Ut[Ut.Additive=1]="Additive",Ut[Ut.Subtract=2]="Subtract",Ut[Ut.Multiply=3]="Multiply",Ut[Ut.Screen=4]="Screen",Ut[Ut.Darken=5]="Darken",Ut[Ut.Lighten=6]="Lighten",Ut[Ut.Overlay=7]="Overlay",Ut[Ut.ColorDodge=8]="ColorDodge",Ut[Ut.ColorBurn=9]="ColorBurn",Ut[Ut.HardLight=10]="HardLight",Ut[Ut.SoftLight=11]="SoftLight",Ut[Ut.Difference=12]="Difference",Ut[Ut.Exclusion=13]="Exclusion",Ut[Ut.Hue=14]="Hue",Ut[Ut.Saturation=15]="Saturation",Ut[Ut.Color=16]="Color",Ut[Ut.Luminosity=17]="Luminosity";const Gt=t=>t>=e.BlendModes.Darken;var Nt,Ot,Vt,zt,qt,Wt,Yt;e.ScaleModes=void 0,(Nt=e.ScaleModes||(e.ScaleModes={}))[Nt.Nearest=9728]="Nearest",Nt[Nt.Linear=9729]="Linear",Nt[Nt.NearestMipmapNearest=9984]="NearestMipmapNearest",Nt[Nt.LinearMipmapNearest=9985]="LinearMipmapNearest",Nt[Nt.NearestMipmapLinear=9986]="NearestMipmapLinear",Nt[Nt.LinearMipmapLinear=9987]="LinearMipmapLinear",e.WrapModes=void 0,(Ot=e.WrapModes||(e.WrapModes={}))[Ot.Repeat=10497]="Repeat",Ot[Ot.ClampToEdge=33071]="ClampToEdge",Ot[Ot.MirroredRepeat=33648]="MirroredRepeat",e.RenderingPrimitives=void 0,(Vt=e.RenderingPrimitives||(e.RenderingPrimitives={}))[Vt.Points=0]="Points",Vt[Vt.Lines=1]="Lines",Vt[Vt.LineLoop=2]="LineLoop",Vt[Vt.LineStrip=3]="LineStrip",Vt[Vt.Triangles=4]="Triangles",Vt[Vt.TriangleStrip=5]="TriangleStrip",Vt[Vt.TriangleFan=6]="TriangleFan",e.BufferTypes=void 0,(zt=e.BufferTypes||(e.BufferTypes={}))[zt.ArrayBuffer=34962]="ArrayBuffer",zt[zt.ElementArrayBuffer=34963]="ElementArrayBuffer",zt[zt.CopyReadBuffer=36662]="CopyReadBuffer",zt[zt.CopyWriteBuffer=36663]="CopyWriteBuffer",zt[zt.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",zt[zt.UniformBuffer=35345]="UniformBuffer",zt[zt.PixelPackBuffer=35051]="PixelPackBuffer",zt[zt.PixelUnpackBuffer=35052]="PixelUnpackBuffer",e.BufferUsage=void 0,(qt=e.BufferUsage||(e.BufferUsage={}))[qt.StaticDraw=35044]="StaticDraw",qt[qt.StaticRead=35045]="StaticRead",qt[qt.StaticCopy=35046]="StaticCopy",qt[qt.DynamicDraw=35048]="DynamicDraw",qt[qt.DynamicRead=35049]="DynamicRead",qt[qt.DynamicCopy=35050]="DynamicCopy",qt[qt.StreamDraw=35040]="StreamDraw",qt[qt.StreamRead=35041]="StreamRead",qt[qt.StreamCopy=35042]="StreamCopy",e.ShaderPrimitives=void 0,(Wt=e.ShaderPrimitives||(e.ShaderPrimitives={}))[Wt.Int=5124]="Int",Wt[Wt.IntVec2=35667]="IntVec2",Wt[Wt.IntVec3=35668]="IntVec3",Wt[Wt.IntVec4=35669]="IntVec4",Wt[Wt.UnsignedInt=5125]="UnsignedInt",Wt[Wt.UnsignedIntVec2=36294]="UnsignedIntVec2",Wt[Wt.UnsignedIntVec3=36295]="UnsignedIntVec3",Wt[Wt.UnsignedIntVec4=36296]="UnsignedIntVec4",Wt[Wt.Float=5126]="Float",Wt[Wt.FloatVec2=35664]="FloatVec2",Wt[Wt.FloatVec3=35665]="FloatVec3",Wt[Wt.FloatVec4=35666]="FloatVec4",Wt[Wt.Bool=35670]="Bool",Wt[Wt.BoolVec2=35671]="BoolVec2",Wt[Wt.BoolVec3=35672]="BoolVec3",Wt[Wt.BoolVec4=35673]="BoolVec4",Wt[Wt.FloatMat2=35674]="FloatMat2",Wt[Wt.FloatMat3=35675]="FloatMat3",Wt[Wt.FloatMat4=35676]="FloatMat4",Wt[Wt.Sampler2D=35678]="Sampler2D",function(e){e[e.Draw=0]="Draw",e[e.Group=1]="Group",e[e.Barrier=2]="Barrier"}(Yt||(Yt={}));const $t=new WeakMap,Xt=new WeakMap,Ht=new WeakMap,jt=new WeakMap;let Kt=1,Qt=1,Zt=1;const Jt=(e,t,i)=>{const n=e.get(t);if(void 0!==n)return n;const r=i();return e.set(t,r),r},ei=e=>e.material??null,ti=(e,t,i)=>{const n=((e,t)=>{const i=t?.rendererRegistry;if(i&&"function"==typeof i.resolve)try{const t=i.resolve(e);if(t&&"object"==typeof t)return Jt($t,t,()=>Kt++)}catch{}const n=e.constructor;return n&&"function"==typeof n?Jt(Xt,n,()=>Kt++):0})(t,i),r=t.blendMode,s=(e=>{const t=e.texture;return t&&"object"==typeof t?Jt(Ht,t,()=>Qt++):-1})(t),o=(e=>{const t=e.shader;return t&&"object"==typeof t?Jt(jt,t,()=>Zt++):-1})(t),a=ei(t);return e.rendererId=n,e.blendMode=r,e.textureId=s,e.shaderId=o,e.pipelineKey=null!==a?a.pipelineKey:31*n+r,e.bindKey=null!==a?a.bindKey:31*n+(s>0?s:0),e},ii=(e,t)=>{const i=t.rendererRegistry;if(!i||"function"!=typeof i.resolve)return!0;try{return!1!==i.resolve(e.drawable)._consumesSharedTransform}catch{return!0}};class ni{passes=[];nodeCount=0;reset(){this.passes.length=0,this.nodeCount=0}}var ri;!function(e){e[e.None=0]="None",e[e.Rect=1]="Rect",e[e.Stencil=2]="Stencil"}(ri||(ri={}));class si{static _available=[];static _active=[];static acquire(){const e=si._available.pop()??new si;return si._active.push(e),e}static release(e){const t=si._active.lastIndexOf(e);-1!==t&&(si._active.splice(t,1),e._resetRuntimeState(),si._available.push(e))}backend;_view=null;_plan=new ni;_groupPool=[];_scopeStack=[];_groupPoolCursor=0;_commandPool=[];_commandPoolCursor=0;_drawEntryPool=[];_drawEntryPoolCursor=0;_groupEntryPool=[];_groupEntryPoolCursor=0;_barrierEntryPool=[];_barrierEntryPoolCursor=0;_reservedSeq=0;_reservedZ=0;_hasPending=!1;_pendingSeq=0;_pendingZ=0;_nodeIndex=0;build(e,t){this.backend=t,this._view=null,this._plan.reset(),this._groupPoolCursor=0,this._drawEntryPoolCursor=0,this._groupEntryPoolCursor=0,this._barrierEntryPoolCursor=0,this._scopeStack.length=0,this._hasPending=!1;const i=t.transformBufferCount??0;this._nodeIndex=i,this._commandPoolCursor=i;const n=this._acquireGroupScope(!1);return this._scopeStack.push(n),e._collect(this),this._scopeStack.pop(),n.entries.length>0&&this._plan.passes.push({target:null,view:this.view,clearColor:null,root:n}),this._plan.nodeCount=this._nodeIndex-i,this._plan}get view(){return null===this._view&&(this._view=this.backend.view),this._view}emitNode(e,t){this._reserveEntryPlacement(t,e.zIndex);const i=this._reservedSeq,n=this._reservedZ;if(e._renderPlanHasBarrierEffects()){const t=this._createEffectDescriptor(e),r=null!==t.maskSource&&!(t.maskSource instanceof et);let s=0,o=0,a=0,h=0;if(t.cacheAsBitmap||t.filters.length>0||r||(t.needsBackdropBlend??!1)){const t=e.getBounds();if(t.width<=0||t.height<=0)return;s=Math.floor(t.left),o=Math.floor(t.top),a=Math.max(1,Math.ceil(t.width)),h=Math.max(1,Math.ceil(t.height))}const l=t.cacheAsBitmap&&e._renderPlanCanReuseBitmapCache(s,o,a,h)?null:this._acquireGroupScope(this._resolvePreserveDrawOrder(e)),u={kind:Yt.Barrier,node:e,effect:t,childPlan:l,left:s,top:o,width:a,height:h};if(this._pushBarrierEntry(i,n,u),null!==l){this._scopeStack.push(l);try{e._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}return}if(e._isDrawableForRenderPlan()){this._hasPending=!0,this._pendingSeq=i,this._pendingZ=n;try{e._collectForRenderPlan(this)}finally{this._hasPending=!1}return}const r=this._acquireGroupScope(this._resolvePreserveDrawOrder(e));this._pushGroupEntry(i,n,r),this._scopeStack.push(r);try{e._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}emitDraw(e,t){const i=this._hasPending,n=this._pendingSeq,r=this._pendingZ;i&&(this._hasPending=!1);const s=i?r:e.zIndex;this._reserveEntryPlacement(t??(i?n:void 0),s);const o=this._reservedSeq,a=this._reservedZ,h=e.getBounds(),l=this._acquireDrawCommand();l.drawable=e,l.nodeIndex=this._nodeIndex++,l.seq=o,l.zIndex=a,l.groupIndex=void 0,l.material=e._getOrComputeMaterialKey(this.backend),l.minX=h.left,l.minY=h.top,l.maxX=h.right,l.maxY=h.bottom,this._pushDrawEntry(o,a,l)}_resetRuntimeState(){this._scopeStack.length=0,this._hasPending=!1,this._groupPoolCursor=0,this._commandPoolCursor=0,this._drawEntryPoolCursor=0,this._groupEntryPoolCursor=0,this._barrierEntryPoolCursor=0,this._view=null,this._nodeIndex=0}_acquireGroupScope(e){const t=this._groupPool[this._groupPoolCursor]??{kind:Yt.Group,entries:[],hasMixedZ:!1,preserveDrawOrder:!1,_nextSeq:0,firstZ:null};return this._groupPool[this._groupPoolCursor]=t,this._groupPoolCursor++,t.entries.length=0,t.hasMixedZ=!1,t.preserveDrawOrder=e,t._nextSeq=0,t.firstZ=null,t}_acquireDrawCommand(){const e=this._commandPool[this._commandPoolCursor];if(void 0!==e)return this._commandPoolCursor++,e;const t={kind:Yt.Draw,drawable:void 0,nodeIndex:0,seq:0,zIndex:0,material:void 0,groupIndex:void 0,minX:0,minY:0,maxX:0,maxY:0};return this._commandPool[this._commandPoolCursor]=t,this._commandPoolCursor++,t}_pushDrawEntry(e,t,i){let n=this._drawEntryPool[this._drawEntryPoolCursor];void 0===n?(n={kind:Yt.Draw,seq:e,zIndex:t,command:i},this._drawEntryPool[this._drawEntryPoolCursor]=n):(n.seq=e,n.zIndex=t,n.command=i),this._drawEntryPoolCursor++,this._currentScope().entries.push(n)}_pushGroupEntry(e,t,i){let n=this._groupEntryPool[this._groupEntryPoolCursor];void 0===n?(n={kind:Yt.Group,seq:e,zIndex:t,scope:i},this._groupEntryPool[this._groupEntryPoolCursor]=n):(n.seq=e,n.zIndex=t,n.scope=i),this._groupEntryPoolCursor++,this._currentScope().entries.push(n)}_pushBarrierEntry(e,t,i){let n=this._barrierEntryPool[this._barrierEntryPoolCursor];void 0===n?(n={kind:Yt.Barrier,seq:e,zIndex:t,scope:i},this._barrierEntryPool[this._barrierEntryPoolCursor]=n):(n.seq=e,n.zIndex=t,n.scope=i),this._barrierEntryPoolCursor++,this._currentScope().entries.push(n)}_reserveEntryPlacement(e,t){const i=this._currentScope(),n=e??i._nextSeq;n>=i._nextSeq&&(i._nextSeq=n+1),null===i.firstZ?i.firstZ=t:i.hasMixedZ||i.firstZ===t||(i.hasMixedZ=!0),this._reservedSeq=n,this._reservedZ=t}_currentScope(){const e=this._scopeStack[this._scopeStack.length-1];if(!e)throw new Error("RenderPlanBuilder scope stack is empty.");return e}_resolvePreserveDrawOrder(e){return e.preserveDrawOrder}_createEffectDescriptor(e){const t=e._renderPlanGetMaskSource();let i=ri.None,n=null;if(e.clip){const t=e.clipShape;null===t||t instanceof et?(i=ri.Rect,n=t):(i=ri.Stencil,n=t)}const r=e._renderPlanGetBlendMode();return{filters:e._renderPlanGetFilters(),clip:i,clipShape:n,maskSource:t,cacheAsBitmap:e.cacheAsBitmap,blendMode:r,needsBackdropBlend:Gt(r)}}}const oi=e=>`${e.pipelineKey}:${e.bindKey}`,ai=(e,t)=>e.minX<t.maxX&&e.maxX>t.minX&&e.minY<t.maxY&&e.maxY>t.minY;class hi{static optimize(e){for(const t of e.passes)this._optimizeGroup(t.root)}static _optimizeGroup(e){if(e.hasMixedZ){const t=e.entries.map((e,t)=>({entry:e,index:t}));t.sort((e,t)=>e.entry.zIndex-t.entry.zIndex||e.entry.seq-t.entry.seq||e.index-t.index);for(let i=0;i<t.length;i++)e.entries[i]=t[i].entry}this._applyMaterialGrouping(e);for(const t of e.entries)t.kind===Yt.Group?this._optimizeGroup(t.scope):t.kind===Yt.Barrier&&null!==t.scope.childPlan&&this._optimizeGroup(t.scope.childPlan)}static _applyMaterialGrouping(e){const t=e.entries,i=t.length;if(0===i)return;let n=0;for(let r=0;r<=i;r++){const s=r<i?t[r]:null,o=null===s||s.kind===Yt.Group||s.kind===Yt.Barrier;if(o&&r>n){const i=r;i-n>=1&&this._materialGroupSegment(t,n,i,e.preserveDrawOrder),n=r+1}else o&&(n=r+1)}this._assignGroupIndices(e)}static _assignGroupIndices(e){let t=1,i=null,n=null;for(const r of e.entries){if(r.kind!==Yt.Draw){i=null,n=null;continue}const e=oi(r.command.material),s=r.zIndex;null!==i&&null!==n&&e===i&&s===n||(t++,i=e,n=s),r.command.groupIndex=t}}static _materialGroupSegment(e,t,i,n){if(i-t<=1)return;const r=[];for(let n=t;n<i;n++){const t=e[n];t.kind===Yt.Draw&&r.push({entry:t,origIdx:n})}if(!(r.length<=1||n)){const n=new Map;for(const e of r){const t=e.entry.zIndex,i=n.get(t)??[];i.push(e),n.set(t,i)}for(const r of n.values())r.length>1&&this._overlapAwareGroup(r,e,t,i)}}static _overlapAwareGroup(e,t,i,n){const r=new Map;for(const t of e){const e=oi(t.entry.command.material),i=r.get(e)??[];i.push(t),r.set(e,i)}if(r.size<=1)return;const s=new Map;for(let e=i;e<n;e++)s.set(t[e],e);for(const e of r.values()){if(e.length<=1)continue;const r=[];for(const t of e){const e=s.get(t.entry);void 0!==e&&r.push(e)}if(r.sort((e,t)=>e-t),0===r.length)continue;const o=r[0],a=r[r.length-1];if(a-o+1===r.length)continue;let h=!1;for(let i=o+1;i<a&&!h;i++){const n=t[i];if(n.kind!==Yt.Draw)continue;if(oi(n.command.material)!==oi(e[0].entry.command.material))for(const t of e)if(ai(t.entry.command,n.command)){h=!0;break}}if(h)continue;const l=[];for(let e=i;e<o;e++)l.push(t[e]);const u=[];for(let e=a+1;e<n;e++)u.push(t[e]);const c=new Set(e.map(e=>e.entry)),d=[];for(let e=o;e<=a;e++){const i=t[e];c.has(i)||d.push(i)}const _=e.map(e=>e.entry),f=[...l,..._,...d,...u];for(let e=i;e<n;e++)t[e]=f[e-i];break}}}class li extends l{_callback;constructor(e,t=0,i=0){super(t,i),this._callback=e}get width(){return this._width}set width(e){this._width!==e&&(this._width=e,this._callback())}get height(){return this._height}set height(e){this._height!==e&&(this._height=e,this._callback())}set(e=this._width,t=this._height){return this._width===e&&this._height===t||(this._width=e,this._height=t,this._callback()),this}add(e,t=e){return this.set(this._width+e,this._height+t)}subtract(e,t=e){return this.set(this._width-e,this._height-t)}scale(e,t=e){return this.set(this._width*e,this._height*t)}divide(e,t=e){return this.set(this._width/e,this._height/t)}copy(e){return this.set(e.width,e.height)}clone(){return new li(this._callback,this._width,this._height)}}var ui;e.ViewFlags=void 0,(ui=e.ViewFlags||(e.ViewFlags={}))[ui.None=0]="None",ui[ui.Translation=1]="Translation",ui[ui.Rotation=2]="Rotation",ui[ui.Scaling=4]="Scaling",ui[ui.Origin=8]="Origin",ui[ui.Transform=15]="Transform",ui[ui.TransformInverse=16]="TransformInverse",ui[ui.BoundingBox=32]="BoundingBox",ui[ui.TextureCoords=64]="TextureCoords",ui[ui.VertexTint=128]="VertexTint";class ci{_center;_size;_viewport=new et(0,0,1,1);_transform=new At;_inverseTransform=new At;_bounds=new kt;_flags=new Mt;_rotation=0;_sin=0;_cos=1;_zoomLevel=1;_zoomBaseWidth;_zoomBaseHeight;_followTarget=null;_followLerp=1;_followOffsetX=0;_followOffsetY=0;_boundsConstraint=null;_shakeIntensity=0;_shakeDurationMs=0;_shakeElapsedMs=0;_shakeFrequency=16;_shakeDecay=!0;_shakePhase=0;_shakeOffsetX=0;_shakeOffsetY=0;_updateId=0;constructor(t,i,n,r){this._center=new Qe(this,0,t,i),this._size=new li(this._setScalingDirty.bind(this),n,r),this._zoomBaseWidth=n,this._zoomBaseHeight=r,this._flags.push(e.ViewFlags.Transform,e.ViewFlags.TransformInverse,e.ViewFlags.BoundingBox)}static from(e={}){const t=new ci(e.center?.x??0,e.center?.y??0,e.size?.width??0,e.size?.height??0);return e.viewport&&(t.viewport=e.viewport),e.rotation&&0!==e.rotation&&(t.rotation=e.rotation),void 0!==e.zoom&&1!==e.zoom&&t.setZoom(e.zoom),t}_onObservableChange(){this._setPositionDirty()}get center(){return this._center}set center(e){this._center.copy(e)}get size(){return this._size}set size(e){this._size.copy(e)}get width(){return this._size.width}set width(e){this._size.width=e}get height(){return this._size.height}set height(e){this._size.height=e}get rotation(){return this._rotation}set rotation(e){this.setRotation(e)}get viewport(){return this._viewport}set viewport(e){this._viewport.equals(e)||(this._viewport.copy(e),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(e,t){return this._center.set(e,t),this}resize(e,t){return this._zoomBaseWidth=e,this._zoomBaseHeight=t,this._zoomLevel=1,this._size.set(e,t),this}setRotation(e){const t=q(e);return this._rotation!==t&&(this._rotation=t,this._setRotationDirty()),this}setViewport(e,t,i,n){return this._viewport.x===e&&this._viewport.y===t&&this._viewport.width===i&&this._viewport.height===n||(this._viewport.set(e,t,i,n),this._setDirty()),this}move(e,t){return this.setCenter(this._center.x+e,this._center.y+t),this}zoom(e){return this.resize(this._size.width*e,this._size.height*e),this}setZoom(e){const t=Math.max(1e-4,e);return this._zoomLevel=t,this._size.set(this._zoomBaseWidth/t,this._zoomBaseHeight/t),this}zoomIn(e=.1){return this.setZoom(this._zoomLevel+e)}zoomOut(e=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-e))}follow(e,t={}){return this._followTarget=e,this._followLerp=Y(t.lerp??1,0,1),this._followOffsetX=t.offsetX??0,this._followOffsetY=t.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(e){return null===e?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=e.clone():this._boundsConstraint.copy(e),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(e,t,i={}){return this._shakeIntensity=Math.max(0,e),this._shakeDurationMs=Math.max(0,t),this._shakeElapsedMs=0,this._shakeFrequency=Math.max(0,i.frequency??16),this._shakeDecay=i.decay??!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty(),this}stopShake(){return this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakePhase=0,0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()),this}update(e){return this._updateFollowTarget(),this._updateShake(e),this._applyBoundsConstraint(),this}rotate(e){return this.setRotation(this._rotation+e),this}reset(t,i,n,r){return this._zoomBaseWidth=n,this._zoomBaseHeight=r,this._zoomLevel=1,this._size.set(n,r),this._center.set(t,i),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(e.ViewFlags.Transform),this}getTransform(){return this._flags.has(e.ViewFlags.Transform)&&(this.updateTransform(),this._flags.remove(e.ViewFlags.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,i=this._center.y+this._shakeOffsetY,n=2/this.width,r=-2/this.height;if(this._flags.has(e.ViewFlags.Rotation)){const e=W(this._rotation);this._cos=Math.cos(e),this._sin=Math.sin(e)}return this._flags.has(e.ViewFlags.Rotation|e.ViewFlags.Scaling)&&(this._transform.a=n*this._cos,this._transform.b=n*this._sin,this._transform.c=-r*this._sin,this._transform.d=r*this._cos),this._transform.x=n*-this._transform.a-r*this._transform.b+-n*t,this._transform.y=n*-this._transform.c-r*this._transform.d+-r*i,this}getInverseTransform(){return this._flags.has(e.ViewFlags.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(e.ViewFlags.TransformInverse)),this._inverseTransform}screenToWorld(e,t,i,n){let r,s;if(void 0===i||void 0===n){r=e/(this.width||1)*2-1,s=1-t/(this.height||1)*2}else{const o=this._viewport.width*i,a=this._viewport.height*n;r=(e-this._viewport.x*i)/o*2-1,s=1-(t-this._viewport.y*n)/a*2}const o=this.getTransform(),a=o.a*o.d-o.b*o.c;if(0===a)return{x:0,y:0};const h=r-o.x,l=s-o.y;return{x:(h*o.d-l*o.b)/a,y:(l*o.a-h*o.c)/a}}worldToScreen(e,t,i,n){const r=this.getTransform(),s=r.a*e+r.b*t+r.x,o=r.c*e+r.d*t+r.y;if(void 0===i||void 0===n)return{x:(s+1)/2*this.width,y:(1-o)/2*this.height};const a=this._viewport.x*i,h=this._viewport.y*n;return{x:a+(s+1)/2*this._viewport.width*i,y:h+(1-o)/2*this._viewport.height*n}}getBounds(){return this._flags.has(e.ViewFlags.BoundingBox)&&(this.updateBounds(),this._flags.remove(e.ViewFlags.BoundingBox)),this._bounds.getRect()}updateBounds(){const e=this._center.x+this._shakeOffsetX,t=this._center.y+this._shakeOffsetY,i=this.width/2,n=this.height/2;return this._bounds.reset().addCoords(e-i,t-n).addCoords(e+i,t+n),this}destroy(){this.stopShake(),this.clearFollow(),this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this._center.destroy(),this._size.destroy(),this._viewport.destroy(),this._transform.destroy(),this._inverseTransform.destroy(),this._bounds.destroy(),this._flags.destroy()}_setDirty(){this._flags.push(e.ViewFlags.TransformInverse,e.ViewFlags.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(e.ViewFlags.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(e.ViewFlags.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(e.ViewFlags.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;let e,t;if(this._followTarget instanceof Lt){const i=this._followTarget.getGlobalTransform();e=i.x+this._followOffsetX,t=i.y+this._followOffsetY}else e=this._followTarget.x+this._followOffsetX,t=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(e,t):this.setCenter(this._center.x+(e-this._center.x)*this._followLerp,this._center.y+(t-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const e=this._boundsConstraint,t=this.width/2,i=this.height/2,n=e.left+t,r=e.right-t,s=e.top+i,o=e.bottom-i,a=n>r?(e.left+e.right)/2:Y(this._center.x,n,r),h=s>o?(e.top+e.bottom)/2:Y(this._center.y,s,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(e){if(this._shakeDurationMs<=0||this._shakeIntensity<=0)return void(0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()));this._shakeElapsedMs=Math.min(this._shakeDurationMs,this._shakeElapsedMs+Math.max(0,e));const t=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-t):this._shakeIntensity;this._shakePhase+=Math.max(0,e)/1e3*this._shakeFrequency*Math.PI*2;const n=Math.sin(1.7*this._shakePhase)*i,r=Math.cos(1.3*this._shakePhase)*i;n===this._shakeOffsetX&&r===this._shakeOffsetY||(this._shakeOffsetX=n,this._shakeOffsetY=r,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}class di{needsStencil=!1;_root;_destroyListeners=new Set;_version=0;_size;_viewport=new et;_defaultView;_view;constructor(e,t,i=!1){this._size=new l(e,t),this._root=i,this._defaultView=new ci(e/2,t/2,e,t),this._view=this._defaultView}get view(){return this._view}set view(e){this.setView(e)}get size(){return this._size}set size(e){this.resize(e.width,e.height)}get width(){return this._size.width}set width(e){this.resize(e,this.height)}get height(){return this._size.height}set height(e){this.resize(this.width,e)}get root(){return this._root}get version(){return this._version}addDestroyListener(e){return this._destroyListeners.add(e),this}removeDestroyListener(e){return this._destroyListeners.delete(e),this}setView(e){const t=e||this._defaultView;return this._view!==t&&(this._view=t,this._touch()),this}resize(e,t){return this._size.equals({width:e,height:t})||(this._size.set(e,t),this._touch()),this}getViewport(e=this._view){const{x:t,y:i,width:n,height:r}=e.viewport;return this._viewport.set(Math.round(t*this.width),Math.round(i*this.height),Math.round(n*this.width),Math.round(r*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(e,t=this._view){const i=this.getViewport(t);return new it(2*(e.x-i.left)/i.width-1,1-2*(e.y-i.top)/i.height).transform(t.getInverseTransform())}mapCoordsToPixel(e,t=this._view){const i=this.getViewport(t),n=e.clone().transform(t.getTransform());return n.set((n.x+1)/2*i.width+i.left|0,(1-n.y)/2*i.height+i.top|0)}destroy(){for(const e of[...this._destroyListeners])e();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}class _i extends di{static defaultSamplerOptions={scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};_source=null;_textureVersion=0;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;constructor(e,t,i){super(e,t,!1);const{scaleMode:n,wrapMode:r,premultiplyAlpha:s,generateMipMap:o,flipY:a}={..._i.defaultSamplerOptions,...i};this._scaleMode=n,this._wrapMode=r,this._premultiplyAlpha=s,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(e){this.setSource(e)}get scaleMode(){return this._scaleMode}set scaleMode(e){this.setScaleMode(e)}get wrapMode(){return this._wrapMode}set wrapMode(e){this.setWrapMode(e)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(e){this.setPremultiplyAlpha(e)}get generateMipMap(){return this._generateMipMap}set generateMipMap(e){this._generateMipMap=e}get flipY(){return this._flipY}set flipY(e){this._flipY=e}get powerOfTwo(){return X(this.width)&&X(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(e){return this._scaleMode!==e&&(this._scaleMode=e,this._touchTexture()),this}setWrapMode(e){return this._wrapMode!==e&&(this._wrapMode=e,this._touchTexture()),this}setPremultiplyAlpha(e){return this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._touchTexture()),this}setSource(e){return this._source!==e&&(this._source=e,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(e,t){return this._size.equals({width:e,height:t})||(this._size.set(e,t),this._defaultView.resize(e,t),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}const fi=(e={})=>{const{canvas:t,fillStyle:i,width:n,height:r}=e,s=t??document.createElement("canvas"),o=s.getContext("2d");return s.width=n??10,s.height=r??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,s.width,s.height),s};class pi{static _black=null;static _white=null;static defaultSamplerOptions={scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1};static empty=new pi(null);static get black(){return null===pi._black&&(pi._black=new pi(fi({fillStyle:"#000"}))),pi._black}static get white(){return null===pi._white&&(pi._white=new pi(fi({fillStyle:"#fff"}))),pi._white}_version=0;_source=null;_size=new l(0,0);_destroyListeners=new Set;_scaleMode;_wrapMode;_premultiplyAlpha=!1;_generateMipMap=!1;_flipY=!1;constructor(e=null,t){const{scaleMode:i,wrapMode:n,premultiplyAlpha:r,generateMipMap:s,flipY:o}={...pi.defaultSamplerOptions,...t};this._scaleMode=i,this._wrapMode=n,this._premultiplyAlpha=r,this._generateMipMap=s,this._flipY=o,null!==e&&this.setSource(e)}get source(){return this._source}set source(e){this.setSource(e)}get size(){return this._size}set size(e){this.setSize(e.width,e.height)}get width(){return this._size.width}set width(e){this.setSize(e,this.height)}get height(){return this._size.height}set height(e){this.setSize(this.width,e)}get scaleMode(){return this._scaleMode}set scaleMode(e){this.setScaleMode(e)}get wrapMode(){return this._wrapMode}set wrapMode(e){this.setWrapMode(e)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(e){this.setPremultiplyAlpha(e)}get generateMipMap(){return this._generateMipMap}set generateMipMap(e){this._generateMipMap=e}get flipY(){return this._flipY}set flipY(e){this._flipY=e}get powerOfTwo(){return X(this.width)&&X(this.height)}get version(){return this._version}_bumpVersion(){this._version++}addDestroyListener(e){return this._destroyListeners.add(e),this}removeDestroyListener(e){return this._destroyListeners.delete(e),this}setScaleMode(e){return this._scaleMode!==e&&(this._scaleMode=e,this._touch()),this}setWrapMode(e){return this._wrapMode!==e&&(this._wrapMode=e,this._touch()),this}setPremultiplyAlpha(e){return this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._touch()),this}setSource(e){return this._source!==e&&(this._source=e,this.updateSource()),this}updateSource(){const{width:e,height:t}=null===(i=this._source)?l.zero:y(i);var i;return this.setSize(e,t),this._touch(),this}setSize(e,t){return this._size.equals({width:e,height:t})||(this._size.set(e,t),this._touch()),this}destroy(){for(const e of[...this._destroyListeners])e();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}class mi{static play(e,t,i){const{node:n,effect:r}=e,s=r.filters.length>0,o=r.cacheAsBitmap,{left:a,top:h,width:l,height:u}=e;if(!s&&!o&&!r.needsBackdropBlend)return void this._withClip(n,t,e,()=>{null!==e.childPlan&&i(e.childPlan)});if(o&&null===e.childPlan){const i=n._renderPlanGetCacheTexture();return void(null!==i&&this._withClip(n,t,e,()=>{n._renderPlanDrawTexture(t,i,a,h,l,u,r.blendMode)}))}const c=o?n._renderPlanEnsureCacheTexture(l,u):null;let d=null;try{const _=o&&!s?c:t.acquireRenderTexture(l,u);_!==c&&(d=_),n._renderPlanRenderToTexture(t,_,a,h,l,u,()=>{null!==e.childPlan&&i(e.childPlan)});let f=_;if(s)for(let e=0;e<r.filters.length;e++){const i=e===r.filters.length-1&&o?c:t.acquireRenderTexture(l,u);try{r.filters[e].apply(t,f,i)}catch(e){throw i!==c&&t.releaseRenderTexture(i),e}null!==d&&(t.releaseRenderTexture(d),d=null),f=i,i!==c&&(d=i)}o&&n._renderPlanStoreCacheTexture(c,a,h,l,u),this._withClip(n,t,e,()=>{r.needsBackdropBlend?t.composeWithBackdropBlend(f,a,h,l,u,r.blendMode):n._renderPlanDrawTexture(t,f,a,h,l,u,r.blendMode)})}finally{null!==d&&t.releaseRenderTexture(d)}}static _withClip(e,t,i,n){if(i.effect.clip!==ri.Stencil)this._withRectClip(e,t,i,n);else{t.pushStencilClip(i.effect.clipShape,e.getGlobalTransform());try{this._withRectClip(e,t,i,n)}finally{t.popStencilClip()}}}static _withRectClip(e,t,i,n){if(i.effect.clip===ri.Rect){const r=i.effect.clipShape??e.getBounds();if(r.width<=0||r.height<=0)return;t.pushScissorRect(r);try{this._withMask(e,t,i,n)}finally{t.popScissorRect()}return}this._withMask(e,t,i,n)}static _withMask(e,t,i,n){const r=i.effect.maskSource;if(null===r)return void n();if(r instanceof et){if(r.width<=0||r.height<=0)return;t.pushScissorRect(r);try{n()}finally{t.popScissorRect()}return}const s=t.acquireRenderTexture(i.width,i.height),o=[s];try{e._renderPlanRenderToTexture(t,s,i.left,i.top,i.width,i.height,n);const a=this._resolveMaskTexture(e,t,r,i,o);t.composeWithAlphaMask(s,a,i.left,i.top,i.width,i.height,i.effect.blendMode)}finally{for(const e of o)t.releaseRenderTexture(e)}}static _resolveMaskTexture(e,t,i,n,r){if(!(i instanceof pi||i instanceof _i)){const s=t.acquireRenderTexture(n.width,n.height);return r.push(s),e._renderPlanRenderToTexture(t,s,n.left,n.top,n.width,n.height,()=>{i.render(t)}),s}return i}}const gi=(e,t)=>{const i=e[t].command.groupIndex;if(void 0===i)return 1;let n=1;for(let r=t+1;r<e.length;r++){const t=e[r];if(t.kind!==Yt.Draw||t.command.groupIndex!==i)break;n++}return n};class yi{static play(e,t){const i=t;i._beginDrawPlan?.(e.nodeCount);try{for(const n of e.passes)null!==n.target&&t.renderTarget!==n.target&&t.setRenderTarget(n.target),t.view!==n.view&&t.setView(n.view),null!==n.clearColor&&t.clear(n.clearColor),this._playScope(n.root,t,i,this._createPlaybackContext())}finally{i._endDrawPlan?.()}}static playScope(e,t){const i=t;this._playScope(e,t,i,this._createPlaybackContext())}static _playScope(e,t,i,n){e.kind!==Yt.Barrier?this._playGroup(e,t,i,n):mi.play(e,t,e=>{this._playScope(e,t,i,n)})}static _playGroup(e,t,i,n){const r=e.entries;if(void 0!==i._prepareRenderGroupUpload){let e=n.passInstructionIndex,t=0;for(let s=0;s<r.length;){if(r[s].kind!==Yt.Draw){s++;continue}const o=gi(r,s);i._prepareRenderGroupUpload(r,s,o,this._createRenderGroupPlaybackContext(o,e,n.passGroupIndex+t)),e+=o,t++,s+=o}}let s=-1,o=0,a=0;for(let e=0;e<r.length;e++){const h=r[e];if(h.kind===Yt.Draw){if(-1===s&&(s=e,o=gi(r,e),a=0,i._beginRenderGroup?.(r,s,o),n.passGroupIndex++),void 0!==i._prepareRenderInstructionSlot){const e=this._createRenderInstructionSlot(a,n.passInstructionIndex);i._prepareRenderInstructionSlot(h.command,e)}i._prepareDrawCommand?.(h.command),t.draw(h.command.drawable),a++,n.passInstructionIndex++,a===o&&(i._endRenderGroup?.(r,s,o),s=-1,o=0,a=0)}else h.kind===Yt.Group?this._playGroup(h.scope,t,i,n):mi.play(h.scope,t,e=>{this._playScope(e,t,i,n)})}}static _createPlaybackContext(){return{passInstructionIndex:0,passGroupIndex:0}}static _createRenderGroupPlaybackContext(e,t,i){return Object.freeze({groupInstructionCount:e,firstPassInstructionIndex:t,lastPassInstructionIndex:t+e-1,passGroupIndex:i})}static _createRenderInstructionSlot(e,t){return Object.freeze({groupInstructionIndex:e,passInstructionIndex:t})}}function wi(e,t){const i=si.acquire();try{const n=i.build(e,t);hi.optimize(n),yi.play(n,t)}finally{si.release(i)}}var xi;!function(e){e[e.None=0]="None",e[e.Enabled=1]="Enabled"}(xi||(xi={}));class vi{_callback;_target;_view;_clearColor;constructor(e,t={}){this._callback=e,this._target=t.target??null,this._view=t.view??null,this._clearColor=t.clearColor??null}execute(e){const t=e._passCoordinator;if(t)return void t.withChildPass({target:this._target,view:this._view,load:null!==this._clearColor?"clear":"load",clearColor:this._clearColor,stencil:xi.None},()=>{this._callback(e)});const i=e.renderTarget,n=e.view;e.setRenderTarget(this._target),e.setView(this._view),null!==this._clearColor&&e.clear(this._clearColor);try{this._callback(e)}finally{e.setRenderTarget(i),e.setView(n)}}}const bi=e=>"destroy"in e&&"function"==typeof e.destroy;class Si extends Lt{static _spriteFactory=null;_interactive=!1;cursor=null;get interactive(){return this._interactive}set interactive(e){this._interactive!==e&&(this._interactive=e,this._stage?.interaction._notifyInteractiveChanged(this,e))}draggable=!1;preserveDrawOrder=!1;clip=!1;clipShape=null;_signals=null;get onPointerDown(){return this._interactionSignal("pointerdown")}get onPointerUp(){return this._interactionSignal("pointerup")}get onPointerMove(){return this._interactionSignal("pointermove")}get onPointerOver(){return this._interactionSignal("pointerover")}get onPointerOut(){return this._interactionSignal("pointerout")}get onPointerTap(){return this._interactionSignal("pointertap")}get onDragStart(){return this._interactionSignal("dragstart")}get onDrag(){return this._interactionSignal("drag")}get onDragEnd(){return this._interactionSignal("dragend")}_interactionSignal(e){const t=this._signals??=new Map;let i=t.get(e);return void 0===i&&(i=new x,t.set(e,i)),i}_peekInteractionSignal(e){return this._signals?.get(e)??null}focusable=!1;tabIndex=0;_onFocus=null;_onBlur=null;_onKeyDown=null;_onKeyUp=null;get onFocus(){return this._onFocus??=new x}get onBlur(){return this._onBlur??=new x}get onKeyDown(){return this._onKeyDown??=new x}get onKeyUp(){return this._onKeyUp??=new x}_peekFocusSignal(e){return"focus"===e?this._onFocus:this._onBlur}_peekKeySignal(e){return"keydown"===e?this._onKeyDown:this._onKeyUp}focus(){return this._stage?.focus.focus(this),this}blur(){return this._stage?.focus.blur(this),this}_filters=[];_cacheBounds=new et;_cacheSprite=null;_captureView=null;_mask=null;_cacheAsBitmap=!1;_cacheDirty=!0;_cacheTexture=null;get filters(){return this._filters}set filters(e){this._filters.length=0,this._filters.push(...e),this.invalidateCache()}get mask(){return this._mask}set mask(e){if(e===this)throw new Error("A RenderNode cannot use itself as its own mask source.");this._mask!==e&&(this._mask=e,this.invalidateCache())}render(e){return wi(this,e),this}_collect(e,t){this.visible&&(this.inView(e.view)?e.emitNode(this,t):e.backend.stats.culledNodes++)}_collectForRenderPlan(e){this._collectContent(e)}_isDrawableForRenderPlan(){return!1}_collectContent(e){}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(e){this._cacheAsBitmap!==e&&(this._cacheAsBitmap=e,this.invalidateCache(),e||this._destroyCacheTexture())}addFilter(e){return this._filters.push(e),this.invalidateCache()}removeFilter(e){const t=this._filters.indexOf(e);return-1!==t&&(this._filters.splice(t,1),this.invalidateCache()),this}static setInternalSpriteFactory(e){Si._spriteFactory=e}clearFilters(){return this._filters.length>0&&(this._filters.length=0,this.invalidateCache()),this}invalidateCache(){return this._cacheDirty=!0,this}_renderPlanHasBarrierEffects(){return this._filters.length>0||null!==this._mask||this._cacheAsBitmap||this.clip||Gt(this._renderPlanGetBlendMode())}_renderPlanGetMaskSource(){return this._mask}_renderPlanGetFilters(){return this._filters}_renderPlanGetBlendMode(){return e.BlendModes.Normal}_renderPlanCanReuseBitmapCache(e,t,i,n){return this._cacheAsBitmap&&!this._cacheDirty&&null!==this._cacheTexture&&this._cacheBounds.equals({x:e,y:t,width:i,height:n})}_renderPlanGetCacheTexture(){return this._cacheTexture}_renderPlanEnsureCacheTexture(e,t){return this._ensureCacheTexture(e,t)}_renderPlanStoreCacheTexture(e,t,i,n,r){this._cacheTexture=e,this._cacheBounds.set(t,i,n,r),this._cacheDirty=!1}_renderPlanRenderToTexture(e,t,i,n,r,s,o){this._renderContentToTexture(e,t,i,n,r,s,o)}_renderPlanDrawTexture(e,t,i,n,r,s,o){this._drawTexture(e,t,i,n,r,s,o)}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const e of this._filters)bi(e)&&e.destroy();if(this._filters.length=0,this._mask=null,null!==this._signals){for(const e of this._signals.values())e.destroy();this._signals.clear(),this._signals=null}this._onFocus?.destroy(),this._onBlur?.destroy(),this._onKeyDown?.destroy(),this._onKeyUp?.destroy(),this._onFocus=this._onBlur=this._onKeyDown=this._onKeyUp=null}_renderContentToTexture(e,t,i,n,r,s,o){null===this._captureView?this._captureView=new ci(i+r/2,n+s/2,r,s):this._captureView.reset(i+r/2,n+s/2,r,s),e.execute(new vi(()=>{o()},{target:t,view:this._captureView,clearColor:Tt.transparentBlack}))}_drawTexture(e,t,i,n,r,s,o){const a=this._getCacheSprite();a.setTexture(t).setBlendMode(o).setTint(Tt.white).setPosition(i,n).setRotation(0).setScale(1,1),a.width=r,a.height=s,a.render(e)}_ensureCacheTexture(e,t){return null===this._cacheTexture?this._cacheTexture=new _i(e,t):this._cacheTexture.width===e&&this._cacheTexture.height===t||this._cacheTexture.setSize(e,t),this._cacheTexture}_destroyCacheTexture(){null!==this._cacheTexture&&(this._cacheTexture.destroy(),this._cacheTexture=null),this._cacheDirty=!0}_getCacheSprite(){if(null===this._cacheSprite){if(null===Si._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=Si._spriteFactory()}return this._cacheSprite}}class Bi extends Si{_children=[];get children(){return this._children}get width(){return Math.abs(this.scale.x)*this.getBounds().width}set width(e){this.scale.x=e/this.getBounds().width}get height(){return Math.abs(this.scale.y)*this.getBounds().height}set height(e){this.scale.y=e/this.getBounds().height}get left(){return this.x-this.width*this.origin.x}get top(){return this.y-this.height*this.origin.y}get right(){return this.x+this.width-this.origin.x}get bottom(){return this.y+this.height-this.origin.y}addChild(...e){for(const t of e)this.addChildAt(t,this._children.length);return this}addChildAt(e,t){if(t<0||t>this._children.length)throw new Error(`The index ${t} is out of bounds ${this._children.length}`);return e===this||(e.parent&&e.parent.removeChild(e),e.parent=this,this._children.splice(t,0,e),this.invalidateCache(),e._invalidateSubtreeTransform(),this._invalidateBoundsCascade(),e._setStage(this._stage),this._stage?.interaction._notifyNodeAdded(e)),this}swapChildren(e,t){if(e!==t){const i=this.getChildIndex(e),n=this.getChildIndex(t);this._children[i]=t,this._children[n]=e,this.invalidateCache()}return this}getChildIndex(e){const t=this._children.indexOf(e);if(-1===t)throw new Error("Drawable is not a child of the container.");return t}setChildIndex(e,t){if(t<0||t>=this._children.length)throw new Error(`The index ${t} is out of bounds ${this._children.length}`);return g(this._children,this.getChildIndex(e),1),this._children.splice(t,0,e),this.invalidateCache(),this}getChildAt(e){if(e<0||e>=this._children.length)throw new Error(`getChildAt: Index (${e}) does not exist.`);return this._children[e]}removeChild(e){const t=this._children.indexOf(e);return-1!==t&&this.removeChildAt(t),this}removeChildAt(e){const t=this._children[e];return g(this._children,e,1),t?.parent===this&&(this._invalidateBoundsCascade(),t.parent=null,t._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(t),this._stage?.focus._notifyNodeRemoved(t),t._setStage(null)),this.invalidateCache(),this}removeChildren(e=0,t=this._children.length){const i=t-e;if(i<0||i>t)throw new Error("Values are outside the acceptable range.");i>0&&this._invalidateBoundsCascade();for(let i=e;i<t;i++){const e=this._children[i];e?.parent===this&&(e.parent=null,e._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(e),this._stage?.focus._notifyNodeRemoved(e),e._setStage(null))}return g(this._children,e,i),this.invalidateCache(),this}_setStage(e){if(this._stage!==e){this._stage=e;for(const t of this._children)t._setStage(e)}}_collectContent(e){if(0!==this._children.length)for(let t=0;t<this._children.length;t++)this._children[t]._collect(e,t)}contains(e,t){const i=this._children;for(let n=0;n<i.length;n++)if(i[n].contains(e,t))return!0;return!1}_invalidateChildrenTransform(){for(const e of this._children)e._invalidateSubtreeTransform()}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const e of this._children)e.visible&&this._bounds.addRect(e.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}}class Ci{type;channel;target;_defaultPrevented=!1;constructor(e,t,i){this.type=e,this.channel=t,this.target=i}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}}var Ti,Mi;e.ChannelSize=void 0,(Ti=e.ChannelSize||(e.ChannelSize={}))[Ti.Container=768]="Container",Ti[Ti.Category=256]="Category",Ti[Ti.Gamepad=64]="Gamepad",e.ChannelOffset=void 0,(Mi=e.ChannelOffset||(e.ChannelOffset={}))[Mi.Keyboard=0]="Keyboard",Mi[Mi.Pointers=256]="Pointers",Mi[Mi.Gamepads=512]="Gamepads";var Pi;e.Keyboard=void 0,(Pi=e.Keyboard||(e.Keyboard={}))[Pi.Backspace=8]="Backspace",Pi[Pi.Tab=9]="Tab",Pi[Pi.Clear=12]="Clear",Pi[Pi.Enter=13]="Enter",Pi[Pi.Shift=16]="Shift",Pi[Pi.Control=17]="Control",Pi[Pi.Alt=18]="Alt",Pi[Pi.Pause=19]="Pause",Pi[Pi.CapsLock=20]="CapsLock",Pi[Pi.Escape=27]="Escape",Pi[Pi.Space=32]="Space",Pi[Pi.PageUp=33]="PageUp",Pi[Pi.PageDown=34]="PageDown",Pi[Pi.End=35]="End",Pi[Pi.Home=36]="Home",Pi[Pi.Left=37]="Left",Pi[Pi.Up=38]="Up",Pi[Pi.Right=39]="Right",Pi[Pi.Down=40]="Down",Pi[Pi.Insert=45]="Insert",Pi[Pi.Delete=46]="Delete",Pi[Pi.Help=47]="Help",Pi[Pi.Zero=48]="Zero",Pi[Pi.One=49]="One",Pi[Pi.Two=50]="Two",Pi[Pi.Three=51]="Three",Pi[Pi.Four=52]="Four",Pi[Pi.Five=53]="Five",Pi[Pi.Six=54]="Six",Pi[Pi.Seven=55]="Seven",Pi[Pi.Eight=56]="Eight",Pi[Pi.Nine=57]="Nine",Pi[Pi.A=65]="A",Pi[Pi.B=66]="B",Pi[Pi.C=67]="C",Pi[Pi.D=68]="D",Pi[Pi.E=69]="E",Pi[Pi.F=70]="F",Pi[Pi.G=71]="G",Pi[Pi.H=72]="H",Pi[Pi.I=73]="I",Pi[Pi.J=74]="J",Pi[Pi.K=75]="K",Pi[Pi.L=76]="L",Pi[Pi.M=77]="M",Pi[Pi.N=78]="N",Pi[Pi.O=79]="O",Pi[Pi.P=80]="P",Pi[Pi.Q=81]="Q",Pi[Pi.R=82]="R",Pi[Pi.S=83]="S",Pi[Pi.T=84]="T",Pi[Pi.U=85]="U",Pi[Pi.V=86]="V",Pi[Pi.W=87]="W",Pi[Pi.X=88]="X",Pi[Pi.Y=89]="Y",Pi[Pi.Z=90]="Z",Pi[Pi.NumPad0=96]="NumPad0",Pi[Pi.NumPad1=97]="NumPad1",Pi[Pi.NumPad2=98]="NumPad2",Pi[Pi.NumPad3=99]="NumPad3",Pi[Pi.NumPad4=100]="NumPad4",Pi[Pi.NumPad5=101]="NumPad5",Pi[Pi.NumPad6=102]="NumPad6",Pi[Pi.NumPad7=103]="NumPad7",Pi[Pi.NumPad8=104]="NumPad8",Pi[Pi.NumPad9=105]="NumPad9",Pi[Pi.NumPadMultiply=106]="NumPadMultiply",Pi[Pi.NumPadAdd=107]="NumPadAdd",Pi[Pi.NumPadEnter=108]="NumPadEnter",Pi[Pi.NumPadSubtract=109]="NumPadSubtract",Pi[Pi.NumPadDecimal=110]="NumPadDecimal",Pi[Pi.NumPadDivide=111]="NumPadDivide",Pi[Pi.F1=112]="F1",Pi[Pi.F2=113]="F2",Pi[Pi.F3=114]="F3",Pi[Pi.F4=115]="F4",Pi[Pi.F5=116]="F5",Pi[Pi.F6=117]="F6",Pi[Pi.F7=118]="F7",Pi[Pi.F8=119]="F8",Pi[Pi.F9=120]="F9",Pi[Pi.F10=121]="F10",Pi[Pi.F11=122]="F11",Pi[Pi.F12=123]="F12",Pi[Pi.NumLock=144]="NumLock",Pi[Pi.ScrollLock=145]="ScrollLock",Pi[Pi.Colon=186]="Colon",Pi[Pi.Equals=187]="Equals",Pi[Pi.Comma=188]="Comma",Pi[Pi.Dash=189]="Dash",Pi[Pi.Period=190]="Period",Pi[Pi.QuestionMark=191]="QuestionMark",Pi[Pi.Tilde=192]="Tilde",Pi[Pi.OpenBracket=219]="OpenBracket",Pi[Pi.BackwardSlash=220]="BackwardSlash",Pi[Pi.ClosedBracket=221]="ClosedBracket",Pi[Pi.Quotes=222]="Quotes";class Ai{_app;_focused=null;_shiftDown=!1;_scopeStack=[];_onKeyDownHandler;_onKeyUpHandler;constructor(e){this._app=e,this._onKeyDownHandler=this._handleKeyDown.bind(this),this._onKeyUpHandler=this._handleKeyUp.bind(this),e.input.onKeyDown.add(this._onKeyDownHandler),e.input.onKeyUp.add(this._onKeyUpHandler)}get focused(){return this._focused}focus(e){e!==this._focused&&e.focusable&&(this.blur(),this._focused=e,e._peekFocusSignal("focus")?.dispatch(e))}blur(e){const t=this._focused;null===t||void 0!==e&&e!==t||(this._focused=null,t._peekFocusSignal("blur")?.dispatch(t))}pushScope(e){this._scopeStack.push(e)}popScope(){this._scopeStack.pop()}focusNext(){this._step(1)}focusPrevious(){this._step(-1)}_notifyNodeRemoved(e){let t=this._focused;for(;null!==t;){if(t===e)return void this.blur();t=t.parent}}destroy(){this._app.input.onKeyDown.remove(this._onKeyDownHandler),this._app.input.onKeyUp.remove(this._onKeyUpHandler),this._scopeStack.length=0,this._focused=null}_handleKeyDown(t){t===e.Keyboard.Shift&&(this._shiftDown=!0);const i=this._focused;let n=!1;if(null!==i){const e=new Ci("keydown",t,i);i._peekKeySignal("keydown")?.dispatch(e),n=e.defaultPrevented}n||t!==e.Keyboard.Tab||(this._shiftDown?this.focusPrevious():this.focusNext())}_handleKeyUp(t){t===e.Keyboard.Shift&&(this._shiftDown=!1);const i=this._focused;null!==i&&i._peekKeySignal("keyup")?.dispatch(new Ci("keyup",t,i))}_step(e){const t=this._collectFocusables();if(0===t.length)return;const i=null===this._focused?-1:t.indexOf(this._focused),n=t.length;let r;r=-1===i?1===e?0:n-1:(i+e+n)%n;const s=t[r];void 0!==s&&this.focus(s)}_collectFocusables(){const e=this._scopeStack.at(-1)??this._app.scene.currentScene?.root??null;if(null===e)return[];const t=[];return this._collectInto(e,t),t.map((e,t)=>({node:e,index:t})).sort((e,t)=>e.node.tabIndex-t.node.tabIndex||e.index-t.index).map(e=>e.node)}_collectInto(e,t){if(e.visible&&(e.focusable&&t.push(e),e instanceof Bi))for(const i of e.children)this._collectInto(i,t)}}let Ei=null;class Ri{_milliseconds;constructor(e=0,t=Ri.milliseconds){this._milliseconds=e*t}get milliseconds(){return this._milliseconds}set milliseconds(e){this._milliseconds=e}get seconds(){return this._milliseconds/Ri.seconds}set seconds(e){this._milliseconds=e*Ri.seconds}get minutes(){return this._milliseconds/Ri.minutes}set minutes(e){this._milliseconds=e*Ri.minutes}get hours(){return this._milliseconds/Ri.hours}set hours(e){this._milliseconds=e*Ri.hours}set(e=0,t=Ri.milliseconds){return this._milliseconds=e*t,this}setMilliseconds(e){return this.milliseconds=e,this}setSeconds(e){return this.seconds=e,this}setMinutes(e){return this.minutes=e,this}setHours(e){return this.hours=e,this}equals({milliseconds:e,seconds:t,minutes:i,hours:n}={}){return!(void 0!==e&&this.milliseconds!==e||void 0!==t&&this.seconds!==t||void 0!==i&&this.minutes!==i||void 0!==n&&this.hours!==n)}greaterThan(e){return this._milliseconds>e.milliseconds}lessThan(e){return this._milliseconds<e.milliseconds}clone(){return new Ri(this._milliseconds)}copy(e){return this._milliseconds=e.milliseconds,this}add(e=0,t=Ri.milliseconds){return this._milliseconds+=e*t,this}addTime(e){return this._milliseconds+=e.milliseconds,this}subtract(e=0,t=Ri.milliseconds){return this._milliseconds-=e*t,this}subtractTime(e){return this._milliseconds-=e.milliseconds,this}destroy(){}static milliseconds=1;static seconds=1e3;static minutes=6e4;static hours=36e5;static now(){return new Ri(performance.now())}static fromMilliseconds(e){return new Ri(e,Ri.milliseconds)}static fromSeconds(e){return new Ri(e,Ri.seconds)}static fromMinutes(e){return new Ri(e,Ri.minutes)}static fromHours(e){return new Ri(e,Ri.hours)}static zero=new Ri(0);static oneMillisecond=new Ri(1);static oneSecond=new Ri(1,Ri.seconds);static oneMinute=new Ri(1,Ri.minutes);static oneHour=new Ri(1,Ri.hours);static get temp(){return null===Ei&&(Ei=new Ri),Ei}}class ki{_startTime;_elapsedTime=new Ri(0);_running=!1;constructor(e=Ri.zero,t=!1){this._startTime=e.clone(),t&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const e=p();this._elapsedTime.add(e-this._startTime.milliseconds),this._startTime.milliseconds=e}return this._elapsedTime}get elapsedMilliseconds(){return this.elapsedTime.milliseconds}get elapsedSeconds(){return this.elapsedTime.seconds}get elapsedMinutes(){return this.elapsedTime.minutes}get elapsedHours(){return this.elapsedTime.hours}start(){return this._running||(this._running=!0,this._startTime.milliseconds=p()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(p()-this._startTime.milliseconds)),this}reset(){return this._running=!1,this._elapsedTime.setMilliseconds(0),this}restart(){return this.reset(),this.start(),this}destroy(){this._startTime.destroy(),this._elapsedTime.destroy()}}class Di extends ki{_limit;constructor(e,t=!1){super(),this._limit=e.clone(),t&&this.restart()}get limit(){return this._limit}set limit(e){this._limit.copy(e)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/Ri.seconds}get remainingMinutes(){return this.remainingMilliseconds/Ri.minutes}get remainingHours(){return this.remainingMilliseconds/Ri.hours}}class Fi{static defaultTriggerThreshold=300;channels;onStart=new x;onActive=new x;onStop=new x;onTrigger=new x;_triggerTimer;_detacher;_value=0;_unbound=!1;constructor(e,t={},i=null){this.channels=e,this._triggerTimer=new Di(Ri.fromMilliseconds(t.threshold??Fi.defaultTriggerThreshold)),this._detacher=i}get value(){return this._value}get active(){return this._value>0}update(e){if(this._unbound)return;let t=0;for(const i of this.channels){const n=e[i];void 0!==n&&Math.abs(n)>Math.abs(t)&&(t=n)}this._value=t,0!==t?(this._triggerTimer.running||(this._triggerTimer.restart(),this.onStart.dispatch(t)),this.onActive.dispatch(t)):this._triggerTimer.running&&(this.onStop.dispatch(0),this._triggerTimer.expired||this.onTrigger.dispatch(0),this._triggerTimer.stop())}unbind(){this._unbound||(this._unbound=!0,this._detacher?.detach(this),this._triggerTimer.destroy(),this.onStart.destroy(),this.onActive.destroy(),this.onStop.destroy(),this.onTrigger.destroy())}}class Ii{onConnect=new x;onDisconnect=new x;onButtonDown=new x;onButtonUp=new x;onAxisChange=new x;onPadReassigned=new x;_slot;_channels;_bindings=new Set;_detacher={detach:e=>{this._bindings.delete(e)}};_channelOffset;_mapping=null;_info=null;_browserGamepad=null;constructor(t,i){this._slot=t,this._channels=i,this._channelOffset=e.ChannelOffset.Gamepads+t*e.ChannelSize.Gamepad}get slot(){return this._slot}get connected(){return null!==this._browserGamepad}get mapping(){return this._mapping}get mappingFamily(){return this._mapping?.family??null}get info(){return this._info}get browserGamepad(){return this._browserGamepad}get internalIndex(){return this._browserGamepad?.index??null}get canVibrate(){return null!=this._browserGamepad?.vibrationActuator}hasChannel(e){return this._mapping?.hasChannel(e)??!1}async vibrate(e){const t=this._browserGamepad?.vibrationActuator;t?.playEffect&&await t.playEffect("dual-rumble",{duration:e.duration,weakMagnitude:e.weakMagnitude??1,strongMagnitude:e.strongMagnitude??1,startDelay:e.startDelay??0})}stopVibration(){this._browserGamepad?.vibrationActuator?.reset?.()}onStart(e,t,i){const n=this._createBinding(e,i);return n.onStart.add(t),n}onActive(e,t,i){const n=this._createBinding(e,i);return n.onActive.add(t),n}onStop(e,t,i){const n=this._createBinding(e,i);return n.onStop.add(t),n}onTrigger(e,t,i){const n=this._createBinding(e,i);return n.onTrigger.add(t),n}_bind(e,t){this._browserGamepad=e,this._mapping=t.mapping,this._info={name:t.name,label:t.descriptor.label,vendorId:t.descriptor.vendorId,productId:t.descriptor.productId,productKey:t.descriptor.productKey},this.onConnect.dispatch()}_refreshBrowserGamepad(e){this._browserGamepad=e}_unbind(){null!==this._browserGamepad&&(this._clearMappedChannels(),this._browserGamepad=null,this._mapping=null,this._info=null,this.onDisconnect.dispatch())}_silentUnbind(){null!==this._browserGamepad&&(this._clearMappedChannels(),this._browserGamepad=null,this._mapping=null,this._info=null)}_dispatchDisconnect(){this.onDisconnect.dispatch()}_rebindFrom(e){const t=e._browserGamepad,i=e._mapping,n=e._info;this._clearMappedChannels(),e._clearMappedChannels(),e._browserGamepad=null,e._mapping=null,e._info=null,this._browserGamepad=t,this._mapping=i,this._info=n}update(){if(null===this._browserGamepad||null===this._mapping)return void this._updateBindings();const e=this._channels,{buttons:t,axes:i}=this._browserGamepad;for(const i of this._mapping.buttons){const n=t[i.index];if(void 0===n)continue;const r=this._resolveOffset(i.channel),s=e[r],o=i.transformValue(n.value)||0;s!==o&&(e[r]=o,0===s&&0!==o?this.onButtonDown.dispatch(i,o):0!==s&&0===o&&this.onButtonUp.dispatch(i,o))}for(const t of this._mapping.axes){const n=i[t.index];if(void 0===n)continue;const r=this._resolveOffset(t.channel),s=e[r],o=t.transformValue(n)||0;s!==o&&(e[r]=o,this.onAxisChange.dispatch(t,o))}this._updateBindings()}destroy(){for(const e of[...this._bindings])e.unbind();this._bindings.clear(),this._unbind(),this.onConnect.destroy(),this.onDisconnect.destroy(),this.onButtonDown.destroy(),this.onButtonUp.destroy(),this.onAxisChange.destroy(),this.onPadReassigned.destroy()}resolveChannelOffset(e){return this._resolveOffset(e)}static resolveChannelOffset(t,i){return e.ChannelOffset.Gamepads+t*e.ChannelSize.Gamepad+(i^e.ChannelOffset.Gamepads)}_resolveOffset(t){return this._channelOffset+(t^e.ChannelOffset.Gamepads)}_clearMappedChannels(){if(null!==this._mapping){for(const e of this._mapping.buttons)this._channels[this._resolveOffset(e.channel)]=0;for(const e of this._mapping.axes)this._channels[this._resolveOffset(e.channel)]=0}}_createBinding(e,t={}){const i=(Array.isArray(e)?e:[e]).map(e=>this._resolveExternalChannel(e)),n=new Fi(i,t,this._detacher);return this._bindings.add(n),n}_resolveExternalChannel(t){return t>=e.ChannelOffset.Gamepads&&t<e.ChannelOffset.Gamepads+e.ChannelSize.Category?this._resolveOffset(t):t}_updateBindings(){for(const e of this._bindings)e.update(this._channels)}}class Li{index;channel;invert;threshold;constructor(e,t,i={}){this.index=e,this.channel=t,this.invert=i.invert??!1,this.threshold=Y(i.threshold??.2,0,1)}transformValue(e){let t=Y(e,0,1);return this.invert&&(t=1-t),t>this.threshold?t:0}}const Ui=t=>e.ChannelOffset.Gamepads+t;var Gi;!function(e){e.South=Ui(0),e.East=Ui(1),e.West=Ui(2),e.North=Ui(3),e.LeftShoulder=Ui(4),e.RightShoulder=Ui(5),e.LeftTrigger=Ui(6),e.RightTrigger=Ui(7),e.Select=Ui(8),e.Start=Ui(9),e.LeftStick=Ui(10),e.RightStick=Ui(11),e.DPadUp=Ui(12),e.DPadDown=Ui(13),e.DPadLeft=Ui(14),e.DPadRight=Ui(15),e.Guide=Ui(16),e.Share=Ui(17),e.Capture=Ui(18),e.Touchpad=Ui(19),e.Paddle1=Ui(20),e.Paddle2=Ui(21),e.Paddle3=Ui(22),e.Paddle4=Ui(23)}(Li||(Li={})),e.GamepadMappingFamily=void 0,(Gi=e.GamepadMappingFamily||(e.GamepadMappingFamily={})).GenericDualAnalog="genericDualAnalog",Gi.Xbox="xbox",Gi.PlayStation="playStation",Gi.SwitchPro="switchPro",Gi.JoyConLeft="joyConLeft",Gi.JoyConRight="joyConRight",Gi.GameCube="gameCube",Gi.SteamController="steamController",Gi.SteamDeck="steamDeck",Gi.ArcadeStick="arcadeStick";class Ni{buttons;axes;constructor(e,t){this.buttons=e,this.axes=t}hasChannel(e){for(const t of this.buttons)if(t.channel===e)return!0;for(const t of this.axes)if(t.channel===e)return!0;return!1}destroy(){this.buttons.length=0,this.axes.length=0}}class Oi extends Ni{family=e.GamepadMappingFamily.ArcadeStick;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(6,Li.LeftTrigger),new Li(7,Li.RightTrigger),new Li(8,Li.Select),new Li(9,Li.Start),new Li(12,Li.DPadUp),new Li(13,Li.DPadDown),new Li(14,Li.DPadLeft),new Li(15,Li.DPadRight),new Li(16,Li.Guide)],[])}}class Vi{index;channel;invert;normalize;threshold;bipolar;constructor(e,t,i={}){this.index=e,this.channel=t,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=Y(i.threshold??.2,0,1),this.bipolar=i.bipolar??!1}transformValue(e){let t=Y(e,-1,1);return this.invert&&(t*=-1),this.normalize&&(t=(t+1)/2),this.bipolar?Math.abs(t)>this.threshold?t:0:t>this.threshold?t:0}}const zi=t=>e.ChannelOffset.Gamepads+t;!function(e){e.LeftStickLeft=zi(32),e.LeftStickRight=zi(33),e.LeftStickUp=zi(34),e.LeftStickDown=zi(35),e.RightStickLeft=zi(36),e.RightStickRight=zi(37),e.RightStickUp=zi(38),e.RightStickDown=zi(39),e.LeftStickX=zi(40),e.LeftStickY=zi(41),e.RightStickX=zi(42),e.RightStickY=zi(43),e.TouchpadX=zi(44),e.TouchpadY=zi(45),e.Touchpad2X=zi(46),e.Touchpad2Y=zi(47),e.AuxiliaryAxis0Negative=zi(48),e.AuxiliaryAxis0Positive=zi(49),e.AuxiliaryAxis1Negative=zi(50),e.AuxiliaryAxis1Positive=zi(51),e.AuxiliaryAxis2Negative=zi(52),e.AuxiliaryAxis2Positive=zi(53),e.AuxiliaryAxis3Negative=zi(54),e.AuxiliaryAxis3Positive=zi(55)}(Vi||(Vi={}));class qi extends Ni{family=e.GamepadMappingFamily.GenericDualAnalog;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(6,Li.LeftTrigger),new Li(7,Li.RightTrigger),new Li(8,Li.Select),new Li(9,Li.Start),new Li(10,Li.LeftStick),new Li(11,Li.RightStick),new Li(12,Li.DPadUp),new Li(13,Li.DPadDown),new Li(14,Li.DPadLeft),new Li(15,Li.DPadRight),new Li(16,Li.Guide),new Li(17,Li.Share),new Li(18,Li.Capture),new Li(19,Li.Touchpad),new Li(20,Li.Paddle1)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(2,Vi.RightStickLeft,{invert:!0}),new Vi(2,Vi.RightStickRight),new Vi(3,Vi.RightStickUp,{invert:!0}),new Vi(3,Vi.RightStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0}),new Vi(2,Vi.RightStickX,{bipolar:!0}),new Vi(3,Vi.RightStickY,{bipolar:!0}),new Vi(4,Vi.AuxiliaryAxis0Negative,{invert:!0}),new Vi(4,Vi.AuxiliaryAxis0Positive),new Vi(5,Vi.AuxiliaryAxis1Negative,{invert:!0}),new Vi(5,Vi.AuxiliaryAxis1Positive),new Vi(6,Vi.AuxiliaryAxis2Negative,{invert:!0}),new Vi(6,Vi.AuxiliaryAxis2Positive),new Vi(7,Vi.AuxiliaryAxis3Negative,{invert:!0}),new Vi(7,Vi.AuxiliaryAxis3Positive)])}}class Wi extends qi{family=e.GamepadMappingFamily.GameCube}class Yi extends Ni{family=e.GamepadMappingFamily.JoyConLeft;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(8,Li.Select),new Li(10,Li.LeftStick),new Li(16,Li.Capture)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0})])}}class $i extends Ni{family=e.GamepadMappingFamily.JoyConRight;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(9,Li.Start),new Li(10,Li.LeftStick),new Li(16,Li.Guide)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0})])}}class Xi extends qi{family=e.GamepadMappingFamily.PlayStation}class Hi extends qi{family=e.GamepadMappingFamily.SteamController}class ji extends Ni{family=e.GamepadMappingFamily.SteamDeck;constructor(){super([new Li(2,Li.Capture),new Li(3,Li.South),new Li(4,Li.East),new Li(5,Li.West),new Li(6,Li.North),new Li(7,Li.LeftShoulder),new Li(8,Li.RightShoulder),new Li(11,Li.Select),new Li(12,Li.Start),new Li(13,Li.Guide),new Li(14,Li.LeftStick),new Li(15,Li.RightStick),new Li(16,Li.DPadUp),new Li(17,Li.DPadDown),new Li(18,Li.DPadLeft),new Li(19,Li.DPadRight),new Li(20,Li.Paddle2),new Li(21,Li.Paddle1),new Li(22,Li.Paddle4),new Li(23,Li.Paddle3)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(2,Vi.RightStickLeft,{invert:!0}),new Vi(2,Vi.RightStickRight),new Vi(3,Vi.RightStickUp,{invert:!0}),new Vi(3,Vi.RightStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0}),new Vi(2,Vi.RightStickX,{bipolar:!0}),new Vi(3,Vi.RightStickY,{bipolar:!0}),new Vi(8,Vi.AuxiliaryAxis0Positive,{normalize:!0}),new Vi(9,Vi.AuxiliaryAxis1Positive,{normalize:!0})])}}class Ki extends qi{family=e.GamepadMappingFamily.SwitchPro}class Qi extends qi{family=e.GamepadMappingFamily.Xbox}const Zi=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Ji=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,en=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,tn=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,nn=(e,t,i)=>({...void 0!==i&&{ids:i},name:e,resolve:()=>({name:e,mapping:t()})}),rn=e=>e.trim().toLowerCase(),sn=e=>{const t=e.replace(Ji,"").replace(Zi,"").replace(tn,"").replace(en,"").replaceAll(/\s+/g," ").trim();return t.length>0?t:null},on=(e,t)=>{if(!t)return!0;for(const i of(e=>e?(Array.isArray(e)?e:[e]).map(rn):[])(t))if(i.includes(":")){if(e.productKey===i)return!0}else if(e.vendorId===i)return!0;return!1},an=e=>{const t=e.id.trim()||`Gamepad ${e.index}`,i=(e=>{const t=Ji.exec(e)||Zi.exec(e)||tn.exec(e)||en.exec(e);if(!t)return null;const[,i,n]=t;return void 0===i||void 0===n?null:`${i.toLowerCase()}:${n.toLowerCase()}`})(t),n=i?.slice(0,4)??null,r=i?.slice(5)??null;return{id:e.id,index:e.index,label:t,vendorId:n,productId:r,productKey:i,name:sn(t)}},hn=(e,t)=>on(t,e.ids)?((e,t)=>{const i=e.resolve(t);return null==i?null:"mapping"in i?{descriptor:t,name:i.name??e.name??t.name??t.label,mapping:i.mapping}:{descriptor:t,name:e.name??t.name??t.label,mapping:i}})(e,t):null,ln=[...[nn("Xbox 360 Controller",()=>new Qi,"045e:028e"),nn("Xbox One Controller",()=>new Qi,["045e:02d1","045e:02dd"]),nn("Xbox Wireless Controller",()=>new Qi,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),nn("Xbox One Elite Controller",()=>new Qi,"045e:02e3"),nn("Xbox Elite Wireless Controller Series 2",()=>new Qi,["045e:0b00","045e:0b05","045e:0b22"]),nn("Xbox Series Controller",()=>new Qi,["045e:0b12","045e:0b13"]),nn("PlayStation 3 Controller",()=>new Xi,"054c:0268"),nn("DualShock 4 Controller",()=>new Xi,["054c:05c4","054c:09cc","054c:0ba0"]),nn("DualSense Controller",()=>new Xi,"054c:0ce6"),nn("DualSense Edge Controller",()=>new Xi,"054c:0df2"),nn("GameCube Controller Adapter",()=>new Wi,"057e:0337"),nn("Joy-Con (L)",()=>new Yi,"057e:2006"),nn("Joy-Con (R)",()=>new $i,"057e:2007"),nn("Joy-Con Charging Grip",()=>new Ki,"057e:200e"),nn("Switch Pro Controller",()=>new Ki,"057e:2009"),nn("Joy-Con 2 (L)",()=>new Yi,"057e:2066"),nn("Joy-Con 2 (R)",()=>new $i,"057e:2067"),nn("Switch 2 Pro Controller",()=>new Ki,"057e:2069"),nn("Switch 2 GameCube Controller",()=>new Wi,"057e:2073"),nn("Steam Controller",()=>new Hi,["28de:1102","28de:1142"]),nn("Steam Virtual Gamepad",()=>new qi,"28de:11ff"),nn("Steam Deck",()=>new ji,"28de:1205"),nn("F310 Gamepad",()=>new qi,"046d:c216"),nn("F710 Gamepad",()=>new qi,["046d:c219","046d:c21f"]),nn("8BitDo P30 Controller",()=>new qi,["2dc8:5107","2dc8:5108"]),nn("8BitDo SF30 Pro Controller",()=>new Ki,["2dc8:3000","2dc8:6100","2dc8:6101"]),nn("8BitDo SN30 Controller",()=>new Ki,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),nn("8BitDo NES30 Controller",()=>new qi,"2dc8:ab12"),nn("PowerA Switch Controller",()=>new Ki,"20d6:a713"),nn("PowerA OPS Pro Wireless Controller",()=>new qi,"20d6:4033"),nn("PowerA OPS Wireless Controller",()=>new qi,"20d6:4026"),nn("Nacon Revolution 3 Controller",()=>new Xi,"146b:0611"),nn("Nacon Revolution Unlimited Pro Controller",()=>new Xi,"146b:0d08"),nn("Nacon Revolution Infinity Controller",()=>new Xi,"146b:0d10"),nn("Nacon Revolution 5 Pro Controller",()=>new Xi,["3285:0d17","3285:0d19"]),nn("Razer Raiju Controller",()=>new Xi,"1532:1000"),nn("Razer Raiju Mobile Controller",()=>new Xi,["1532:0705","1532:0707"]),nn("Razer Raiju Tournament Edition Controller",()=>new Xi,["1532:1007","1532:100a"]),nn("Razer Raiju Ultimate Controller",()=>new Xi,["1532:1004","1532:1009"]),nn("Razer Raion Controller",()=>new Oi,"1532:1100")],...[nn("Microsoft Controller",()=>new Qi,"045e"),nn("Sony Controller",()=>new Xi,"054c"),nn("Valve Controller",()=>new ji,"28de")],nn("Generic Gamepad",()=>new qi)];class un{onPinch;onRotate;onLongPress;touchPointers=new Map;longPressEntries=new Map;prevDistance=-1;prevAngle=0;centerVec=new it;constructor(e,t,i,n){this.onPinch=t,this.onRotate=i,this.onLongPress=n}onPointerDown(e){"touch"===e.type&&(this.touchPointers.set(e.id,e),this._resetTwoTouchBaseline());const t=setTimeout(()=>{this.longPressEntries.delete(e.id),this.onLongPress.dispatch(e)},500);this.longPressEntries.set(e.id,{pointerId:e.id,pointer:e,timerId:t,startX:e.x,startY:e.y})}onPointerMove(e,t){const i=this.longPressEntries.get(e.id);if(i){const n=e.x-i.startX,r=e.y-i.startY;Math.sqrt(n*n+r*r)>t&&(clearTimeout(i.timerId),this.longPressEntries.delete(e.id))}"touch"===e.type&&(this.touchPointers.size<2||this._processTwoTouchGestures())}onPointerUp(e){this._cancelLongPress(e.id)}onPointerLeave(e){this._cancelLongPress(e.id),"touch"===e.type&&(this.touchPointers.delete(e.id),this._resetTwoTouchBaseline())}onPointerCancel(e){this._cancelLongPress(e.id),"touch"===e.type&&(this.touchPointers.delete(e.id),this._resetTwoTouchBaseline())}destroy(){for(const e of this.longPressEntries.values())clearTimeout(e.timerId);this.longPressEntries.clear(),this.touchPointers.clear(),this.centerVec.destroy()}_cancelLongPress(e){const t=this.longPressEntries.get(e);t&&(clearTimeout(t.timerId),this.longPressEntries.delete(e))}_resetTwoTouchBaseline(){this.prevDistance=-1,this.prevAngle=0}_processTwoTouchGestures(){const e=this.touchPointers.values(),t=e.next().value,i=e.next().value,n=i.x-t.x,r=i.y-t.y,s=Math.sqrt(n*n+r*r),o=Math.atan2(r,n),a=(t.x+i.x)/2,h=(t.y+i.y)/2;if(this.centerVec.set(a,h),this.prevDistance>0){const e=s/this.prevDistance;Math.abs(e-1)>1e-4&&this.onPinch.dispatch(e,this.centerVec);const t=o-this.prevAngle;Math.abs(t)>1e-4&&this.onRotate.dispatch(t,this.centerVec)}this.prevDistance=s,this.prevAngle=o}}const cn=t=>e.ChannelOffset.Pointers+t,dn=(e,t)=>cn(16*e+t);var _n,fn;e.PointerStateFlag=void 0,(_n=e.PointerStateFlag||(e.PointerStateFlag={}))[_n.None=0]="None",_n[_n.Over=1]="Over",_n[_n.Leave=2]="Leave",_n[_n.Down=4]="Down",_n[_n.Move=8]="Move",_n[_n.Up=16]="Up",_n[_n.Cancel=32]="Cancel",e.PointerState=void 0,(fn=e.PointerState||(e.PointerState={}))[fn.Unknown=0]="Unknown",fn[fn.InsideCanvas=1]="InsideCanvas",fn[fn.OutsideCanvas=2]="OutsideCanvas",fn[fn.Pressed=3]="Pressed",fn[fn.Moving=4]="Moving",fn[fn.Released=5]="Released",fn[fn.Cancelled=6]="Cancelled";class pn{id;type;position;startPos=new it(-1,-1);size;tilt;stateFlags=new Mt;_app;_canvas;_channels;_slotIndex;_channelBase;_buttons;_pressure;_rotation;_isPrimary;_currentState=e.PointerState.Unknown;constructor(t,i,n,r,s){const{pointerId:o,pointerType:a,clientX:h,clientY:u,width:c,height:d,tiltX:_,tiltY:f,buttons:p,pressure:m,twist:g,isPrimary:y}=t;this._app=i,this._canvas=n,this._channels=r,this._slotIndex=s,this._channelBase=e.ChannelOffset.Pointers+16*s;const w=this._computeDesignGeometry(h,u,c,d);this.id=o,this.type=a,this.position=new it(w.x,w.y),this.size=new l(w.width,w.height),this.tilt=new it(_,f),this._buttons=p,this._pressure=m,this._rotation=g,this._isPrimary=y,this.stateFlags.push(e.PointerStateFlag.Over),this._writeChannels(!0)}get x(){return this.position.x}get y(){return this.position.y}get width(){return this.size.width}get height(){return this.size.height}get buttons(){return this._buttons}get pressure(){return this._pressure}get rotation(){return this._rotation}get twist(){return this._rotation}get tiltX(){return this.tilt.x}get tiltY(){return this.tilt.y}get isPrimary(){return this._isPrimary}get slotIndex(){return this._slotIndex}get currentState(){return this._currentState}handleEnter(t){this.handleEvent(t),this._currentState=e.PointerState.InsideCanvas,this._writeChannels(!0)}handleLeave(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Leave),this._currentState=e.PointerState.OutsideCanvas,this._writeChannels(!1)}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(e.PointerStateFlag.Down),this._currentState=e.PointerState.Pressed,this._writeChannels(!0)}handleMove(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Move),this._currentState=e.PointerState.Moving,this._writeChannels(!0)}handleRelease(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Up),this._currentState=e.PointerState.Released,this._writeChannels(!0)}handleCancel(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Cancel),this._currentState=e.PointerState.Cancelled,this._writeChannels(!1)}destroy(){this._clearChannels(),this.position.destroy(),this.startPos.destroy(),this.size.destroy(),this.tilt.destroy(),this._app=null,this._canvas=null,this._channels=null}handleEvent(e){const{clientX:t,clientY:i,width:n,height:r,tiltX:s,tiltY:o,buttons:a,pressure:h,twist:l,isPrimary:u}=e,c=this._computeDesignGeometry(t,i,n,r);return this.position.set(c.x,c.y),this.size.set(c.width,c.height),this.tilt.set(s,o),this._buttons=a,this._pressure=h,this._rotation=l,this._isPrimary=u,this}_computeDesignGeometry(e,t,i,n){const r=this._app,s=this._canvas;if(!r||!s)return{x:0,y:0,width:0,height:0};const o=s.getBoundingClientRect(),a=o.width>0?(e-o.left)/o.width:0,h=o.height>0?(t-o.top)/o.height:0,l=a*s.width,u=h*s.height,c=o.width>0?i/o.width*s.width:0,d=o.height>0?n/o.height*s.height:0,_=r._backingStoreToDesign(l,u),f=r._backingStoreToDesign(l+c,u+d);return{x:_.x,y:_.y,width:Math.abs(f.x-_.x),height:Math.abs(f.y-_.y)}}_writeChannels(e){const t=this._channels,i=this._canvas;if(!t||!i)return;const n=this._channelBase,r=this._app,s=(r?r.width:i.width)||1,o=(r?r.height:i.height)||1;if(!e){for(let e=0;e<16;e++)t[n+e]=0;return}const a=Math.min(1,Math.max(0,this.position.x/s)),h=Math.min(1,Math.max(0,this.position.y/o));t[n+0]=1,t[n+1]=a,t[n+2]=h,t[n+3]=this._pressure,t[n+4]=Math.min(1,this.size.width/s),t[n+5]=Math.min(1,this.size.height/o),t[n+6]=this._rotation/359,t[n+7]=(this.tilt.x+90)/180,t[n+8]=(this.tilt.y+90)/180,t[n+9]=1&this._buttons?1:0,t[n+10]=2&this._buttons?1:0,t[n+11]=4&this._buttons?1:0,t[n+12]="mouse"===this.type?1:0,t[n+13]="touch"===this.type?1:0,t[n+14]="pen"===this.type?1:0,t[n+15]=this._isPrimary?1:0}_clearChannels(){const e=this._channels;if(!e)return;const t=this._channelBase;for(let i=0;i<16;i++)e[t+i]=0}}!function(e){e.Active=cn(0),e.X=cn(1),e.Y=cn(2),e.Pressure=cn(3),e.Width=cn(4),e.Height=cn(5),e.Twist=cn(6),e.TiltX=cn(7),e.TiltY=cn(8),e.Left=cn(9),e.Right=cn(10),e.Middle=cn(11),e.IsMouse=cn(12),e.IsTouch=cn(13),e.IsPen=cn(14),e.IsPrimary=cn(15),e.Slot0Active=dn(0,0),e.Slot0X=dn(0,1),e.Slot0Y=dn(0,2),e.Slot1Active=dn(1,0),e.Slot1X=dn(1,1),e.Slot1Y=dn(1,2),e.Slot2Active=dn(2,0),e.Slot2X=dn(2,1),e.Slot2Y=dn(2,2),e.Slot3Active=dn(3,0),e.Slot3X=dn(3,1),e.Slot3Y=dn(3,2),e.Slot4Active=dn(4,0),e.Slot4X=dn(4,1),e.Slot4Y=dn(4,2),e.Slot5Active=dn(5,0),e.Slot5X=dn(5,1),e.Slot5Y=dn(5,2),e.Slot6Active=dn(6,0),e.Slot6X=dn(6,1),e.Slot6Y=dn(6,2),e.Slot7Active=dn(7,0),e.Slot7X=dn(7,1),e.Slot7Y=dn(7,2),e.Slot8Active=dn(8,0),e.Slot8X=dn(8,1),e.Slot8Y=dn(8,2),e.Slot9Active=dn(9,0),e.Slot9X=dn(9,1),e.Slot9Y=dn(9,2),e.Slot10Active=dn(10,0),e.Slot10X=dn(10,1),e.Slot10Y=dn(10,2),e.Slot11Active=dn(11,0),e.Slot11X=dn(11,1),e.Slot11Y=dn(11,2),e.Slot12Active=dn(12,0),e.Slot12X=dn(12,1),e.Slot12Y=dn(12,2),e.Slot13Active=dn(13,0),e.Slot13X=dn(13,1),e.Slot13Y=dn(13,2),e.Slot14Active=dn(14,0),e.Slot14X=dn(14,1),e.Slot14Y=dn(14,2),e.Slot15Active=dn(15,0),e.Slot15X=dn(15,1),e.Slot15Y=dn(15,2)}(pn||(pn={}));var mn,gn;!function(e){e[e.None=0]="None",e[e.KeyDown=1]="KeyDown",e[e.KeyUp=2]="KeyUp",e[e.MouseWheel=4]="MouseWheel",e[e.PointerUpdate=8]="PointerUpdate"}(mn||(mn={}));class yn{order=100;_app;canvas;channels=new Float32Array(e.ChannelSize.Container);pointers=new Map;_gamepads;gamepadsByBrowserIndex=new Map;bindings=new Set;capturedKeyChannels=new Map;bindingDetacher={detach:t=>{this.bindings.delete(t);for(const i of t.channels)if(i<e.ChannelSize.Category){const e=this.capturedKeyChannels.get(i);void 0!==e&&(e<=1?this.capturedKeyChannels.delete(i):this.capturedKeyChannels.set(i,e-1))}}};wheelOffset=new it;flags=new Mt;channelsPressed=[];channelsReleased=[];gamepadDefinitions;slotStrategy;pointerSlots=new Map;freeSlots=Array.from({length:16},(e,t)=>t);gestureRecognizer;canvasFocusedValue;pointerDistanceThreshold;keyDownHandler=this.handleKeyDown.bind(this);keyUpHandler=this.handleKeyUp.bind(this);canvasFocusHandler=this.handleCanvasFocus.bind(this);canvasBlurHandler=this.handleCanvasBlur.bind(this);windowBlurHandler=this.handleWindowBlur.bind(this);mouseWheelHandler=this.handleMouseWheel.bind(this);pointerOverHandler=this.handlePointerOver.bind(this);pointerLeaveHandler=this.handlePointerLeave.bind(this);pointerDownHandler=this.handlePointerDown.bind(this);pointerMoveHandler=this.handlePointerMove.bind(this);pointerUpHandler=this.handlePointerUp.bind(this);pointerCancelHandler=this.handlePointerCancel.bind(this);onCanvasFocusChange=new x;onPointerEnter=new x;onPointerLeave=new x;onPointerDown=new x;onPointerMove=new x;onPointerUp=new x;onPointerTap=new x;onPointerSwipe=new x;onPointerCancel=new x;onMouseWheel=new x;onKeyDown=new x;onKeyUp=new x;onGamepadConnected=new x;onGamepadDisconnected=new x;onAnyGamepadReassigned=new x;onAnyGamepadButtonDown=new x;onAnyGamepadButtonUp=new x;onAnyGamepadAxisChange=new x;onPinch=new x;onRotate=new x;onLongPress=new x;constructor(e){const t=e.options.input??{},i=t.gamepadDefinitions??[],n=t.pointerDistanceThreshold??10,r=t.gamepadSlotStrategy??"sticky";this._app=e,this.canvas=e.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=n,this.gamepadDefinitions=[...i,...ln],this.slotStrategy=r,this.canvas.style.touchAction="none",this.gestureRecognizer=new un(n,this.onPinch,this.onRotate,this.onLongPress);const s=new Ii(0,this.channels),o=new Ii(1,this.channels),a=new Ii(2,this.channels),h=new Ii(3,this.channels);this._gamepads=[s,o,a,h];for(const e of this._gamepads)this.wireGamepadEvents(e);this.addEventListeners()}getPrimaryPointerPosition(){for(const t of this.pointers.values())if(t.isPrimary&&t.currentState!==e.PointerState.Cancelled)return{x:t.x,y:t.y};for(const t of this.pointers.values())if(t.currentState!==e.PointerState.Cancelled)return{x:t.x,y:t.y};return null}get pointersInCanvas(){for(const t of this.pointers.values())if(t.currentState!==e.PointerState.OutsideCanvas&&t.currentState!==e.PointerState.Cancelled)return!0;return!1}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this._gamepads}get gamepadSlotStrategy(){return this.slotStrategy}getGamepad(e){return this._gamepads[e]}get connectedGamepads(){const e=[];for(const t of this._gamepads)t.connected&&e.push(t);return e}get connectedGamepadCount(){let e=0;for(const t of this._gamepads)t.connected&&e++;return e}get firstConnectedGamepad(){for(const e of this._gamepads)if(e.connected)return e;return null}get hasGamepad(){for(const e of this._gamepads)if(e.connected)return!0;return!1}onStart(e,t,i){const n=this.createBinding(e,i);return n.onStart.add(t),n}onActive(e,t,i){const n=this.createBinding(e,i);return n.onActive.add(t),n}onStop(e,t,i){const n=this.createBinding(e,i);return n.onStop.add(t),n}onTrigger(e,t,i){const n=this.createBinding(e,i);return n.onTrigger.add(t),n}update(e){this.updateGamepads();for(const e of this.bindings)e.update(this.channels);this.flags.value!==mn.None&&this.updateEvents()}destroy(){this.removeEventListeners(),this.gestureRecognizer.destroy();for(const e of this.pointers.values())e.destroy();this.pointers.clear();for(const e of this._gamepads)e.destroy();for(const e of[...this.bindings])e.unbind();this.bindings.clear(),this.capturedKeyChannels.clear(),this.gamepadsByBrowserIndex.clear(),this.channelsPressed.length=0,this.channelsReleased.length=0,this.pointerSlots.clear(),this.freeSlots.length=0,this.wheelOffset.destroy(),this.flags.destroy(),this.onPointerEnter.destroy(),this.onPointerLeave.destroy(),this.onPointerDown.destroy(),this.onPointerMove.destroy(),this.onPointerUp.destroy(),this.onPointerTap.destroy(),this.onPointerSwipe.destroy(),this.onPointerCancel.destroy(),this.onMouseWheel.destroy(),this.onKeyDown.destroy(),this.onKeyUp.destroy(),this.onGamepadConnected.destroy(),this.onGamepadDisconnected.destroy(),this.onAnyGamepadReassigned.destroy(),this.onAnyGamepadButtonDown.destroy(),this.onAnyGamepadButtonUp.destroy(),this.onAnyGamepadAxisChange.destroy(),this.onPinch.destroy(),this.onRotate.destroy(),this.onLongPress.destroy(),this.onCanvasFocusChange.destroy()}createBinding(t,i={}){const n=Array.isArray(t)?t:[t],r=i.gamepadSlot??0,s=n.map(e=>this.resolveExternalChannel(e,r)),o=new Fi(s,i,this.bindingDetacher);this.bindings.add(o);for(const t of s)t<e.ChannelSize.Category&&this.capturedKeyChannels.set(t,(this.capturedKeyChannels.get(t)??0)+1);return o}resolveExternalChannel(t,i){return t>=e.ChannelOffset.Gamepads&&t<e.ChannelOffset.Gamepads+e.ChannelSize.Category?e.ChannelOffset.Gamepads+i*e.ChannelSize.Gamepad+(t^e.ChannelOffset.Gamepads):t}wireGamepadEvents(e){e.onButtonDown.add((t,i)=>{this.onAnyGamepadButtonDown.dispatch(e,t,i)}),e.onButtonUp.add((t,i)=>{this.onAnyGamepadButtonUp.dispatch(e,t,i)}),e.onAxisChange.add((t,i)=>{this.onAnyGamepadAxisChange.dispatch(e,t,i)})}_assignSlot(e){if(this.pointerSlots.has(e))return this.pointerSlots.get(e);if(0===this.freeSlots.length)return null;const t=this.freeSlots.shift();return this.pointerSlots.set(e,t),t}_releaseSlot(e){const t=this.pointerSlots.get(e);void 0!==t&&(this.pointerSlots.delete(e),this.freeSlots.unshift(t))}handleKeyDown(t){if(!this.canvasFocusedValue)return;const i=e.ChannelOffset.Keyboard+t.keyCode;this.channels[i]=1,this.channelsPressed.push(i),this.flags.push(mn.KeyDown),this.capturedKeyChannels.has(i)&&_(t)}handleKeyUp(t){if(!this.canvasFocusedValue)return;const i=e.ChannelOffset.Keyboard+t.keyCode;this.channels[i]=0,this.channelsReleased.push(i),this.flags.push(mn.KeyUp),this.capturedKeyChannels.has(i)&&_(t)}handlePointerOver(e){const t=this._assignSlot(e.pointerId);null!==t&&(this.pointers.set(e.pointerId,new pn(e,this._app,this.canvas,this.channels,t)),this.flags.push(mn.PointerUpdate))}handlePointerLeave(e){const t=this.pointers.get(e.pointerId);t&&(t.handleLeave(e),this.gestureRecognizer.onPointerLeave(t),this._releaseSlot(e.pointerId),this.flags.push(mn.PointerUpdate))}handlePointerDown(e){this.canvas.focus(),this.canvasFocusedValue=!0;const t=this.pointers.get(e.pointerId);t&&(t.handlePress(e),this.gestureRecognizer.onPointerDown(t),this.flags.push(mn.PointerUpdate),_(e))}handlePointerMove(e){const t=this.pointers.get(e.pointerId);t&&(t.handleMove(e),this.gestureRecognizer.onPointerMove(t,this.pointerDistanceThreshold),this.flags.push(mn.PointerUpdate))}handlePointerUp(e){const t=this.pointers.get(e.pointerId);t&&(t.handleRelease(e),this.gestureRecognizer.onPointerUp(t),this.flags.push(mn.PointerUpdate),_(e))}handlePointerCancel(e){const t=this.pointers.get(e.pointerId);t&&(t.handleCancel(e),this.gestureRecognizer.onPointerCancel(t),this._releaseSlot(e.pointerId),this.flags.push(mn.PointerUpdate))}handleMouseWheel(e){this.canvasFocusedValue&&(this.wheelOffset.set(e.deltaX,e.deltaY),this.flags.push(mn.MouseWheel),_(e))}handleCanvasFocus(){this.canvasFocusedValue||(this.canvasFocusedValue=!0,this.onCanvasFocusChange.dispatch(!0))}handleCanvasBlur(){this.canvasFocusedValue&&(this.canvasFocusedValue=!1,this.releaseAllKeyboardChannels(),this.onCanvasFocusChange.dispatch(!1))}handleWindowBlur(){this.canvasFocusedValue&&(this.canvasFocusedValue=!1,this.releaseAllKeyboardChannels(),this.onCanvasFocusChange.dispatch(!1))}releaseAllKeyboardChannels(){for(let t=0;t<e.ChannelSize.Category;t++){const i=e.ChannelOffset.Keyboard+t;0!==this.channels[i]&&(this.channels[i]=0,this.channelsReleased.push(i),this.flags.push(mn.KeyUp))}}addEventListeners(){const e=window,t={capture:!0,passive:!1},i={capture:!0,passive:!0};e.addEventListener("keydown",this.keyDownHandler,!0),e.addEventListener("keyup",this.keyUpHandler,!0),e.addEventListener("blur",this.windowBlurHandler,!0),this.canvas.addEventListener("focus",this.canvasFocusHandler,!0),this.canvas.addEventListener("blur",this.canvasBlurHandler,!0),this.canvas.addEventListener("wheel",this.mouseWheelHandler,t),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,t),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",_,t),this.canvas.addEventListener("selectstart",_,t)}removeEventListeners(){const e={capture:!0,passive:!1},t={capture:!0,passive:!0};window.removeEventListener("keydown",this.keyDownHandler,!0),window.removeEventListener("keyup",this.keyUpHandler,!0),window.removeEventListener("blur",this.windowBlurHandler,!0),this.canvas.removeEventListener("focus",this.canvasFocusHandler,!0),this.canvas.removeEventListener("blur",this.canvasBlurHandler,!0),this.canvas.removeEventListener("wheel",this.mouseWheelHandler,e),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,t),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,t),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,t),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,e),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,t),this.canvas.removeEventListener("contextmenu",_,e),this.canvas.removeEventListener("selectstart",_,e)}updateGamepads(){const e=window.navigator.getGamepads(),t=new Set;for(const i of e){if(!i)continue;const e=i.index;if(e<0)continue;t.add(e);const n=this.gamepadsByBrowserIndex.get(e);if(void 0===n){const t=this.assignSlotForNewPad(i);if(null===t)continue;this.gamepadsByBrowserIndex.set(e,t),this.onGamepadConnected.dispatch(t)}else n._refreshBrowserGamepad(i)}for(const[e,i]of[...this.gamepadsByBrowserIndex.entries()])t.has(e)||(this.gamepadsByBrowserIndex.delete(e),this.handleGamepadDisconnect(i));for(const e of this._gamepads)e.update();return this}assignSlotForNewPad(e){const t=((e,t=ln)=>{const i="connected"in e?an(e):e;for(const e of t){const t=hn(e,i);if(t)return t}return{descriptor:i,name:i.name??i.label,mapping:new qi}})(e,this.gamepadDefinitions);for(const i of this._gamepads)if(!i.connected)return i._bind(e,t),i;return null}handleGamepadDisconnect(e){if("compact"!==this.slotStrategy)return e._unbind(),void this.onGamepadDisconnected.dispatch(e);let t=-1;for(let e=3;e>=0;e--){const i=this._gamepads[e];if(void 0!==i&&i.connected){t=e;break}}e._silentUnbind();for(let e=0;e<4;e++){const t=this._gamepads[e];if(void 0!==t&&!t.connected)for(let i=e+1;i<4;i++){const e=this._gamepads[i];if(void 0===e||!e.connected)continue;const n=e.browserGamepad?.index,r=e.slot;t._rebindFrom(e),void 0!==n&&this.gamepadsByBrowserIndex.set(n,t),t.onPadReassigned.dispatch(r),this.onAnyGamepadReassigned.dispatch(t,r);break}}if(t>=0){const e=this._gamepads[t];void 0!==e&&(e._dispatchDisconnect(),this.onGamepadDisconnected.dispatch(e))}}updateEvents(){if(this.flags.pop(mn.KeyDown)){for(const e of this.channelsPressed)this.onKeyDown.dispatch(e);this.channelsPressed.length=0}if(this.flags.pop(mn.KeyUp)){for(const e of this.channelsReleased)this.onKeyUp.dispatch(e);this.channelsReleased.length=0}return this.flags.pop(mn.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(mn.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of this.pointers.values()){const{stateFlags:i}=t;if(i.value!==e.PointerStateFlag.None){if(i.pop(e.PointerStateFlag.Over)&&this.onPointerEnter.dispatch(t),i.pop(e.PointerStateFlag.Down)&&this.onPointerDown.dispatch(t),i.pop(e.PointerStateFlag.Move)&&this.onPointerMove.dispatch(t),i.pop(e.PointerStateFlag.Up)){const{x:e,y:i}=t.startPos;this.onPointerUp.dispatch(t),e>=0&&i>=0&&(j(e,i,t.x,t.y)<this.pointerDistanceThreshold?this.onPointerTap.dispatch(t):this.onPointerSwipe.dispatch(t)),t.startPos.set(-1,-1)}i.pop(e.PointerStateFlag.Cancel)&&this.onPointerCancel.dispatch(t),i.pop(e.PointerStateFlag.Leave)&&(this.onPointerLeave.dispatch(t),this.pointers.delete(t.id))}}}}class wn{_bounds;_maxItems;_maxDepth;_depth;_items;_children;constructor(e,t=8,i=5,n=0){this._bounds=e,this._maxItems=t,this._maxDepth=i,this._depth=n,this._items=[],this._children=null}insert(e){if(null===this._children&&this._items.length<this._maxItems)this._items.push(e);else{if(null===this._children&&this._depth<this._maxDepth&&this._subdivide(),null!==this._children)for(const t of this._children)if(t._bounds.containsRect(e.bounds))return void t.insert(e);this._items.push(e)}}queryPoint(e,t,i=[]){if(!this._bounds.contains(e,t))return i;for(const n of this._items)n.bounds.contains(e,t)&&i.push(n);if(null!==this._children)for(const n of this._children)n.queryPoint(e,t,i);return i}queryRect(e,t=[]){if(e.right<this._bounds.left||e.left>this._bounds.right||e.bottom<this._bounds.top||e.top>this._bounds.bottom)return t;for(const i of this._items)i.bounds.right<e.left||i.bounds.left>e.right||i.bounds.bottom<e.top||i.bounds.top>e.bottom||t.push(i);if(null!==this._children)for(const i of this._children)i.queryRect(e,t);return t}remove(e){const t=this._items.indexOf(e);if(-1!==t)return this._items.splice(t,1),!0;if(null!==this._children)for(const t of this._children)if(t.remove(e))return!0;return!1}clear(){if(this._items.length=0,null!==this._children){for(const e of this._children)e.clear();this._children=null}}_walkBounds(e){if(e(this._bounds),null!==this._children)for(const t of this._children)t._walkBounds(e)}destroy(){if(this._items.length=0,this._bounds.destroy(),null!==this._children){for(const e of this._children)e.destroy();this._children=null}}_subdivide(){const{x:e,y:t,width:i,height:n}=this._bounds,r=i/2,s=n/2,o=this._depth+1,a=this._maxItems,h=this._maxDepth;this._children=[new wn(new et(e,t,r,s),a,h,o),new wn(new et(e+r,t,r,s),a,h,o),new wn(new et(e,t+s,r,s),a,h,o),new wn(new et(e+r,t+s,r,s),a,h,o)]}}class xn{type;target;currentTarget;pointer;worldX;worldY;_stopped=!1;constructor(e,t,i,n,r){this.type=e,this.target=t,this.currentTarget=t,this.pointer=i,this.worldX=n,this.worldY=r}get propagationStopped(){return this._stopped}stopPropagation(){this._stopped=!0}}!function(e){e[e.None=0]="None",e[e.Down=1]="Down",e[e.Move=2]="Move",e[e.Up=4]="Up",e[e.Tap=8]="Tap",e[e.Cancel=16]="Cancel",e[e.Leave=32]="Leave"}(gn||(gn={}));class vn{order=200;_app;_quadtree=null;_interactiveNodes=new Set;_staleNodes=new Set;_quadtreeItems=new Map;_quadtreeOrderCounter=0;_quadtreeQueryBuffer=[];_stage;_uiInteraction={_notifyNodeAdded:()=>{},_notifyNodeRemoved:()=>{},_notifyInteractiveChanged:()=>{},_notifyBoundsInvalidated:()=>{}};_uiStage;_lastHit=new Map;_pending=new Map;_capturedPointers=new Map;_drags=new Map;_captureStack=[];_dirty=!1;_onPointerDownHandler;_onPointerMoveHandler;_onPointerUpHandler;_onPointerTapHandler;_onPointerCancelHandler;_onPointerLeaveHandler;constructor(e){this._app=e,this._stage={interaction:this,focus:e.focus,app:e},this._uiStage={interaction:this._uiInteraction,focus:e.focus,app:e},this._onPointerDownHandler=this._handlePointerDown.bind(this),this._onPointerMoveHandler=this._handlePointerMove.bind(this),this._onPointerUpHandler=this._handlePointerUp.bind(this),this._onPointerTapHandler=this._handlePointerTap.bind(this),this._onPointerCancelHandler=this._handlePointerCancel.bind(this),this._onPointerLeaveHandler=this._handlePointerLeave.bind(this),e.input.onPointerDown.add(this._onPointerDownHandler),e.input.onPointerMove.add(this._onPointerMoveHandler),e.input.onPointerUp.add(this._onPointerUpHandler),e.input.onPointerTap.add(this._onPointerTapHandler),e.input.onPointerCancel.add(this._onPointerCancelHandler),e.input.onPointerLeave.add(this._onPointerLeaveHandler)}getHoveredNode(e){if(void 0!==e)return this._lastHit.get(e)??null;const t=this._lastHit.values().next();return t.done?null:t.value}getCapturedNodes(){return[...this._capturedPointers.values()]}pushInputCapture(e){this._captureStack.push(e)}popInputCapture(){this._captureStack.pop()}_getDebugQuadtree(){return this._quadtree}destroy(){this._app.input.onPointerDown.remove(this._onPointerDownHandler),this._app.input.onPointerMove.remove(this._onPointerMoveHandler),this._app.input.onPointerUp.remove(this._onPointerUpHandler),this._app.input.onPointerTap.remove(this._onPointerTapHandler),this._app.input.onPointerCancel.remove(this._onPointerCancelHandler),this._app.input.onPointerLeave.remove(this._onPointerLeaveHandler),this._lastHit.clear(),this._pending.clear(),this._capturedPointers.clear(),this._drags.clear(),this._captureStack.length=0,this._interactiveNodes.clear(),this._staleNodes.clear(),this._quadtreeItems.clear(),this._dirty=!1,null!==this._quadtree&&(this._quadtree.destroy(),this._quadtree=null)}update(e){if(this._dirty){this._dirty=!1,this._flushStaleEntries();for(const e of this._pending.values())this._processQueue(e);this._pending.clear(),this._updateCursor()}}attachRoot(e){e._setStage(this._stage),this._notifyNodeAdded(e)}detachRoot(e){this._app.focus.blur(),this._captureStack.length=0,this._notifyNodeRemoved(e),e._setStage(null)}attachUIRoot(e){e._setStage(this._uiStage)}detachUIRoot(e){e._setStage(null)}_notifyNodeAdded(e){for(const t of this._iterateSubtree(e))t.interactive&&this._registerNode(t)}_notifyNodeRemoved(e){for(const t of this._iterateSubtree(e))this._interactiveNodes.has(t)&&this._unregisterNode(t)}_notifyInteractiveChanged(e,t){t?this._registerNode(e):this._unregisterNode(e)}_notifyBoundsInvalidated(e){this._interactiveNodes.has(e)&&this._staleNodes.add(e)}_handlePointerDown(e){this._enqueue(e,gn.Down)}_handlePointerMove(e){this._enqueue(e,gn.Move)}_handlePointerUp(e){this._enqueue(e,gn.Up)}_handlePointerTap(e){this._enqueue(e,gn.Tap)}_handlePointerCancel(e){this._enqueue(e,gn.Cancel)}_handlePointerLeave(e){this._enqueue(e,gn.Leave)}_enqueue(e,t){let i=this._pending.get(e.id);i?i.pointer=e:(i={pointer:e,events:0},this._pending.set(e.id,i)),i.events|=t,this._dirty=!0}_processQueue(e){const{pointer:t,events:i}=e,{id:n}=t,r=this._capturedPointers.get(n)??null;let s,o,a;if(null!==r){const e=this._pointerCoords(t,this._isUINode(r));s=r,o=e.x,a=e.y}else{const e=this._resolveHit(t);s=e.node,o=e.x,a=e.y}const h=this._drags.get(n)??null,l=this._lastHit.get(n)??null,u=0!==(i&(gn.Cancel|gn.Leave));if(null!==r||s===l||u||(null!==l&&this._dispatchBubble(new xn("pointerout",l,t,o,a)),null!==s&&this._dispatchBubble(new xn("pointerover",s,t,o,a)),this._setLastHit(n,s)),0!==(i&gn.Down)&&null!==s&&(this._dispatchBubble(new xn("pointerdown",s,t,o,a)),s.draggable&&!this._drags.has(n))){const e=s.position.x-o,i=s.position.y-a;this._drags.set(n,{pointerId:n,node:s,offsetX:e,offsetY:i}),this._capturedPointers.set(n,s);try{this._app.canvas.setPointerCapture(n)}catch{}this._dispatchDirect(new xn("dragstart",s,t,o,a),s._peekInteractionSignal("dragstart"))}0!==(i&gn.Move)&&(null!==h&&(h.node.position.x=o+h.offsetX,h.node.position.y=a+h.offsetY),null!==s&&this._dispatchBubble(new xn("pointermove",s,t,o,a)),null!==h&&this._dispatchDirect(new xn("drag",h.node,t,o,a),h.node._peekInteractionSignal("drag"))),0!==(i&gn.Up)&&(null!==s&&this._dispatchBubble(new xn("pointerup",s,t,o,a)),null!==h&&(this._dispatchDirect(new xn("dragend",h.node,t,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(n))),0!==(i&gn.Tap)&&null!==s&&this._dispatchBubble(new xn("pointertap",s,t,o,a)),u&&(null!==h?(this._dispatchDirect(new xn("dragend",h.node,t,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(n)):null!==l&&this._dispatchBubble(new xn("pointerout",l,t,o,a)),this._lastHit.delete(n))}_endDrag(e){this._drags.delete(e),this._capturedPointers.delete(e);try{this._app.canvas.releasePointerCapture(e)}catch{}}_resolveHit(e){const t=this._captureStack.at(-1);if(void 0!==t){const i=this._pointerCoords(e,this._isUINode(t));return{node:this._hitTestNode(t,i.x,i.y),x:i.x,y:i.y}}const i=this._app.scene.currentScene?._peekUI()??null;if(null!==i){const t=this._app.rendering.screenView.screenToWorld(e.x,e.y),n=this._hitTestNode(i,t.x,t.y);if(null!==n)return{node:n,x:t.x,y:t.y}}const n=this._app.rendering.view.screenToWorld(e.x,e.y);return{node:this._hitTest(n.x,n.y),x:n.x,y:n.y}}_pointerCoords(e,t){return(t?this._app.rendering.screenView:this._app.rendering.view).screenToWorld(e.x,e.y)}_isUINode(e){const t=this._app.scene.currentScene?._peekUI()??null;if(null===t)return!1;let i=e;for(;null!==i;){if(i===t)return!0;i=i.parent}return!1}_hitTest(e,t){if(null!==this._quadtree)return this._hitTestIndexed(e,t);const i=this._app.scene.currentScene?.root;return i?this._hitTestNode(i,e,t):null}_hitTestIndexed(e,t){const i=this._quadtreeQueryBuffer;i.length=0,this._quadtree.queryPoint(e,t,i);let n=-1,r=null;for(const s of i){const i=s.payload;i.order>n&&i.node.contains(e,t)&&(n=i.order,r=i.node)}return r}_hitTestNode(e,t,i){if(!e.visible)return null;if(e instanceof Bi){const n=e.children;for(let e=n.length-1;e>=0;e--){const r=n[e];if(void 0===r)continue;const s=this._hitTestNode(r,t,i);if(s)return s}}return e.interactive&&e.contains(t,i)?e:null}_registerNode(e){this._interactiveNodes.has(e)||(this._interactiveNodes.add(e),null===this._quadtree&&(this._quadtree=this._createQuadtree()),this._insertNode(e))}_unregisterNode(e){if(!this._interactiveNodes.has(e))return;this._interactiveNodes.delete(e),this._staleNodes.delete(e);const t=this._quadtreeItems.get(e);void 0!==t&&null!==this._quadtree&&this._quadtree.remove(t),this._quadtreeItems.delete(e),0===this._interactiveNodes.size&&null!==this._quadtree&&(this._quadtree.destroy(),this._quadtree=null,this._quadtreeOrderCounter=0)}_insertNode(e){if(null===this._quadtree)return;const t=e.getBounds(),i={bounds:new et(t.x,t.y,t.width,t.height),payload:{node:e,order:this._quadtreeOrderCounter++}};this._quadtree.insert(i),this._quadtreeItems.set(e,i)}_flushStaleEntries(){if(null!==this._quadtree&&0!==this._staleNodes.size){for(const e of this._staleNodes){const t=this._quadtreeItems.get(e);void 0!==t&&(this._quadtree.remove(t),t.bounds.destroy()),this._quadtreeItems.delete(e);const i=e.getBounds(),n={bounds:new et(i.x,i.y,i.width,i.height),payload:{node:e,order:t?.payload.order??this._quadtreeOrderCounter++}};this._quadtree.insert(n),this._quadtreeItems.set(e,n)}this._staleNodes.clear()}}_createQuadtree(){const e=this._app.width||800,t=this._app.height||600,i=new et(0,0,e,t),n=this._app.scene.currentScene?.root;if(n){const e=n.getBounds(),t=Math.min(i.left,e.left),r=Math.min(i.top,e.top),s=Math.max(i.right,e.right),o=Math.max(i.bottom,e.bottom);i.set(t,r,s-t,o-r)}return new wn(i)}*_iterateSubtree(e){const t=[e];for(;t.length>0;){const e=t.pop();if(yield e,e instanceof Bi)for(let i=e.children.length-1;i>=0;i--){const n=e.children[i];void 0!==n&&t.push(n)}}}_dispatchBubble(e){let t=e.target;for(;null!==t&&!e.propagationStopped;){e.currentTarget=t;const i=this._signalFor(e.type,t);if(i?.dispatch(e),e.propagationStopped)break;const n=t.parent;t=null!==n&&n.interactive?n:null}}_dispatchDirect(e,t){e.currentTarget=e.target,t?.dispatch(e)}_signalFor(e,t){return t._peekInteractionSignal(e)}_setLastHit(e,t){null!==t?this._lastHit.set(e,t):this._lastHit.delete(e)}_updateCursor(){let e=null;for(const t of this._lastHit.values()){let i=t;for(;null!==i;){if(null!==i.cursor){e=i.cursor;break}i=i.parent}if(null!==e)break}this._app.canvas.style.cursor=e??""}}const bn=(e,t)=>(e<<t|e>>>32-t)>>>0,Sn=1/2**32;class Bn{_state=new Uint32Array(4);_seed=0;_value=0;constructor(e=Date.now()){this.setSeed(e)}get seed(){return this._seed}get value(){return this._value}setSeed(e){return this._seed=e,this.reset(),this}reset(){let e=0|this._seed;for(let t=0;t<4;t++){e=e+2654435769|0;let i=e^e>>>16;i=Math.imul(i,569420461),i^=i>>>15,i=Math.imul(i,1935289751),i^=i>>>15,this._state[t]=i>>>0}return this._value=0,this}next(e=0,t=1){const i=this._state;let n=i[0],r=i[1],s=i[2],o=i[3];const a=Math.imul(bn(Math.imul(r,5),7),9)>>>0,h=r<<9;return s^=n,o^=r,r^=s,n^=o,s^=h,o=bn(o,11),i[0]=n,i[1]=r,i[2]=s,i[3]=o,this._value=a*Sn*(t-e)+e,this._value}destroy(){}}const Cn=new Set(["none","position","geometry"]);function Tn(e){return"string"==typeof e&&Cn.has(e)}const Mn=1e-6;function Pn(e,t,i,n){const r=e.x,s=e.y;if(!(i>0&&n>0))return An(r,s);const o=t.worldToScreen(r,s,i,n);if(!Number.isFinite(o.x)||!Number.isFinite(o.y))return An(r,s);const a=t.worldToScreen(r+1,s,i,n),h=t.worldToScreen(r,s+1,i,n),l=a.x-o.x,u=a.y-o.y,c=h.x-o.x,d=h.y-o.y,_=e.a*l+e.c*c,f=e.a*u+e.c*d,p=e.b*l+e.d*c,m=e.b*u+e.d*d,g=Math.abs(f)<Mn&&Math.abs(p)<Mn,y=Math.round(o.x),w=Math.round(o.y);let x=r,v=s;const b=l*d-c*u;if(Math.abs(b)>Mn){const e=y-o.x,t=w-o.y;x=r+(d*e-c*t)/b,v=s+(l*t-u*e)/b}return{originX:o.x,originY:o.y,snappedOriginX:y,snappedOriginY:w,worldX:x,worldY:v,scaleX:_,scaleY:m,axisAligned:g}}function An(e,t){return{originX:e,originY:t,snappedOriginX:e,snappedOriginY:t,worldX:e,worldY:t,scaleX:0,scaleY:0,axisAligned:!1}}function En(e,t){return!Number.isFinite(e)||Math.abs(t)<Mn?e:Math.round(e*t)/t}function Rn(e,t,i){const{scaleX:n,scaleY:r}=t;i.length=e.length;for(let t=0;t<e.length;t++){const s=e[t];let o=i[t];void 0===o&&(o=i[t]={x0:0,y0:0,x1:0,y1:0,u0:0,v0:0,u1:0,v1:0}),o.x0=En(s.x0,n),o.x1=En(s.x1,n),o.y0=En(s.y0,r),o.y1=En(s.y1,r),o.u0=s.u0,o.v0=s.v0,o.u1=s.u1,o.v1=s.v1}return i}function kn(e,t,i,n,r){const s=e.getGlobalTransform();if("none"===e.pixelSnapMode)return s;return function(e,t,i){return e.copy(t),e.x=i.worldX,e.y=i.worldY,e}(r,s,Pn(s,t,i,n))}function Dn(e,t,i){const n=En(e.left,t.scaleX),r=En(e.top,t.scaleY),s=En(e.right,t.scaleX),o=En(e.bottom,t.scaleY);return i.set(n,r,s-n,o-r)}class Fn extends Si{_tint=Tt.white.clone();_blendMode=e.BlendModes.Normal;_pixelSnapMode="none";_materialKey=null;_materialKeyBackend=null;get tint(){return this._tint}set tint(e){this.setTint(e)}get blendMode(){return this._blendMode}set blendMode(e){this.setBlendMode(e)}get pixelSnapMode(){return this._pixelSnapMode}set pixelSnapMode(e){if(e!==this._pixelSnapMode){if(!Tn(e))throw new Error(`Drawable.pixelSnapMode must be 'none', 'position', or 'geometry' (got ${String(e)}).`);this._pixelSnapMode=e,this.invalidateCache()}}setTint(e){return e&&(this._tint.copy(e),this.invalidateCache()),this}setBlendMode(e){return this._blendMode!==e&&(this._blendMode=e,this.invalidateCache()),this}_collectContent(e){e.emitDraw(this)}_isDrawableForRenderPlan(){return!0}_renderPlanGetBlendMode(){return this._blendMode}_getOrComputeMaterialKey(e){const t=this._materialKey;if(null!==t)return null!==ei(this)?ti(t,this,e):this._materialKeyBackend===e?t:(this._materialKeyBackend=e,ti(t,this,e));const i=ti({rendererId:0,blendMode:this._blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},this,e);return this._materialKey=i,this._materialKeyBackend=e,i}invalidateCache(){return super.invalidateCache(),this._materialKeyBackend=null,this}destroy(){super.destroy(),this._tint.destroy()}}class In extends Fn{_vertices;_indices;_uvs;_colors;_material;_geometry;get vertices(){return this._vertices}get indices(){return this._indices}get uvs(){return this._uvs}get colors(){return this._colors}get material(){return this._material}get geometry(){return this._geometry}_texture;constructor(e){super();const{texture:t=null,material:i=null}=e;let n,r,s,o,a;if(void 0!==e.geometry){if(void 0!==e.vertices)throw new Error("Mesh accepts either `vertices` or `geometry`, not both.");a=e.geometry;const t=On(a);n=t.vertices,s=t.uvs,o=t.colors,r=t.indices}else{if(void 0===e.vertices)throw new Error("Mesh requires either `vertices` or `geometry`.");a=null,n=e.vertices,r=e.indices??null,s=e.uvs??null,o=e.colors??null}if(0===n.length||n.length%2!=0)throw new Error(`Mesh vertices must be a non-empty flat array of (x,y) pairs (got length ${n.length}).`);const h=n.length/2;if(h<3)throw new Error(`Mesh requires at least 3 vertices (got ${h}).`);if(null!==s&&s.length!==n.length)throw new Error(`Mesh uvs length ${s.length} must equal vertices length ${n.length}.`);if(null!==o&&o.length!==h)throw new Error(`Mesh colors length ${o.length} must equal vertex count ${h}.`);if(null!==r){if(0===r.length||r.length%3!=0)throw new Error(`Mesh indices must be a non-empty multiple of 3 (got length ${r.length}).`);for(let e=0;e<r.length;e++)if(r[e]>=h)throw new Error(`Mesh index ${r[e]} at position ${e} is out of range for vertex count ${h}.`)}else if(h%3!=0)throw new Error(`Non-indexed Mesh requires a vertex count that is a multiple of 3 (got ${h}).`);this._vertices=n,this._indices=r,this._uvs=s,this._colors=o,this._material=i,this._geometry=a,this._texture=t,this.recomputeLocalBounds()}get vertexCount(){return this.vertices.length/2}get indexCount(){return this.indices?.length??this.vertexCount}get texture(){return this._texture}set texture(e){this._texture=e,this.invalidateCache()}recomputeLocalBounds(){let e=1/0,t=1/0,i=-1/0,n=-1/0;for(let r=0;r<this.vertices.length;r+=2){const s=this.vertices[r],o=this.vertices[r+1];s<e&&(e=s),s>i&&(i=s),o<t&&(t=o),o>n&&(n=o)}return this.getLocalBounds().set(e,t,i-e,n-t),this._invalidateBoundsCascade(),this}}const Ln=new Set(["a_position","position"]),Un=new Set(["a_texcoord","texcoord","a_uv","uv"]),Gn=new Set(["a_color","color"]),Nn=(e,t)=>e.find(e=>t.has(e.name));function On(e){if("triangle-list"!==e.topology)throw new Error(`Mesh only supports triangle-list geometry (got "${e.topology}").`);const t=Nn(e.attributes,Ln);if(void 0===t)throw new Error("Mesh geometry requires a position attribute named `a_position` or `position`.");if("f32"!==t.type||t.size<2)throw new Error("Mesh geometry position attribute must be a float vector with at least 2 components.");const i=Nn(e.attributes,Un);if(void 0!==i&&("f32"!==i.type||i.size<2))throw new Error("Mesh geometry texcoord attribute must be a float vector with at least 2 components.");const n=Nn(e.attributes,Gn),r=e.vertexCount,{stride:s}=e,o=e.vertexData,a=o instanceof Float32Array?new DataView(o.buffer,o.byteOffset,o.byteLength):new DataView(o),h=new Float32Array(2*r),l=void 0!==i?new Float32Array(2*r):null,u=void 0!==n?new Uint32Array(r):null;for(let e=0;e<r;e++){const r=e*s;h[2*e]=a.getFloat32(r+t.offset,!0),h[2*e+1]=a.getFloat32(r+t.offset+4,!0),null!==l&&void 0!==i&&(l[2*e]=a.getFloat32(r+i.offset,!0),l[2*e+1]=a.getFloat32(r+i.offset+4,!0)),null!==u&&void 0!==n&&(u[e]=Vn(a,r+n.offset,n))}const c=function(e,t){if(null===e)return null;if(e instanceof Uint16Array)return e;if(t>65535)throw new Error(`Mesh geometry with ${t} vertices exceeds the 16-bit index limit.`);return Uint16Array.from(e)}(e.indices,r);return{vertices:h,uvs:l,colors:u,indices:c}}function Vn(e,t,i){if("u32"===i.type&&1===i.size)return e.getUint32(t,!0)>>>0;if("u8"===i.type&&4===i.size){return(e.getUint8(t)|e.getUint8(t+1)<<8|e.getUint8(t+2)<<16|e.getUint8(t+3)<<24)>>>0}if("f32"===i.type&&4===i.size){return(Math.round(255*zn(e.getFloat32(t,!0)))|Math.round(255*zn(e.getFloat32(t+4,!0)))<<8|Math.round(255*zn(e.getFloat32(t+8,!0)))<<16|Math.round(255*zn(e.getFloat32(t+12,!0)))<<24)>>>0}throw new Error("Mesh geometry color attribute must be u8x4, u32x1, or f32x4.")}function zn(e){return e<0?0:e>1?1:e}function qn(e){return"number"==typeof e&&Number.isFinite(e)}class Wn{texture;x;y;width;height;u0;v0;u1;v1;extrusion;constructor(e,t){if(!e)throw new Error("TextureRegion requires a non-null Texture.");const i=e.width,n=e.height;!function(e,t,i){const{x:n,y:r,width:s,height:o}=e;if(!(qn(n)&&qn(r)&&qn(s)&&qn(o)))throw new Error(`TextureRegion coordinates and dimensions must be finite numbers (got x=${n}, y=${r}, width=${s}, height=${o}).`);if(s<=0||o<=0)throw new Error(`TextureRegion dimensions must be positive (got width=${s}, height=${o}).`);if(t<=0||i<=0)throw new Error(`Texture must have positive dimensions (got ${t}x${i}).`);if(n<0||r<0)throw new Error(`TextureRegion origin must be non-negative (got x=${n}, y=${r}).`);if(n>=t||r>=i)throw new Error(`TextureRegion origin (${n}, ${r}) is outside texture bounds (${t}x${i}).`);if(n+s>t)throw new Error(`TextureRegion right edge (${n+s}) exceeds texture width (${t}).`);if(r+o>i)throw new Error(`TextureRegion bottom edge (${r+o}) exceeds texture height (${i}).`)}(t,i,n);const r=function(e){return void 0===e?Object.freeze({left:0,top:0,right:0,bottom:0}):"number"==typeof e?Object.freeze({left:e,top:e,right:e,bottom:e}):Object.freeze({left:e.left,top:e.top,right:e.right,bottom:e.bottom})}(t.extrusion);!function(e,t,i,n,r,s,o){const{left:a,top:h,right:l,bottom:u}=e;if(!(qn(a)&&qn(h)&&qn(l)&&qn(u)))throw new Error(`TextureRegion extrusion values must be finite numbers (got left=${a}, top=${h}, right=${l}, bottom=${u}).`);if(a<0||h<0||l<0||u<0)throw new Error(`TextureRegion extrusion values must be non-negative (got left=${a}, top=${h}, right=${l}, bottom=${u}).`);if(a>t||h>i||l>s-(t+n)||u>o-(i+r))throw new Error(`TextureRegion extrusion exceeds available source texture bounds: left=${a} (>${t}), top=${h} (>${i}), right=${l} (>${s-(t+n)}), bottom=${u} (>${o-(i+r)}).`)}(r,t.x,t.y,t.width,t.height,i,n),this.texture=e,this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this.u0=t.x/i,this.v0=t.y/n,this.u1=(t.x+t.width)/i,this.v1=(t.y+t.height)/n,this.extrusion=r}}function Yn(e,t,i){if(0===e)return{destinationLength:0,sourceLength:t,segments:[]};const n=[];let r=0,s=0;for(;r<e;){const o=e-r,a=Math.min(t,o),h=a/t,l=i&&s%2==1,u={destinationStart:r,destinationLength:a,sourceStart:l?1:0,sourceEnd:l?1-h:h,mirrored:l};n.push(u),r+=a,s++}return{destinationLength:e,sourceLength:t,segments:n}}function $n(e,t,i){if(0===e)return{destinationLength:0,sourceLength:t,segments:[]};const n=e/t,r=Math.max(1,Math.round(n)),s=e/r,o=[];for(let e=0;e<r;e++){const t=i&&e%2==1,n={destinationStart:e*s,destinationLength:s,sourceStart:t?1:0,sourceEnd:t?0:1,mirrored:t};o.push(n)}return{destinationLength:e,sourceLength:t,segments:o}}function Xn(e,t,i,n="round"){switch(function(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`RepeatPlanner: sourceLength and destinationLength must be finite numbers (got ${e}, ${t}).`);if(e<=0)throw new Error(`RepeatPlanner: sourceLength must be positive (got ${e}).`);if(t<0)throw new Error(`RepeatPlanner: destinationLength must be non-negative (got ${t}).`)}(e,t),i){case"stretch":return function(e,t){return 0===e?{destinationLength:0,sourceLength:t,segments:[]}:{destinationLength:e,sourceLength:t,segments:[{destinationStart:0,destinationLength:e,sourceStart:0,sourceEnd:1,mirrored:!1}]}}(t,e);case"repeat":return"round"===n?$n(t,e,!1):Yn(t,e,!1);case"mirror-repeat":return"round"===n?$n(t,e,!0):Yn(t,e,!0);default:throw new Error("RepeatPlanner: unknown RepeatMode.")}}const Hn=.5;function jn(e){return"number"==typeof e&&Number.isFinite(e)}function Kn(e,t,i){const{left:n,top:r,right:s,bottom:o}=e;if(!(jn(n)&&jn(r)&&jn(s)&&jn(o)))throw new Error(`NineSliceSprite: slice values must be finite numbers (got left=${n}, top=${r}, right=${s}, bottom=${o}).`);if(n<0||r<0||s<0||o<0)throw new Error(`NineSliceSprite: slice values must be non-negative (got left=${n}, top=${r}, right=${s}, bottom=${o}).`);if(n+s>t)throw new Error(`NineSliceSprite: slices.left (${n}) + slices.right (${s}) exceeds region width (${t}).`);if(r+o>i)throw new Error(`NineSliceSprite: slices.top (${r}) + slices.bottom (${o}) exceeds region height (${i}).`)}function Qn(e){const{left:t,top:i,right:n,bottom:r}=e;if(!(jn(t)&&jn(i)&&jn(n)&&jn(r)))throw new Error(`NineSliceSprite: border values must be finite numbers (got left=${t}, top=${i}, right=${n}, bottom=${r}).`);if(t<0||i<0||n<0||r<0)throw new Error(`NineSliceSprite: border values must be non-negative (got left=${t}, top=${i}, right=${n}, bottom=${r}).`)}function Zn(e,t){return"number"==typeof e?Object.freeze({left:e,top:e,right:e,bottom:e}):Object.freeze({left:e.left??t?.left??0,top:e.top??t?.top??0,right:e.right??t?.right??0,bottom:e.bottom??t?.bottom??0})}const Jn=new Set(["stretch","repeat","mirror-repeat"]),er=new Set(["clip","round"]);function tr(e,t){if("string"!=typeof e||!Jn.has(e))throw new Error(`NineSliceSprite: ${t} must be "stretch", "repeat", or "mirror-repeat".`)}function ir(e,t){if("string"!=typeof e||!er.has(e))throw new Error(`NineSliceSprite: ${t} must be "clip" or "round".`)}function nr(e){if(!e)return rr;const t={};return void 0!==e.edges&&(tr(e.edges,"modes.edges"),t.edges=e.edges),void 0!==e.center&&(tr(e.center,"modes.center"),t.center=e.center),void 0!==e.top&&(tr(e.top,"modes.top"),t.top=e.top),void 0!==e.right&&(tr(e.right,"modes.right"),t.right=e.right),void 0!==e.bottom&&(tr(e.bottom,"modes.bottom"),t.bottom=e.bottom),void 0!==e.left&&(tr(e.left,"modes.left"),t.left=e.left),void 0!==e.edgeFit&&(ir(e.edgeFit,"modes.edgeFit"),t.edgeFit=e.edgeFit),void 0!==e.centerFit&&(ir(e.centerFit,"modes.centerFit"),t.centerFit=e.centerFit),Object.freeze(t)}const rr=Object.freeze({});function sr(e,t){return e.left===t.left&&e.top===t.top&&e.right===t.right&&e.bottom===t.bottom}function or(e,t){return e?.[t]??e?.edges??"stretch"}function ar(e,t,i){return!jn(e)||e<t?t:e>i?i:e}function hr(e,t,i,n,r,s){const o=function(e,t){const i=e.texture.width,n=e.texture.height,r=e.x,s=e.y,o=e.width,a=e.height,h=e.extrusion,l=h.left>0||h.right>0?0:Hn/i,u=h.top>0||h.bottom>0?0:Hn/n,c=Hn/i,d=Hn/n,_=(r+t.left)/i,f=(r+o-t.right)/i,p=(s+t.top)/n,m=(s+a-t.bottom)/n,g=e.u0+l,y=e.u1-l,w=e.v0+u,x=e.v1-u,v=ar(_-c,g,y),b=ar(f+c,g,y),S=ar(p-d,w,x),B=ar(m+d,w,x);return{col0:{u0:g,u1:v},col1:{u0:v,u1:b},col2:{u0:b,u1:y},row0:{u0:w,u1:S},row1:{u0:S,u1:B},row2:{u0:B,u1:x}}}(e,t),a=function(e,t,i){let n=e.left,r=e.right,s=e.top,o=e.bottom;if(n+r>t&&n+r>0){const e=t/(n+r);n*=e,r*=e}if(s+o>i&&s+o>0){const e=i/(s+o);s*=e,o*=e}return{bl:n,br:r,bt:s,bb:o}}(i,n,r),h=a.bl,l=a.br,u=a.bt,c=a.bb,d=Math.max(0,n-h-l),_=Math.max(0,r-u-c),f=h,p=h+d,m=n,g=u,y=u+_,w=r,x=Math.max(0,e.width-t.left-t.right),v=Math.max(0,e.height-t.top-t.bottom),b=x*(t.top>0?u/t.top:1),S=x*(t.bottom>0?c/t.bottom:1),B=v*(t.left>0?h/t.left:1),C=v*(t.right>0?l/t.right:1),T=b,M=B,P=or(s,"top"),A=or(s,"bottom"),E=or(s,"left"),R=or(s,"right"),k=function(e){return e?.center??"stretch"}(s),D=function(e){return e?.edgeFit??"round"}(s),F=function(e){return e?.centerFit??"round"}(s),I=[],{col0:L,col1:U,col2:G,row0:N,row1:O,row2:V}=o;h>0&&u>0&&I.push({x0:0,y0:0,x1:f,y1:g,u0:L.u0,v0:N.u0,u1:L.u1,v1:N.u1}),l>0&&u>0&&I.push({x0:p,y0:0,x1:m,y1:g,u0:G.u0,v0:N.u0,u1:G.u1,v1:N.u1}),h>0&&c>0&&I.push({x0:0,y0:y,x1:f,y1:w,u0:L.u0,v0:V.u0,u1:L.u1,v1:V.u1}),l>0&&c>0&&I.push({x0:p,y0:y,x1:m,y1:w,u0:G.u0,v0:V.u0,u1:G.u1,v1:V.u1});const z=U.u0,q=U.u1,W=O.u0,Y=O.u1;if(d>0&&u>0&&x>0&&b>0){const e=Xn(b,d,P,D);for(const t of e.segments){const e=f+t.destinationStart,i=f+t.destinationStart+t.destinationLength,n=z+t.sourceStart*(q-z),r=z+t.sourceEnd*(q-z);I.push({x0:e,y0:0,x1:i,y1:g,u0:n,v0:N.u0,u1:r,v1:N.u1})}}if(d>0&&c>0&&x>0&&S>0){const e=Xn(S,d,A,D);for(const t of e.segments){const e=f+t.destinationStart,i=f+t.destinationStart+t.destinationLength,n=z+t.sourceStart*(q-z),r=z+t.sourceEnd*(q-z);I.push({x0:e,y0:y,x1:i,y1:w,u0:n,v0:V.u0,u1:r,v1:V.u1})}}if(h>0&&_>0&&v>0&&B>0){const e=Xn(B,_,E,D);for(const t of e.segments){const e=g+t.destinationStart,i=g+t.destinationStart+t.destinationLength,n=W+t.sourceStart*(Y-W),r=W+t.sourceEnd*(Y-W);I.push({x0:0,y0:e,x1:f,y1:i,u0:L.u0,v0:n,u1:L.u1,v1:r})}}if(l>0&&_>0&&v>0&&C>0){const e=Xn(C,_,R,D);for(const t of e.segments){const e=g+t.destinationStart,i=g+t.destinationStart+t.destinationLength,n=W+t.sourceStart*(Y-W),r=W+t.sourceEnd*(Y-W);I.push({x0:p,y0:e,x1:m,y1:i,u0:G.u0,v0:n,u1:G.u1,v1:r})}}if(d>0&&_>0&&x>0&&v>0&&T>0&&M>0){const e=Xn(T,d,k,F),t=Xn(M,_,k,F);for(const i of t.segments){const t=g+i.destinationStart,n=g+i.destinationStart+i.destinationLength,r=W+i.sourceStart*(Y-W),s=W+i.sourceEnd*(Y-W);for(const i of e.segments){const e=f+i.destinationStart,o=f+i.destinationStart+i.destinationLength,a=z+i.sourceStart*(q-z),h=z+i.sourceEnd*(q-z);I.push({x0:e,y0:t,x1:o,y1:n,u0:a,v0:r,u1:h,v1:s})}}}return I}function lr(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`NineSliceSprite: width and height must be finite numbers (got ${e}, ${t}).`);if(e<0)throw new Error(`NineSliceSprite: width must be non-negative (got ${e}).`);if(t<0)throw new Error(`NineSliceSprite: height must be non-negative (got ${t}).`)}class ur extends Fn{_region;_slices;_border;_width;_height;_modes;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(e,t){super(),this._region=e instanceof Wn?e:new Wn(e,{x:0,y:0,width:e.width,height:e.height});const i=this._region,n=Zn(t.slices);Kn(n,i.width,i.height),this._slices=n;const r=void 0!==t.border?Zn(t.border):Zn(t.slices);Qn(r),this._border=r;const s=t.width??i.width,o=t.height??i.height;lr(s,o),this._width=s,this._height=o,this._modes=nr(t.modes)}get region(){return this._region}get texture(){return this._region.texture}get slices(){return this._slices}get border(){return this._border}get modes(){return this._modes}get width(){return this._width}set width(e){this.setSize(e,this._height)}get height(){return this._height}set height(e){this.setSize(this._width,e)}setSize(e,t){return lr(e,t),this._width===e&&this._height===t||(this._width=e,this._height=t,this._geometryDirty=!0,this.invalidateCache()),this}setSlices(e){const t=this._region,i=Zn(e);return Kn(i,t.width,t.height),sr(i,this._slices)||(this._slices=i,this._geometryDirty=!0,this.invalidateCache()),this}setBorder(e){const t=Zn(e);return Qn(t),sr(t,this._border)||(this._border=t,this._geometryDirty=!0,this.invalidateCache()),this}setModes(e){const t=nr(e);return i=t,n=this._modes,i.edges===n.edges&&i.center===n.center&&i.top===n.top&&i.right===n.right&&i.bottom===n.bottom&&i.left===n.left&&i.edgeFit===n.edgeFit&&i.centerFit===n.centerFit||(this._modes=t,this._geometryDirty=!0,this.invalidateCache()),this;var i,n}getLocalBounds(){const e=super.getLocalBounds();return e.set(0,0,this._width,this._height),e}get quads(){return this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(e,t,i){const n=this.quads;if(0===n.length)return n;const r=Pn(this.getGlobalTransform(),e,t,i);return r.axisAligned?Rn(n,r,this._renderQuads):n}_rebuildGeometry(){this._quads=hr(this._region,this._slices,this._border,this._width,this._height,this._modes),this._geometryDirty=!1}}const cr=new Set(["stretch","repeat","mirror-repeat"]),dr=new Set(["clip","round"]);function _r(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`RepeatingSprite: width and height must be finite numbers (got ${e}, ${t}).`);if(e<0)throw new Error(`RepeatingSprite: width must be non-negative (got ${e}).`);if(t<0)throw new Error(`RepeatingSprite: height must be non-negative (got ${t}).`)}function fr(e,t){if("string"!=typeof e||!cr.has(e))throw new Error(`RepeatingSprite: ${t} must be "stretch", "repeat", or "mirror-repeat" (got ${String(e)}).`)}function pr(e,t){if("string"!=typeof e||!dr.has(e))throw new Error(`RepeatingSprite: ${t} must be "clip" or "round" (got ${String(e)}).`)}function mr(e,t){if(!Number.isFinite(e))throw new Error(`RepeatingSprite: ${t} must be a finite number (got ${e}).`)}function gr(e,t,i,n){return"stretch"===i||e<=0||t<=0?1:"round"===n?Math.max(1,Math.round(t/e)):t/e}function yr(e,t,i,n,r){if(0===t||e<=0)return[];if("stretch"===i)return[...Xn(e,t,i,n).segments];const s=(r%e+e)%e;if(0===s)return[...Xn(e,t,i,n).segments];const o=Xn(e,t+s,i,n),a=[];for(const e of o.segments){const i=e.destinationStart-s,n=i+e.destinationLength;if(n<=0||i>=t)continue;const r=Math.max(0,i),o=Math.min(t,n),h=o-r;if(h<=0)continue;const l=(r-i)/e.destinationLength,u=(o-i)/e.destinationLength,c=e.sourceEnd-e.sourceStart;a.push({destinationStart:r,destinationLength:h,sourceStart:e.sourceStart+l*c,sourceEnd:e.sourceStart+u*c,mirrored:e.mirrored})}return a}class wr extends Fn{_source;_region;_width;_height;_modeX;_modeY;_fitX;_fitY;_offsetX;_offsetY;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(e,t){super(),this._source=e,this._region=e instanceof Wn?e:new Wn(e,{x:0,y:0,width:e.width,height:e.height});const i=this._region,n=t??{},r=n.modeX??"repeat",s=n.modeY??"repeat";fr(r,"modeX"),fr(s,"modeY"),this._modeX=r,this._modeY=s;const o=n.fitX??"round",a=n.fitY??"round";pr(o,"fitX"),pr(a,"fitY"),this._fitX=o,this._fitY=a;const h=n.offsetX??0,l=n.offsetY??0;mr(h,"offsetX"),mr(l,"offsetY"),this._offsetX=h,this._offsetY=l;const u=n.width??i.width,c=n.height??i.height;_r(u,c),this._width=u,this._height=c}get source(){return this._source}get region(){return this._region}get texture(){return this._region.texture}get width(){return this._width}set width(e){this.setSize(e,this._height)}get height(){return this._height}set height(e){this.setSize(this._width,e)}get modeX(){return this._modeX}set modeX(e){fr(e,"modeX"),this._modeX!==e&&(this._modeX=e,this._geometryDirty=!0,this.invalidateCache())}get modeY(){return this._modeY}set modeY(e){fr(e,"modeY"),this._modeY!==e&&(this._modeY=e,this._geometryDirty=!0,this.invalidateCache())}get fitX(){return this._fitX}set fitX(e){pr(e,"fitX"),this._fitX!==e&&(this._fitX=e,this._geometryDirty=!0,this.invalidateCache())}get fitY(){return this._fitY}set fitY(e){pr(e,"fitY"),this._fitY!==e&&(this._fitY=e,this._geometryDirty=!0,this.invalidateCache())}get offsetX(){return this._offsetX}set offsetX(e){this.setOffset(e,this._offsetY)}get offsetY(){return this._offsetY}set offsetY(e){this.setOffset(this._offsetX,e)}setSize(e,t){return _r(e,t),this._width===e&&this._height===t||(this._width=e,this._height=t,this._geometryDirty=!0,this.invalidateCache()),this}setOffset(e,t){return mr(e,"offsetX"),mr(t,"offsetY"),this._offsetX===e&&this._offsetY===t||(this._offsetX=e,this._offsetY=t,"geometry"===this.resolvedStrategy&&(this._geometryDirty=!0),this.invalidateCache()),this}getLocalBounds(){const e=super.getLocalBounds();return e.set(0,0,this._width,this._height),e}get resolvedStrategy(){return this._source instanceof Wn?"geometry":"shader"}get quads(){return"geometry"===this.resolvedStrategy&&this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(e,t,i){const n=this.quads;if("geometry"!==this.pixelSnapMode||0===n.length)return n;const r=Pn(this.getGlobalTransform(),e,t,i);return r.axisAligned?Rn(n,r,this._renderQuads):n}getRenderBounds(e,t,i,n){const r=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return r;const s=Pn(this.getGlobalTransform(),e,t,i);return s.axisAligned?Dn(r,s,n):r}_rebuildGeometry(){this._quads=function(e,t,i,n,r,s,o,a,h){if(0===t||0===i||e.width<=0||e.height<=0)return[];const l=e.texture.width,u=e.texture.height,c=e.extrusion,d=c.left>0||c.right>0?0:.5/l,_=c.top>0||c.bottom>0?0:.5/u,f=e.u0+d,p=e.u1-d,m=e.v0+_,g=e.v1-_,y=e.width,w=e.height,x=p-f,v=g-m,b=yr(y,t,n,s,a),S=yr(w,i,r,o,h),B=[];for(const e of S){const t=e.destinationStart,i=e.destinationStart+e.destinationLength,n=m+e.sourceStart*v,r=m+e.sourceEnd*v;for(const e of b){const s=e.destinationStart,o=e.destinationStart+e.destinationLength,a=f+e.sourceStart*x,h=f+e.sourceEnd*x;B.push({x0:s,y0:t,x1:o,y1:i,u0:a,v0:n,u1:h,v1:r})}}return B}(this._region,this._width,this._height,this._modeX,this._modeY,this._fitX,this._fitY,this._offsetX,this._offsetY),this._geometryDirty=!1}}var xr;e.SpriteFlags=void 0,(xr=e.SpriteFlags||(e.SpriteFlags={}))[xr.None=0]="None",xr[xr.Translation=1]="Translation",xr[xr.Rotation=2]="Rotation",xr[xr.Scaling=4]="Scaling",xr[xr.Origin=8]="Origin",xr[xr.Transform=15]="Transform",xr[xr.TransformInverse=16]="TransformInverse",xr[xr.BoundingBox=32]="BoundingBox",xr[xr.TextureCoords=64]="TextureCoords",xr[xr.VertexTint=128]="VertexTint",xr[xr.Vertices=1024]="Vertices",xr[xr.Normals=2048]="Normals";class vr extends Fn{_texture=null;_textureFrame=new et;_material=null;_vertices=new Float32Array(8);_texCoords=new Uint32Array(4);_normals=[new it,new it,new it,new it];constructor(t){super(),this.flags.push(e.SpriteFlags.Vertices|e.SpriteFlags.Normals),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(e){this.setTexture(e)}get textureFrame(){return this._textureFrame}set textureFrame(e){this.setTextureFrame(e)}get material(){return this._material}set material(e){if(null!==e&&"sprite"!==e.target)throw new Error(`Sprite requires a SpriteMaterial (got a ${e.target} material).`);this._material=e,this.invalidateCache()}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(e){this.scale.x=e/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(e){this.scale.y=e/this._textureFrame.height}get vertices(){if(this.flags.has(e.SpriteFlags.Vertices)){const{left:t,top:i,right:n,bottom:r}=this.getLocalBounds(),{a:s,b:o,x:a,c:h,d:l,y:u}=this.getGlobalTransform();this._vertices[0]=t*s+i*o+a,this._vertices[1]=t*h+i*l+u,this._vertices[2]=n*s+i*o+a,this._vertices[3]=n*h+i*l+u,this._vertices[4]=n*s+r*o+a,this._vertices[5]=n*h+r*l+u,this._vertices[6]=t*s+r*o+a,this._vertices[7]=t*h+r*l+u,this.flags.remove(e.SpriteFlags.Vertices)}return this._vertices}getRenderBounds(e,t,i,n){const r=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return r;const s=Pn(this.getGlobalTransform(),e,t,i);return s.axisAligned?Dn(r,s,n):r}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(e.SpriteFlags.TextureCoords)){const{width:e,height:t}=this._texture,{left:i,top:n,right:r,bottom:s}=this._textureFrame,o=i/e*65535&65535,a=(n/t*65535&65535)<<16,h=r/e*65535&65535,l=(s/t*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o)}return this._texCoords}setTexture(e){return this._texture!==e&&(this._texture=e,null!==e&&this.resetTextureFrame(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,i=!0){const n=this.width,r=this.height;return this._textureFrame.copy(t),this.flags.push(e.SpriteFlags.TextureCoords),this.getLocalBounds().set(0,0,t.width,t.height),this._invalidateBoundsCascade(),i?(this.width=t.width,this.height=t.height):(this.width=n,this.height=r),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(et.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){if(this.flags.has(e.SpriteFlags.Normals)){const t=this.vertices,i=t[0],n=t[1],r=t[2],s=t[3],o=t[4],a=t[5],h=t[6],l=t[7];this._normals[0].set(r-i,s-n).rperp().normalize(),this._normals[1].set(o-r,a-s).rperp().normalize(),this._normals[2].set(h-o,l-a).rperp().normalize(),this._normals[3].set(i-h,n-l).rperp().normalize(),this.flags.remove(e.SpriteFlags.Normals)}return this._normals}project(e,t=new me){const i=this.vertices,n=i[0],r=i[1],s=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=e.dot(n,r),d=e.dot(s,o),_=e.dot(a,h),f=e.dot(l,u);return t.set(Math.min(c,d,_,f),Math.max(c,d,_,f))}contains(e,t){if(this.isAlignedBox)return this.getBounds().contains(e,t);const i=this.vertices,n=i[0],r=i[1],s=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=(s-n)*(t-r)-(o-r)*(e-n),d=(a-s)*(t-o)-(h-o)*(e-s),_=(l-a)*(t-h)-(u-h)*(e-a),f=(n-l)*(t-u)-(r-u)*(e-l);return c>=0&&d>=0&&_>=0&&f>=0||c<=0&&d<=0&&_<=0&&f<=0}_invalidateSubtreeTransform(){super._invalidateSubtreeTransform(),this.flags.push(e.SpriteFlags.Vertices|e.SpriteFlags.Normals)}_invalidateBoundsCascade(){super._invalidateBoundsCascade(),this.flags.push(e.SpriteFlags.Vertices|e.SpriteFlags.Normals)}destroy(){super.destroy();for(const e of this._normals)e.destroy();this._textureFrame.destroy(),this._texture=null,this._material=null}}Si.setInternalSpriteFactory(()=>new vr(null));class br extends Fn{_text;constructor(e){super(),this._text=e}get text(){return this._text}get textBounds(){return{width:0,height:0}}syncDirty(){}update(e){this.syncDirty()}}class Sr{fontData;textures;constructor(e,t){t.length,e.pages.length,t.length,e.pages.length,this.fontData=e,this.textures=t}}function Br(e,t,i,n){if(0===e.length)return[];const{fontSize:r,lineHeight:s,leading:o,align:a}=t,h=r*s+o,l=i.letterSpacing??0,u=i.maxWidth,c=i.breakWords??!1,d=function(e,t){if("pre"===t)return e;if("normal"===t)return e.replaceAll("\n"," ").replaceAll(/[ \t]+/g," ");return e.split("\n").map(e=>e.replaceAll(/[ \t]+/g," ")).join("\n")}(e,i.whiteSpace??"pre-line"),_=d.split("\n"),f=[];for(const e of _)void 0===u?f.push(e):f.push(...Tr(e,r,n,u,l,c));const p=[];let m=0;for(let e=0;e<f.length;e++){const t=f[e],i=e*h;let s=0,o=0,a=!1;const u=[];let c=null;for(const e of t){null!==c&&void 0!==n.getKerning&&(s+=n.getKerning(c,e,r));const t=n.getGlyph(e,r);u.push({info:t,x:s,y:i,char:e}),s+=t.advance+l," "===e?a=!1:a||(a=!0,o++),c=e}const d=s-(u.length>0?l:0);d>m&&(m=d),p.push({placements:u,width:d,wordCount:o})}const g=[],y=p.length-1;for(let e=0;e<p.length;e++){const t=p[e];let i=0;if("right"===a)i=m-t.width;else if("center"===a)i=(m-t.width)/2;else if("justify"===a&&e!==y&&t.wordCount>1){const e=t.wordCount-1,s=(m-t.width)/e;let o=-1,a=!0;const h=n.getGlyph(" ",r).advance;for(const e of t.placements)a&&e.info.advance!==h?(o++,a=!1):a||e.info.advance!==h||(a=!0),g.push({x:e.x+i+o*s+(e.info.xBearing??0),y:e.y+(e.info.yBearing??0),width:e.info.width,height:e.info.height,page:e.info.page,uvLeft:e.info.uvLeft,uvTop:e.info.uvTop,uvRight:e.info.uvRight,uvBottom:e.info.uvBottom});continue}for(const{info:e,x:n,y:r}of t.placements)g.push({x:n+i+(e.xBearing??0),y:r+(e.yBearing??0),width:e.width,height:e.height,page:e.page,uvLeft:e.uvLeft,uvTop:e.uvTop,uvRight:e.uvRight,uvBottom:e.uvBottom})}return g}function Cr(e){const t=new Map;for(const i of e){if(i.width<=0||i.height<=0)continue;let e=t.get(i.page);void 0===e&&t.set(i.page,e=[]),e.push(i)}const i=[];for(const[e,n]of t){const t=n.length,r=new Float32Array(8*t),s=new Float32Array(8*t),o=new Uint16Array(6*t);for(let e=0;e<t;e++){const t=n[e],i=8*e,a=4*e,h=6*e;r[i+0]=t.x,r[i+1]=t.y,r[i+2]=t.x+t.width,r[i+3]=t.y,r[i+4]=t.x+t.width,r[i+5]=t.y+t.height,r[i+6]=t.x,r[i+7]=t.y+t.height,s[i+0]=t.uvLeft,s[i+1]=t.uvTop,s[i+2]=t.uvRight,s[i+3]=t.uvTop,s[i+4]=t.uvRight,s[i+5]=t.uvBottom,s[i+6]=t.uvLeft,s[i+7]=t.uvBottom,o[h+0]=a,o[h+1]=a+1,o[h+2]=a+2,o[h+3]=a,o[h+4]=a+2,o[h+5]=a+3}i.push({pageIndex:e,vertices:r,uvs:s,indices:o,quadCount:t})}return i}function Tr(e,t,i,n,r,s){if(0===e.length)return[""];const o=e.split(" "),a=[];let h="",l=0;const u=i.getGlyph(" ",t).advance+r;for(const e of o){let o=0;for(const n of e)o+=i.getGlyph(n,t).advance+r;if(o=Math.max(0,o-r),s&&o>n){h.length>0&&(a.push(h),h="",l=0);let s="",o=0;for(const h of e){const e=i.getGlyph(h,t).advance+r;s.length>0&&o+e>n?(a.push(s),s=h,o=e):(s+=h,o+=e)}s.length>0&&(h=s,l=o)}else if(0===h.length)h=e,l=o;else{const t=l+u+o;t<=n?(h+=` ${e}`,l=t):(a.push(h),h=e,l=o)}}return a.push(h),a}class Mr{_dirty=!1;_pendingHint="tint";onChange=new x;_fontFamily;_fontWeight;_fontStyle;_fontSize;_fillColor;_outlineColor;_outlineWidth;_align;_lineHeight;_leading;_shadowColor;_shadowOffsetX;_shadowOffsetY;_shadowAlpha;_shadowBlur;_gradientColors;_gradientAxis;constructor(e={}){const t="undefined"!=typeof FontFace&&e.font instanceof FontFace?e.font:null;this._fontFamily=t?t.family:e.fontFamily??"Arial",this._fontWeight=e.fontWeight??"normal",this._fontStyle=e.fontStyle??"normal",this._fontSize=e.fontSize??20,this._fillColor=e.fillColor?e.fillColor.clone():Tt.white.clone(),this._outlineColor=e.outlineColor?e.outlineColor.clone():Tt.black.clone(),this._outlineWidth=e.outlineWidth??0,this._align=e.align??"left",this._lineHeight=e.lineHeight??1.2,this._leading=e.leading??0,this._shadowColor=e.shadowColor?e.shadowColor.clone():Tt.black.clone(),this._shadowOffsetX=e.shadowOffsetX??0,this._shadowOffsetY=e.shadowOffsetY??0,this._shadowAlpha=e.shadowAlpha??0,this._shadowBlur=e.shadowBlur??0,this._gradientColors=e.gradientColors?[e.gradientColors[0].clone(),e.gradientColors[1].clone()]:null,this._gradientAxis=e.gradientAxis??"vertical",this._dirty=!0,this._pendingHint="font"}consumeDirty(){if(!this._dirty)return null;const e=this._pendingHint;return this._dirty=!1,this._pendingHint="tint",e}_markDirty(e){var t,i;this._pendingHint=(t=this._pendingHint,i=e,"font"===t||"font"===i?"font":"layout"===t||"layout"===i?"layout":"tint"),this._dirty||(this._dirty=!0,this.onChange.dispatch())}get fontFamily(){return this._fontFamily}set fontFamily(e){const t="undefined"!=typeof FontFace&&e instanceof FontFace?e.family:e;this._fontFamily!==t&&(this._fontFamily=t,this._markDirty("font"))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this._markDirty("font"))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this._markDirty("font"))}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(this._fontSize=e,this._markDirty("layout"))}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this._markDirty("layout"))}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this._markDirty("layout"))}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this._markDirty("layout"))}get fillColor(){return this._fillColor}set fillColor(e){this._fillColor=e.clone(),this._markDirty("tint")}get outlineColor(){return this._outlineColor}set outlineColor(e){this._outlineColor=e.clone(),this._markDirty("tint")}get outlineWidth(){return this._outlineWidth}set outlineWidth(e){this._outlineWidth!==e&&(this._outlineWidth=e,this._markDirty("tint"))}get shadowColor(){return this._shadowColor}set shadowColor(e){this._shadowColor=e.clone(),this._markDirty("tint")}get shadowOffsetX(){return this._shadowOffsetX}set shadowOffsetX(e){this._shadowOffsetX!==e&&(this._shadowOffsetX=e,this._markDirty("tint"))}get shadowOffsetY(){return this._shadowOffsetY}set shadowOffsetY(e){this._shadowOffsetY!==e&&(this._shadowOffsetY=e,this._markDirty("tint"))}get shadowAlpha(){return this._shadowAlpha}set shadowAlpha(e){this._shadowAlpha!==e&&(this._shadowAlpha=e,this._markDirty("tint"))}get shadowBlur(){return this._shadowBlur}set shadowBlur(e){this._shadowBlur!==e&&(this._shadowBlur=e,this._markDirty("tint"))}get gradientColors(){return this._gradientColors}set gradientColors(e){this._gradientColors=e?[e[0].clone(),e[1].clone()]:null,this._markDirty("tint")}get gradientAxis(){return this._gradientAxis}set gradientAxis(e){this._gradientAxis!==e&&(this._gradientAxis=e,this._markDirty("tint"))}get font(){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}copy(e){return e!==this&&(this._fontFamily=e._fontFamily,this._fontWeight=e._fontWeight,this._fontStyle=e._fontStyle,this._fontSize=e._fontSize,this._fillColor=e._fillColor.clone(),this._outlineColor=e._outlineColor.clone(),this._outlineWidth=e._outlineWidth,this._align=e._align,this._lineHeight=e._lineHeight,this._leading=e._leading,this._shadowColor=e._shadowColor.clone(),this._shadowOffsetX=e._shadowOffsetX,this._shadowOffsetY=e._shadowOffsetY,this._shadowAlpha=e._shadowAlpha,this._shadowBlur=e._shadowBlur,this._gradientColors=e._gradientColors?[e._gradientColors[0].clone(),e._gradientColors[1].clone()]:null,this._gradientAxis=e._gradientAxis,this._markDirty("font")),this}clone(){const e=new Mr;return e._fontFamily=this._fontFamily,e._fontWeight=this._fontWeight,e._fontStyle=this._fontStyle,e._fontSize=this._fontSize,e._fillColor=this._fillColor.clone(),e._outlineColor=this._outlineColor.clone(),e._outlineWidth=this._outlineWidth,e._align=this._align,e._lineHeight=this._lineHeight,e._leading=this._leading,e._shadowColor=this._shadowColor.clone(),e._shadowOffsetX=this._shadowOffsetX,e._shadowOffsetY=this._shadowOffsetY,e._shadowAlpha=this._shadowAlpha,e._shadowBlur=this._shadowBlur,e._gradientColors=this._gradientColors?[this._gradientColors[0].clone(),this._gradientColors[1].clone()]:null,e._gradientAxis=this._gradientAxis,e._dirty=!0,e._pendingHint="font",e}}class Pr{_fontData;_textures;_scale;_fallbackAdvance;_fontId;constructor(e,t,i){this._fontData=e,this._textures=t,this._scale=i,this._fallbackAdvance=e.lineHeight*i*.5,this._fontId=e.pages[0]??"unknown"}getGlyph(e,t){const i=e.codePointAt(0)??0,n=this._fontData.chars.get(i),r=this._scale,s=this._fontData.lineHeight,o=this._fontData.base;if(void 0===n)return{x:0,y:0,width:0,height:0,advance:this._fallbackAdvance,ascent:0,page:0,uvLeft:0,uvTop:0,uvRight:0,uvBottom:0};n.page,this._textures.length,n.page,this._fontId,this._textures.length;const a=this._textures[n.page]?.width??1,h=this._textures[n.page]?.height??1;return{x:n.x,y:n.y,width:n.width*r,height:n.height*r,advance:n.xAdvance*r,ascent:0,page:n.page,uvLeft:n.x/a,uvTop:n.y/h,uvRight:(n.x+n.width)/a,uvBottom:(n.y+n.height)/h,xBearing:n.xOffset*r,yBearing:(n.yOffset-o)*r+s*r}}getKerning(e,t,i){const n=e.codePointAt(0),r=t.codePointAt(0);return void 0===n||void 0===r?0:(this._fontData.kernings.get(`${n},${r}`)??0)*this._scale}}class Ar extends br{_font;_fontScale;_msdf;_style;_layout;_pageQuads=[];_textBounds={width:0,height:0};_adapter;constructor(e,t,i={}){super(e),this._font=t,this._fontScale=i.scale??1,this._msdf=i.msdf??!1,this._style=new Mr(i),this._layout=i.layout??{},this._adapter=new Pr(t.fontData,t.textures,this._fontScale),this._rebuild()}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuild())}get style(){return this._style}set style(e){this._style=e instanceof Mr?e:new Mr(e),this._rebuild()}get layout(){return this._layout}set layout(e){this._layout=e,this._rebuild()}get fontScale(){return this._fontScale}set fontScale(e){this._fontScale!==e&&(this._fontScale=e,this._adapter=new Pr(this._font.fontData,this._font.textures,e),this._rebuild())}get msdf(){return this._msdf}get font(){return this._font}get pageQuads(){return this._pageQuads}get textBounds(){return this._textBounds}get textures(){return this._font.textures}setFont(e){this._font=e,this._adapter=new Pr(e.fontData,e.textures,this._fontScale),this._rebuild()}destroy(){this._pageQuads=[],super.destroy()}_rebuild(){if(this._pageQuads=[],this._textBounds={width:0,height:0},0===this._text.length)return;const e={fontSize:this._font.fontData.lineHeight*this._fontScale,lineHeight:this._style.lineHeight,leading:this._style.leading,align:this._style.align},t=Br(this._text,e,this._layout,this._adapter);let i=0,n=0;for(const e of t){const t=e.x+e.width,r=e.y+e.height;t>i&&(i=t),r>n&&(n=r)}this._textBounds={width:i,height:n},this.getLocalBounds().set(0,0,i,n),this._invalidateBoundsCascade(),this._pageQuads=Cr(t)}}const Er={r8:1,r32f:1,rgba8:4,rgba32f:4},Rr={r8:1,r32f:4,rgba8:1,rgba32f:4};class kr extends pi{static defaultSamplerOptions={scaleMode:e.ScaleModes.Nearest,wrapMode:e.WrapModes.ClampToEdge,premultiplyAlpha:!1,generateMipMap:!1,flipY:!1};format;buffer;_dirty=null;constructor(e){super(null,{...kr.defaultSamplerOptions,...e.samplerOptions});const{width:t,height:i,format:n,data:r}=e;if(!Number.isInteger(t)||t<=0)throw new Error(`DataTexture width must be a positive integer (got ${t}).`);if(!Number.isInteger(i)||i<=0)throw new Error(`DataTexture height must be a positive integer (got ${i}).`);const s=t*i*Er[n]*Rr[n];let o;if(void 0===r)o=Dr(n)?new Float32Array(s/4):new Uint8Array(s);else if(r instanceof ArrayBuffer){if(r.byteLength!==s)throw new Error(`DataTexture data byteLength ${r.byteLength} does not match ${t}x${i} ${n} (${s} bytes expected).`);o=Dr(n)?new Float32Array(r):new Uint8Array(r)}else if(r instanceof Uint8Array){if(Dr(n))throw new Error(`DataTexture format '${n}' requires a Float32Array, got Uint8Array.`);if(r.byteLength!==s)throw new Error(`DataTexture Uint8Array length ${r.length} does not match ${t}x${i} ${n} (${s} expected).`);o=r}else{if(!Dr(n))throw new Error(`DataTexture format '${n}' requires a Uint8Array, got Float32Array.`);if(r.byteLength!==s)throw new Error(`DataTexture Float32Array byteLength ${r.byteLength} does not match ${t}x${i} ${n} (${s} expected).`);o=r}this.format=n,this.buffer=o,this.setSize(t,i),this._dirty={full:!0,x:0,y:0,width:t,height:i}}updateSource(){return this.commit()}commit(){return this._dirty={full:!0,x:0,y:0,width:this.width,height:this.height},this.setSize(this.width,this.height),this._bumpVersion(),this}commitRect(e,t,i,n){if(!(Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(i)&&Number.isInteger(n)))throw new Error(`DataTexture commitRect requires integer coordinates (got ${e}, ${t}, ${i}, ${n}).`);if(i<=0||n<=0)throw new Error(`DataTexture commitRect requires positive width and height (got ${i}, ${n}).`);if(e<0||t<0||e+i>this.width||t+n>this.height)throw new Error(`DataTexture commitRect (${e}, ${t}, ${i}, ${n}) is out of bounds for ${this.width}x${this.height}.`);if(null===this._dirty)this._dirty={full:!1,x:e,y:t,width:i,height:n};else if(this._dirty.full);else{const r=Math.min(this._dirty.x,e),s=Math.min(this._dirty.y,t),o=Math.max(this._dirty.x+this._dirty.width,e+i),a=Math.max(this._dirty.y+this._dirty.height,t+n);this._dirty={full:!1,x:r,y:s,width:o-r,height:a-s}}return this._bumpVersion(),this}_consumeDirtyRegion(){const e=this._dirty;return this._dirty=null,e}}function Dr(e){return"r32f"===e||"rgba32f"===e}const Fr=1e20;class Ir{_buffer;_radius;_cutoff;_font;_fontSize;_fontAscent=0;_fontDescent=0;_metricsReady=!1;_canvasW=0;_canvasH=0;_canvas;_ctx;_gridOuter=new Float64Array(0);_gridInner=new Float64Array(0);_f=new Float64Array(0);_d=new Float64Array(0);_z=new Float64Array(0);_v=new Int16Array(0);_out=new Uint8ClampedArray(0);constructor(e){this._buffer=e.buffer??8,this._radius=e.radius??this._buffer,this._cutoff=e.cutoff??.5,this._fontSize=e.fontSize;const t=e.fontStyle&&"normal"!==e.fontStyle?`${e.fontStyle} `:"",i=e.fontWeight??"normal";if(this._font=`${t}${i} ${e.fontSize}px ${e.fontFamily}`,"undefined"!=typeof OffscreenCanvas){const e=new OffscreenCanvas(1,1);this._canvas=e,this._ctx=e.getContext("2d",{willReadFrequently:!0})}else{const e=document.createElement("canvas");this._canvas=e,this._ctx=e.getContext("2d",{willReadFrequently:!0})}}_ensureFontMetrics(){if(this._metricsReady)return;const e=this._ctx;e.font=this._font,e.textBaseline="alphabetic";const t=e.measureText("HgjpqyÉÅ");this._fontAscent=Math.max(1,Math.ceil(t.fontBoundingBoxAscent??t.actualBoundingBoxAscent??.8*this._fontSize)),this._fontDescent=Math.max(1,Math.ceil(t.fontBoundingBoxDescent??t.actualBoundingBoxDescent??.2*this._fontSize)),this._metricsReady=!0}draw(e){this._ensureFontMetrics();const t=this._ctx,i=this._buffer;t.font=this._font,t.textBaseline="alphabetic";const n=t.measureText(e),r=n.width,s=Math.max(0,Math.ceil(n.actualBoundingBoxLeft??0)),o=Math.max(0,Math.ceil(n.actualBoundingBoxRight??r)),a=Math.max(1,s+o),h=this._fontAscent+this._fontDescent,l=a+2*i,u=h+2*i;this._canvasW===l&&this._canvasH===u||(this._canvas.width=l,this._canvas.height=u,this._canvasW=l,this._canvasH=u),t.clearRect(0,0,l,u),t.font=this._font,t.textBaseline="alphabetic",t.fillStyle="#ffffff",t.fillText(e,i+s,i+this._fontAscent);const c=t.getImageData(0,0,l,u).data,d=l*u;if(d>this._gridOuter.length){const e=Math.max(l,u);this._gridOuter=new Float64Array(d),this._gridInner=new Float64Array(d),this._f=new Float64Array(e),this._d=new Float64Array(e),this._z=new Float64Array(e+1),this._v=new Int16Array(e)}d>this._out.length&&(this._out=new Uint8ClampedArray(d));for(let e=0;e<d;e++){const t=c[4*e+3]/255;1===t?(this._gridOuter[e]=0,this._gridInner[e]=Fr):0===t?(this._gridOuter[e]=Fr,this._gridInner[e]=0):(this._gridOuter[e]=Math.max(0,.5-t)**2,this._gridInner[e]=Math.max(0,t-.5)**2)}Lr(this._gridOuter,l,u,this._f,this._d,this._v,this._z),Lr(this._gridInner,l,u,this._f,this._d,this._v,this._z);for(let e=0;e<d;e++){const t=this._gridOuter[e]-this._gridInner[e];this._out[e]=Math.max(0,Math.min(255,Math.round(255-255*(t/this._radius+this._cutoff))))}return{data:this._out.slice(0,d),width:l,height:u,glyphWidth:a,glyphHeight:h,glyphTop:i,glyphLeft:i,glyphAdvance:r}}}function Lr(e,t,i,n,r,s,o){for(let a=0;a<t;a++){for(let r=0;r<i;r++)n[r]=e[r*t+a];Ur(n,r,s,o,i);for(let n=0;n<i;n++)e[n*t+a]=r[n]}for(let a=0;a<i;a++){for(let i=0;i<t;i++)n[i]=e[a*t+i];Ur(n,r,s,o,t);for(let i=0;i<t;i++)e[a*t+i]=Math.sqrt(r[i])}}function Ur(e,t,i,n,r){let s=0;i[0]=0,n[0]=-Fr,n[1]=Fr;for(let t=1;t<r;t++){let r;do{const o=i[s];if(r=(e[t]+t*t-e[o]-o*o)/(2*(t-o)),r>n[s])break;s--}while(s>=0);s++,i[s]=t,n[s]=r,n[s+1]=Fr}s=0;for(let o=0;o<r;o++){for(;n[s+1]<o;)s++;const r=i[s];t[o]=(o-r)*(o-r)+e[r]}}class Gr{_shelves=[];_width;_height;constructor(e,t){this._width=e,this._height=t}insert(e,t){for(const i of this._shelves)if(i.height>=t&&i.cursorX+e<=this._width){const t=i.cursorX;return i.cursorX+=e,{x:t,y:i.y}}const i=this._shelves[this._shelves.length-1],n=void 0===i?0:i.y+i.height;return n+t>this._height?null:(this._shelves.push({y:n,height:t,cursorX:e}),{x:0,y:n})}reset(){this._shelves.length=0}}class Nr{texture;index;mode;_packer;_width;_height;_sdfBuffer=null;_sdfTexture=null;_ctx=null;_colorGlyphs;constructor(e,t,i,n){if(this.index=e,this.mode=n,this._width=t,this._height=i,this._colorGlyphs="color"===n,this._packer=new Gr(t,i),"sdf"===n)this._sdfBuffer=new Uint8Array(t*i),this._sdfTexture=new kr({width:t,height:i,format:"r8",data:this._sdfBuffer}),this._sdfTexture.setSize(t,i),this.texture=this._sdfTexture;else{const{canvas:e,ctx:n}=function(e,t){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(e,t),n=i.getContext("2d");if(!n)throw new Error("GlyphAtlas: could not obtain OffscreenCanvas 2D context.");return{canvas:i,ctx:n}}const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");if(!n)throw new Error("GlyphAtlas: could not obtain canvas 2D context.");return{canvas:i,ctx:n}}(t,i);this._ctx=n,this.texture=new pi(e),this.texture.setSize(t,i)}}insert(e,t){return this._packer.insert(e,t)}writeSdf(e,t,i,n,r){const s=this._sdfBuffer,o=this._width;for(let a=0;a<r;a++){const r=a*n,h=(i+a)*o+t;s.set(e.subarray(r,r+n),h)}this._sdfTexture.commitRect(t,i,n,r)}measureGlyph(e,t){if(null!==this._ctx)return this._ctx.font=t,this._ctx.textBaseline="alphabetic",this._ctx.measureText(e);const i=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")).getContext("2d");return i.font=t,i.textBaseline="alphabetic",i.measureText(e)}rasterize(e,t,i,n,r,s){const o=this._ctx;o.font=s,o.textBaseline="alphabetic",this._colorGlyphs||(o.fillStyle="#ffffff"),o.fillText(e,t+2+r,i+2+n)}uploadDirtyRegion(){null!==this._sdfTexture?this._sdfTexture.commit():this.texture.updateSource()}reset(){this._packer.reset(),null!==this._sdfBuffer&&null!==this._sdfTexture?(this._sdfBuffer.fill(0),this._sdfTexture.commit()):null!==this._ctx&&(this._ctx.clearRect(0,0,this._width,this._height),this.texture.updateSource())}}class Or{_pages=[];_cache=new Map;_kerningCache=new Map;_pageSize;_family;_fontStyle;_fontWeight;_mode;_sdfRadius;onPageAdded=new x;_sdfInstances=new Map;constructor(e,t,i,n=1024,r="sdf",s=8){this._family=e,this._fontStyle=t,this._fontWeight=i,this._pageSize=n,this._mode=r,this._sdfRadius=s,this._addPage()}get pages(){return this._pages}get mode(){return this._mode}getGlyph(e,t){const i=`${e}:${t}`,n=this._cache.get(i);return void 0!==n?n:"sdf"===this._mode?this._rasterizeSdf(e,t,i):this._rasterizeCanvas(e,t,i)}getKerning(e,t,i){const n=`${e}${t}:${i}`,r=this._kerningCache.get(n);if(void 0!==r)return r;const s=this._cssFont(i),o=this._pages[0],a=o.measureGlyph(e+t,s).width-o.measureGlyph(e,s).width-o.measureGlyph(t,s).width;return this._kerningCache.set(n,a),a}clear(){this._cache.clear(),this._kerningCache.clear(),this._sdfInstances.clear();for(const e of this._pages)e.reset();this._pages=[],this._addPage()}_addPage(){const e=this._pages.length,t=new Nr(e,this._pageSize,this._pageSize,this._mode);return this._pages.push(t),e>0&&this.onPageAdded.dispatch(e),t}_cssFont(e){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${e}px ${this._family}`}_getSdf(e){let t=this._sdfInstances.get(e);return void 0===t&&(t=new Ir({fontSize:e,fontFamily:this._family,fontWeight:this._fontWeight,fontStyle:this._fontStyle,buffer:this._sdfRadius,radius:this._sdfRadius,cutoff:.5}),this._sdfInstances.set(e,t)),t}_rasterizeSdf(e,t,i){const n=this._getSdf(t).draw(e),{page:r,slot:s}=this._allocateSlot(n.width,n.height);r.writeSdf(n.data,s.x,s.y,n.width,n.height);const o=this._pageSize,a={x:s.x,y:s.y,width:n.width,height:n.height,advance:n.glyphAdvance,ascent:n.glyphTop+n.glyphHeight,page:r.index,uvLeft:s.x/o,uvTop:s.y/o,uvRight:(s.x+n.width)/o,uvBottom:(s.y+n.height)/o,xBearing:-n.glyphLeft,yBearing:-n.glyphTop};return this._cache.set(i,a),a}_rasterizeCanvas(e,t,i){const n=this._cssFont(t),r=this._pages[0].measureGlyph(e,n),s=Math.ceil(r.fontBoundingBoxAscent??r.actualBoundingBoxAscent??.8*t),o=Math.ceil(r.fontBoundingBoxDescent??r.actualBoundingBoxDescent??.2*t),a=r.width,h=r.actualBoundingBoxLeft??0,l=r.actualBoundingBoxRight??0,u=Math.max(1,Math.ceil(h+l)||Math.ceil(a)),c=Math.max(1,s+o),d=u+4,_=c+4,{page:f,slot:p}=this._allocateSlot(d,_);f.rasterize(e,p.x,p.y,s,h,n),f.uploadDirtyRegion();const m=this._pageSize,g={x:p.x,y:p.y,width:u,height:c,advance:a,ascent:s,page:f.index,uvLeft:p.x/m,uvTop:p.y/m,uvRight:(p.x+d)/m,uvBottom:(p.y+_)/m};return this._cache.set(i,g),g}_allocateSlot(e,t){for(const i of this._pages){const n=i.insert(e,t);if(null!==n)return{page:i,slot:n}}const i=this._addPage(),n=i.insert(e,t);if(null===n)throw new Error(`GlyphAtlas: glyph (${e}×${t}px) exceeds page size (${this._pageSize}px).`);return{page:i,slot:n}}}class Vr{_atlases=new Map;_pageSize;constructor(e=1024){this._pageSize=e}getAtlas(e,t,i,n="sdf",r=8){const s=`${e}:${t}:${i}:${n}:${r}`;let o=this._atlases.get(s);return void 0===o&&(o=new Or(e,t,i,this._pageSize,n,r),this._atlases.set(s,o)),o}clearAll(){for(const e of this._atlases.values())e.clear()}}let zr=null;function qr(){return null===zr&&(zr=new Vr),zr}class Wr extends br{_style;_layout;_colorGlyphs;_sdfRadius;_atlas=null;_destroyed=!1;_faceLoadVersion=0;_pageQuads=[];_textBounds={width:0,height:0};constructor(e,t={}){super(e),this._style=new Mr(t),this._layout=t,this._colorGlyphs=t.colorGlyphs??!1,this._sdfRadius=t.sdfRadius??8;const i=this._extractFace(t);null!==i&&this._loadFace(i),this._rebuild("font")}get style(){return this._style}set style(e){if(this._style=e instanceof Mr?e:new Mr(e),!(e instanceof Mr)){const t=this._extractFace(e);null!==t&&this._loadFace(t)}this._rebuild("font")}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuild("layout"))}get layout(){return this._layout}set layout(e){this._layout=e,this._rebuild("layout")}get colorGlyphs(){return this._colorGlyphs}get sdfRadius(){return this._sdfRadius}get atlasMode(){return this._colorGlyphs?"color":"sdf"}get pageQuads(){return this._pageQuads}get textBounds(){return this._textBounds}get atlas(){return this._atlas}syncDirty(){const e=this._style.consumeDirty();null!==e&&"tint"!==e&&this._rebuild(e)}destroy(){this._destroyed=!0,this._faceLoadVersion++,this._pageQuads=[],this._atlas=null,super.destroy()}_extractFace(e){return"undefined"==typeof FontFace?null:e.font instanceof FontFace?e.font:null}async _loadFace(e){if("undefined"==typeof document||!document.fonts)return;const t=++this._faceLoadVersion;document.fonts.has(e)||document.fonts.add(e);try{await e.load()}catch{return}if(this._destroyed||t!==this._faceLoadVersion)return;qr().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius).clear(),this._rebuild("font")}_rebuild(e){if(this._pageQuads=[],this._textBounds={width:0,height:0},0===this._text.length)return void this._style.consumeDirty();const t=qr().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius);this._atlas=t;const i=Br(this._text,this._style,this._layout,t);if(0===i.length)return void this._style.consumeDirty();let n=0,r=0;for(const e of i){const t=e.x+e.width,i=e.y+e.height;t>n&&(n=t),i>r&&(r=i)}this._textBounds={width:n,height:r},this.getLocalBounds().set(0,0,n,r),this._invalidateBoundsCascade(),this._pageQuads=Cr(i),this._style.consumeDirty()}}class Yr{attributes=new Map;uniforms=new Map;_vertexSource;_fragmentSource;_program=null;constructor(e,t){this._vertexSource=e,this._fragmentSource=t}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(e){return this._program=e,e.initialize(this),this}disconnect(){return this._program=null,this.attributes.clear(),this.uniforms.clear(),this}bind(){return this._program?.bind(this),this}unbind(){return this._program?.unbind(this),this}sync(){return this._program?.sync(this),this}getAttribute(e){const t=this.attributes.get(e);if(!t)throw new Error(`Attribute "${e}" is not available.`);return t}getUniform(e){const t=this.uniforms.get(e);if(!t)throw new Error(`Uniform "${e}" is not available.`);return t}destroy(){this._program?.destroy(this),this._program=null,this.attributes.clear(),this.uniforms.clear()}}var $r;e.RenderBackendType=void 0,($r=e.RenderBackendType||(e.RenderBackendType={}))[$r.WebGl2=0]="WebGl2",$r[$r.WebGpu=1]="WebGpu";class Xr{backendType=e.RenderBackendType.WebGl2;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==e.RenderBackendType.WebGl2)throw new Error(`${this.constructor.name} requires a WebGL2 backend, but received backendType ${String(t.backendType)}.`);this._backend=t,this.onConnect(t)}}disconnect(){null!==this._backend&&(this.flush(),this.onDisconnect(),this._backend=null)}getBackend(){if(null===this._backend)throw new Error(`${this.constructor.name} is not connected to a backend.`);return this._backend}getBackendOrNull(){return this._backend}}class Hr{_type;_usage;_runtime=null;_data=m;_version=0;_accountant=null;_accountedBytes=0;constructor(e,t,i){this._type=e,this._usage=i,t&&this.upload(t)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(e,t){return this._runtime=e,this._accountant=t??null,this._data.byteLength>0&&(e.upload(this,0),this._bookUpload()),this}disconnect(){return this._runtime=null,this}upload(e,t=0){this._data=e,this._version++,this._runtime?.upload(this,t),this._bookUpload()}bind(){this._runtime?.bind(this)}destroy(){this._runtime?.destroy(this),this._runtime=null,this._accountedBytes>0&&(this._accountant?.free(this._accountedBytes),this._accountedBytes=0)}_bookUpload(){const e=this._accountant;if(null===e||null===this._runtime)return;const t=this._data.byteLength;e.recordBufferUpload(t),t>this._accountedBytes&&(this._accountedBytes=e.reallocate(this._accountedBytes,t))}}const jr={[e.ShaderPrimitives.Float]:1,[e.ShaderPrimitives.FloatVec2]:2,[e.ShaderPrimitives.FloatVec3]:3,[e.ShaderPrimitives.FloatVec4]:4,[e.ShaderPrimitives.Int]:1,[e.ShaderPrimitives.IntVec2]:2,[e.ShaderPrimitives.IntVec3]:3,[e.ShaderPrimitives.IntVec4]:4,[e.ShaderPrimitives.UnsignedInt]:1,[e.ShaderPrimitives.UnsignedIntVec2]:2,[e.ShaderPrimitives.UnsignedIntVec3]:3,[e.ShaderPrimitives.UnsignedIntVec4]:4,[e.ShaderPrimitives.Bool]:1,[e.ShaderPrimitives.BoolVec2]:2,[e.ShaderPrimitives.BoolVec3]:3,[e.ShaderPrimitives.BoolVec4]:4,[e.ShaderPrimitives.FloatMat2]:4,[e.ShaderPrimitives.FloatMat3]:9,[e.ShaderPrimitives.FloatMat4]:16,[e.ShaderPrimitives.Sampler2D]:1},Kr={[e.ShaderPrimitives.Float]:Float32Array,[e.ShaderPrimitives.FloatVec2]:Float32Array,[e.ShaderPrimitives.FloatVec3]:Float32Array,[e.ShaderPrimitives.FloatVec4]:Float32Array,[e.ShaderPrimitives.Int]:Int32Array,[e.ShaderPrimitives.IntVec2]:Int32Array,[e.ShaderPrimitives.IntVec3]:Int32Array,[e.ShaderPrimitives.IntVec4]:Int32Array,[e.ShaderPrimitives.UnsignedInt]:Int32Array,[e.ShaderPrimitives.UnsignedIntVec2]:Int32Array,[e.ShaderPrimitives.UnsignedIntVec3]:Int32Array,[e.ShaderPrimitives.UnsignedIntVec4]:Int32Array,[e.ShaderPrimitives.Bool]:Uint8Array,[e.ShaderPrimitives.BoolVec2]:Uint8Array,[e.ShaderPrimitives.BoolVec3]:Uint8Array,[e.ShaderPrimitives.BoolVec4]:Uint8Array,[e.ShaderPrimitives.FloatMat2]:Float32Array,[e.ShaderPrimitives.FloatMat3]:Float32Array,[e.ShaderPrimitives.FloatMat4]:Float32Array,[e.ShaderPrimitives.Sampler2D]:Uint8Array};e.ShaderPrimitives.Float,e.ShaderPrimitives.FloatVec2,e.ShaderPrimitives.FloatVec3,e.ShaderPrimitives.FloatVec4,e.ShaderPrimitives.Int,e.ShaderPrimitives.IntVec2,e.ShaderPrimitives.IntVec3,e.ShaderPrimitives.IntVec4,e.ShaderPrimitives.UnsignedInt,e.ShaderPrimitives.UnsignedIntVec2,e.ShaderPrimitives.UnsignedIntVec3,e.ShaderPrimitives.UnsignedIntVec4,e.ShaderPrimitives.Bool,e.ShaderPrimitives.BoolVec2,e.ShaderPrimitives.BoolVec3,e.ShaderPrimitives.BoolVec4,e.ShaderPrimitives.FloatMat2,e.ShaderPrimitives.FloatMat3,e.ShaderPrimitives.FloatMat4,e.ShaderPrimitives.Sampler2D;class Qr{index;name;type;size;location=-1;constructor(e,t,i){this.index=e,this.name=t,this.type=i,this.size=jr[i]}destroy(){}}class Zr{index;type;size;name;_value;_dirty=!0;constructor(e,t,i,n,r){this.name=n.replace(/\[.*?]/,""),this.index=e,this.type=t,this.size=i,this._value=r}get propName(){return this.name.substring(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(e){return this._value.set(e),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class Jr{index;name;binding;dataSize;_context;_program;_blockData;_uniformBuffer;_uniforms=new Map;constructor(e,t,i){this._context=e,this._program=t,this.index=i,this.name=e.getActiveUniformBlockName(t,i)||"",this.binding=e.getActiveUniformBlockParameter(t,i,e.UNIFORM_BLOCK_BINDING),this.dataSize=e.getActiveUniformBlockParameter(t,i,e.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=e.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),e.bindBuffer(e.UNIFORM_BUFFER,this._uniformBuffer),e.bufferData(e.UNIFORM_BUFFER,this._blockData,e.DYNAMIC_DRAW),e.bindBufferBase(e.UNIFORM_BUFFER,this.binding,this._uniformBuffer),e.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(e){if(!this._uniforms.has(e))throw new Error(`Uniform "${e}" is not available.`);return this._uniforms.get(e)}upload(){const e=this._context;e.bindBuffer(e.UNIFORM_BUFFER,this._uniformBuffer),e.bufferSubData(e.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const e of this._uniforms.values())e.destroy();this._uniforms.clear()}_extractUniforms(){const e=this._context,t=this._program,i=this._blockData,n=e.getActiveUniformBlockParameter(t,this.index,e.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),r=e.getActiveUniforms(t,n,e.UNIFORM_OFFSET),s=n.length;for(let o=0;o<s;o++){const s=n[o],{type:a,size:h,name:l}=e.getActiveUniform(t,s),u=Kr[a],c=jr[a];if(void 0===u||void 0===c)throw new Error(`Unsupported uniform type ${a} for uniform "${l}".`);const d=new u(i,r[o],c*h),_=new Zr(s,a,h,l,d);this._uniforms.set(_.propName,_)}}}const es={[e.ShaderPrimitives.Float]:(e,t,i)=>{e.uniform1f(t,i[0])},[e.ShaderPrimitives.FloatVec2]:(e,t,i)=>{e.uniform2fv(t,i)},[e.ShaderPrimitives.FloatVec3]:(e,t,i)=>{e.uniform3fv(t,i)},[e.ShaderPrimitives.FloatVec4]:(e,t,i)=>{e.uniform4fv(t,i)},[e.ShaderPrimitives.Int]:(e,t,i)=>{e.uniform1i(t,i[0])},[e.ShaderPrimitives.IntVec2]:(e,t,i)=>{e.uniform2iv(t,i)},[e.ShaderPrimitives.IntVec3]:(e,t,i)=>{e.uniform3iv(t,i)},[e.ShaderPrimitives.IntVec4]:(e,t,i)=>{e.uniform4iv(t,i)},[e.ShaderPrimitives.Bool]:(e,t,i)=>{e.uniform1i(t,i[0])},[e.ShaderPrimitives.BoolVec2]:(e,t,i)=>{e.uniform2iv(t,i)},[e.ShaderPrimitives.BoolVec3]:(e,t,i)=>{e.uniform3iv(t,i)},[e.ShaderPrimitives.BoolVec4]:(e,t,i)=>{e.uniform4iv(t,i)},[e.ShaderPrimitives.FloatMat2]:(e,t,i)=>{e.uniformMatrix2fv(t,!1,i)},[e.ShaderPrimitives.FloatMat3]:(e,t,i)=>{e.uniformMatrix3fv(t,!1,i)},[e.ShaderPrimitives.FloatMat4]:(e,t,i)=>{e.uniformMatrix4fv(t,!1,i)},[e.ShaderPrimitives.Sampler2D]:(e,t,i)=>{e.uniform1i(t,i[0])}};function ts(e){let t=null,i=null,n=null,r=null;const s=[],o=[],a=e.getExtension("KHR_parallel_shader_compile"),h=a?.COMPLETION_STATUS_KHR??37297;function l(s){t||(i=is(e,e.VERTEX_SHADER,s.vertexSource),n=is(e,e.FRAGMENT_SHADER,s.fragmentSource),t=function(e,t,i){const n=e.createProgram();if(!n)throw new Error("Could not create shader program.");return e.attachShader(n,t),e.attachShader(n,i),e.linkProgram(n),n}(e,i,n),r=s)}function u(){if(null!==r&&null!==t&&null!==i&&null!==n){if(null!==a&&e.getProgramParameter(t,h),!e.getShaderParameter(i,e.COMPILE_STATUS)){const t=e.getShaderInfoLog(i);throw new Error(`Vertex shader compilation failed: ${t??"<no log>"}`)}if(!e.getShaderParameter(n,e.COMPILE_STATUS)){const t=e.getShaderInfoLog(n);throw new Error(`Fragment shader compilation failed: ${t??"<no log>"}`)}if(!e.getProgramParameter(t,e.LINK_STATUS)){const i=e.getProgramInfoLog(t);throw new Error(`Shader program linking failed: ${i??"<no log>"}`)}!function(e,t,i){const n=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<n;r++){const n=e.getActiveAttrib(t,r);if(!n)continue;const s=new Qr(r,n.name,n.type);s.location=e.getAttribLocation(t,n.name),i.attributes.set(n.name,s)}}(e,t,r),function(e,t,i,n){const r=e.getProgramParameter(t,e.ACTIVE_UNIFORMS),s=new Uint8Array(r).map((e,t)=>t),o=e.getActiveUniforms(t,s,e.UNIFORM_BLOCK_INDEX),a=s.filter(e=>-1===o[e]);for(const r of a){const s=e.getActiveUniform(t,r);if(!s)continue;const o=Kr[s.type],a=jr[s.type],h=es[s.type];if(void 0===o||void 0===a||void 0===h)throw new Error(`Unsupported uniform type ${s.type} for uniform "${s.name}".`);const l=new o(a*s.size),u=new Zr(r,s.type,s.size,s.name,l),c=e.getUniformLocation(t,u.name);i.uniforms.set(u.name,u),c&&n.push({location:c,uploadFn:h,uniform:u})}}(e,t,r,s),function(e,t,i){const n=e.getProgramParameter(t,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<n;r++){const n=new Jr(e,t,r);i.push(n)}}(e,t,o),r=null}}function c(){for(const t of s)t.uniform.dirty&&(t.uploadFn(e,t.location,t.uniform.value),t.uniform.markClean());for(const e of o)e.upload()}return{initialize:l,bind:i=>{l(i),u(),e.useProgram(t),c()},unbind:()=>{e.useProgram(null)},sync:()=>{u(),e.useProgram(t),c()},destroy:a=>{e.deleteShader(i),e.deleteShader(n),e.deleteProgram(t);for(const e of o)e.destroy();i=null,n=null,t=null,r=null,s.length=0,o.length=0,a.disconnect()}}}function is(e,t,i){const n=e.createShader(t);if(!n)throw new Error("Could not create shader.");return e.shaderSource(n,i),e.compileShader(n),n}class ns{_attributes=[];_indexBuffer=null;_drawMode;_runtime=null;_version=0;constructor(t=e.RenderingPrimitives.Triangles){this._drawMode=t}get attributes(){return this._attributes}get indexBuffer(){return this._indexBuffer}get drawMode(){return this._drawMode}get version(){return this._version}connect(e){return this._runtime=e,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(t,i,n=e.ShaderPrimitives.Float,r=!1,s=0,o=0,a=!1,h=0){const{location:l,size:u}=i;return this._attributes.push({buffer:t,location:l,size:u,type:n,normalized:r,stride:s,start:o,integer:a,divisor:h}),this._version++,this}addIndex(e){return this._indexBuffer=e,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(e,t,i=this._drawMode){return this._runtime?.draw(this,e,t,i),this}drawInstanced(e,t,i,n=this._drawMode){return this._runtime?.drawInstanced?.(this,e,t,i,n),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}const rs=20;class ss extends Xr{_defaultShader=new Yr("#version 300 es\nprecision lowp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 6) in uint a_nodeIndex;\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms;\n\nout vec2 v_texcoord;\nout vec4 v_color;\nout vec4 v_tint;\n\nvoid main(void) {\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0); // a,b,c,d\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0); // tx,ty,0,0\n mat3 transform = mat3(\n m0.x, m0.z, 0.0,\n m0.y, m0.w, 0.0,\n m1.x, m1.y, 1.0\n );\n\n gl_Position = vec4((u_projection * transform * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n v_color = a_color;\n v_tint = texelFetch(u_transforms, ivec2(2, row), 0);\n}\n","#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\nin vec4 v_tint;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 base = texture(u_texture, v_texcoord) * v_color * v_tint;\n fragColor = vec4(base.rgb * base.a, base.a);\n}\n");_customShaders=new Map;_compatibilityCache=new Map;_textureUnitScratch=new Int32Array([0]);_transformUnitScratch=new Int32Array([8]);_slotScratches=Array.from({length:Math.max(9,9)},(e,t)=>new Int32Array([t]));_vertexCapacity=64;_indexCapacity=192;_nodeIndexCapacity=64;_vertexData=new ArrayBuffer(1280);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_indexData=new Uint16Array(192);_nodeIndexData=new Uint32Array(64);_pendingDraws=[];_pendingCount=0;_staticGeometryCache=new Map;_connection=null;_currentBlendMode=null;render(t){const i=this._connection;if(!i)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(0===t.vertexCount)return;const n=this.getBackend(),r=t.material,s=null===r?this._defaultShader:this._getOrCreateCustomShader(r,i.gl),o=null!==r&&t.blendMode===e.BlendModes.Normal?r.blendMode:t.blendMode,a=t.texture??pi.white,h=n.activeDrawCommand,l=null===r||this._isInstancingCompatible(s);let u=this._pendingDraws[this._pendingCount];void 0===u?(u={mesh:t,command:h,material:r,shader:s,blendMode:o,texture:a,supportsInstancing:l},this._pendingDraws.push(u)):(u.mesh=t,u.command=h,u.material=r,u.shader=s,u.blendMode=o,u.texture=a,u.supportsInstancing=l),this._pendingCount++}drawInstancedBatch(t,i,n){const r=this._connection;if(!r)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(n<=0||0===t.vertexCount)return;const s=t.geometry;if(null===s)throw new Error("drawInstancedBatch requires a mesh constructed from a geometry.");if(null!==t.material)throw new Error("RenderBatch custom materials are not supported yet (v1 renders with the default mesh material).");const o=this.getBackend(),a=this._defaultShader,h=t.blendMode,l=t.texture??pi.white,u=this._getOrCreateStaticGeometryEntry(s,t,r),c=this._getOrCreateStaticGeometryVao(u,a,r.gl,r.dynamicNodeIndexBuffer);this._setBlendMode(h,o),this._ensureNodeIndexCapacity(n);const d=i+n-1>>>0;for(let e=0;e<n;e++)this._nodeIndexData[e]=i+e>>>0;this._bindInstancedShaderState(a,l,null,o,d),o.bindVertexArrayObject(c),r.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,n)),c.drawInstanced(u.indexCount,0,n,e.RenderingPrimitives.Triangles),o.stats.batches++,o.stats.drawCalls++}flush(){const e=this.getBackendOrNull(),t=this._connection,i=this._pendingCount;if(null!==e&&null!==t&&0!==i){for(let n=0;n<i;n++){const r=this._pendingDraws[n];if(this._canBatchStatic(r)){let r=n+1;for(;r<i&&this._isSameBatch(this._pendingDraws[r-1],this._pendingDraws[r]);)r++;if(r-n>=2){this._drawStaticBatch(n,r,e,t),n=r-1;continue}}this._drawSingle(n,e,t)}this._pendingCount=0}else this._pendingCount=0}destroy(){this.disconnect(),this._defaultShader.destroy();for(const e of this._customShaders.values())e.destroy();this._customShaders.clear(),this._compatibilityCache.clear()}onConnect(t){const i=t.context;this._defaultShader.connect(ts(i)),this._defaultShader.sync();for(const e of this._customShaders.values())e.connect(ts(i)),e.sync();const n=new Map,r=new Hr(e.BufferTypes.ElementArrayBuffer,this._indexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),s=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),o=new Hr(e.BufferTypes.ArrayBuffer,this._nodeIndexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),a=i.createVertexArray();if(null===a)throw new Error("Could not create vertex array object.");const h=(new ns).addIndex(r).addAttribute(s,this._defaultShader.getAttribute("a_position"),i.FLOAT,!1,rs,0).addAttribute(s,this._defaultShader.getAttribute("a_texcoord"),i.FLOAT,!1,rs,8).addAttribute(s,this._defaultShader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,rs,16).addAttribute(o,this._defaultShader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(i,a));this._connection={gl:i,buffers:n,dynamicVao:h,dynamicVertexBuffer:s,dynamicIndexBuffer:r,dynamicNodeIndexBuffer:o}}onDisconnect(){const e=this._connection;if(e){this._defaultShader.disconnect();for(const e of this._customShaders.values())e.disconnect();for(const e of this._staticGeometryCache.values()){for(const t of e.vaos.values())t.destroy();e.vaos.clear(),e.indexBuffer.destroy(),e.vertexBuffer.destroy()}this._staticGeometryCache.clear(),e.dynamicNodeIndexBuffer.destroy(),e.dynamicIndexBuffer.destroy(),e.dynamicVertexBuffer.destroy(),e.dynamicVao.destroy(),this._connection=null,this._currentBlendMode=null,this._pendingDraws.length=0,this._pendingCount=0}}_drawSingle(e,t,i){const n=this._pendingDraws[e];this._canBatchStatic(n)?this._drawStaticBatch(e,e+1,t,i):n.supportsInstancing&&null===n.material?this._drawDynamicInstancedSingle(n,t,i):this._drawLegacyImmediate(n,t,i)}_drawDynamicInstancedSingle(t,i,n){const r=t.command?.nodeIndex??0;null===t.command&&i._writeTransformCommand(this._createSyntheticCommand(t.mesh,r)),this._setBlendMode(t.blendMode,i),this._bindInstancedShaderState(t.shader,t.texture,t.material,i,r),this._ensureVertexCapacity(t.mesh.vertexCount),this._ensureIndexCapacity(t.mesh.indexCount),this._ensureNodeIndexCapacity(1),this._packVertices(t.mesh,0),this._packIndices(t.mesh,0),this._nodeIndexData[0]=r>>>0,i.bindVertexArrayObject(n.dynamicVao),n.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*t.mesh.vertexCount)),n.dynamicIndexBuffer.upload(this._indexData.subarray(0,t.mesh.indexCount)),n.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,1)),n.dynamicVao.drawInstanced(t.mesh.indexCount,0,1,e.RenderingPrimitives.Triangles),i.stats.batches++,i.stats.drawCalls++}_drawStaticBatch(t,i,n,r){const s=this._pendingDraws[t],o=s.mesh.geometry,a=i-t,h=this._getOrCreateStaticGeometryEntry(o,s.mesh,r),l=this._getOrCreateStaticGeometryVao(h,s.shader,r.gl,r.dynamicNodeIndexBuffer);this._setBlendMode(s.blendMode,n);let u=0;this._ensureNodeIndexCapacity(a);for(let e=0;e<a;e++){const i=this._pendingDraws[t+e].command.nodeIndex>>>0;this._nodeIndexData[e]=i,i>u&&(u=i)}this._bindInstancedShaderState(s.shader,s.texture,s.material,n,u),n.bindVertexArrayObject(l),r.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,a)),l.drawInstanced(h.indexCount,0,a,e.RenderingPrimitives.Triangles),n.stats.batches++,n.stats.drawCalls++}_drawLegacyImmediate(t,i,n){const r=t.mesh,s=t.shader;this._setBlendMode(t.blendMode,i),s.uniforms.has("u_projection")&&s.getUniform("u_projection").setValue(i.view.getTransform().toArray(!1)),s.uniforms.has("u_translation")&&s.getUniform("u_translation").setValue(r.getGlobalTransform().toArray(!1)),s.uniforms.has("u_tint")&&s.getUniform("u_tint").setValue(r.tint.toArray(!1)),s.uniforms.has("u_texture")&&(s.getUniform("u_texture").setValue(this._textureUnitScratch),i.bindTexture(t.texture,0)),null!==t.material&&this._bindCustomUniforms(s,t.material,i),this._ensureVertexCapacity(r.vertexCount),this._ensureIndexCapacity(r.indexCount),this._packVertices(r,0),this._packIndices(r,0),s.sync(),i.bindVertexArrayObject(n.dynamicVao),n.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*r.vertexCount)),n.dynamicIndexBuffer.upload(this._indexData.subarray(0,r.indexCount)),n.dynamicVao.draw(r.indexCount,0,e.RenderingPrimitives.Triangles),i.stats.batches++,i.stats.drawCalls++}_bindInstancedShaderState(e,t,i,n,r){e.uniforms.has("u_projection")&&e.getUniform("u_projection").setValue(n.view.getTransform().toArray(!1)),e.uniforms.has("u_transforms")&&(n.bindTransformBufferTexture(8,r+1),e.getUniform("u_transforms").setValue(this._transformUnitScratch)),e.uniforms.has("u_texture")&&(e.getUniform("u_texture").setValue(this._textureUnitScratch),n.bindTexture(t,0)),null!==i&&this._bindCustomUniforms(e,i,n),e.sync()}_canBatchStatic(e){if(!e.supportsInstancing)return!1;if(void 0===e.command?.groupIndex)return!1;const t=e.mesh.geometry;return"static"===t?.usage}_isSameBatch(e,t){return!(!this._canBatchStatic(e)||!this._canBatchStatic(t))&&(e.command.groupIndex===t.command.groupIndex&&e.mesh.geometry===t.mesh.geometry&&e.shader===t.shader&&e.material===t.material&&e.blendMode===t.blendMode&&e.texture===t.texture&&e.command.material.pipelineKey===t.command.material.pipelineKey&&e.command.material.bindKey===t.command.material.bindKey)}_isInstancingCompatible(e){const t=this._compatibilityCache.get(e);if(void 0!==t)return t;const i=e.attributes.has("a_nodeIndex")&&e.uniforms.has("u_transforms")&&!e.uniforms.has("u_translation")&&!e.uniforms.has("u_tint");return this._compatibilityCache.set(e,i),i}_getOrCreateStaticGeometryEntry(t,i,n){const r=this._staticGeometryCache.get(t);if(void 0!==r)return r;const s=i.vertexCount,o=i.indexCount,a=new ArrayBuffer(s*rs),h=new Float32Array(a),l=new Uint32Array(a);this._packVertices(i,0,h,l);const u=new Uint16Array(o);this._packIndices(i,0,u);const c=this.getBackend().accountant,d=new Hr(e.BufferTypes.ArrayBuffer,h,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(n.gl,n.buffers),c),_=new Hr(e.BufferTypes.ElementArrayBuffer,u,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(n.gl,n.buffers),c);d.upload(h),_.upload(u);const f=()=>{const e=this._staticGeometryCache.get(t);if(void 0!==e){for(const t of e.vaos.values())t.destroy();e.vaos.clear(),e.indexBuffer.destroy(),e.vertexBuffer.destroy(),this._staticGeometryCache.delete(t)}};t._onDispose(f);const p={geometry:t,vertexBuffer:d,indexBuffer:_,vaos:new Map,disposeListener:f,indexCount:o};return this._staticGeometryCache.set(t,p),p}_getOrCreateStaticGeometryVao(e,t,i,n){const r=e.vaos.get(t);if(void 0!==r)return r;const s=i.createVertexArray();if(null===s)throw new Error("Could not create vertex array object.");const o=t.getAttribute("a_nodeIndex"),a=(new ns).addIndex(e.indexBuffer).addAttribute(e.vertexBuffer,t.getAttribute("a_position"),i.FLOAT,!1,rs,0).addAttribute(e.vertexBuffer,t.getAttribute("a_texcoord"),i.FLOAT,!1,rs,8).addAttribute(e.vertexBuffer,t.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,rs,16).addAttribute(n,o,i.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(i,s));return e.vaos.set(t,a),a}_setBlendMode(e,t){this._currentBlendMode!==e&&(this._currentBlendMode=e,t.setBlendMode(e))}_packVertices(e,t,i=this._float32View,n=this._uint32View){const r=e.vertices,s=e.uvs,o=e.colors,a=e.vertexCount;for(let e=0;e<a;e++){const a=5*(t+e),h=2*e;i[a]=r[h],i[a+1]=r[h+1],null!==s?(i[a+2]=s[h],i[a+3]=s[h+1]):(i[a+2]=0,i[a+3]=0),n[a+4]=null!==o?o[e]:4294967295}}_packIndices(e,t,i=this._indexData){const n=e.indexCount;if(null===e.indices)for(let e=0;e<n;e++)i[t+e]=e;else i.set(e.indices,t)}_ensureVertexCapacity(e){if(!(e<=this._vertexCapacity)){for(;this._vertexCapacity<e;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*rs),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(e){if(!(e<=this._indexCapacity)){for(;this._indexCapacity<e;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeIndexCapacity(e){if(!(e<=this._nodeIndexCapacity)){for(;this._nodeIndexCapacity<e;)this._nodeIndexCapacity*=2;this._nodeIndexData=new Uint32Array(this._nodeIndexCapacity)}}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:(n,r)=>{const s=t.get(n),o=n.data;e.bindBuffer(n.type,i),s&&s.dataByteLength>=o.byteLength?(e.bufferSubData(n.type,r,o),s.dataByteLength=o.byteLength):(e.bufferData(n.type,o,n.usage),t.set(n,{handle:i,dataByteLength:o.byteLength}))},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),i.integer?e.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location),e.vertexAttribDivisor(i.location,i.divisor);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{t.indexBuffer?e.drawElementsInstanced(s,i,e.UNSIGNED_SHORT,n,r):e.drawArraysInstanced(s,n,i,r)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}_getOrCreateCustomShader(e,t){const i=this._customShaders.get(e);if(void 0!==i)return i;const n=e.shader.glsl;if(null===n)throw new Error("Mesh material shader has no `glsl` source; cannot render through the WebGL2 backend.");const r=new Yr(n.vertex,n.fragment);return r.connect(ts(t)),r.sync(),this._customShaders.set(e,r),e._onDispose(()=>{const t=this._customShaders.get(e);void 0!==t&&(t.destroy(),this._customShaders.delete(e))}),r}_bindCustomUniforms(e,t,i){let n=1;const r=t.uniforms;for(const t in r){if(!e.uniforms.has(t))continue;const s=r[t],o=e.getUniform(t);if(s instanceof pi||s instanceof _i){if(n>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(s,n),o.setValue(this._slotScratches[n]),n++}else o.setValue(this._marshalUniformValue(s))}const s=t.textures;for(const t in s)if(e.uniforms.has(t)){if(n>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(s[t],n),e.getUniform(t).setValue(this._slotScratches[n]),n++}}_marshalUniformValue(e){return e instanceof Float32Array||e instanceof Int32Array?e:"number"==typeof e?new Float32Array([e]):new Float32Array(e)}_createSyntheticCommand(e,t){return{kind:Yt.Draw,drawable:e,nodeIndex:t,seq:0,zIndex:e.zIndex,material:{rendererId:0,blendMode:e.blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},minX:0,minY:0,maxX:0,maxY:0,groupIndex:0}}}const os=32,as=os/Uint32Array.BYTES_PER_ELEMENT;class hs extends Xr{_shader;_batchSize;_instanceData;_instanceFloat32;_instanceUint32;_transformUnitScratch=new Int32Array([1]);_quadIndex=0;_maxNodeIndex=0;_currentBlendMode=null;_currentTexture=null;_currentView=null;_currentViewId=-1;_instanceBuffer=null;_vao=null;_connection=null;constructor(e){super(),this._batchSize=e,this._shader=new Yr("#version 300 es\nprecision lowp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). One entry per nine-slice quad.\n// gl_VertexID 0..3 selects which corner of the quad this invocation computes.\nlayout(location = 0) in vec4 a_quadBounds; // x0, y0, x1, y1 (local space)\nlayout(location = 1) in vec4 a_uvBounds; // u0, v0, u1, v1 (normalised, flipY pre-applied)\nlayout(location = 2) in vec4 a_color; // RGBA tint\nlayout(location = 3) in uint a_nodeIndex; // row into the shared transform buffer\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms; // shared per-frame transform buffer (3 texels/row)\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n // gl_VertexID 0..3 -> corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n float localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\n float localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0); // a, b, c, d\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0); // tx, ty, 0, 0\n\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n gl_Position = vec4((u_projection * vec3(worldX, worldY, 1.0)).xy, 0.0, 1.0);\n\n float u = (cornerX == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cornerY == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}","#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 sampleColor = texture(u_texture, v_texcoord);\n fragColor = sampleColor * v_color;\n}"),this._instanceData=new ArrayBuffer(e*os),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(e){const t=this.getBackend();let i=e.quads;if("geometry"===e.pixelSnapMode){const n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}if(0===i.length)return;const n=e.texture,r=e.blendMode,s=e.tint.toRgba(),o=t.activeDrawCommand,a=null!==o?o.nodeIndex:t._pushTransform(e),h=null!==this._currentTexture&&n!==this._currentTexture,l=r!==this._currentBlendMode;this._quadIndex>0&&(l||h||this._quadIndex+i.length>this._batchSize)&&this.flush(),null!==this._currentBlendMode&&this._currentBlendMode===r||(this._currentBlendMode=r,t.setBlendMode(r)),this._currentTexture!==n&&(this._currentTexture=n,t.bindTexture(n,0));let u=0;for(;u<i.length;){const e=Math.min(u+this._batchSize,i.length);this._writeQuadChunk(i,u,e,n,s,a),u=e,u<i.length&&(this.flush(),this._currentBlendMode=r,t.setBlendMode(r),this._currentTexture=n,t.bindTexture(n,0))}}_writeQuadChunk(e,t,i,n,r,s){const o=this._instanceFloat32,a=this._instanceUint32,h=n.flipY;for(let n=t;n<i;n++){const t=e[n],i=this._quadIndex*as;o[i+0]=t.x0,o[i+1]=t.y0,o[i+2]=t.x1,o[i+3]=t.y1;const l=65535*t.u0&65535,u=65535*t.u1&65535,c=65535*t.v0&65535,d=65535*t.v1&65535,_=h?d:c,f=h?c:d;a[i+4]=l|_<<16,a[i+5]=u|f<<16,a[i+6]=r,a[i+7]=s>>>0,this._quadIndex++,s>this._maxNodeIndex&&(this._maxNodeIndex=s)}}flush(){const t=this.getBackendOrNull(),i=this._instanceBuffer,n=this._vao;if(0===this._quadIndex||null===t||null===i||null===n)return this._quadIndex=0,void(this._maxNodeIndex=0);const r=t.view;this._currentView===r&&this._currentViewId===r.updateId||(this._currentView=r,this._currentViewId=r.updateId,this._shader.getUniform("u_projection").setValue(r.getTransform().toArray(!1))),null!==this._currentTexture&&this._shader.getUniform("u_texture").setValue(new Int32Array([0])),t.bindTransformBufferTexture(1,this._maxNodeIndex+1),this._shader.getUniform("u_transforms").setValue(this._transformUnitScratch),this._shader.sync(),t.bindVertexArrayObject(n),i.upload(this._instanceFloat32.subarray(0,this._quadIndex*as)),n.drawInstanced(4,0,this._quadIndex,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._quadIndex=0,this._maxNodeIndex=0}onConnect(t){const i=t.context;this._shader.connect(ts(i)),this._connection=this._createConnection(i),this._instanceBuffer=new Hr(e.BufferTypes.ArrayBuffer,this._instanceData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_quadBounds"),i.FLOAT,!1,os,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),i.UNSIGNED_SHORT,!0,os,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,os,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,os,28,!0,1).connect(this._createVaoRuntime(this._connection))}onDisconnect(){this._shader.disconnect(),this._instanceBuffer?.destroy(),this._instanceBuffer=null,this._vao?.destroy(),this._vao=null,this._connection=null,this._currentBlendMode=null,this._currentTexture=null,this._currentView=null,this._currentViewId=-1,this._quadIndex=0,this._maxNodeIndex=0}destroy(){this.disconnect(),this._shader.destroy()}_createConnection(e){const t=e.createVertexArray();if(null===t)throw new Error("WebGl2NineSliceSpriteRenderer: could not create vertex array object.");return{gl:e,buffers:new Map,vaoHandle:t}}_createBufferRuntime(e){const t=e.gl.createBuffer();if(null===t)throw new Error("WebGl2NineSliceSpriteRenderer: could not create render buffer.");return{bind:i=>{e.gl.bindBuffer(i.type,t)},upload:(i,n)=>{const r=e.gl,s=i.data,o=e.buffers.get(i);r.bindBuffer(i.type,t),o&&o.dataByteLength>=s.byteLength?(r.bufferSubData(i.type,n,s),o.dataByteLength=s.byteLength):(r.bufferData(i.type,s,i.usage),e.buffers.set(i,{handle:t,dataByteLength:s.byteLength}))},destroy:i=>{e.gl.deleteBuffer(t),e.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(e){let t=-1;return{bind:i=>{const n=e.gl;if(n.bindVertexArray(e.vaoHandle),t!==i.version){let e=null;for(const t of i.attributes)e!==t.buffer&&(t.buffer.bind(),e=t.buffer),t.integer?n.vertexAttribIPointer(t.location,t.size,t.type,t.stride,t.start):n.vertexAttribPointer(t.location,t.size,t.type,t.normalized,t.stride,t.start),n.enableVertexAttribArray(t.location),n.vertexAttribDivisor(t.location,t.divisor);t=i.version}},unbind:()=>{e.gl.bindVertexArray(null)},draw:(t,i,n,r)=>{e.gl.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{e.gl.drawArraysInstanced(s,n,i,r)},destroy:t=>{e.gl.deleteVertexArray(e.vaoHandle),t.disconnect()}}}}const ls="#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n fragColor = texture(u_texture, v_texcoord) * v_color;\n}",us=40,cs=us/Uint32Array.BYTES_PER_ELEMENT,ds=32,_s=ds/Uint32Array.BYTES_PER_ELEMENT;function fs(t){return"repeat"===t?e.WrapModes.Repeat:"mirror-repeat"===t?e.WrapModes.MirroredRepeat:e.WrapModes.ClampToEdge}class ps extends Xr{_shaderPathShader;_geoPathShader;_batchSize;_shaderData;_shaderF32;_shaderU32;_shaderBuf=null;_shaderVao=null;_shaderQuadCount=0;_geoData;_geoF32;_geoU32;_geoBuf=null;_geoVao=null;_geoQuadCount=0;_samplers=new Map;_maxNodeIndex=0;_currentTexture=null;_currentBlendMode=null;_currentModeX=null;_currentModeY=null;_currentPath=null;_connection=null;_transformUnitScratch=new Int32Array([1]);_snapBounds=new et;_currentView=null;_currentViewId=-1;constructor(e){super(),this._batchSize=e,this._shaderPathShader=new Yr("#version 300 es\nprecision mediump float;\nprecision highp int;\n\nlayout(location = 0) in vec4 a_quadBounds; // x0,y0,x1,y1 (local space)\nlayout(location = 1) in vec4 a_uvParams; // tilingX, tilingY, offsetU, offsetV\nlayout(location = 2) in vec4 a_color; // RGBA tint (normalised)\nlayout(location = 3) in uint a_nodeIndex; // transform row\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms;\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n int vid = gl_VertexID;\n int cx = vid & 1;\n int cy = (vid >> 1) & 1;\n\n float lx = (cx == 0) ? a_quadBounds.x : a_quadBounds.z;\n float ly = (cy == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n float destW = a_quadBounds.z - a_quadBounds.x;\n float destH = a_quadBounds.w - a_quadBounds.y;\n\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0);\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0);\n\n float wx = m0.x * lx + m0.y * ly + m1.x;\n float wy = m0.z * lx + m0.w * ly + m1.y;\n gl_Position = vec4((u_projection * vec3(wx, wy, 1.0)).xy, 0.0, 1.0);\n\n float u = (destW > 0.0)\n ? ((lx - a_quadBounds.x) / destW) * a_uvParams.x + a_uvParams.z\n : a_uvParams.z;\n float v = (destH > 0.0)\n ? ((ly - a_quadBounds.y) / destH) * a_uvParams.y + a_uvParams.w\n : a_uvParams.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}",ls),this._geoPathShader=new Yr("#version 300 es\nprecision lowp float;\nprecision highp int;\n\nlayout(location = 0) in vec4 a_quadBounds; // x0,y0,x1,y1 (local space)\nlayout(location = 1) in vec4 a_uvBounds; // u0,v0,u1,v1 (normalised, flipY pre-applied)\nlayout(location = 2) in vec4 a_color; // RGBA tint\nlayout(location = 3) in uint a_nodeIndex; // transform row\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms;\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n int vid = gl_VertexID;\n int cx = vid & 1;\n int cy = (vid >> 1) & 1;\n\n float lx = (cx == 0) ? a_quadBounds.x : a_quadBounds.z;\n float ly = (cy == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0);\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0);\n\n float wx = m0.x * lx + m0.y * ly + m1.x;\n float wy = m0.z * lx + m0.w * ly + m1.y;\n gl_Position = vec4((u_projection * vec3(wx, wy, 1.0)).xy, 0.0, 1.0);\n\n float u = (cx == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cy == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}",ls),this._shaderData=new ArrayBuffer(e*us),this._shaderF32=new Float32Array(this._shaderData),this._shaderU32=new Uint32Array(this._shaderData),this._geoData=new ArrayBuffer(e*ds),this._geoF32=new Float32Array(this._geoData),this._geoU32=new Uint32Array(this._geoData)}render(e){const t=e.resolvedStrategy,i=e.texture,n=e.blendMode,r=e.modeX,s=e.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const e=this._currentPath!==t,o=this._currentTexture!==i,a=this._currentBlendMode!==n,h="shader"===t&&(this._currentModeX!==r||this._currentModeY!==s);(e||o||a||h)&&this.flush()}const o=this.getBackend();this._currentTexture!==i&&(this._currentTexture=i,o.bindTexture(i,0)),this._currentBlendMode!==n&&(this._currentBlendMode=n,o.setBlendMode(n)),this._currentPath=t;const a=o.activeDrawCommand,h=null!==a?a.nodeIndex:o._pushTransform(e);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===t?(this._currentModeX=r,this._currentModeY=s,this._writeShaderInstance(e,h)):this._writeGeoQuads(e,h)}_writeShaderInstance(e,t){const i=e.texture,n=e.region.width,r=e.region.height;let s=e.width,o=e.height;const a=i instanceof pi&&i.flipY;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),i=t._getSnapPixelSize(),n=e.getRenderBounds(t.view,i.width,i.height,this._snapBounds);s=n.width,o=n.height}const h=gr(n,s,e.modeX,e.fitX),l=gr(r,o,e.modeY,e.fitY),u=e.offsetX/(n>0?n:1),c=e.offsetY/(r>0?r:1),d=a?-l:l,_=a?l+c:c;this._shaderQuadCount>=this._batchSize&&this.flush();const f=this._shaderQuadCount*cs,p=this._shaderF32,m=this._shaderU32;p[f+0]=0,p[f+1]=0,p[f+2]=s,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,m[f+8]=e.tint.toRgba(),m[f+9]=t>>>0,this._shaderQuadCount++}_writeGeoQuads(e,t){let i=e.quads;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}const n=e.texture instanceof pi&&e.texture.flipY,r=e.tint.toRgba();let s=0;for(;s<i.length;){const o=i.length-s,a=Math.min(o,this._batchSize-this._geoQuadCount);if(a<=0){this.flush();const i=this.getBackend();i.bindTexture(e.texture,0),i.setBlendMode(e.blendMode),this._currentTexture=e.texture,this._currentBlendMode=e.blendMode,this._currentPath="geometry",t>this._maxNodeIndex&&(this._maxNodeIndex=t);continue}const h=this._geoF32,l=this._geoU32;for(let e=0;e<a;e++){const o=i[s+e],a=(this._geoQuadCount+e)*_s;h[a+0]=o.x0,h[a+1]=o.y0,h[a+2]=o.x1,h[a+3]=o.y1;const u=65535*o.u0&65535,c=65535*o.u1&65535,d=65535*o.v0&65535,_=65535*o.v1&65535,f=n?_:d,p=n?d:_;l[a+4]=u|f<<16,l[a+5]=c|p<<16,l[a+6]=r,l[a+7]=t>>>0}this._geoQuadCount+=a,s+=a}}flush(){const e=this.getBackendOrNull();if(null===e)return void this._resetBatchState();const t=e.view;if(this._currentView!==t||this._currentViewId!==t.updateId){this._currentView=t,this._currentViewId=t.updateId;const e=t.getTransform().toArray(!1);this._shaderPathShader.getUniform("u_projection").setValue(e),this._geoPathShader.getUniform("u_projection").setValue(e)}this._shaderQuadCount>0&&this._flushShaderBatch(e),this._geoQuadCount>0&&this._flushGeoBatch(e),this._resetBatchState()}_flushShaderBatch(t){const i=this._connection,n=this._shaderBuf,r=this._shaderVao;if(!i||!n||!r||0===this._shaderQuadCount)return;const s=i.gl,o=this._currentTexture,a=o instanceof pi?o.scaleMode:e.ScaleModes.Linear,h=fs(this._currentModeX??"repeat"),l=fs(this._currentModeY??"repeat"),u=this._getOrCreateSampler(s,h,l,a);s.bindSampler(0,u),t.bindTransformBufferTexture(1,this._maxNodeIndex+1),this._shaderPathShader.getUniform("u_texture").setValue(new Int32Array([0])),this._shaderPathShader.getUniform("u_transforms").setValue(this._transformUnitScratch),this._shaderPathShader.sync(),t.bindVertexArrayObject(r),n.upload(this._shaderF32.subarray(0,this._shaderQuadCount*cs)),r.drawInstanced(4,0,this._shaderQuadCount,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,s.bindSampler(0,null),this._shaderQuadCount=0}_flushGeoBatch(t){const i=this._connection,n=this._geoBuf,r=this._geoVao;i&&n&&r&&0!==this._geoQuadCount&&(t.bindTransformBufferTexture(1,this._maxNodeIndex+1),this._geoPathShader.getUniform("u_texture").setValue(new Int32Array([0])),this._geoPathShader.getUniform("u_transforms").setValue(this._transformUnitScratch),this._geoPathShader.sync(),t.bindVertexArrayObject(r),n.upload(this._geoF32.subarray(0,this._geoQuadCount*_s)),r.drawInstanced(4,0,this._geoQuadCount,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._geoQuadCount=0)}_resetBatchState(){this._shaderQuadCount=0,this._geoQuadCount=0,this._maxNodeIndex=0,this._currentTexture=null,this._currentBlendMode=null,this._currentModeX=null,this._currentModeY=null,this._currentPath=null}_getOrCreateSampler(e,t,i,n){const r=`${t}:${i}:${n}`,s=this._samplers.get(r);if(void 0!==s)return s;const o=e.createSampler();if(null===o)throw new Error("WebGl2RepeatingSpriteRenderer: could not create sampler.");return e.samplerParameteri(o,e.TEXTURE_WRAP_S,t),e.samplerParameteri(o,e.TEXTURE_WRAP_T,i),e.samplerParameteri(o,e.TEXTURE_MAG_FILTER,n),e.samplerParameteri(o,e.TEXTURE_MIN_FILTER,n),this._samplers.set(r,o),o}onConnect(t){const i=t.context;this._shaderPathShader.connect(ts(i)),this._geoPathShader.connect(ts(i)),this._shaderPathShader.sync(),this._geoPathShader.sync();const n=this._createConnection(i);this._connection=n,this._shaderBuf=new Hr(e.BufferTypes.ArrayBuffer,this._shaderData,e.BufferUsage.DynamicDraw).connect(this._createBufRuntime(n,"shader"),t.accountant),this._shaderVao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_quadBounds"),i.FLOAT,!1,us,0,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_uvParams"),i.FLOAT,!1,us,16,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,us,32,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,us,36,!0,1).connect(this._createVaoRuntime(n,"shader")),this._geoBuf=new Hr(e.BufferTypes.ArrayBuffer,this._geoData,e.BufferUsage.DynamicDraw).connect(this._createBufRuntime(n,"geo"),t.accountant),this._geoVao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_quadBounds"),i.FLOAT,!1,ds,0,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_uvBounds"),i.UNSIGNED_SHORT,!0,ds,16,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,ds,24,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,ds,28,!0,1).connect(this._createVaoRuntime(n,"geo"))}onDisconnect(){const e=this._connection?.gl;if(void 0!==e)for(const t of this._samplers.values())e.deleteSampler(t);this._samplers.clear(),this._shaderPathShader.disconnect(),this._geoPathShader.disconnect(),this._shaderBuf?.destroy(),this._shaderBuf=null,this._shaderVao?.destroy(),this._shaderVao=null,this._geoBuf?.destroy(),this._geoBuf=null,this._geoVao?.destroy(),this._geoVao=null,this._connection=null,this._currentView=null,this._currentViewId=-1,this._resetBatchState()}destroy(){this.disconnect(),this._shaderPathShader.destroy(),this._geoPathShader.destroy()}_createConnection(e){const t=e.createVertexArray(),i=e.createVertexArray();if(null===t||null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create vertex array object.");return{gl:e,buffers:new Map,shaderVaoHandle:t,geoVaoHandle:i}}_createBufRuntime(e,t){const i=e.gl.createBuffer();if(null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create render buffer.");return{bind:t=>{e.gl.bindBuffer(t.type,i)},upload:(t,n)=>{const r=e.gl,s=t.data,o=e.buffers.get(t);r.bindBuffer(t.type,i),o&&o.dataByteLength>=s.byteLength?(r.bufferSubData(t.type,n,s),o.dataByteLength=s.byteLength):(r.bufferData(t.type,s,t.usage),e.buffers.set(t,{handle:i,dataByteLength:s.byteLength}))},destroy:t=>{e.gl.deleteBuffer(i),e.buffers.delete(t),t.disconnect()}}}_createVaoRuntime(e,t){const i="shader"===t?e.shaderVaoHandle:e.geoVaoHandle;let n=-1;return{bind:t=>{const r=e.gl;if(r.bindVertexArray(i),n!==t.version){let e=null;for(const i of t.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),i.integer?r.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):r.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),r.enableVertexAttribArray(i.location),r.vertexAttribDivisor(i.location,i.divisor);n=t.version}},unbind:()=>{e.gl.bindVertexArray(null)},draw:(t,i,n,r)=>{e.gl.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{e.gl.drawArraysInstanced(s,n,i,r)},destroy:t=>{e.gl.deleteVertexArray(i),t.disconnect()}}}}const ms=36,gs=ms/Uint32Array.BYTES_PER_ELEMENT;class ys extends Xr{_shader;_batchSize;_instanceData;_instanceFloat32;_instanceUint32;_activeTextures=new Array(8).fill(null);_textureSlots=new Map;_slotCount=0;_customShaders=new Map;_slotScratches=Array.from({length:8},(e,t)=>new Int32Array([t]));_transformUnitScratch=new Int32Array([8]);_currentMaterial=null;_currentBaseTexture=null;_snapBounds=new et;_activeBounds=null;_instanceCount=0;_maxNodeIndex=0;_currentBlendMode=null;_currentView=null;_currentViewId=-1;_instanceBuffer=null;_vao=null;_connection=null;constructor(e){super(),this._batchSize=e,this._shader=new Yr("#version 300 es\nprecision lowp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). Each Sprite contributes one entry\n// to the per-instance buffer; gl_VertexID 0..3 selects which corner of the\n// quad this invocation is computing.\nlayout(location = 0) in vec4 a_localBounds; // left, top, right, bottom (local space)\nlayout(location = 3) in vec4 a_uvBounds; // uMin, vMin, uMax, vMax (normalised, already flipY-swapped)\nlayout(location = 4) in vec4 a_color; // RGBA tint\nlayout(location = 5) in uint a_textureSlot;\nlayout(location = 6) in uint a_nodeIndex; // row into the shared transform buffer\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms; // shared per-frame transform buffer (3 texels/row)\n\nout vec2 v_texcoord;\nout vec4 v_color;\nflat out uint v_textureSlot;\n\nvoid main(void) {\n // gl_VertexID 0..3 → corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n // Local-space corner: pick from the bounds rectangle.\n float localX = (cornerX == 0) ? a_localBounds.x : a_localBounds.z;\n float localY = (cornerY == 0) ? a_localBounds.y : a_localBounds.w;\n\n // Fetch the world transform for this instance from the shared buffer,\n // keyed by a_nodeIndex. Row layout: texel 0 = (a, b, c, d),\n // texel 1 = (tx, ty, 0, 0). (texel 2 carries tint, unused here — the\n // sprite keeps its own per-instance a_color.)\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0); // a, b, c, d\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0); // tx, ty, 0, 0\n\n // world = M * (localX, localY, 1)\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n gl_Position = vec4((u_projection * vec3(worldX, worldY, 1.0)).xy, 0.0, 1.0);\n\n // UV: pick from the bounds rectangle. The CPU pre-swaps Y bounds when\n // the texture is flipY, so the shader doesn't have to know.\n float u = (cornerX == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cornerY == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n v_textureSlot = a_textureSlot;\n}\n","#version 300 es\nprecision lowp float;\nprecision lowp int;\n\n// Multi-texture sprite batching: up to 8 textures bound per draw call,\n// each fragment selects its source via a flat-interpolated slot index.\n//\n// GLSL ES 3.0 forbids non-constant array-of-sampler indexing unless the\n// expression is dynamically uniform — which a per-vertex slot is not\n// once different triangles in the same batch carry different slots. The\n// if/else chain below dispatches statically and dodges that constraint.\n\nuniform sampler2D u_texture0;\nuniform sampler2D u_texture1;\nuniform sampler2D u_texture2;\nuniform sampler2D u_texture3;\nuniform sampler2D u_texture4;\nuniform sampler2D u_texture5;\nuniform sampler2D u_texture6;\nuniform sampler2D u_texture7;\n\nin vec2 v_texcoord;\nin vec4 v_color;\nflat in uint v_textureSlot;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 sampleColor;\n\n if (v_textureSlot == 0u) {\n sampleColor = texture(u_texture0, v_texcoord);\n } else if (v_textureSlot == 1u) {\n sampleColor = texture(u_texture1, v_texcoord);\n } else if (v_textureSlot == 2u) {\n sampleColor = texture(u_texture2, v_texcoord);\n } else if (v_textureSlot == 3u) {\n sampleColor = texture(u_texture3, v_texcoord);\n } else if (v_textureSlot == 4u) {\n sampleColor = texture(u_texture4, v_texcoord);\n } else if (v_textureSlot == 5u) {\n sampleColor = texture(u_texture5, v_texcoord);\n } else if (v_textureSlot == 6u) {\n sampleColor = texture(u_texture6, v_texcoord);\n } else {\n sampleColor = texture(u_texture7, v_texcoord);\n }\n\n fragColor = sampleColor * v_color;\n}\n"),this._instanceData=new ArrayBuffer(e*ms),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(e){const t=e.texture;if(null===t)return this;const i=this.getBackend(),n=e.material,r=i.activeDrawCommand,s=null!==r?r.nodeIndex:i._pushTransform(e);return this._activeBounds=this._resolveBounds(e,i),null===n?this._renderDefault(e,t,i,s):this._renderCustom(e,t,n,i,s),this}_resolveBounds(e,t){if("geometry"!==e.pixelSnapMode)return e.getLocalBounds();const i=t._getSnapPixelSize();return e.getRenderBounds(t.view,i.width,i.height,this._snapBounds)}flush(){const t=this.getBackendOrNull(),i=this._instanceBuffer,n=this._vao,r=this._connection;if(0===this._instanceCount||null===t||null===i||null===n||null===r)return this._maxNodeIndex=0,void this._resetSlots();const s=this._currentMaterial,o=null===s?this._shader:this._getOrCreateCustomShader(s,r.gl);if(null===s){const e=t.view;this._currentView===e&&this._currentViewId===e.updateId||(this._currentView=e,this._currentViewId=e.updateId,this._shader.getUniform("u_projection").setValue(e.getTransform().toArray(!1)))}else{o.uniforms.has("u_projection")&&o.getUniform("u_projection").setValue(t.view.getTransform().toArray(!1));const e=this._currentBaseTexture;null!==e&&o.uniforms.has("u_texture")&&(t.bindTexture(e,0),o.getUniform("u_texture").setValue(this._slotScratches[0])),this._bindCustomUniforms(o,s,t)}t.bindTransformBufferTexture(8,this._maxNodeIndex+1),o.uniforms.has("u_transforms")&&o.getUniform("u_transforms").setValue(this._transformUnitScratch),o.sync(),t.bindVertexArrayObject(n),i.upload(this._instanceFloat32.subarray(0,this._instanceCount*gs)),n.drawInstanced(4,0,this._instanceCount,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots()}onConnect(t){const i=t.context;this._shader.connect(ts(i)),this._connection=this._createConnection(i),this._instanceBuffer=new Hr(e.BufferTypes.ArrayBuffer,this._instanceData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_localBounds"),i.FLOAT,!1,ms,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),i.UNSIGNED_SHORT,!0,ms,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,ms,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_textureSlot"),i.UNSIGNED_INT,!1,ms,28,!0,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,ms,32,!0,1).connect(this._createVaoRuntime(this._connection));const n=new Int32Array(1);for(let e=0;e<8;e++)n[0]=e,this._shader.getUniform(`u_texture${e}`).setValue(n)}onDisconnect(){this._shader.disconnect();for(const e of this._customShaders.values())e.destroy();this._customShaders.clear(),this._currentMaterial=null,this._currentBaseTexture=null,this._instanceBuffer?.destroy(),this._instanceBuffer=null,this._vao?.destroy(),this._vao=null,this._connection=null,this._currentBlendMode=null,this._currentView=null,this._currentViewId=-1,this._instanceCount=0,this._maxNodeIndex=0}destroy(){this.disconnect(),this._shader.destroy()}_renderDefault(e,t,i,n){const r=e.blendMode,s=this._instanceCount>=this._batchSize,o=r!==this._currentBlendMode,a=!this._textureSlots.has(t)&&this._slotCount>=8,h=null!==this._currentMaterial&&this._instanceCount>0;(s||o||a||h)&&(this.flush(),o&&(this._currentBlendMode=r,i.setBlendMode(r))),this._currentMaterial=null;let l=this._textureSlots.get(t);void 0===l&&(l=this._slotCount++,this._textureSlots.set(t,l),this._activeTextures[l]=t,i.bindTexture(t,l)),this._packInstance(e,t,l,n),this._instanceCount++}_renderCustom(t,i,n,r,s){const o=t.blendMode===e.BlendModes.Normal?n.blendMode:t.blendMode,a=this._instanceCount>=this._batchSize,h=o!==this._currentBlendMode,l=n!==this._currentMaterial,u=i!==this._currentBaseTexture;this._instanceCount>0&&(a||h||l||u)&&this.flush(),h&&(this._currentBlendMode=o,r.setBlendMode(o)),this._currentMaterial=n,this._currentBaseTexture=i,this._packInstance(t,i,0,s),this._instanceCount++}_packInstance(e,t,i,n){const r=this._instanceCount*gs,s=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??e.getLocalBounds();s[r+0]=a.left,s[r+1]=a.top,s[r+2]=a.right,s[r+3]=a.bottom;const h=e.textureFrame,l=t.width,u=t.height,c=h.left/l*65535&65535,d=h.right/l*65535&65535,_=h.top/u*65535&65535,f=h.bottom/u*65535&65535,p=t.flipY?f:_,m=t.flipY?_:f;o[r+4]=c|p<<16,o[r+5]=d|m<<16,o[r+6]=e.tint.toRgba(),o[r+7]=i;const g=n>>>0;o[r+8]=g,g>this._maxNodeIndex&&(this._maxNodeIndex=g)}_getOrCreateCustomShader(e,t){const i=this._customShaders.get(e);if(void 0!==i)return i;const n=e.shader.glsl;if(null===n)throw new Error("SpriteMaterial shader has no `glsl` source; cannot render through the WebGL2 backend.");const r=new Yr("#version 300 es\nprecision highp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). Each Sprite contributes one entry\n// to the per-instance buffer; gl_VertexID 0..3 selects which corner of the\n// quad this invocation is computing.\nlayout(location = 0) in vec4 a_localBounds; // left, top, right, bottom (local space)\nlayout(location = 3) in vec4 a_uvBounds; // uMin, vMin, uMax, vMax (normalised, already flipY-swapped)\nlayout(location = 4) in vec4 a_color; // RGBA tint\nlayout(location = 5) in uint a_textureSlot;\nlayout(location = 6) in uint a_nodeIndex; // row into the shared transform buffer\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms; // shared per-frame transform buffer (3 texels/row)\n\nout vec2 v_texcoord;\nout vec4 v_color;\nflat out uint v_textureSlot;\n\nvoid main(void) {\n // gl_VertexID 0..3 → corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n float localX = (cornerX == 0) ? a_localBounds.x : a_localBounds.z;\n float localY = (cornerY == 0) ? a_localBounds.y : a_localBounds.w;\n\n // Fetch the per-instance world transform from the shared buffer (row =\n // a_nodeIndex): texel 0 = (a, b, c, d), texel 1 = (tx, ty, 0, 0).\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0);\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0);\n\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n gl_Position = vec4((u_projection * vec3(worldX, worldY, 1.0)).xy, 0.0, 1.0);\n\n float u = (cornerX == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cornerY == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n v_textureSlot = a_textureSlot;\n}\n",n.fragment);return r.connect(ts(t)),r.sync(),this._customShaders.set(e,r),e._onDispose(()=>{const t=this._customShaders.get(e);void 0!==t&&(t.destroy(),this._customShaders.delete(e))}),r}_bindCustomUniforms(e,t,i){let n=1;const r=t.uniforms;for(const t in r){if(!e.uniforms.has(t))continue;const s=r[t],o=e.getUniform(t);if(s instanceof pi||s instanceof _i){if(n>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(s,n),o.setValue(this._slotScratches[n]),n++}else o.setValue(this._marshalUniformValue(s))}const s=t.textures;for(const t in s)if(e.uniforms.has(t)){if(n>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(s[t],n),e.getUniform(t).setValue(this._slotScratches[n]),n++}}_marshalUniformValue(e){return e instanceof Float32Array||e instanceof Int32Array?e:"number"==typeof e?new Float32Array([e]):new Float32Array(e)}_resetSlots(){if(this._slotCount>0){for(let e=0;e<this._slotCount;e++)this._activeTextures[e]=null;this._textureSlots.clear(),this._slotCount=0}}_createConnection(e){const t=e.createVertexArray();if(null===t)throw new Error("WebGl2SpriteRenderer: could not create vertex array object.");return{gl:e,buffers:new Map,vaoHandle:t}}_createBufferRuntime(e){const t=e.gl.createBuffer();if(null===t)throw new Error("WebGl2SpriteRenderer: could not create render buffer.");return{bind:i=>{e.gl.bindBuffer(i.type,t)},upload:(i,n)=>{const r=e.gl,s=i.data,o=e.buffers.get(i);r.bindBuffer(i.type,t),o&&o.dataByteLength>=s.byteLength?(r.bufferSubData(i.type,n,s),o.dataByteLength=s.byteLength):(r.bufferData(i.type,s,i.usage),e.buffers.set(i,{handle:t,dataByteLength:s.byteLength}))},destroy:i=>{e.gl.deleteBuffer(t),e.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(e){let t=-1;return{bind:i=>{const n=e.gl;if(n.bindVertexArray(e.vaoHandle),t!==i.version){let e=null;for(const t of i.attributes)e!==t.buffer&&(t.buffer.bind(),e=t.buffer),t.integer?n.vertexAttribIPointer(t.location,t.size,t.type,t.stride,t.start):n.vertexAttribPointer(t.location,t.size,t.type,t.normalized,t.stride,t.start),n.enableVertexAttribArray(t.location),n.vertexAttribDivisor(t.location,t.divisor);t=i.version}},unbind:()=>{e.gl.bindVertexArray(null)},draw:(t,i,n,r)=>{e.gl.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{e.gl.drawArraysInstanced(s,n,i,r)},destroy:t=>{e.gl.deleteVertexArray(e.vaoHandle),t.disconnect()}}}}var ws="#version 300 es\nprecision highp float;\n\n// a_position arrives already in WORLD space: the renderer applies each node's\n// world transform on the CPU while building the vertex buffer. This deliberately\n// avoids a vertex-stage texelFetch of the per-node data texture — on ANGLE/D3D11\n// a vertex texture fetch of the RGBA32F data texture returns garbage (RGB read as\n// 0) whenever an RGBA8 atlas is also bound, which collapsed all text glyphs to a\n// point and made colour/MSDF bitmap text invisible. The fragment still reads the\n// per-node style from the data texture (a fragment texture fetch is unaffected).\nlayout(location = 0) in vec2 a_position; // world-space quad corner\nlayout(location = 1) in vec2 a_texcoord;\nlayout(location = 2) in float a_nodeIndex; // row into the per-node data texture (style lookup)\nlayout(location = 3) in vec2 a_gradUV; // normalised gradient UV (CPU-computed)\n\nuniform mat3 u_projection;\n\nflat out int v_nodeIndex;\n out vec2 v_texcoord;\n out vec2 v_gradUV;\n\nvoid main(void) {\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n v_nodeIndex = int(a_nodeIndex);\n v_gradUV = a_gradUV;\n}\n";const xs=28;class vs extends Xr{_consumesSharedTransform=!1;_sdfShader=new Yr(ws,"#version 300 es\nprecision mediump float;\n\nuniform sampler2D u_texture; // R8 SDF atlas\nuniform sampler2D u_nodeData; // RGBA32F per-node data (see WebGl2TextRenderer)\nuniform float u_pageSize; // atlas page size in px (for shadow UV conversion)\n\nflat in int v_nodeIndex;\n in vec2 v_texcoord;\n in vec2 v_gradUV;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n int ni = v_nodeIndex;\n\n // texel 2: fillColor\n // texel 3: outlineColor\n // texel 4: (outlineMin, shadowAlpha, softness, gradientEnabled)\n // outlineMin = 0.5 → disabled; outlineMin < 0.5 → enabled\n // texel 5: shadowColor\n // texel 6: (shadowOffsetX_px, shadowOffsetY_px, gradientVertical, unused)\n // texel 7: gradientTop\n // texel 8: gradientBottom\n vec4 tFill = texelFetch(u_nodeData, ivec2(2, ni), 0);\n vec4 tOutline = texelFetch(u_nodeData, ivec2(3, ni), 0);\n vec4 tParams = texelFetch(u_nodeData, ivec2(4, ni), 0);\n vec4 tShadow = texelFetch(u_nodeData, ivec2(5, ni), 0);\n vec4 tShadow2 = texelFetch(u_nodeData, ivec2(6, ni), 0);\n vec4 tGradTop = texelFetch(u_nodeData, ivec2(7, ni), 0);\n vec4 tGradBot = texelFetch(u_nodeData, ivec2(8, ni), 0);\n\n float outlineMin = tParams.x;\n float shadowAlpha = tParams.y;\n float soft = max(tParams.z, 0.001);\n float gradEnabled = tParams.w;\n vec2 shadowOffset = tShadow2.xy / u_pageSize;\n float gradVertical = tShadow2.z;\n\n float sd = texture(u_texture, v_texcoord).r;\n float fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n float outline = outlineMin < 0.5\n ? smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill)\n : 0.0;\n\n float shadowSd = texture(u_texture, v_texcoord - shadowOffset).r;\n float shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n vec4 fillColor;\n if (gradEnabled > 0.5) {\n float t = gradVertical > 0.5 ? v_gradUV.y : v_gradUV.x;\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n fragColor = fillColor * fill\n + tOutline * outline\n + tShadow * shadow;\n}\n");_msdfShader=new Yr(ws,"#version 300 es\nprecision mediump float;\n\nuniform sampler2D u_texture; // RGB MSDF atlas\nuniform sampler2D u_nodeData; // RGBA32F per-node data (see WebGl2TextRenderer)\nuniform float u_pageSize; // atlas page size in px (for shadow UV conversion)\n\nflat in int v_nodeIndex;\n in vec2 v_texcoord;\n in vec2 v_gradUV;\n\nlayout(location = 0) out vec4 fragColor;\n\nfloat median(float r, float g, float b) {\n return max(min(r, g), min(max(r, g), b));\n}\n\nvoid main(void) {\n int ni = v_nodeIndex;\n\n // Same node data layout as text-sdf.frag\n vec4 tFill = texelFetch(u_nodeData, ivec2(2, ni), 0);\n vec4 tOutline = texelFetch(u_nodeData, ivec2(3, ni), 0);\n vec4 tParams = texelFetch(u_nodeData, ivec2(4, ni), 0); // (outlineMin, shadowAlpha, softness, gradientEnabled)\n vec4 tShadow = texelFetch(u_nodeData, ivec2(5, ni), 0);\n vec4 tShadow2 = texelFetch(u_nodeData, ivec2(6, ni), 0); // (shadowOffX_px, shadowOffY_px, gradientVertical, 0)\n vec4 tGradTop = texelFetch(u_nodeData, ivec2(7, ni), 0);\n vec4 tGradBot = texelFetch(u_nodeData, ivec2(8, ni), 0);\n\n float outlineMin = tParams.x;\n float shadowAlpha = tParams.y;\n float soft = max(tParams.z, 0.001);\n float gradEnabled = tParams.w;\n vec2 shadowOffset = tShadow2.xy / u_pageSize;\n float gradVertical = tShadow2.z;\n\n vec3 msd = texture(u_texture, v_texcoord).rgb;\n float sd = median(msd.r, msd.g, msd.b);\n float fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n float outline = outlineMin < 0.5\n ? smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill)\n : 0.0;\n\n vec3 shadowMsd = texture(u_texture, v_texcoord - shadowOffset).rgb;\n float shadowSd = median(shadowMsd.r, shadowMsd.g, shadowMsd.b);\n float shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n vec4 fillColor;\n if (gradEnabled > 0.5) {\n float t = gradVertical > 0.5 ? v_gradUV.y : v_gradUV.x;\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n fragColor = fillColor * fill\n + tOutline * outline\n + tShadow * shadow;\n}\n");_colorShader=new Yr(ws,"#version 300 es\nprecision mediump float;\n\nuniform sampler2D u_texture; // RGBA colour-font / emoji atlas\nuniform sampler2D u_nodeData; // RGBA32F per-node data\n\nflat in int v_nodeIndex;\n in vec2 v_texcoord;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n // texel 2: fillColor (tint multiplier; (1,1,1,1) = no tint)\n vec4 tint = texelFetch(u_nodeData, ivec2(2, v_nodeIndex), 0);\n vec4 texel = texture(u_texture, v_texcoord);\n fragColor = texel * tint;\n}\n");_textureUnitScratch=new Int32Array([0]);_nodeDataUnitScratch=new Int32Array([1]);_floatScratch=new Float32Array(1);_vertexCapacity=256;_indexCapacity=384;_vertexData=new ArrayBuffer(7168);_float32View=new Float32Array(this._vertexData);_indexData=new Uint16Array(384);_nodeDataArray=new Float32Array(1280);_nodeCapacity=32;_nodeCount=0;_pendingQuads=[];_nodeIndexMap=new Map;_textureKeyMap=new Map;_textureKeyCounter=0;_connection=null;render(e){if(!this._connection)throw new Error("WebGl2TextRenderer is not connected to a backend.");e instanceof Wr?this._collectText(e):this._collectBitmapText(e)}flush(){const e=this._connection;e&&0!==this._pendingQuads.length?(this._uploadNodeData(e),this._drawBatches(e),this._resetFrameState()):this._resetFrameState()}destroy(){this.disconnect(),this._sdfShader.destroy(),this._msdfShader.destroy(),this._colorShader.destroy()}onConnect(t){const i=t.context,n=new Map;this._sdfShader.connect(ts(i)),this._msdfShader.connect(ts(i)),this._colorShader.connect(ts(i)),this._sdfShader.sync(),this._msdfShader.sync(),this._colorShader.sync();const r=new Hr(e.BufferTypes.ElementArrayBuffer,this._indexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),s=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),o=i.createVertexArray();if(null===o)throw new Error("WebGl2TextRenderer: could not create VAO.");const a=(new ns).addIndex(r).addAttribute(s,this._sdfShader.getAttribute("a_position"),i.FLOAT,!1,xs,0).addAttribute(s,this._sdfShader.getAttribute("a_texcoord"),i.FLOAT,!1,xs,8).addAttribute(s,this._sdfShader.getAttribute("a_nodeIndex"),i.FLOAT,!1,xs,16);this._sdfShader.attributes.has("a_gradUV")&&a.addAttribute(s,this._sdfShader.getAttribute("a_gradUV"),i.FLOAT,!1,xs,20),a.connect(this._createVaoRuntime(i,o));const h=this._createNodeDataTexture(i,32);this._connection={gl:i,buffers:n,vertexBuffer:s,indexBuffer:r,vao:a,nodeDataTexture:h,nodeDataCapacity:32}}onDisconnect(){const e=this._connection;e&&(this._sdfShader.disconnect(),this._msdfShader.disconnect(),this._colorShader.disconnect(),e.indexBuffer.destroy(),e.vertexBuffer.destroy(),e.vao.destroy(),e.gl.deleteTexture(e.nodeDataTexture),this._connection=null)}_collectText(e){e.syncDirty();const{pageQuads:t,atlas:i}=e;if(0===t.length||null===i)return;const n=this._assignNodeIndex(e),r=e.colorGlyphs?"color":"sdf",s=i.pages;for(const e of t){const t=s[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:n,shaderType:r,atlasTexture:t.texture})}}_collectBitmapText(e){const{pageQuads:t,textures:i,msdf:n}=e;if(0===t.length)return;const r=this._assignNodeIndex(e),s=n?"msdf":"color";for(const e of t){const t=i[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:r,shaderType:s,atlasTexture:t})}}_assignNodeIndex(e){const t=this._nodeIndexMap.get(e);if(void 0!==t)return t;const i=this._nodeCount++;return this._nodeIndexMap.set(e,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,e),i}_packNodeData(e,t){const i=this._nodeDataArray,n=40*e,r=t.style,s=t.getGlobalTransform().toArray(!1);i[n+0]=s[0],i[n+1]=s[1],i[n+2]=s[2],i[n+3]=s[6],i[n+4]=s[3],i[n+5]=s[4],i[n+6]=s[5],i[n+7]=s[7];const o=r.fillColor;i[n+8]=o.r/255,i[n+9]=o.g/255,i[n+10]=o.b/255,i[n+11]=o.a;const a=r.outlineColor;i[n+12]=a.r/255,i[n+13]=a.g/255,i[n+14]=a.b/255,i[n+15]=a.a;const h=r.outlineWidth>0?Math.max(0,.5-r.outlineWidth):.5;i[n+16]=h,i[n+17]=r.shadowAlpha,i[n+18]=Math.max(.03,.1*r.shadowBlur),i[n+19]=null!==r.gradientColors?1:0;const l=r.shadowColor;i[n+20]=l.r/255,i[n+21]=l.g/255,i[n+22]=l.b/255,i[n+23]=l.a,i[n+24]=r.shadowOffsetX,i[n+25]=r.shadowOffsetY,i[n+26]="vertical"===r.gradientAxis?1:0,i[n+27]=0;const u=r.gradientColors;null!==u?(i[n+28]=u[0].r/255,i[n+29]=u[0].g/255,i[n+30]=u[0].b/255,i[n+31]=u[0].a,i[n+32]=u[1].r/255,i[n+33]=u[1].g/255,i[n+34]=u[1].b/255,i[n+35]=u[1].a):(i[n+28]=i[n+29]=i[n+30]=i[n+31]=0,i[n+32]=i[n+33]=i[n+34]=i[n+35]=0);const c=t.textBounds;i[n+36]=0,i[n+37]=0,i[n+38]=c.width,i[n+39]=c.height}_uploadNodeData(e){const t=e.gl,i=this._nodeCount;if(i>e.nodeDataCapacity){let n=e.nodeDataCapacity;for(;n<i;)n*=2;t.deleteTexture(e.nodeDataTexture),e.nodeDataTexture=this._createNodeDataTexture(t,n),e.nodeDataCapacity=n}this.getBackend().setActiveTextureUnit(1),t.bindTexture(t.TEXTURE_2D,e.nodeDataTexture),t.texSubImage2D(t.TEXTURE_2D,0,0,0,10,i,t.RGBA,t.FLOAT,this._nodeDataArray.subarray(0,40*i))}_drawBatches(t){const i=this.getBackend(),n=i.view;for(const e of this._pendingQuads)this._textureKeyMap.has(e.atlasTexture)||this._textureKeyMap.set(e.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((e,t)=>{const i=e.shaderType.localeCompare(t.shaderType);return 0!==i?i:(this._textureKeyMap.get(e.atlasTexture)??0)-(this._textureKeyMap.get(t.atlasTexture)??0)});const r=this._pendingQuads;let s=0;for(;s<r.length;){const o=r[s],a=this._textureKeyMap.get(o.atlasTexture);let h=s+1;for(;h<r.length;){const e=r[h];if(e.shaderType!==o.shaderType||this._textureKeyMap.get(e.atlasTexture)!==a)break;h++}const l=this._shaderFor(o.shaderType);let u=0,c=0;for(let e=s;e<h;e++)u+=4*r[e].quads.quadCount,c+=r[e].quads.indices.length;this._ensureVertexCapacity(u),this._ensureIndexCapacity(c);let d=0,_=0,f=0;for(let e=s;e<h;e++){const{quads:t,nodeIndex:i}=r[e],n=4*t.quadCount,{vertices:s,uvs:o,indices:a}=t,h=40*i,l=this._nodeDataArray[h+0],u=this._nodeDataArray[h+1],c=this._nodeDataArray[h+3],p=this._nodeDataArray[h+4],m=this._nodeDataArray[h+5],g=this._nodeDataArray[h+7],y=this._nodeDataArray[h+36],w=this._nodeDataArray[h+37],x=this._nodeDataArray[h+38],v=this._nodeDataArray[h+39],b=x>0&&v>0;for(let e=0;e<n;e++){const t=7*(d+e),n=2*e,r=s[n],a=s[n+1];this._float32View[t+0]=l*r+p*a+c,this._float32View[t+1]=u*r+m*a+g,this._float32View[t+2]=o[n],this._float32View[t+3]=o[n+1],this._float32View[t+4]=i,this._float32View[t+5]=b?Math.min(1,Math.max(0,(r-y)/x)):0,this._float32View[t+6]=b?Math.min(1,Math.max(0,(a-w)/v)):0}for(let e=0;e<a.length;e++)this._indexData[_+e]=a[e]+f;d+=n,_+=a.length,f+=n}t.vertexBuffer.upload(this._float32View.subarray(0,7*u)),t.indexBuffer.upload(this._indexData.subarray(0,c)),l.sync(),i.bindVertexArrayObject(t.vao),i.bindTexture(o.atlasTexture,0),l.uniforms.has("u_projection")&&l.getUniform("u_projection").setValue(n.getTransform().toArray(!1)),l.uniforms.has("u_texture")&&l.getUniform("u_texture").setValue(this._textureUnitScratch),l.uniforms.has("u_nodeData")&&l.getUniform("u_nodeData").setValue(this._nodeDataUnitScratch),l.uniforms.has("u_pageSize")&&(this._floatScratch[0]=o.atlasTexture.width,l.getUniform("u_pageSize").setValue(this._floatScratch)),t.vao.draw(c,0,e.RenderingPrimitives.Triangles),i.stats.batches++,i.stats.drawCalls++,s=h}}_shaderFor(e){return"sdf"===e?this._sdfShader:"msdf"===e?this._msdfShader:this._colorShader}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}_ensureVertexCapacity(e){if(!(e<=this._vertexCapacity)){for(;this._vertexCapacity<e;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*xs),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(e){if(!(e<=this._indexCapacity)){for(;this._indexCapacity<e;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(e){if(e<=this._nodeCapacity)return;for(;this._nodeCapacity<e;)this._nodeCapacity*=2;const t=new Float32Array(40*this._nodeCapacity);t.set(this._nodeDataArray),this._nodeDataArray=t}_createNodeDataTexture(e,t){const i=e.createTexture();if(null===i)throw new Error("WebGl2TextRenderer: could not create node data texture.");return e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA32F,10,t,0,e.RGBA,e.FLOAT,null),e.bindTexture(e.TEXTURE_2D,null),i}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("WebGl2TextRenderer: could not create buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:(n,r)=>{const s=t.get(n),o=n.data;e.bindBuffer(n.type,i),s&&s.dataByteLength>=o.byteLength?(e.bufferSubData(n.type,r,o),s.dataByteLength=o.byteLength):(e.bufferData(n.type,o,n.usage),t.set(n,{handle:i,dataByteLength:o.byteLength}))},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}class bs{backendType=e.RenderBackendType.WebGpu;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==e.RenderBackendType.WebGpu)throw new Error(`${this.constructor.name} requires a WebGPU backend, but received backendType ${String(t.backendType)}.`);this._backend=t,this.onConnect(t)}}disconnect(){null!==this._backend&&(this.flush(),this.onDisconnect(),this._backend=null)}getBackend(){if(null===this._backend)throw new Error(`${this.constructor.name} is not connected to a backend.`);return this._backend}getBackendOrNull(){return this._backend}}function Ss(t){switch(t){case e.BlendModes.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case e.BlendModes.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case e.BlendModes.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case e.BlendModes.Screen:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}};default:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}}const Bs="depth24plus-stencil8",Cs=new Set(["a_position","position"]);class Ts{_matrix=new At;_matrixData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_positions=new Float32Array(64);_device=null;_shaderModule=null;_bindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_bindGroup=null;_vertexBuffer=null;_vertexBufferCapacity=0;_incrementPipelines=new Map;_decrementPipelines=new Map;_stencilTextures=new Map;connect(e){null===this._device&&(this._device=e,this._shaderModule=e.createShaderModule({code:"\nstruct Uniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> u: Uniforms;\n\n@vertex\nfn vertexMain(@location(0) position: vec2<f32>) -> @builtin(position) vec4<f32> {\n return u.matrix * vec4<f32>(position, 0.0, 1.0);\n}\n\n@fragment\nfn fragmentMain() -> @location(0) vec4<f32> {\n // Color writes are masked off (writeMask 0); only the stencil aspect is touched.\n return vec4<f32>(0.0);\n}\n"}),this._bindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._pipelineLayout=e.createPipelineLayout({bindGroupLayouts:[this._bindGroupLayout]}),this._uniformBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._bindGroup=e.createBindGroup({layout:this._bindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}))}disconnect(){if(null!==this._device){this._uniformBuffer?.destroy(),this._vertexBuffer?.destroy();for(const e of this._stencilTextures.values())e.texture.destroy();this._stencilTextures.clear(),this._incrementPipelines.clear(),this._decrementPipelines.clear(),this._uniformBuffer=null,this._vertexBuffer=null,this._bindGroup=null,this._pipelineLayout=null,this._bindGroupLayout=null,this._shaderModule=null,this._vertexBufferCapacity=0,this._device=null}}getAttachmentView(e,t,i){const n=this._device;if(null===n)throw new Error("WebGpuStencilClipper: not connected.");const r=Math.max(1,t),s=Math.max(1,i),o=this._stencilTextures.get(e);if(o?.width===r&&o.height===s)return o.view;o?.texture.destroy();const a=n.createTexture({size:{width:r,height:s},format:Bs,usage:GPUTextureUsage.RENDER_ATTACHMENT}),h={texture:a,view:a.createView(),width:r,height:s};return this._stencilTextures.set(e,h),h.view}releaseAttachment(e){const t=this._stencilTextures.get(e);void 0!==t&&(t.texture.destroy(),this._stencilTextures.delete(e))}draw(e,t,i,n,r,s){const o=this._device;if(null===o||null===this._bindGroup)throw new Error("WebGpuStencilClipper: not connected.");const a=this._extractPositions(n);0!==a&&(this._matrix.copy(r).combine(s.getTransform()),this._packMatrix(this._matrix),o.queue.writeBuffer(this._uniformBuffer,0,this._matrixData.buffer,this._matrixData.byteOffset,this._matrixData.byteLength),this._ensureVertexCapacity(a),o.queue.writeBuffer(this._vertexBuffer,0,this._positions.buffer,this._positions.byteOffset,2*a*Float32Array.BYTES_PER_ELEMENT),e.setPipeline(this._getPipeline(t,i,n.topology)),e.setBindGroup(0,this._bindGroup),e.setVertexBuffer(0,this._vertexBuffer),e.draw(a))}_getPipeline(e,t,i){const n=t?this._incrementPipelines:this._decrementPipelines,r=n.get(e);if(void 0!==r)return r;const s={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:t?"increment-clamp":"decrement-clamp"},o=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,writeMask:0}]},primitive:{topology:"triangle-strip"===i?"triangle-strip":"triangle-list"},depthStencil:{format:Bs,depthWriteEnabled:!1,depthCompare:"always",stencilFront:s,stencilBack:s,stencilReadMask:255,stencilWriteMask:255}});return n.set(e,o),o}_packMatrix(e){const t=this._matrixData;t[0]=e.a,t[1]=e.c,t[2]=0,t[3]=0,t[4]=e.b,t[5]=e.d,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e.x,t[13]=e.y,t[14]=0,t[15]=e.z}_extractPositions(e){const t=this._resolvePositionAttribute(e.attributes);if("f32"!==t.type)throw new Error(`Stencil clipShape position attribute "${t.name}" must be of type f32 (got "${t.type}").`);const{stride:i,vertexData:n,indices:r}=e,s=n instanceof Float32Array?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),o=null!==r?r.length:e.vertexCount;this._ensurePositionCapacity(o);const a=this._positions;for(let e=0;e<o;e++){const n=(null!==r?r[e]:e)*i+t.offset;a[2*e]=s.getFloat32(n,!0),a[2*e+1]=s.getFloat32(n+4,!0)}return o}_resolvePositionAttribute(e){const t=e.find(e=>Cs.has(e.name));if(t)return t;const i=e.find(e=>e.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensurePositionCapacity(e){const t=2*e;this._positions.length<t&&(this._positions=new Float32Array(Math.max(t,2*this._positions.length)))}_ensureVertexCapacity(e){const t=2*e*Float32Array.BYTES_PER_ELEMENT;t>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(t,2*this._vertexBufferCapacity||512),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}}const Ms={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:"keep"};function Ps(){return{format:Bs,depthWriteEnabled:!1,depthCompare:"always",stencilFront:Ms,stencilBack:Ms,stencilReadMask:255,stencilWriteMask:0}}const As=20;function Es(e,t,i){return`${e}:${t}:${i?"s":"n"}`}const Rs=256;class ks extends bs{_combinedTransform=new At;_drawCalls=[];_pipelines=new Map;_instancedPipelines=new Map;_staticGeometryCache=new Map;_textureBindGroups=new WeakMap;_customShaders=new Map;_device=null;_shaderModule=null;_instancedShaderModule=null;_uniformBindGroupLayout=null;_instancedTransformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_instancedPipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_uniformBuffer=null;_uniformBindGroup=null;_instancedUniformBuffer=null;_instancedUniformBufferCapacity=0;_instancedUniformScratch=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_instancedNodeIndexBuffer=null;_instancedNodeIndexBufferCapacity=0;_instancedNodeIndexData=new Uint32Array(0);_instancedTransformBindGroup=null;_instancedTransformStorageBuffer=null;_uniformAlignment=256;_vertexBufferCapacity=0;_indexBufferCapacity=0;_uniformBufferCapacity=0;_vertexData=new ArrayBuffer(0);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_packedIndexData=new Uint16Array(0);_drawCallCount=0;render(t){const i=this._backend;if(null===i)throw new Error("WebGpuMeshRenderer is not connected to a backend.");const n=t.material;if(null!==n&&null===n.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const r=t.vertexCount;if(0===r)return;const s=null!==n&&t.blendMode===e.BlendModes.Normal?n.blendMode:t.blendMode;i.setBlendMode(s);const o=t.texture??pi.white,a=i.activeDrawCommand,h=i.shouldPremultiplyTextureSample(o),l=t.indexCount;let u=-1;if(null!==n){const e=this._getOrCreateCustomShaderResources(n);u=e.drawCount,e.drawCount++,e.totalVertices+=r,e.totalIndices+=l}const c={mesh:t,customShader:n,command:a,blendMode:s,texture:o,premultiplySample:h,vertexByteOffset:0,vertexCount:r,indexByteOffset:0,indexCount:l,customDrawIndex:u};this._drawCalls[this._drawCallCount++]=c}drawInstancedBatch(e,t,i){const n=this._backend,r=this._device;if(null===n||null===r||i<=0||0===e.vertexCount)return;if(null!==e.material)throw new Error("RenderBatch custom materials are not supported on the WebGPU backend yet (v1 renders with the default mesh material).");const s=e.geometry;if("static"!==s?.usage)throw new Error('drawInstancedBatch requires a mesh with usage="static" geometry.');const o=e.texture??pi.white,a=n.shouldPremultiplyTextureSample(o);this._ensureInstancedUniformCapacity(1);const h=this._uploadInstancedNodeIndexRange(t,i),l=n.getTransformStorageBuffer(h+1);this._writeInstancedUniformSlot(0,n,a);const u=this._getOrCreateStaticGeometryEntry(e),c=this._instancedNodeIndexBuffer;if(null===c)throw new Error("Instanced node-index buffer must be initialized before drawing.");const d=n.renderTargetFormat,_=n._passCoordinator.stencilActive,f=n._passCoordinator.acquirePass().pass;f.setPipeline(this._getInstancedPipeline({blendMode:e.blendMode,format:d,stencil:_})),f.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(l.buffer),[0]),f.setBindGroup(1,this._getTextureBindGroup(n,o)),f.setVertexBuffer(0,u.vertexBuffer),f.setVertexBuffer(1,c),f.setIndexBuffer(u.indexBuffer,"uint16"),f.drawIndexed(u.indexCount,i),n._passCoordinator.endPass(),n.stats.batches++,n.stats.drawCalls++}flush(){const e=this._backend,t=this._device;if(!e||!t)return;if(0===this._drawCallCount&&!e.clearRequested)return;const i=e.getScissorRect(),n=null!==i&&(i.width<=0||i.height<=0);if(0===this._drawCallCount||n)return e.clearRequested&&(e._passCoordinator.acquirePass(),e._passCoordinator.endPass()),void this._resetFrame();let r=0,s=0;const o=new Map,a=new Map;for(let e=0;e<this._drawCallCount;e++){const t=this._drawCalls[e];if(null===t.customShader)t.vertexByteOffset=r*As,t.indexByteOffset=s*Uint16Array.BYTES_PER_ELEMENT,r+=t.vertexCount,s+=t.indexCount;else{const e=o.get(t.customShader)??0,i=a.get(t.customShader)??0;t.vertexByteOffset=e*As,t.indexByteOffset=i*Uint16Array.BYTES_PER_ELEMENT,o.set(t.customShader,e+t.vertexCount),a.set(t.customShader,i+t.indexCount)}}this._ensureVertexCapacity(r),this._ensureIndexCapacity(s);const h=this._drawCallCount-this._totalCustomDraws();this._ensureUniformCapacity(h),this._ensureInstancedUniformCapacity(this._drawCallCount);const l=h*this._uniformAlignment,u=l>0?new ArrayBuffer(l):null,c=null!==u?new Float32Array(u):null;let d=0;for(let t=0;t<this._drawCallCount;t++){const i=this._drawCalls[t];if(null===i.customShader){if(this._writeMeshVertices(e,i.mesh,i.vertexByteOffset/As,!0),null!==i.mesh.indices)this._packedIndexData.set(i.mesh.indices,i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT);else{const e=i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT;for(let t=0;t<i.indexCount;t++)this._packedIndexData[e+t]=t}if(null!==c){const e=d*this._uniformAlignment/Float32Array.BYTES_PER_ELEMENT,t=i.mesh.tint;c[e+0]=t.r/255,c[e+1]=t.g/255,c[e+2]=t.b/255,c[e+3]=t.a,c[e+4]=i.premultiplySample?1:0,c[e+5]=0,c[e+6]=0,c[e+7]=0}d++}}for(const[i,n]of this._customShaders){if(0===n.drawCount)continue;this._ensureCustomCapacities(n);let r=0,s=0,o=0;for(let t=0;t<this._drawCallCount;t++){const a=this._drawCalls[t];if(a.customShader===i){if(this._writeMeshVerticesIntoBuffer(a.mesh,r,n.vertexFloatView,n.vertexUintView),null!==a.mesh.indices)n.indexData.set(a.mesh.indices,s);else for(let e=0;e<a.indexCount;e++)n.indexData[s+e]=e;this._writeCustomMeshUniform(i,n,o,a.mesh,e),r+=a.vertexCount,s+=a.indexCount,o++}}t.queue.writeBuffer(n.vertexBuffer,0,n.vertexData,0,n.totalVertices*As),t.queue.writeBuffer(n.indexBuffer,0,n.indexData.buffer,n.indexData.byteOffset,n.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4),this._uploadUserUniforms(i,n)}r>0&&(t.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,r*As),t.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,s*Uint16Array.BYTES_PER_ELEMENT+3&-4)),null!==u&&t.queue.writeBuffer(this._uniformBuffer,0,u,0,l);const _=e._passCoordinator.acquirePass().pass,f=e.renderTargetFormat,p=e._passCoordinator.stencilActive;let m=null,g=null,y=null,w=null,x=0,v=0;const b=new Map;for(let t=0;t<this._drawCallCount;t++){const i=this._drawCalls[t];if(null===i.customShader){const n=this._getStaticBatchLength(t);if(n>=2){("instanced"!==m||i.blendMode!==g||f!==y)&&(_.setPipeline(this._getInstancedPipeline({blendMode:i.blendMode,format:f,stencil:p})),m="instanced",g=i.blendMode,y=f,w=null);const r=this._uploadInstancedNodeIndices(t,n),s=e.getTransformStorageBuffer(r+1);this._writeInstancedUniformSlot(v,e,i.premultiplySample),_.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(s.buffer),[v*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(e,i.texture)));const o=this._getOrCreateStaticGeometryEntry(i.mesh),a=this._instancedNodeIndexBuffer;if(null===a)throw new Error("Instanced node-index buffer must be initialized before drawing.");_.setVertexBuffer(0,o.vertexBuffer),_.setVertexBuffer(1,a),_.setIndexBuffer(o.indexBuffer,"uint16"),_.drawIndexed(o.indexCount,n),e.stats.batches++,e.stats.drawCalls++,x+=n,v++,t+=n-1;continue}("default"!==m||i.blendMode!==g||f!==y)&&(_.setPipeline(this._getPipeline({blendMode:i.blendMode,format:f,stencil:p})),m="default",g=i.blendMode,y=f,w=null),_.setBindGroup(0,this._uniformBindGroup,[x*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(e,i.texture))),_.setVertexBuffer(0,this._vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(this._indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),x++}else{const t=this._customShaders.get(i.customShader),n=m!==i.customShader||i.blendMode!==g||f!==y;_.pushDebugGroup("MeshMaterial (custom)"),n&&(_.setPipeline(this._getOrCreateCustomPipeline(t,i.blendMode,f,p)),m=i.customShader,g=i.blendMode,y=f,w=null,_.setBindGroup(2,this._buildUserBindGroup(e,i.customShader,t)));const r=b.get(i.customShader)??0;_.setBindGroup(0,t.meshUniformBindGroup,[r*Rs]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getOrCreateMeshTextureBindGroup(t,e,i.texture))),_.setVertexBuffer(0,t.vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(t.indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),_.popDebugGroup(),b.set(i.customShader,r+1)}e.stats.batches++,e.stats.drawCalls++}e._passCoordinator.endPass(),this._resetFrame()}destroy(){this.disconnect(),this._combinedTransform.destroy()}async prewarmPipelines(t){const i=this._device;if(!i||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof i.createRenderPipelineAsync)return;const n=[e.BlendModes.Normal,e.BlendModes.Additive,e.BlendModes.Subtract,e.BlendModes.Multiply,e.BlendModes.Screen,e.BlendModes.Darken,e.BlendModes.Lighten],r=[];for(const e of n)for(const n of t){const t=Es(e,n,!1);this._pipelines.has(t)||(r.push(i.createRenderPipelineAsync(this._buildPipelineDescriptor(e,n)).then(e=>{this._pipelines.set(t,e)})),this._instancedPipelines.has(t)||r.push(i.createRenderPipelineAsync(this._buildInstancedPipelineDescriptor(e,n)).then(e=>{this._instancedPipelines.set(t,e)})))}await Promise.all(r)}onConnect(e){this._device||(this._device=e.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n};\n\nstruct TintUniform {\n tint: vec4<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> uniforms: TintUniform;\n\n@group(1) @binding(0) var meshTexture: texture_2d<f32>;\n@group(1) @binding(1) var meshSampler: sampler;\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = input.color;\n output.premultiplySample = u32(uniforms.flags.x);\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(meshTexture, meshSampler, input.texcoord);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n let modulated = resolvedSample * input.color * uniforms.tint;\n return vec4<f32>(modulated.rgb * modulated.a, modulated.a);\n}\n"}),this._instancedShaderModule=this._device.createShaderModule({code:"\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n @location(6) nodeIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) tint: vec4<f32>,\n @location(3) @interpolate(flat) premultiplySample: u32,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\nstruct TransformUniforms {\n projection: mat3x3<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> uniforms: TransformUniforms;\n@group(0) @binding(1) var<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0) var meshTexture: texture_2d<f32>;\n@group(1) @binding(1) var meshSampler: sampler;\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let slot = transforms[input.nodeIndex];\n let world = vec3<f32>(\n slot.m0.x * input.position.x + slot.m0.z * input.position.y + slot.m1.x,\n slot.m0.y * input.position.x + slot.m0.w * input.position.y + slot.m1.y,\n 1.0\n );\n\n var output: VertexOutput;\n output.position = vec4<f32>((uniforms.projection * world).xy, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = input.color;\n output.tint = slot.m2;\n output.premultiplySample = u32(uniforms.flags.x);\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(meshTexture, meshSampler, input.texcoord);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n let modulated = resolvedSample * input.color * input.tint;\n return vec4<f32>(modulated.rgb * modulated.a, modulated.a);\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._instancedTransformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._instancedPipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._instancedTransformBindGroupLayout,this._textureBindGroupLayout]}))}onDisconnect(){this.flush(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._instancedUniformBuffer?.destroy(),this._instancedNodeIndexBuffer?.destroy(),this._pipelines.clear(),this._instancedPipelines.clear(),this._textureBindGroups=new WeakMap;for(const e of this._staticGeometryCache.values())e.vertexBuffer.destroy(),e.indexBuffer.destroy();this._staticGeometryCache.clear(),this._vertexBuffer=null,this._indexBuffer=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._instancedUniformBuffer=null,this._instancedNodeIndexBuffer=null,this._instancedTransformBindGroup=null,this._instancedTransformStorageBuffer=null,this._pipelineLayout=null,this._instancedPipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._instancedTransformBindGroupLayout=null,this._shaderModule=null,this._instancedShaderModule=null;for(const e of this._customShaders.values())this._releaseCustomShaderResources(e);this._customShaders.clear(),this._device=null,this._backend=null,this._drawCallCount=0,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._uniformBufferCapacity=0,this._instancedUniformBufferCapacity=0,this._instancedNodeIndexBufferCapacity=0,this._instancedNodeIndexData=new Uint32Array(0)}_writeMeshVertices(e,t,i,n){const r=t.vertices,s=t.uvs,o=t.colors,a=t.vertexCount;if(n){const n=this._combinedTransform.copy(t.getGlobalTransform()).combine(e.view.getTransform()),h=n.a,l=n.b,u=n.c,c=n.d,d=n.x,_=n.y;for(let e=0;e<a;e++){const t=2*e,n=5*(i+e),a=r[t],f=r[t+1];this._float32View[n+0]=h*a+l*f+d,this._float32View[n+1]=u*a+c*f+_,this._float32View[n+2]=null!==s?s[t]:0,this._float32View[n+3]=null!==s?s[t+1]:0,this._uint32View[n+4]=null!==o?o[e]:4294967295}}else for(let e=0;e<a;e++){const t=2*e,n=5*(i+e);this._float32View[n+0]=r[t],this._float32View[n+1]=r[t+1],this._float32View[n+2]=null!==s?s[t]:0,this._float32View[n+3]=null!==s?s[t+1]:0,this._uint32View[n+4]=null!==o?o[e]:4294967295}}_getPipeline(e){const t=Es(e.blendMode,e.format,e.stencil);let i=this._pipelines.get(t);return i||(i=this._device.createRenderPipeline(this._buildPipelineDescriptor(e.blendMode,e.format,e.stencil)),this._pipelines.set(t,i)),i}_buildPipelineDescriptor(e,t,i=!1){const n={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:As,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(n.depthStencil=Ps()),n}_getTextureBindGroup(e,t){const i=e.getTextureBinding(t),n=this._textureBindGroups.get(t);if(n?.view===i.view)return n.group;const r=this._device.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:i.view},{binding:1,resource:i.sampler}]});return this._textureBindGroups.set(t,{group:r,view:i.view}),r}_getStaticBatchLength(e){const t=this._drawCalls[e];if(!this._isStaticBatchCandidate(t))return 1;let i=1;for(let n=e+1;n<this._drawCallCount;n++){const e=this._drawCalls[n];if(!this._isSameStaticBatch(t,e))break;i++}return i}_isStaticBatchCandidate(e){const t=e.command;return null===e.customShader&&void 0!==t?.groupIndex&&"static"===e.mesh.geometry?.usage}_isSameStaticBatch(e,t){return!(!this._isStaticBatchCandidate(e)||!this._isStaticBatchCandidate(t))&&(e.command.groupIndex===t.command.groupIndex&&e.mesh.geometry===t.mesh.geometry&&e.texture===t.texture&&e.blendMode===t.blendMode&&e.command.material.pipelineKey===t.command.material.pipelineKey&&e.command.material.bindKey===t.command.material.bindKey)}_uploadInstancedNodeIndices(e,t){this._ensureInstancedNodeIndexCapacity(t);let i=0;for(let n=0;n<t;n++){const t=this._drawCalls[e+n].command.nodeIndex>>>0;this._instancedNodeIndexData[n]=t,t>i&&(i=t)}return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,t*Uint32Array.BYTES_PER_ELEMENT),i}_uploadInstancedNodeIndexRange(e,t){this._ensureInstancedNodeIndexCapacity(t);for(let i=0;i<t;i++)this._instancedNodeIndexData[i]=e+i>>>0;return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,t*Uint32Array.BYTES_PER_ELEMENT),e+t-1>>>0}_ensureInstancedNodeIndexCapacity(e){const t=e*Uint32Array.BYTES_PER_ELEMENT;this._instancedNodeIndexData.length<e&&(this._instancedNodeIndexData=new Uint32Array(Math.max(e,2*this._instancedNodeIndexData.length||1))),t>this._instancedNodeIndexBufferCapacity&&(this._instancedNodeIndexBuffer?.destroy(),this._instancedNodeIndexBufferCapacity=Math.max(t,2*this._instancedNodeIndexBufferCapacity||Uint32Array.BYTES_PER_ELEMENT),this._instancedNodeIndexBuffer=this._device.createBuffer({size:this._instancedNodeIndexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureInstancedUniformCapacity(e){if(0===e)return;const t=e*this._uniformAlignment;t>this._instancedUniformBufferCapacity&&(this._instancedUniformBuffer?.destroy(),this._instancedUniformBufferCapacity=Math.max(t,2*this._instancedUniformBufferCapacity||this._uniformAlignment),this._instancedUniformBuffer=this._device.createBuffer({size:this._instancedUniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._instancedTransformBindGroup=null,this._instancedTransformStorageBuffer=null)}_writeInstancedUniformSlot(e,t,i){const n=this._instancedUniformScratch,r=t.view.getTransform();n.fill(0),n[0]=r.a,n[1]=r.b,n[4]=r.c,n[5]=r.d,n[8]=r.x,n[9]=r.y,n[10]=1,n[12]=i?1:0,this._device.queue.writeBuffer(this._instancedUniformBuffer,e*this._uniformAlignment,n.buffer,n.byteOffset,64)}_getOrCreateInstancedTransformBindGroup(e){return null!==this._instancedTransformBindGroup&&this._instancedTransformStorageBuffer===e||(this._instancedTransformStorageBuffer=e,this._instancedTransformBindGroup=this._device.createBindGroup({layout:this._instancedTransformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._instancedUniformBuffer,size:64}},{binding:1,resource:{buffer:e}}]})),this._instancedTransformBindGroup}_getInstancedPipeline(e){const t=Es(e.blendMode,e.format,e.stencil);let i=this._instancedPipelines.get(t);return i||(i=this._device.createRenderPipeline(this._buildInstancedPipelineDescriptor(e.blendMode,e.format,e.stencil)),this._instancedPipelines.set(t,i)),i}_buildInstancedPipelineDescriptor(e,t,i=!1){const n={layout:this._instancedPipelineLayout,vertex:{module:this._instancedShaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:As,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]},{arrayStride:Uint32Array.BYTES_PER_ELEMENT,stepMode:"instance",attributes:[{shaderLocation:6,offset:0,format:"uint32"}]}]},fragment:{module:this._instancedShaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(n.depthStencil=Ps()),n}_getOrCreateStaticGeometryEntry(e){const t=e.geometry;if("static"!==t?.usage)throw new Error('Static mesh batching requires Geometry with usage="static".');const i=this._staticGeometryCache.get(t);if(void 0!==i)return i;const n=new ArrayBuffer(e.vertexCount*As),r=new Float32Array(n),s=new Uint32Array(n);this._writeMeshVerticesIntoBuffer(e,0,r,s);const o=new Uint16Array(e.indexCount+(1&e.indexCount));if(null!==e.indices)o.set(e.indices,0);else for(let t=0;t<e.indexCount;t++)o[t]=t;const a=e.indexCount*Uint16Array.BYTES_PER_ELEMENT+3&-4,h=this._device.createBuffer({size:n.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),l=this._device.createBuffer({size:a,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});this._device.queue.writeBuffer(h,0,n,0,n.byteLength),this._device.queue.writeBuffer(l,0,o.buffer,o.byteOffset,a);const u=()=>{const e=this._staticGeometryCache.get(t);void 0!==e&&(e.vertexBuffer.destroy(),e.indexBuffer.destroy(),this._staticGeometryCache.delete(t))};t._onDispose(u);const c={geometry:t,vertexBuffer:h,indexBuffer:l,indexCount:e.indexCount,disposeListener:u};return this._staticGeometryCache.set(t,c),c}_ensureVertexCapacity(e){const t=e*As;if(t>this._vertexData.byteLength){const e=Math.max(t,0===this._vertexData.byteLength?As:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(e),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}t>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(t,0===this._vertexBufferCapacity?As:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(e){const t=e*Uint16Array.BYTES_PER_ELEMENT+3&-4;this._packedIndexData.length*Uint16Array.BYTES_PER_ELEMENT<t&&(this._packedIndexData=new Uint16Array(Math.max(t/Uint16Array.BYTES_PER_ELEMENT,0===this._packedIndexData.length?2:2*this._packedIndexData.length))),t>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(t,0===this._indexBufferCapacity?4:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_ensureUniformCapacity(e){if(0===e)return;const t=e*this._uniformAlignment;t>this._uniformBufferCapacity&&(this._uniformBuffer?.destroy(),this._uniformBufferCapacity=Math.max(t,0===this._uniformBufferCapacity?this._uniformAlignment:2*this._uniformBufferCapacity),this._uniformBuffer=this._device.createBuffer({size:this._uniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer,size:32}}]}))}_totalCustomDraws(){let e=0;for(const t of this._customShaders.values())e+=t.drawCount;return e}_resetFrame(){this._drawCallCount=0;for(const e of this._customShaders.values())e.drawCount=0,e.totalVertices=0,e.totalIndices=0}_getOrCreateCustomShaderResources(e){let t=this._customShaders.get(e);if(void 0!==t)return t;if(null===this._device)throw new Error("WebGpuMeshRenderer is not connected to a backend.");if(null===e.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const i=this._device,n=i.createShaderModule({code:e.shader.wgsl}),r=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}}]}),s=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),o=this._buildUserBindGroupLayout(i,e),a=i.createPipelineLayout({bindGroupLayouts:[r,s,o]}),h=i.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),l=new ArrayBuffer(1280);return t={shaderModule:n,meshUniformLayout:r,meshTextureLayout:s,userLayout:o,pipelineLayout:a,pipelines:new Map,vertexBuffer:null,indexBuffer:null,vertexBufferCapacity:0,indexBufferCapacity:0,vertexData:l,vertexFloatView:new Float32Array(l),vertexUintView:new Uint32Array(l),indexData:new Uint16Array(192),meshUniformBuffer:null,meshUniformBufferCapacity:0,meshUniformBindGroup:null,userUniformBuffer:null,userUniformBufferCapacity:0,meshTextureBindGroups:new WeakMap,sampler:h,drawCount:0,totalVertices:0,totalIndices:0},this._customShaders.set(e,t),e._onDispose(()=>{const t=this._customShaders.get(e);void 0!==t&&(this._releaseCustomShaderResources(t),this._customShaders.delete(e))}),t}_ensureCustomCapacities(e){const t=this._device,i=e.totalVertices*As;if(i>e.vertexData.byteLength){const t=Math.max(i,2*e.vertexData.byteLength);e.vertexData=new ArrayBuffer(t),e.vertexFloatView=new Float32Array(e.vertexData),e.vertexUintView=new Uint32Array(e.vertexData)}i>e.vertexBufferCapacity&&(e.vertexBuffer?.destroy(),e.vertexBufferCapacity=Math.max(i,2*e.vertexBufferCapacity||As),e.vertexBuffer=t.createBuffer({size:e.vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}));const n=e.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4;e.indexData.length*Uint16Array.BYTES_PER_ELEMENT<n&&(e.indexData=new Uint16Array(Math.max(n/Uint16Array.BYTES_PER_ELEMENT,2*e.indexData.length))),n>e.indexBufferCapacity&&(e.indexBuffer?.destroy(),e.indexBufferCapacity=Math.max(n,2*e.indexBufferCapacity||4),e.indexBuffer=t.createBuffer({size:e.indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}));const r=e.drawCount*Rs;r>e.meshUniformBufferCapacity&&(e.meshUniformBuffer?.destroy(),e.meshUniformBufferCapacity=Math.max(r,2*e.meshUniformBufferCapacity||Rs),e.meshUniformBuffer=t.createBuffer({size:e.meshUniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.meshUniformBindGroup=t.createBindGroup({layout:e.meshUniformLayout,entries:[{binding:0,resource:{buffer:e.meshUniformBuffer,size:112}}]}))}_writeMeshVerticesIntoBuffer(e,t,i,n){const r=e.vertices,s=e.uvs,o=e.colors,a=e.vertexCount;for(let e=0;e<a;e++){const a=2*e,h=5*(t+e);i[h+0]=r[a],i[h+1]=r[a+1],i[h+2]=null!==s?s[a]:0,i[h+3]=null!==s?s[a+1]:0,n[h+4]=null!==o?o[e]:4294967295}}_writeCustomMeshUniform(e,t,i,n,r){const s=256/Float32Array.BYTES_PER_ELEMENT,o=new Float32Array(s),a=r.view.getTransform(),h=n.getGlobalTransform();let l=0;o[l+0]=a.a,o[l+1]=a.b,o[l+2]=0,o[l+3]=0,o[l+4]=a.c,o[l+5]=a.d,o[l+6]=0,o[l+7]=0,o[l+8]=a.x,o[l+9]=a.y,o[l+10]=1,o[l+11]=0,l+=12,o[l+0]=h.a,o[l+1]=h.b,o[l+2]=0,o[l+3]=0,o[l+4]=h.c,o[l+5]=h.d,o[l+6]=0,o[l+7]=0,o[l+8]=h.x,o[l+9]=h.y,o[l+10]=1,o[l+11]=0,l+=12;const u=n.tint;o[l+0]=u.r/255,o[l+1]=u.g/255,o[l+2]=u.b/255,o[l+3]=u.a,this._device.queue.writeBuffer(t.meshUniformBuffer,256*i,o)}_getOrCreateCustomPipeline(e,t,i,n){const r=`${t}:${i}:${n?"s":"n"}`;let s=e.pipelines.get(r);if(void 0===s){const o={layout:e.pipelineLayout,vertex:{module:e.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:As,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]}]},fragment:{module:e.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:Ss(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};n&&(o.depthStencil=Ps()),s=this._device.createRenderPipeline(o),e.pipelines.set(r,s)}return s}_getOrCreateMeshTextureBindGroup(e,t,i){const n=t.getTextureBinding(i),r=e.meshTextureBindGroups.get(i);if(r?.view===n.view)return r.group;const s=this._device.createBindGroup({layout:e.meshTextureLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]});return e.meshTextureBindGroups.set(i,{group:s,view:n.view}),s}_buildUserBindGroupLayout(e,t){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const n=Fs(t);if(n.length>7)throw new Error("Mesh material requested more than 7 user texture bindings.");let r=1;for(let e=0;e<n.length;e++)i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),r++,i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),r++;return e.createBindGroupLayout({entries:i})}_uploadUserUniforms(e,t){const i=this._device,n=function(e){const t=[];for(const i of Object.values(e.uniforms))Ds(i)||t.push(i);return t}(e),r=16*Math.max(n.length,1);(null===t.userUniformBuffer||t.userUniformBufferCapacity<r)&&(t.userUniformBuffer?.destroy(),t.userUniformBufferCapacity=r,t.userUniformBuffer=i.createBuffer({size:r,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const s=new Float32Array(r/4);let o=0;for(const e of n){const t=4*o;if("number"==typeof e)s[t]=e;else if(e instanceof Float32Array)s.set(e,t);else if(e instanceof Int32Array)for(let i=0;i<e.length;i++)s[t+i]=e[i];else{const i=e;for(let e=0;e<i.length;e++)s[t+e]=i[e]}o++}i.queue.writeBuffer(t.userUniformBuffer,0,s)}_buildUserBindGroup(e,t,i){const n=this._device,r=[];r.push({binding:0,resource:{buffer:i.userUniformBuffer}});let s=1;for(const i of Fs(t)){const t=e.getTextureBinding(i);r.push({binding:s,resource:t.view}),s++,r.push({binding:s,resource:t.sampler}),s++}return n.createBindGroup({layout:i.userLayout,entries:r})}_releaseCustomShaderResources(e){e.vertexBuffer?.destroy(),e.indexBuffer?.destroy(),e.meshUniformBuffer?.destroy(),e.userUniformBuffer?.destroy(),e.pipelines.clear(),e.meshTextureBindGroups=new WeakMap,e.vertexBuffer=null,e.indexBuffer=null,e.meshUniformBuffer=null,e.userUniformBuffer=null,e.meshUniformBindGroup=null,e.vertexBufferCapacity=0,e.indexBufferCapacity=0,e.meshUniformBufferCapacity=0,e.userUniformBufferCapacity=0}}function Ds(e){return!("object"!=typeof e||null===e||!("width"in e)||!("height"in e)||e instanceof Float32Array||e instanceof Int32Array||Array.isArray(e))}function Fs(e){const t=[];for(const i of Object.values(e.uniforms))Ds(i)&&t.push(i);for(const i of Object.values(e.textures))t.push(i);return t}const Is=32/Uint32Array.BYTES_PER_ELEMENT,Ls=new Uint16Array([0,1,2,0,2,3]);class Us extends bs{_projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_transformBindGroup=null;_transformStorageBuffer=null;_indexBuffer=null;_instanceBuffer=null;_instanceCapacity=0;_instanceData=new ArrayBuffer(0);_instanceFloat32=new Float32Array(this._instanceData);_instanceUint32=new Uint32Array(this._instanceData);_pipelines=new Map;_quadIndex=0;_maxNodeIndex=0;_currentBlendMode=null;_currentTexture=null;onConnect(e){this._device||(this._device=e.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1)\nvar<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0)\nvar nineSliceTexture: texture_2d<f32>;\n@group(1) @binding(1)\nvar nineSliceSampler: sampler;\n\nstruct VertexInput {\n @location(0) quadBounds: vec4<f32>, // x0, y0, x1, y1\n @location(1) uvBounds: vec4<f32>, // u0, v0, u1, v1 (normalised, flipY pre-applied)\n @location(2) color: vec4<f32>, // RGBA tint\n @location(3) nodeIndex: u32, // transform buffer row\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput, @builtin(vertex_index) vid: u32) -> VertexOutput {\n var output: VertexOutput;\n\n // vid 0..3 → TL, TR, BR, BL (matches static index buffer [0,1,2,0,2,3])\n let cornerX = ((vid + 1u) >> 1u) & 1u;\n let cornerY = vid >> 1u;\n\n let localX = select(input.quadBounds.x, input.quadBounds.z, cornerX == 1u);\n let localY = select(input.quadBounds.y, input.quadBounds.w, cornerY == 1u);\n\n let slot = transforms[input.nodeIndex];\n let worldX = slot.m0.x * localX + slot.m0.y * localY + slot.m1.x;\n let worldY = slot.m0.z * localX + slot.m0.w * localY + slot.m1.y;\n\n output.position = projection.matrix * vec4<f32>(worldX, worldY, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cornerX == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cornerY == 1u);\n output.texcoord = vec2<f32>(u, v);\n\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(nineSliceTexture, nineSliceSampler, input.texcoord);\n return sample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=this._device.createBuffer({size:Ls.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Ls.buffer,Ls.byteOffset,Ls.byteLength))}onDisconnect(){this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._instanceBuffer=null,this._indexBuffer=null,this._transformBindGroup=null,this._transformStorageBuffer=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._backend=null,this._instanceCapacity=0,this._instanceData=new ArrayBuffer(0),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData),this._quadIndex=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentTexture=null}render(e){const t=this._backend;if(null===t)return;let i=e.quads;if("geometry"===e.pixelSnapMode){const n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}if(0===i.length)return;const n=e.texture;if(0===n.width||0===n.height)return;if(n instanceof pi&&null===n.source)return;const r=e.blendMode,s=t.activeDrawCommand,o=null!==s?s.nodeIndex:t._pushTransform(e),a=null!==this._currentBlendMode&&r!==this._currentBlendMode,h=null!==this._currentTexture&&n!==this._currentTexture,l=this._quadIndex+i.length>this._instanceCapacity&&this._instanceCapacity>0;(a||h||l)&&this._quadIndex>0&&this.flush(),this._currentBlendMode=r,this._currentTexture=n,t.setBlendMode(r),this._ensureInstanceCapacity(this._quadIndex+i.length);const u=this._instanceFloat32,c=this._instanceUint32,d=n instanceof pi&&n.flipY;for(const t of i){const i=this._quadIndex*Is;u[i+0]=t.x0,u[i+1]=t.y0,u[i+2]=t.x1,u[i+3]=t.y1;const n=65535*t.u0&65535,r=65535*t.u1&65535,s=65535*t.v0&65535,a=65535*t.v1&65535,h=d?a:s,l=d?s:a;c[i+4]=n|h<<16,c[i+5]=r|l<<16,c[i+6]=e.tint.toRgba(),c[i+7]=o>>>0,this._quadIndex++,o>this._maxNodeIndex&&(this._maxNodeIndex=o)}}flush(){const e=this._backend,t=this._device,i=this._uniformBuffer;if(!e||!t||!i)return;if(0===this._quadIndex&&!e.clearRequested)return;const n=e.view.getTransform();this._projectionData.set([n.a,n.c,0,0,n.b,n.d,0,0,0,0,1,0,n.x,n.y,0,n.z]),t.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const r=e.getScissorRect(),s=null!==r&&(r.width<=0||r.height<=0),o=e._passCoordinator.acquirePass().pass;if(this._quadIndex>0&&!s&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode&&null!==this._currentTexture){t.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,32*this._quadIndex);const n=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,i,n.buffer),s=this._createTextureBindGroup(t,e,this._currentTexture),a=e._passCoordinator.stencilActive,h=this._getPipeline(this._currentBlendMode,e.renderTargetFormat,a);o.setPipeline(h),o.setBindGroup(0,r),o.setBindGroup(1,s),o.setVertexBuffer(0,this._instanceBuffer),o.setIndexBuffer(this._indexBuffer,"uint16"),o.drawIndexed(6,this._quadIndex,0,0,0),e.stats.batches++,e.stats.drawCalls++}e._passCoordinator.endPass(),this._quadIndex=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentTexture=null}destroy(){this.disconnect()}_getOrCreateTransformBindGroup(e,t,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=e.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_createTextureBindGroup(e,t,i){const n=t.getTextureBinding(i);return e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]})}_getPipeline(e,t,i){const n=`${e}:${t}:${i?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;if(!this._device||!this._shaderModule||!this._pipelineLayout)throw new Error("WebGpuNineSliceSpriteRenderer: renderer must be connected first.");const s={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm16x4"},{shaderLocation:2,offset:24,format:"unorm8x4"},{shaderLocation:3,offset:28,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};i&&(s.depthStencil=Ps());const o=this._device.createRenderPipeline(s);return this._pipelines.set(n,o),o}_ensureInstanceCapacity(e){if(!this._device||e<=this._instanceCapacity)return;let t=Math.max(this._instanceCapacity,32);for(;t<e;)t*=2;const i=this._instanceData,n=Math.min(32*this._quadIndex,i.byteLength),r=new ArrayBuffer(32*t);n>0&&new Uint8Array(r).set(new Uint8Array(i,0,n));const s=this._device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=t,this._instanceData=r,this._instanceFloat32=new Float32Array(r),this._instanceUint32=new Uint32Array(r),this._instanceBuffer=s}}const Gs=new Uint16Array([0,1,2,0,2,3]);function Ns(e){return"repeat"===e?"repeat":"mirror-repeat"===e?"mirror-repeat":"clamp-to-edge"}class Os extends bs{_projData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_device=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_shaderModule=null;_uniformBuffer=null;_indexBuffer=null;_transformBindGroup=null;_transformStorageBuf=null;_pipelines=new Map;_samplers=new Map;_shaderInstBuf=null;_shaderInstCapacity=0;_shaderInstData=new ArrayBuffer(0);_shaderInstF32=new Float32Array(this._shaderInstData);_shaderInstU32=new Uint32Array(this._shaderInstData);_shaderQuadCount=0;_geoInstBuf=null;_geoInstCapacity=0;_geoInstData=new ArrayBuffer(0);_geoInstF32=new Float32Array(this._geoInstData);_geoInstU32=new Uint32Array(this._geoInstData);_geoQuadCount=0;_maxNodeIndex=0;_currentTexture=null;_currentBlendMode=null;_currentModeX=null;_currentModeY=null;_currentPath=null;_snapBounds=new et;onConnect(e){if(this._device)return;const t=e.device;this._device=t,this._shaderModule=t.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1) var<storage, read> transforms: array<TransformSlot>;\n@group(1) @binding(0) var spriteTexture: texture_2d<f32>;\n@group(1) @binding(1) var spriteSampler: sampler;\n\nstruct VOut {\n @builtin(position) pos: vec4<f32>,\n @location(0) uv: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\nstruct ShaderVIn {\n @location(0) quadBounds: vec4<f32>, // x0,y0,x1,y1\n @location(1) uvParams: vec4<f32>, // tilingX, tilingY, offsetU, offsetV\n @location(2) color: vec4<f32>, // RGBA tint\n @location(3) nodeIndex: u32,\n};\n\n@vertex\nfn shaderVert(input: ShaderVIn, @builtin(vertex_index) vid: u32) -> VOut {\n var out: VOut;\n let cx = ((vid + 1u) >> 1u) & 1u;\n let cy = vid >> 1u;\n let lx = select(input.quadBounds.x, input.quadBounds.z, cx == 1u);\n let ly = select(input.quadBounds.y, input.quadBounds.w, cy == 1u);\n\n let destW = input.quadBounds.z - input.quadBounds.x;\n let destH = input.quadBounds.w - input.quadBounds.y;\n\n let slot = transforms[input.nodeIndex];\n let wx = slot.m0.x * lx + slot.m0.y * ly + slot.m1.x;\n let wy = slot.m0.z * lx + slot.m0.w * ly + slot.m1.y;\n out.pos = projection.matrix * vec4<f32>(wx, wy, 0.0, 1.0);\n\n let u = select(input.uvParams.z, ((lx - input.quadBounds.x) / destW) * input.uvParams.x + input.uvParams.z, destW > 0.0);\n let v = select(input.uvParams.w, ((ly - input.quadBounds.y) / destH) * input.uvParams.y + input.uvParams.w, destH > 0.0);\n out.uv = vec2<f32>(u, v);\n out.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n return out;\n}\n\n@fragment\nfn shaderFrag(input: VOut) -> @location(0) vec4<f32> {\n return textureSample(spriteTexture, spriteSampler, input.uv) * input.color;\n}\n\nstruct GeoVIn {\n @location(0) quadBounds: vec4<f32>, // x0,y0,x1,y1\n @location(1) uvBounds: vec4<f32>, // u0,v0,u1,v1 (normalised, flipY pre-applied)\n @location(2) color: vec4<f32>, // RGBA tint\n @location(3) nodeIndex: u32,\n};\n\n@vertex\nfn geoVert(input: GeoVIn, @builtin(vertex_index) vid: u32) -> VOut {\n var out: VOut;\n let cx = ((vid + 1u) >> 1u) & 1u;\n let cy = vid >> 1u;\n let lx = select(input.quadBounds.x, input.quadBounds.z, cx == 1u);\n let ly = select(input.quadBounds.y, input.quadBounds.w, cy == 1u);\n\n let slot = transforms[input.nodeIndex];\n let wx = slot.m0.x * lx + slot.m0.y * ly + slot.m1.x;\n let wy = slot.m0.z * lx + slot.m0.w * ly + slot.m1.y;\n out.pos = projection.matrix * vec4<f32>(wx, wy, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cx == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cy == 1u);\n out.uv = vec2<f32>(u, v);\n out.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n return out;\n}\n\n@fragment\nfn geoFrag(input: VOut) -> @location(0) vec4<f32> {\n return textureSample(spriteTexture, spriteSampler, input.uv) * input.color;\n}\n"}),this._uniformBindGroupLayout=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._uniformBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=t.createBuffer({size:Gs.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this._indexBuffer,0,Gs.buffer,Gs.byteOffset,Gs.byteLength)}onDisconnect(){this._shaderInstBuf?.destroy(),this._geoInstBuf?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._samplers.clear(),this._shaderInstBuf=null,this._geoInstBuf=null,this._indexBuffer=null,this._uniformBuffer=null,this._transformBindGroup=null,this._transformStorageBuf=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._backend=null,this._shaderInstCapacity=0,this._shaderInstData=new ArrayBuffer(0),this._shaderInstF32=new Float32Array(this._shaderInstData),this._shaderInstU32=new Uint32Array(this._shaderInstData),this._geoInstCapacity=0,this._geoInstData=new ArrayBuffer(0),this._geoInstF32=new Float32Array(this._geoInstData),this._geoInstU32=new Uint32Array(this._geoInstData),this._shaderQuadCount=0,this._geoQuadCount=0,this._maxNodeIndex=0,this._currentTexture=null,this._currentBlendMode=null,this._currentModeX=null,this._currentModeY=null,this._currentPath=null}render(e){const t=this._backend;if(!t)return;const i=e.texture;if(i instanceof pi&&null===i.source)return;if(0===i.width||0===i.height)return;const n=e.resolvedStrategy,r=e.blendMode,s=e.modeX,o=e.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const e=this._currentPath!==n,t=this._currentTexture!==i,a=this._currentBlendMode!==r,h="shader"===n&&(this._currentModeX!==s||this._currentModeY!==o);(e||t||a||h)&&this.flush()}this._currentTexture=i,this._currentBlendMode=r,this._currentPath=n,t.setBlendMode(r);const a=t.activeDrawCommand,h=null!==a?a.nodeIndex:t._pushTransform(e);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===n?(this._currentModeX=s,this._currentModeY=o,this._writeShaderInstance(e,h)):this._writeGeoQuads(e,h)}_writeShaderInstance(e,t){const i=e.texture,n=e.region.width,r=e.region.height;let s=e.width,o=e.height;const a=i instanceof pi&&i.flipY;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),i=t._getSnapPixelSize(),n=e.getRenderBounds(t.view,i.width,i.height,this._snapBounds);s=n.width,o=n.height}const h=gr(n,s,e.modeX,e.fitX),l=gr(r,o,e.modeY,e.fitY),u=e.offsetX/(n>0?n:1),c=e.offsetY/(r>0?r:1),d=a?-l:l,_=a?l+c:c;this._ensureShaderCapacity(this._shaderQuadCount+1);const f=10*this._shaderQuadCount,p=this._shaderInstF32,m=this._shaderInstU32;p[f+0]=0,p[f+1]=0,p[f+2]=s,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,m[f+8]=e.tint.toRgba(),m[f+9]=t>>>0,this._shaderQuadCount++}_writeGeoQuads(e,t){let i=e.quads;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}if(0===i.length)return;const n=e.texture instanceof pi&&e.texture.flipY,r=e.tint.toRgba();this._ensureGeoCapacity(this._geoQuadCount+i.length);const s=this._geoInstF32,o=this._geoInstU32;for(let e=0;e<i.length;e++){const a=i[e],h=8*(this._geoQuadCount+e);s[h+0]=a.x0,s[h+1]=a.y0,s[h+2]=a.x1,s[h+3]=a.y1;const l=65535*a.u0&65535,u=65535*a.u1&65535,c=65535*a.v0&65535,d=65535*a.v1&65535,_=n?d:c,f=n?c:d;o[h+4]=l|_<<16,o[h+5]=u|f<<16,o[h+6]=r,o[h+7]=t>>>0}this._geoQuadCount+=i.length}flush(){const e=this._backend,t=this._device,i=this._uniformBuffer;if(!e||!t||!i)return;if(0===this._shaderQuadCount&&0===this._geoQuadCount&&!e.clearRequested)return;const n=e.view.getTransform();this._projData.set([n.a,n.c,0,0,n.b,n.d,0,0,0,0,1,0,n.x,n.y,0,n.z]),t.queue.writeBuffer(i,0,this._projData.buffer,this._projData.byteOffset,this._projData.byteLength);const r=e.getScissorRect(),s=null!==r&&(r.width<=0||r.height<=0),o=e._passCoordinator.acquirePass().pass,a=e._passCoordinator.stencilActive;this._shaderQuadCount>0&&!s&&this._drawShaderBatch(t,e,o,a),this._geoQuadCount>0&&!s&&this._drawGeoBatch(t,e,o,a),e._passCoordinator.endPass(),this._shaderQuadCount=0,this._geoQuadCount=0,this._maxNodeIndex=0,this._currentTexture=null,this._currentBlendMode=null,this._currentModeX=null,this._currentModeY=null,this._currentPath=null}_drawShaderBatch(e,t,i,n){if(!this._shaderInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;e.queue.writeBuffer(this._shaderInstBuf,0,this._shaderInstData,0,40*this._shaderQuadCount);const r=t.getTransformStorageBuffer(this._maxNodeIndex+1),s=this._getOrCreateTransformBindGroup(e,this._uniformBuffer,r.buffer),o=this._currentModeX??"repeat",a=this._currentModeY??"repeat",h=this._getOrCreateSampler(e,o,a),l=t.getTextureBinding(this._currentTexture).view,u=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:l},{binding:1,resource:h}]}),c=this._getPipeline("shader",this._currentBlendMode,t.renderTargetFormat,n);i.setPipeline(c),i.setBindGroup(0,s),i.setBindGroup(1,u),i.setVertexBuffer(0,this._shaderInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._shaderQuadCount,0,0,0),t.stats.batches++,t.stats.drawCalls++}_drawGeoBatch(e,t,i,n){if(!this._geoInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;e.queue.writeBuffer(this._geoInstBuf,0,this._geoInstData,0,32*this._geoQuadCount);const r=t.getTransformStorageBuffer(this._maxNodeIndex+1),s=this._getOrCreateTransformBindGroup(e,this._uniformBuffer,r.buffer),o=t.getTextureBinding(this._currentTexture),a=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:o.view},{binding:1,resource:o.sampler}]}),h=this._getPipeline("geo",this._currentBlendMode,t.renderTargetFormat,n);i.setPipeline(h),i.setBindGroup(0,s),i.setBindGroup(1,a),i.setVertexBuffer(0,this._geoInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._geoQuadCount,0,0,0),t.stats.batches++,t.stats.drawCalls++}destroy(){this.disconnect()}_getOrCreateSampler(e,t,i){const n=`${t}:${i}`,r=this._samplers.get(n);if(r)return r;const s=e.createSampler({addressModeU:Ns(t),addressModeV:Ns(i),magFilter:"linear",minFilter:"linear"});return this._samplers.set(n,s),s}_getOrCreateTransformBindGroup(e,t,i){return null!==this._transformBindGroup&&this._transformStorageBuf===i||(this._transformStorageBuf=i,this._transformBindGroup=e.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_getPipeline(e,t,i,n){const r=`${e}:${t}:${i}:${n?"s":"n"}`,s=this._pipelines.get(r);if(s)return s;if(!(this._device&&this._shaderModule&&this._uniformBindGroupLayout&&this._textureBindGroupLayout))throw new Error("WebGpuRepeatingSpriteRenderer: not connected.");const o="shader"===e,a=o?40:32,h=o?[{arrayStride:a,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"float32x4"},{shaderLocation:2,offset:32,format:"unorm8x4"},{shaderLocation:3,offset:36,format:"uint32"}]}]:[{arrayStride:a,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm16x4"},{shaderLocation:2,offset:24,format:"unorm8x4"},{shaderLocation:3,offset:28,format:"uint32"}]}],l={layout:this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),vertex:{module:this._shaderModule,entryPoint:o?"shaderVert":"geoVert",buffers:h},fragment:{module:this._shaderModule,entryPoint:o?"shaderFrag":"geoFrag",targets:[{format:i,blend:Ss(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};n&&(l.depthStencil=Ps());const u=this._device.createRenderPipeline(l);return this._pipelines.set(r,u),u}_ensureShaderCapacity(e){if(!this._device||e<=this._shaderInstCapacity)return;this._shaderInstCapacity=this._growCapacity(this._shaderInstCapacity,e);const t=this._shaderInstData,i=40*this._shaderQuadCount;this._shaderInstData=new ArrayBuffer(40*this._shaderInstCapacity),i>0&&new Uint8Array(this._shaderInstData).set(new Uint8Array(t,0,i)),this._shaderInstF32=new Float32Array(this._shaderInstData),this._shaderInstU32=new Uint32Array(this._shaderInstData),this._shaderInstBuf?.destroy(),this._shaderInstBuf=this._device.createBuffer({size:this._shaderInstData.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})}_ensureGeoCapacity(e){if(!this._device||e<=this._geoInstCapacity)return;this._geoInstCapacity=this._growCapacity(this._geoInstCapacity,e);const t=this._geoInstData,i=32*this._geoQuadCount;this._geoInstData=new ArrayBuffer(32*this._geoInstCapacity),i>0&&new Uint8Array(this._geoInstData).set(new Uint8Array(t,0,i)),this._geoInstF32=new Float32Array(this._geoInstData),this._geoInstU32=new Uint32Array(this._geoInstData),this._geoInstBuf?.destroy(),this._geoInstBuf=this._device.createBuffer({size:this._geoInstData.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})}_growCapacity(e,t){let i=Math.max(e,32);for(;i<t;)i*=2;return i}}const Vs=36,zs=Vs/Uint32Array.BYTES_PER_ELEMENT,qs=new Uint16Array([0,1,2,0,2,3]);class Ws extends bs{_projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_transformBindGroup=null;_transformStorageBuffer=null;_indexBuffer=null;_instanceBuffer=null;_instanceCapacity=0;_instanceData=new ArrayBuffer(0);_instanceFloat32=new Float32Array(this._instanceData);_instanceUint32=new Uint32Array(this._instanceData);_pipelines=new Map;_activeTextures=new Array(8).fill(null);_textureSlots=new Map;_slotCount=0;_instanceCount=0;_maxNodeIndex=0;_currentBlendMode=null;_customMaterials=new Map;_customBaseTextureLayout=null;_currentMaterial=null;_currentBaseTexture=null;_snapBounds=new et;_activeBounds=null;onConnect(e){this._device||(this._device=e.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1)\nvar<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0)\nvar spriteTexture0: texture_2d<f32>;\n@group(1) @binding(1)\nvar spriteTexture1: texture_2d<f32>;\n@group(1) @binding(2)\nvar spriteTexture2: texture_2d<f32>;\n@group(1) @binding(3)\nvar spriteTexture3: texture_2d<f32>;\n@group(1) @binding(4)\nvar spriteTexture4: texture_2d<f32>;\n@group(1) @binding(5)\nvar spriteTexture5: texture_2d<f32>;\n@group(1) @binding(6)\nvar spriteTexture6: texture_2d<f32>;\n@group(1) @binding(7)\nvar spriteTexture7: texture_2d<f32>;\n\n@group(1) @binding(8)\nvar spriteSampler0: sampler;\n@group(1) @binding(9)\nvar spriteSampler1: sampler;\n@group(1) @binding(10)\nvar spriteSampler2: sampler;\n@group(1) @binding(11)\nvar spriteSampler3: sampler;\n@group(1) @binding(12)\nvar spriteSampler4: sampler;\n@group(1) @binding(13)\nvar spriteSampler5: sampler;\n@group(1) @binding(14)\nvar spriteSampler6: sampler;\n@group(1) @binding(15)\nvar spriteSampler7: sampler;\n\n// Per-instance vertex layout (36 bytes per sprite). The four corners\n// of the quad are derived from @builtin(vertex_index) 0..3 inside the\n// vertex shader — there is no per-vertex stream. The world transform is\n// fetched from the shared transform storage buffer keyed by nodeIndex\n// instead of being packed inline.\nstruct VertexInput {\n @location(0) localBounds: vec4<f32>, // left, top, right, bottom (local space)\n @location(3) uvBounds: vec4<f32>, // uMin, vMin, uMax, vMax (CPU pre-swaps for flipY)\n @location(4) color: vec4<f32>, // RGBA tint\n @location(5) packedSlotFlags: u32, // bits 0..7 = slot, bit 8 = premultiply\n @location(6) nodeIndex: u32, // row into the shared transform storage buffer\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n @location(3) @interpolate(flat) textureSlot: u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput, @builtin(vertex_index) vid: u32) -> VertexOutput {\n var output: VertexOutput;\n\n // vid 0..3 → corners in TL, TR, BR, BL order (matches the static index\n // buffer [0,1,2,0,2,3] used for indexed triangle-list drawing).\n let cornerX = ((vid + 1u) >> 1u) & 1u;\n let cornerY = vid >> 1u;\n\n let localX = select(input.localBounds.x, input.localBounds.z, cornerX == 1u);\n let localY = select(input.localBounds.y, input.localBounds.w, cornerY == 1u);\n\n // Fetch this instance's world transform from the shared storage buffer,\n // keyed by nodeIndex: m0 = (a, b, c, d), m1 = (tx, ty, 0, 0). (m2 carries the\n // node tint, unused here — the sprite keeps its own per-instance color.)\n let slot = transforms[input.nodeIndex];\n let worldX = slot.m0.x * localX + slot.m0.y * localY + slot.m1.x;\n let worldY = slot.m0.z * localX + slot.m0.w * localY + slot.m1.y;\n\n output.position = projection.matrix * vec4<f32>(worldX, worldY, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cornerX == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cornerY == 1u);\n output.texcoord = vec2<f32>(u, v);\n\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n output.textureSlot = input.packedSlotFlags & 0xFFu;\n output.premultiplySample = (input.packedSlotFlags >> 8u) & 1u;\n\n return output;\n}\n\nfn sampleTexture(slot: u32, uv: vec2<f32>, ddx: vec2<f32>, ddy: vec2<f32>) -> vec4<f32> {\n switch slot {\n case 0u: {\n return textureSampleGrad(spriteTexture0, spriteSampler0, uv, ddx, ddy);\n }\n case 1u: {\n return textureSampleGrad(spriteTexture1, spriteSampler1, uv, ddx, ddy);\n }\n case 2u: {\n return textureSampleGrad(spriteTexture2, spriteSampler2, uv, ddx, ddy);\n }\n case 3u: {\n return textureSampleGrad(spriteTexture3, spriteSampler3, uv, ddx, ddy);\n }\n case 4u: {\n return textureSampleGrad(spriteTexture4, spriteSampler4, uv, ddx, ddy);\n }\n case 5u: {\n return textureSampleGrad(spriteTexture5, spriteSampler5, uv, ddx, ddy);\n }\n case 6u: {\n return textureSampleGrad(spriteTexture6, spriteSampler6, uv, ddx, ddy);\n }\n default: {\n return textureSampleGrad(spriteTexture7, spriteSampler7, uv, ddx, ddy);\n }\n }\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n // Compute screen-space derivatives in uniform control flow before the\n // per-slot switch. WGSL requires textureSample (implicit LOD) to run in\n // uniform control flow, which multi-texture batching breaks because the\n // slot varies per fragment. textureSampleGrad takes explicit derivatives\n // and is valid regardless of control-flow uniformity, while preserving\n // mipmap-correct LOD when sprites use mipmapped textures.\n let ddx = dpdx(input.texcoord);\n let ddy = dpdy(input.texcoord);\n let sample = sampleTexture(input.textureSlot, input.texcoord, ddx, ddy);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n\n return resolvedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[...Array.from({length:8},(e,t)=>({binding:t,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(e,t)=>({binding:8+t,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}))]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._customBaseTextureLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=this._device.createBuffer({size:qs.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,qs.buffer,qs.byteOffset,qs.byteLength))}onDisconnect(){this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy();for(const e of this._customMaterials.values())this._releaseCustomResources(e);this._customMaterials.clear(),this._pipelines.clear(),this._instanceBuffer=null,this._indexBuffer=null,this._transformBindGroup=null,this._transformStorageBuffer=null,this._uniformBuffer=null,this._pipelineLayout=null,this._customBaseTextureLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._backend=null,this._instanceCapacity=0,this._instanceData=new ArrayBuffer(0),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData),this._instanceCount=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentMaterial=null,this._currentBaseTexture=null,this._resetSlots()}render(e){const t=this._backend,i=e.texture;if(null===t||!(i instanceof pi)&&!(i instanceof _i)||0===i.width||0===i.height||i instanceof pi&&null===i.source)return;const n=e.material,r=t.activeDrawCommand,s=null!==r?r.nodeIndex:t._pushTransform(e);this._activeBounds=this._resolveBounds(e,t),null===n?this._renderDefault(e,i,t,s):this._renderCustom(e,i,n,t,s)}_resolveBounds(e,t){if("geometry"!==e.pixelSnapMode)return e.getLocalBounds();const i=t._getSnapPixelSize();return e.getRenderBounds(t.view,i.width,i.height,this._snapBounds)}_renderDefault(e,t,i,n){const r=e.blendMode,s=null!==this._currentBlendMode&&r!==this._currentBlendMode,o=!this._textureSlots.has(t)&&this._slotCount>=8,a=null!==this._currentMaterial&&this._instanceCount>0;(s||o||a)&&this.flush(),this._currentBlendMode=r,this._currentMaterial=null,i.setBlendMode(r);let h=this._textureSlots.get(t);void 0===h&&(h=this._slotCount++,this._textureSlots.set(t,h),this._activeTextures[h]=t);const l=h|(i.shouldPremultiplyTextureSample(t)?1:0)<<8;this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(e,t,l,n),this._instanceCount++}_renderCustom(t,i,n,r,s){if(null===n.shader.wgsl)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const o=t.blendMode===e.BlendModes.Normal?n.blendMode:t.blendMode,a=null!==this._currentBlendMode&&o!==this._currentBlendMode,h=null!==this._currentMaterial&&n!==this._currentMaterial,l=null!==this._currentBaseTexture&&i!==this._currentBaseTexture,u=null===this._currentMaterial&&this._instanceCount>0;(a||h||l||u)&&this.flush(),this._currentBlendMode=o,this._currentMaterial=n,this._currentBaseTexture=i,r.setBlendMode(o),this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(t,i,0,s),this._instanceCount++}flush(){const e=this._backend,t=this._device,i=this._uniformBuffer;if(!e||!t||!i)return;if(0===this._instanceCount&&!e.clearRequested)return;const n=e.view.getTransform();this._projectionData.set([n.a,n.c,0,0,n.b,n.d,0,0,0,0,1,0,n.x,n.y,0,n.z]),t.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const r=e.getScissorRect(),s=null!==r&&(r.width<=0||r.height<=0),o=e._passCoordinator.acquirePass().pass;if(this._instanceCount>0&&!s&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode){t.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,this._instanceCount*Vs);const n=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,i,n.buffer),s=this._currentMaterial,a=e._passCoordinator.stencilActive;if(null===s){const i=this._getPipeline(this._currentBlendMode,e.renderTargetFormat,a),n=this._createTextureBindGroup(t,e);o.setPipeline(i),o.setBindGroup(0,r),o.setBindGroup(1,n),o.setVertexBuffer(0,this._instanceBuffer),o.setIndexBuffer(this._indexBuffer,"uint16"),o.drawIndexed(6,this._instanceCount,0,0,0)}else o.pushDebugGroup("SpriteMaterial (custom)"),this._drawCustomBatch(o,t,e,s,r,a),o.popDebugGroup();e.stats.batches++,e.stats.drawCalls++}e._passCoordinator.endPass(),this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots(),this._currentBlendMode=null,this._currentMaterial=null,this._currentBaseTexture=null}_getOrCreateTransformBindGroup(e,t,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=e.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}destroy(){this.disconnect()}async prewarmPipelines(t){const i=this._device;if(!i||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof i.createRenderPipelineAsync)return;const n=[e.BlendModes.Normal,e.BlendModes.Additive,e.BlendModes.Subtract,e.BlendModes.Multiply,e.BlendModes.Screen,e.BlendModes.Darken,e.BlendModes.Lighten],r=[];for(const e of n)for(const n of t){const t=`${e}:${n}`;if(this._pipelines.has(t))continue;const s=i.createRenderPipelineAsync(this._buildPipelineDescriptor(e,n)).then(e=>{this._pipelines.set(t,e)});r.push(s)}await Promise.all(r)}_packInstance(e,t,i,n){const r=this._instanceCount*zs,s=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??e.getLocalBounds();s[r+0]=a.left,s[r+1]=a.top,s[r+2]=a.right,s[r+3]=a.bottom;const h=e.textureFrame,l=t.width,u=t.height,c=h.left/l*65535&65535,d=h.right/l*65535&65535,_=h.top/u*65535&65535,f=h.bottom/u*65535&65535,p=t instanceof pi&&t.flipY,m=p?f:_,g=p?_:f;o[r+4]=c|m<<16,o[r+5]=d|g<<16,o[r+6]=e.tint.toRgba(),o[r+7]=i;const y=n>>>0;o[r+8]=y,y>this._maxNodeIndex&&(this._maxNodeIndex=y)}_ensureInstanceCapacity(e){if(!this._device||e<=this._instanceCapacity)return;let t=Math.max(this._instanceCapacity,32);for(;t<e;)t*=2;const i=this._instanceData,n=Math.min(this._instanceCount*Vs,i.byteLength),r=new ArrayBuffer(t*Vs);n>0&&new Uint8Array(r).set(new Uint8Array(i,0,n));const s=this._device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=t,this._instanceData=r,this._instanceFloat32=new Float32Array(r),this._instanceUint32=new Uint32Array(r),this._instanceBuffer=s}_resetSlots(){if(this._slotCount>0){for(let e=0;e<this._slotCount;e++)this._activeTextures[e]=null;this._textureSlots.clear(),this._slotCount=0}}_createTextureBindGroup(e,t){const i=this._activeTextures[0]??pi.empty,n=t.getTextureBinding(i),r=new Array(8);for(let e=0;e<8;e++){const s=this._activeTextures[e]??i;r[e]=s===i?n:t.getTextureBinding(s)}const s=[];for(let e=0;e<8;e++)s.push({binding:e,resource:r[e].view});for(let e=0;e<8;e++)s.push({binding:8+e,resource:r[e].sampler});return e.createBindGroup({layout:this._textureBindGroupLayout,entries:s})}_getPipeline(e,t,i){const n=`${e}:${t}:${i?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._backend))throw new Error("Renderer has to be connected first!");const s=this._device.createRenderPipeline(this._buildPipelineDescriptor(e,t,i));return this._pipelines.set(n,s),s}_buildPipelineDescriptor(e,t,i=!1){if(!this._shaderModule||!this._pipelineLayout)throw new Error("Renderer has to be connected first!");const n={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Vs,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:3,offset:16,format:"unorm16x4"},{shaderLocation:4,offset:24,format:"unorm8x4"},{shaderLocation:5,offset:28,format:"uint32"},{shaderLocation:6,offset:32,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return i&&(n.depthStencil=Ps()),n}_drawCustomBatch(e,t,i,n,r,s){const o=this._getOrCreateCustomResources(n,t),a=this._currentBaseTexture??pi.empty;this._uploadUserUniforms(n,o,t);const h=this._getOrCreateCustomPipeline(o,this._currentBlendMode,i.renderTargetFormat,s,t);e.setPipeline(h),e.setBindGroup(0,r),e.setBindGroup(1,this._getCustomBaseTextureBindGroup(o,i,a,t)),e.setBindGroup(2,this._buildUserBindGroup(n,o,i,t)),e.setVertexBuffer(0,this._instanceBuffer),e.setIndexBuffer(this._indexBuffer,"uint16"),e.drawIndexed(6,this._instanceCount,0,0,0)}_getOrCreateCustomResources(e,t){const i=this._customMaterials.get(e);if(void 0!==i)return i;const n=e.shader.wgsl;if(null===n)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const r=t.createShaderModule({code:`\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1) var<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0) var u_texture: texture_2d<f32>;\n@group(1) @binding(1) var u_sampler: sampler;\n\nstruct VertexInput {\n @location(0) localBounds: vec4<f32>,\n @location(3) uvBounds: vec4<f32>,\n @location(4) color: vec4<f32>,\n @location(5) textureSlot: u32,\n @location(6) nodeIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput, @builtin(vertex_index) vid: u32) -> VertexOutput {\n var output: VertexOutput;\n\n let cornerX = ((vid + 1u) >> 1u) & 1u;\n let cornerY = vid >> 1u;\n\n let localX = select(input.localBounds.x, input.localBounds.z, cornerX == 1u);\n let localY = select(input.localBounds.y, input.localBounds.w, cornerY == 1u);\n\n // Fetch this instance's world transform from the shared storage buffer,\n // keyed by nodeIndex: m0 = (a, b, c, d), m1 = (tx, ty, 0, 0). (m2 carries the\n // node tint, unused here — the sprite keeps its own per-instance color.)\n let slot = transforms[input.nodeIndex];\n let worldX = slot.m0.x * localX + slot.m0.y * localY + slot.m1.x;\n let worldY = slot.m0.z * localX + slot.m0.w * localY + slot.m1.y;\n\n output.position = projection.matrix * vec4<f32>(worldX, worldY, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cornerX == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cornerY == 1u);\n output.texcoord = vec2<f32>(u, v);\n\n output.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n${n}`}),s=this._buildUserBindGroupLayout(t,e),o={shaderModule:r,userLayout:s,pipelineLayout:t.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._customBaseTextureLayout,s]}),pipelines:new Map,userUniformBuffer:null,userUniformBufferCapacity:0,baseTextureBindGroups:new WeakMap};return this._customMaterials.set(e,o),e._onDispose(()=>{const t=this._customMaterials.get(e);void 0!==t&&(this._releaseCustomResources(t),this._customMaterials.delete(e))}),o}_getOrCreateCustomPipeline(e,t,i,n,r){const s=`${t}:${i}:${n?"s":"n"}`,o=e.pipelines.get(s);if(void 0!==o)return o;const a={layout:e.pipelineLayout,vertex:{module:e.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Vs,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:3,offset:16,format:"unorm16x4"},{shaderLocation:4,offset:24,format:"unorm8x4"},{shaderLocation:5,offset:28,format:"uint32"},{shaderLocation:6,offset:32,format:"uint32"}]}]},fragment:{module:e.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:Ss(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};n&&(a.depthStencil=Ps());const h=r.createRenderPipeline(a);return e.pipelines.set(s,h),h}_getCustomBaseTextureBindGroup(e,t,i,n){const r=t.getTextureBinding(i),s=e.baseTextureBindGroups.get(i);if(s?.view===r.view)return s.group;const o=n.createBindGroup({layout:this._customBaseTextureLayout,entries:[{binding:0,resource:r.view},{binding:1,resource:r.sampler}]});return e.baseTextureBindGroups.set(i,{group:o,view:r.view}),o}_buildUserBindGroupLayout(e,t){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const n=$s(t);if(n.length>7)throw new Error("SpriteMaterial requested more than 7 user texture bindings.");let r=1;for(let e=0;e<n.length;e++)i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),r++,i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),r++;return e.createBindGroupLayout({entries:i})}_uploadUserUniforms(e,t,i){const n=function(e){const t=[];for(const i of Object.values(e.uniforms))Ys(i)||t.push(i);return t}(e),r=16*Math.max(n.length,1);(null===t.userUniformBuffer||t.userUniformBufferCapacity<r)&&(t.userUniformBuffer?.destroy(),t.userUniformBufferCapacity=r,t.userUniformBuffer=i.createBuffer({size:r,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const s=new Float32Array(r/4);let o=0;for(const e of n){const t=4*o;if("number"==typeof e)s[t]=e;else if(e instanceof Float32Array)s.set(e,t);else if(e instanceof Int32Array)for(let i=0;i<e.length;i++)s[t+i]=e[i];else{const i=e;for(let e=0;e<i.length;e++)s[t+e]=i[e]}o++}i.queue.writeBuffer(t.userUniformBuffer,0,s)}_buildUserBindGroup(e,t,i,n){const r=[];r.push({binding:0,resource:{buffer:t.userUniformBuffer}});let s=1;for(const t of $s(e)){const e=i.getTextureBinding(t);r.push({binding:s,resource:e.view}),s++,r.push({binding:s,resource:e.sampler}),s++}return n.createBindGroup({layout:t.userLayout,entries:r})}_releaseCustomResources(e){e.userUniformBuffer?.destroy(),e.pipelines.clear(),e.userUniformBuffer=null,e.userUniformBufferCapacity=0,e.baseTextureBindGroups=new WeakMap}}function Ys(e){return!("object"!=typeof e||null===e||!("width"in e)||!("height"in e)||e instanceof Float32Array||e instanceof Int32Array||Array.isArray(e))}function $s(e){const t=[];for(const i of Object.values(e.uniforms))Ys(i)&&t.push(i);for(const i of Object.values(e.textures))t.push(i);return t}const Xs=20;class Hs extends bs{_consumesSharedTransform=!1;_device=null;_shaderModule=null;_frameBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_pipelines=new Map;_texBindGroups=new WeakMap;_projBuffer=null;_nodeBuffer=null;_vertexBuffer=null;_indexBuffer=null;_nodeBufferCapacity=0;_vertexBufferCapacity=0;_indexBufferCapacity=0;_frameBindGroup=null;_frameBindGroupDirty=!0;_vertexCapacity=256;_indexCapacity=384;_vertexData=new ArrayBuffer(5120);_float32View=new Float32Array(this._vertexData);_indexData=new Uint16Array(384);_projData=new Float32Array(12);_nodeDataArray=new Float32Array(1280);_nodeCapacity=32;_nodeCount=0;_pendingQuads=[];_nodeIndexMap=new Map;_textureKeyMap=new Map;_textureKeyCounter=0;render(e){if(!this._device)throw new Error("WebGpuTextRenderer is not connected to a backend.");e instanceof Wr?this._collectText(e):this._collectBitmapText(e)}flush(){if(0===this._pendingQuads.length)return void this._resetFrameState();const e=this.getBackend(),t=this._device;for(const e of this._pendingQuads)this._textureKeyMap.has(e.atlasTexture)||this._textureKeyMap.set(e.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((e,t)=>{const i=e.shaderType.localeCompare(t.shaderType);return 0!==i?i:(this._textureKeyMap.get(e.atlasTexture)??0)-(this._textureKeyMap.get(t.atlasTexture)??0)});const i=e.view.getTransform().toArray(!1);this._projData[0]=i[0],this._projData[1]=i[1],this._projData[2]=i[2],this._projData[3]=0,this._projData[4]=i[3],this._projData[5]=i[4],this._projData[6]=i[5],this._projData[7]=0,this._projData[8]=i[6],this._projData[9]=i[7],this._projData[10]=i[8],this._projData[11]=0,t.queue.writeBuffer(this._projBuffer,0,this._projData.buffer,0,48),this._uploadNodeBuffer(t);const n=this._pendingQuads,r=[];let s=0,o=0;for(const e of n)s+=4*e.quads.quadCount,o+=e.quads.indices.length;this._ensureVertexCapacity(s),this._ensureIndexCapacity(o);let a=0,h=0,l=0;for(;l<n.length;){const e=n[l],t=this._textureKeyMap.get(e.atlasTexture);let i=l+1;for(;i<n.length;){const r=n[i];if(r.shaderType!==e.shaderType||this._textureKeyMap.get(r.atlasTexture)!==t)break;i++}const s=h;let o=0;for(let e=l;e<i;e++){const{quads:t,nodeIndex:i}=n[e],r=4*t.quadCount,{vertices:s,uvs:l,indices:u}=t;for(let e=0;e<r;e++){const t=5*(a+e),n=2*e;this._float32View[t+0]=s[n],this._float32View[t+1]=s[n+1],this._float32View[t+2]=l[n],this._float32View[t+3]=l[n+1],this._float32View[t+4]=i}for(let e=0;e<u.length;e++)this._indexData[h+e]=u[e]+a;a+=r,h+=u.length,o+=u.length}r.push({shaderType:e.shaderType,atlasTexture:e.atlasTexture,firstIndex:s,indexCount:o}),l=i}this._ensureGpuVertexBuffer(t,a),this._ensureGpuIndexBuffer(t,h),t.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,a*Xs),t.queue.writeBuffer(this._indexBuffer,0,this._indexData.buffer,0,2*h);const u=e.renderTargetFormat,c=e._passCoordinator.stencilActive,d=this._getFrameBindGroup(t),_=e._passCoordinator.acquirePass().pass;_.setVertexBuffer(0,this._vertexBuffer),_.setIndexBuffer(this._indexBuffer,"uint16");let f=null,p=null;for(const i of r)i.shaderType!==f&&(_.setPipeline(this._getPipeline(i.shaderType,u,c)),_.setBindGroup(0,d),f=i.shaderType),i.atlasTexture!==p&&(_.setBindGroup(1,this._getTexBindGroup(t,e,i.atlasTexture)),p=i.atlasTexture),_.drawIndexed(i.indexCount,1,i.firstIndex,0,0),e.stats.batches++,e.stats.drawCalls++;e._passCoordinator.endPass(),this._resetFrameState()}destroy(){this.disconnect()}async prewarmPipelines(e){const t=this._device;if(!t||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof t.createRenderPipelineAsync)return;const i=["sdf","msdf","color"],n=[];for(const r of i)for(const i of e){const e=`${r}:${i}:n`;this._pipelines.has(e)||n.push(t.createRenderPipelineAsync(this._buildPipelineDescriptor(r,i)).then(t=>{this._pipelines.set(e,t)}))}await Promise.all(n)}onConnect(e){const t=e.device;this._device=t,this._shaderModule=t.createShaderModule({label:"WebGpuTextRenderer",code:"\nstruct FrameUniforms {\n projCol0 : vec4<f32>,\n projCol1 : vec4<f32>,\n projCol2 : vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> frame : FrameUniforms;\n@group(0) @binding(1) var<storage, read> nodes : array<vec4<f32>>;\n\n@group(1) @binding(0) var atlasTexture : texture_2d<f32>;\n@group(1) @binding(1) var atlasSampler : sampler;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) texcoord : vec2<f32>,\n @location(2) nodeIndex : f32,\n};\n\nstruct VertexOutput {\n @builtin(position) clipPos : vec4<f32>,\n @location(0) texcoord : vec2<f32>,\n @location(1) gradUV : vec2<f32>,\n @location(2) @interpolate(flat) nodeIdx : u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let ni = u32(input.nodeIndex);\n let base = ni * 10u;\n\n let t0 = nodes[base + 0u];\n let t1 = nodes[base + 1u];\n let t9 = nodes[base + 9u];\n\n let proj = mat3x3<f32>(\n frame.projCol0.xyz,\n frame.projCol1.xyz,\n frame.projCol2.xyz,\n );\n let xf = mat3x3<f32>(\n vec3<f32>(t0.x, t0.y, 0.0),\n vec3<f32>(t1.x, t1.y, 0.0),\n vec3<f32>(t0.w, t1.w, 1.0),\n );\n\n let worldPos = proj * xf * vec3<f32>(input.position, 1.0);\n\n let bSize = t9.zw;\n var gradUV = vec2<f32>(0.0);\n if (bSize.x > 0.0 && bSize.y > 0.0) {\n gradUV = clamp((input.position - t9.xy) / bSize, vec2<f32>(0.0), vec2<f32>(1.0));\n }\n\n var out: VertexOutput;\n out.clipPos = vec4<f32>(worldPos.xy, 0.0, 1.0);\n out.texcoord = input.texcoord;\n out.gradUV = gradUV;\n out.nodeIdx = ni;\n return out;\n}\n\n// ── SDF (R8 atlas) ────────────────────────────────────────────────────────────\n\n@fragment\nfn fragmentSdf(in: VertexOutput) -> @location(0) vec4<f32> {\n let ni = in.nodeIdx;\n let base = ni * 10u;\n\n let tFill = nodes[base + 2u];\n let tOutline = nodes[base + 3u];\n let tParams = nodes[base + 4u];\n let tShadow = nodes[base + 5u];\n let tShadow2 = nodes[base + 6u];\n let tGradTop = nodes[base + 7u];\n let tGradBot = nodes[base + 8u];\n\n let outlineMin = tParams.x;\n let shadowAlpha = tParams.y;\n let soft = max(tParams.z, 0.001);\n let gradEnabled = tParams.w;\n let pageSize = f32(textureDimensions(atlasTexture, 0).x);\n let shadowOffset = tShadow2.xy / pageSize;\n let gradVertical = tShadow2.z;\n\n let sd = textureSample(atlasTexture, atlasSampler, in.texcoord).r;\n let fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n let shadowSd = textureSample(atlasTexture, atlasSampler, in.texcoord - shadowOffset).r;\n\n let outline = select(0.0,\n smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill),\n outlineMin < 0.5);\n\n let shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n var fillColor : vec4<f32>;\n if (gradEnabled > 0.5) {\n let t = select(in.gradUV.x, in.gradUV.y, gradVertical > 0.5);\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n return fillColor * fill + tOutline * outline + tShadow * shadow;\n}\n\n// ── MSDF (RGB atlas) ──────────────────────────────────────────────────────────\n\nfn median3(r: f32, g: f32, b: f32) -> f32 {\n return max(min(r, g), min(max(r, g), b));\n}\n\n@fragment\nfn fragmentMsdf(in: VertexOutput) -> @location(0) vec4<f32> {\n let ni = in.nodeIdx;\n let base = ni * 10u;\n\n let tFill = nodes[base + 2u];\n let tOutline = nodes[base + 3u];\n let tParams = nodes[base + 4u];\n let tShadow = nodes[base + 5u];\n let tShadow2 = nodes[base + 6u];\n let tGradTop = nodes[base + 7u];\n let tGradBot = nodes[base + 8u];\n\n let outlineMin = tParams.x;\n let shadowAlpha = tParams.y;\n let soft = max(tParams.z, 0.001);\n let gradEnabled = tParams.w;\n let pageSize = f32(textureDimensions(atlasTexture, 0).x);\n let shadowOffset = tShadow2.xy / pageSize;\n let gradVertical = tShadow2.z;\n\n let msd = textureSample(atlasTexture, atlasSampler, in.texcoord).rgb;\n let sd = median3(msd.r, msd.g, msd.b);\n let fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n let shadowMsd = textureSample(atlasTexture, atlasSampler, in.texcoord - shadowOffset).rgb;\n let shadowSd = median3(shadowMsd.r, shadowMsd.g, shadowMsd.b);\n\n let outline = select(0.0,\n smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill),\n outlineMin < 0.5);\n\n let shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n var fillColor : vec4<f32>;\n if (gradEnabled > 0.5) {\n let t = select(in.gradUV.x, in.gradUV.y, gradVertical > 0.5);\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n return fillColor * fill + tOutline * outline + tShadow * shadow;\n}\n\n// ── Color (RGBA atlas) ────────────────────────────────────────────────────────\n\n@fragment\nfn fragmentColor(in: VertexOutput) -> @location(0) vec4<f32> {\n let ni = in.nodeIdx;\n let base = ni * 10u;\n let tint = nodes[base + 2u];\n let sample = textureSample(atlasTexture, atlasSampler, in.texcoord);\n return sample * tint;\n}\n"}),this._frameBindGroupLayout=t.createBindGroupLayout({label:"WebGpuTextRenderer/frame",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=t.createBindGroupLayout({label:"WebGpuTextRenderer/texture",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=t.createPipelineLayout({label:"WebGpuTextRenderer",bindGroupLayouts:[this._frameBindGroupLayout,this._textureBindGroupLayout]}),this._projBuffer=t.createBuffer({label:"WebGpuTextRenderer/proj",size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this._nodeBuffer=t.createBuffer({label:"WebGpuTextRenderer/nodes",size:5120,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=5120;this._vertexBuffer=t.createBuffer({label:"WebGpuTextRenderer/vertices",size:5120,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=5120;this._indexBuffer=t.createBuffer({label:"WebGpuTextRenderer/indices",size:768,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._indexBufferCapacity=768,this._frameBindGroupDirty=!0}onDisconnect(){this._projBuffer?.destroy(),this._nodeBuffer?.destroy(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._projBuffer=null,this._nodeBuffer=null,this._vertexBuffer=null,this._indexBuffer=null,this._nodeBufferCapacity=0,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._frameBindGroup=null,this._frameBindGroupDirty=!0,this._pipelines.clear(),this._texBindGroups=new WeakMap,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._frameBindGroupLayout=null,this._shaderModule=null,this._device=null,this._resetFrameState()}_collectText(e){e.syncDirty();const{pageQuads:t,atlas:i}=e;if(0===t.length||null===i)return;const n=this._assignNodeIndex(e),r=e.colorGlyphs?"color":"sdf",s=i.pages;for(const e of t){const t=s[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:n,shaderType:r,atlasTexture:t.texture})}}_collectBitmapText(e){const{pageQuads:t,textures:i,msdf:n}=e;if(0===t.length)return;const r=this._assignNodeIndex(e),s=n?"msdf":"color";for(const e of t){const t=i[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:r,shaderType:s,atlasTexture:t})}}_assignNodeIndex(e){const t=this._nodeIndexMap.get(e);if(void 0!==t)return t;const i=this._nodeCount++;return this._nodeIndexMap.set(e,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,e),i}_packNodeData(e,t){const i=this._nodeDataArray,n=40*e,r=t.style,s=t.getGlobalTransform().toArray(!1);i[n+0]=s[0],i[n+1]=s[1],i[n+2]=s[2],i[n+3]=s[6],i[n+4]=s[3],i[n+5]=s[4],i[n+6]=s[5],i[n+7]=s[7];const o=r.fillColor;i[n+8]=o.r/255,i[n+9]=o.g/255,i[n+10]=o.b/255,i[n+11]=o.a;const a=r.outlineColor;i[n+12]=a.r/255,i[n+13]=a.g/255,i[n+14]=a.b/255,i[n+15]=a.a;const h=r.outlineWidth>0?Math.max(0,.5-r.outlineWidth):.5;i[n+16]=h,i[n+17]=r.shadowAlpha,i[n+18]=Math.max(.03,.1*r.shadowBlur),i[n+19]=null!==r.gradientColors?1:0;const l=r.shadowColor;i[n+20]=l.r/255,i[n+21]=l.g/255,i[n+22]=l.b/255,i[n+23]=l.a,i[n+24]=r.shadowOffsetX,i[n+25]=r.shadowOffsetY,i[n+26]="vertical"===r.gradientAxis?1:0,i[n+27]=0;const u=r.gradientColors;null!==u?(i[n+28]=u[0].r/255,i[n+29]=u[0].g/255,i[n+30]=u[0].b/255,i[n+31]=u[0].a,i[n+32]=u[1].r/255,i[n+33]=u[1].g/255,i[n+34]=u[1].b/255,i[n+35]=u[1].a):(i[n+28]=i[n+29]=i[n+30]=i[n+31]=0,i[n+32]=i[n+33]=i[n+34]=i[n+35]=0);const c=t.textBounds;i[n+36]=0,i[n+37]=0,i[n+38]=c.width,i[n+39]=c.height}_uploadNodeBuffer(e){const t=40*this._nodeCount*4;if(t>this._nodeBufferCapacity){let i=this._nodeBufferCapacity;for(;i<t;)i*=2;this._nodeBuffer?.destroy(),this._nodeBuffer=e.createBuffer({label:"WebGpuTextRenderer/nodes",size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=i,this._frameBindGroupDirty=!0}e.queue.writeBuffer(this._nodeBuffer,0,this._nodeDataArray.buffer,0,t)}_ensureGpuVertexBuffer(e,t){const i=t*Xs;if(i<=this._vertexBufferCapacity)return;let n=this._vertexBufferCapacity;for(;n<i;)n*=2;this._vertexBuffer?.destroy(),this._vertexBuffer=e.createBuffer({label:"WebGpuTextRenderer/vertices",size:n,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=n}_ensureGpuIndexBuffer(e,t){const i=2*t;if(i<=this._indexBufferCapacity)return;let n=this._indexBufferCapacity;for(;n<i;)n*=2;this._indexBuffer?.destroy(),this._indexBuffer=e.createBuffer({label:"WebGpuTextRenderer/indices",size:n,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._indexBufferCapacity=n}_getFrameBindGroup(e){return this._frameBindGroupDirty||null===this._frameBindGroup?(this._frameBindGroup=e.createBindGroup({layout:this._frameBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projBuffer}},{binding:1,resource:{buffer:this._nodeBuffer}}]}),this._frameBindGroupDirty=!1,this._frameBindGroup):this._frameBindGroup}_getTexBindGroup(e,t,i){const{view:n,sampler:r}=t.getTextureBinding(i),s=this._texBindGroups.get(i);if(s?.view===n)return s.group;const o=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:n},{binding:1,resource:r}]});return this._texBindGroups.set(i,{group:o,view:n}),o}_getPipeline(e,t,i){const n=`${e}:${t}:${i?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;const s=this._device.createRenderPipeline(this._buildPipelineDescriptor(e,t,i));return this._pipelines.set(n,s),s}_buildPipelineDescriptor(t,i,n=!1){let r;r="sdf"===t?"fragmentSdf":"msdf"===t?"fragmentMsdf":"fragmentColor";const s={label:`WebGpuTextRenderer/${t}`,layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Xs,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"float32"}]}]},fragment:{module:this._shaderModule,entryPoint:r,targets:[{format:i,blend:Ss(e.BlendModes.Normal),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return n&&(s.depthStencil=Ps()),s}_ensureVertexCapacity(e){if(!(e<=this._vertexCapacity)){for(;this._vertexCapacity<e;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*Xs),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(e){if(!(e<=this._indexCapacity)){for(;this._indexCapacity<e;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(e){if(e<=this._nodeCapacity)return;for(;this._nodeCapacity<e;)this._nodeCapacity*=2;const t=new Float32Array(40*this._nodeCapacity);t.set(this._nodeDataArray),this._nodeDataArray=t}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}}class js extends In{_rawTransform=null;_sourceGeometry=null;_sourceVersion=-1;constructor(){super({vertices:new Float32Array([0,0,1,0,0,1])})}getGlobalTransform(){return this._rawTransform??super.getGlobalTransform()}configure(e,t,i,n){this._flattenGeometry(e),this._geometry=null,this._material=i,this._rawTransform=t,this.setTint(n??Tt.white)}configureBatchSource(e,t){this._flattenGeometry(e),this._geometry=e,this._material=t,this._rawTransform=null,this.setTint(Tt.white)}_flattenGeometry(e){if(e===this._sourceGeometry&&e.version===this._sourceVersion)return;const t=On(e);this._vertices=t.vertices,this._uvs=t.uvs,this._colors=t.colors,this._indices=t.indices,this._sourceGeometry=e,this._sourceVersion=e.version}}const Ks=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0,rawFrameDeltaMs:0,gpuMemoryBytes:0,textureUploadBytes:0,bufferUploadBytes:0,downloadBytes:0,downloadCount:0}),Qs=e=>(e.frame++,e.submittedNodes=0,e.culledNodes=0,e.drawCalls=0,e.batches=0,e.renderPasses=0,e.renderTargetChanges=0,e.frameTimeMs=0,e.rawFrameDeltaMs=0,e.textureUploadBytes=0,e.bufferUploadBytes=0,e.downloadBytes=0,e.downloadCount=0,e);class Zs{order=500;_backend;_view;_screenView;_immediateMesh=null;_batchMesh=null;_trackedViews=new Set;_renderedViews=new Set;constructor(e){this._backend=e;const t=e.view?.width??0,i=e.view?.height??0,n=e.view?.center?.x??t/2,r=e.view?.center?.y??i/2;this._view=ci.from({center:{x:n,y:r},size:{width:t,height:i}}),this._screenView=new ci(n,r,t,i)}get view(){return this._view}set view(e){const t=this._view;this._view=e,t!==e&&t.destroy()}get screenView(){return this._screenView}trackView(e){this._trackedViews.add(e)}untrackView(e){this._trackedViews.delete(e)}update(e){const t=e.milliseconds;this._view.update(t);for(const e of this._trackedViews)e!==this._view&&e.update(t);for(const e of this._renderedViews)e===this._view||this._trackedViews.has(e)||e.update(t);this._renderedViews.clear()}destroy(){this._view.destroy(),this._screenView.destroy(),this._trackedViews.clear(),this._renderedViews.clear(),this._immediateMesh?.destroy(),this._immediateMesh=null,this._batchMesh?.destroy(),this._batchMesh=null}resize(e,t){this._view.resize(e,t),this._screenView.resize(e,t),this._screenView.setCenter(e/2,t/2)}render(e,t={}){const i=t.view??this._view;this._renderedViews.add(i),this._backend.setView(i),wi(e,this._backend)}capture(e,t){const i=new _i(t.width,t.height),n=new ci(t.width/2,t.height/2,t.width,t.height),r=this._backend._passCoordinator;if(r)return r.withChildPass({target:i,view:n,load:void 0!==t.clearColor?"clear":"load",clearColor:t.clearColor??null,stencil:xi.None},()=>{wi(e,this._backend)}),i;const s=this._backend.renderTarget,o=this._backend.view;this._backend.setRenderTarget(i),this._backend.setView(n),void 0!==t.clearColor&&this._backend.clear(t.clearColor);try{wi(e,this._backend)}finally{this._backend.setRenderTarget(s),this._backend.setView(o)}return i}clear(e){const t=this._backend._passCoordinator;t?t.withChildPass({target:t.activeTarget,view:t.activeView,load:"clear",clearColor:e,stencil:xi.None},()=>{}):this._backend.clear(e)}renderTo(e,t){const i=t.view??t.target.view;this._renderedViews.add(i);const n=this._backend._passCoordinator;if(n)return void n.withChildPass({target:t.target,view:i,load:void 0!==t.clear?"clear":"load",clearColor:t.clear??null,stencil:xi.None},()=>{wi(e,this._backend)});const r=this._backend.renderTarget,s=this._backend.view;this._backend.setRenderTarget(t.target),this._backend.setView(i),void 0!==t.clear&&this._backend.clear(t.clear);try{wi(e,this._backend)}finally{this._backend.setRenderTarget(r),this._backend.setView(s)}}drawGeometry(e,t,i={}){const n=i.material??null;if(null!==n&&"mesh"!==n.target)throw new Error(`drawGeometry material must target 'mesh' (got '${String(n.target)}').`);const r=i.view??this._view;this._renderedViews.add(r);const s=this._immediateMesh??=new js;this._backend.setView(r),s.configure(e,t,n,i.tint??null),this._backend.draw(s),this._backend.flush()}drawBatch(e,t={}){if(null!==e.material)throw new Error("drawBatch custom materials are not supported yet — v1 renders batches with the default mesh material.");if(0===e.count)return;const i=t.view??this._view;this._renderedViews.add(i);const n=this._batchMesh??=new js;this._backend.setView(i),n.configureBatchSource(e.geometry,e.material),this._backend.drawInstanced(n,e._instanceTransforms,e._instanceTints,e.count),this._backend.flush()}get stats(){return this._backend.stats}get backend(){return this._backend}}class Js{_stats;_liveBytes=0;constructor(e){this._stats=e,this._stats.gpuMemoryBytes=0}get liveBytes(){return this._liveBytes}allocate(e){e<=0||(this._liveBytes+=e,this._stats.gpuMemoryBytes=this._liveBytes)}free(e){e<=0||(this._liveBytes=Math.max(0,this._liveBytes-e),this._stats.gpuMemoryBytes=this._liveBytes)}reallocate(e,t){return this.free(e),this.allocate(t),t}recordTextureUpload(e){e<=0||(this._stats.textureUploadBytes+=e)}recordBufferUpload(e){e<=0||(this._stats.bufferUploadBytes+=e)}recordDownload(e){e<=0||(this._stats.downloadBytes+=e,this._stats.downloadCount++)}}const eo=(e,t,i,n=1)=>{const r=Math.max(1,Math.floor(e)),s=Math.max(1,Math.floor(t)),o=Math.max(1,Math.floor(n));let a=0,h=r,l=s;for(let e=0;e<o&&(a+=h*l*i,1!==h||1!==l);e++)h=Math.max(1,h>>1),l=Math.max(1,l>>1);return a},to=e=>{switch(e){case"r8":return 1;case"r32f":case"rgba8":return 4;case"rgba32f":return 16}};class io{_entries=new Map;_walk;_dispose;constructor(e={}){this._walk=e.walk??null,this._dispose=e.dispose??null}set(e,t){this._entries.set(e,t)}hasOwn(e){return this._entries.has(e)}has(e){return void 0!==this._find(e)}resolve(e){return this._find(e)}values(){return this._entries.values()}destroy(){if(null!==this._dispose){const e=new Set;for(const t of this._entries.values())e.has(t)||(e.add(t),this._dispose(t))}this._entries.clear()}_find(e){let t,i=e;for(;null!==i&&void 0===t;)t=this._entries.get(i),void 0===t&&(i=null!==this._walk?this._walk(i):null);return t}}const no=e=>{const t=Object.getPrototypeOf(e.prototype);return t?.constructor??null};class ro{_renderers=new io({walk:no,dispose:e=>{e.disconnect(),"destroy"in e&&"function"==typeof e.destroy&&e.destroy()}});_resolved=new Map;_backend=null;registerRenderer(e,t){if(this._renderers.hasOwn(e))throw new Error(`A renderer is already registered for ${e.name}.`);this._renderers.set(e,t),this._resolved.clear(),null!==this._backend&&t.connect(this._backend)}bindRenderer(e,t){if(0===e.length)throw new Error("A RendererBinding must declare at least one target.");const i=new Set;for(const t of e){if(i.has(t))throw new Error(`A RendererBinding declares the same target ${t.name} more than once.`);i.add(t)}for(const t of e)if(this._renderers.hasOwn(t))throw new Error(`A renderer is already registered for ${t.name}.`);for(const i of e)this._renderers.set(i,t);this._resolved.clear(),null!==this._backend&&t.connect(this._backend)}renderers(){return this._renderers.values()}resolve(e){const t=e.constructor,i=this._resolved.get(t);if(void 0!==i)return i;const n=this._renderers.resolve(t);if(!n)throw new Error(`No renderer registered for ${e.constructor.name}. If it comes from an ExoJS extension, import that package before creating the Application, or pass the extension via ApplicationOptions.extensions.`);return this._resolved.set(t,n),n}connect(e){this._backend=e;for(const t of this._renderers.values())t.connect(e)}disconnect(){for(const e of this._renderers.values())e.disconnect();this._backend=null}destroy(){this._renderers.destroy(),this._resolved.clear(),this._backend=null}}const so=new Float32Array(1),oo=new Uint32Array(so.buffer);class ao{_data=new Float32Array(192);_count=0;_version=0;_frameHash=2166136261;_lastCommittedHash=0;_lastCommittedCount=-1;_writeCount=0;_skippedWriteCount=0;_uploadCount=0;_uploadedRecordCount=0;_dirtyMin=0;_dirtyMax=-1;get count(){return this._count}get writeCount(){return this._writeCount}get skippedWriteCount(){return this._skippedWriteCount}get uploadCount(){return this._uploadCount}get uploadedRecordCount(){return this._uploadedRecordCount}get capacity(){return this._data.length/12}get data(){return this._data}get version(){return this._version}get frameHash(){return this._frameHash}begin(e=0){return e>0&&this._ensureCapacity(e),this._count=0,this._frameHash=2166136261,this._writeCount=0,this._skippedWriteCount=0,this._uploadCount=0,this._uploadedRecordCount=0,this._dirtyMin=0,this._dirtyMax=-1,this}push(e,t){const i=this._count;return this.write(i,e,t),i}rewindTo(e,t){return e>=0&&e<this._count&&(this._count=e,void 0!==t&&(this._frameHash=t>>>0)),this}consumeDirtyRange(e){if(this._dirtyMax<this._dirtyMin)return{firstRow:0,rowCount:0};const t=Math.max(0,this._dirtyMin),i=Math.min(this._dirtyMax,e-1),n=i>=t?i-t+1:0;return this._dirtyMin=0,this._dirtyMax=-1,{firstRow:t,rowCount:n}}write(e,t,i){if(!Number.isInteger(e)||e<0)throw new Error(`TransformBuffer slot must be a non-negative integer (got ${e}).`);this._ensureCapacity(e+1);const n=12*e,r=this._data;r[n+0]=t.a,r[n+1]=t.b,r[n+2]=t.c,r[n+3]=t.d,r[n+4]=t.x,r[n+5]=t.y,r[n+6]=0,r[n+7]=0,r[n+8]=i.r/255,r[n+9]=i.g/255,r[n+10]=i.b/255,r[n+11]=i.a,e>=this._count&&(this._count=e+1),this._dirtyMax<this._dirtyMin?(this._dirtyMin=e,this._dirtyMax=e):(e<this._dirtyMin&&(this._dirtyMin=e),e>this._dirtyMax&&(this._dirtyMax=e)),this._frameHash=this._mix(this._frameHash,e);for(let e=0;e<12;e++)this._frameHash=this._mix(this._frameHash,this._hashFloat(r[n+e]));return this._writeCount++,this}recordSkippedWrite(){return this._skippedWriteCount++,this}recordUpload(e){return this._uploadCount++,this._uploadedRecordCount+=e,this}commitSnapshot(e=0){const t=Math.max(this._count,e),i=this._mix(this._frameHash,t),n=i!==this._lastCommittedHash||t!==this._lastCommittedCount;return n&&(this._version++,this._lastCommittedHash=i,this._lastCommittedCount=t),{count:t,hash:i,changed:n,version:this._version}}_ensureCapacity(e){const t=this.capacity;if(e<=t)return;let i=Math.max(t,16);for(;i<e;)i*=2;const n=new Float32Array(12*i);n.set(this._data),this._data=n}_hashFloat(e){return so[0]=e,oo[0]>>>0}_mix(e,t){return Math.imul((e^t)>>>0,16777619)>>>0}}const ho=new Uint16Array([0,1,2,0,2,3]);class lo{_shader=new Yr("#version 300 es\nprecision mediump float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\n\nuniform mat3 u_projection;\n\nout vec2 v_texcoord;\n\nvoid main(void) {\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n}\n","#version 300 es\nprecision highp float;\n\n// Backdrop-aware blend compositor (advanced blend modes).\n//\n// Samples the premultiplied source (the drawable rendered to a texture) and the\n// captured premultiplied backdrop (the target contents behind it), computes the\n// W3C blend B(Cb, Cs) for the requested mode, and outputs the blended source\n// premultiplied by its own alpha. The caller draws this with normal\n// (premultiplied source-over) blending, so the GPU composites it over the\n// untouched backdrop already in the target — transparent source regions\n// (alpha 0) leave the backdrop showing through instead of going black.\n//\n// Mode values match the BlendModes enum (src/rendering/types.ts).\n\nuniform sampler2D u_source;\nuniform sampler2D u_backdrop;\nuniform int u_mode;\n// 1.0 when the target is opaque (the on-screen root canvas), whose captured\n// alpha is unreliable — an opaque framebuffer reports backdrop alpha 0, which\n// would make the blend ignore the backdrop. Forces backdrop coverage to full.\nuniform float u_opaqueBackdrop;\n\nin vec2 v_texcoord;\n\nlayout(location = 0) out vec4 fragColor;\n\nconst int MODE_MULTIPLY = 3;\nconst int MODE_SCREEN = 4;\nconst int MODE_DARKEN = 5;\nconst int MODE_LIGHTEN = 6;\nconst int MODE_OVERLAY = 7;\nconst int MODE_COLOR_DODGE = 8;\nconst int MODE_COLOR_BURN = 9;\nconst int MODE_HARD_LIGHT = 10;\nconst int MODE_SOFT_LIGHT = 11;\nconst int MODE_DIFFERENCE = 12;\nconst int MODE_EXCLUSION = 13;\nconst int MODE_HUE = 14;\nconst int MODE_SATURATION = 15;\nconst int MODE_COLOR = 16;\n\nvec3 unpremultiply(vec4 color) {\n return color.a > 0.0 ? color.rgb / color.a : vec3(0.0);\n}\n\n// W3C separable blend B(Cb, Cs) for one channel (straight color in [0, 1]).\nfloat blendChannel(int mode, float cb, float cs) {\n if (mode == MODE_MULTIPLY) {\n return cb * cs;\n }\n if (mode == MODE_SCREEN) {\n return cb + cs - cb * cs;\n }\n if (mode == MODE_DARKEN) {\n return min(cb, cs);\n }\n if (mode == MODE_LIGHTEN) {\n return max(cb, cs);\n }\n if (mode == MODE_OVERLAY) {\n return cb <= 0.5 ? (2.0 * cb * cs) : (1.0 - 2.0 * (1.0 - cb) * (1.0 - cs));\n }\n if (mode == MODE_HARD_LIGHT) {\n return cs <= 0.5 ? (2.0 * cb * cs) : (1.0 - 2.0 * (1.0 - cb) * (1.0 - cs));\n }\n if (mode == MODE_COLOR_DODGE) {\n if (cb <= 0.0) {\n return 0.0;\n }\n return cs >= 1.0 ? 1.0 : min(1.0, cb / (1.0 - cs));\n }\n if (mode == MODE_COLOR_BURN) {\n if (cb >= 1.0) {\n return 1.0;\n }\n return cs <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - cb) / cs);\n }\n if (mode == MODE_SOFT_LIGHT) {\n if (cs <= 0.5) {\n return cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb);\n }\n float d = cb <= 0.25 ? (((16.0 * cb - 12.0) * cb + 4.0) * cb) : sqrt(cb);\n return cb + (2.0 * cs - 1.0) * (d - cb);\n }\n if (mode == MODE_DIFFERENCE) {\n return abs(cb - cs);\n }\n if (mode == MODE_EXCLUSION) {\n return cb + cs - 2.0 * cb * cs;\n }\n return min(cb, cs); // default: Darken\n}\n\nvec3 blendSeparable(int mode, vec3 cb, vec3 cs) {\n return vec3(blendChannel(mode, cb.r, cs.r), blendChannel(mode, cb.g, cs.g), blendChannel(mode, cb.b, cs.b));\n}\n\n// Non-separable helpers (W3C): operate on the whole color.\nfloat lum(vec3 c) {\n return dot(c, vec3(0.3, 0.59, 0.11));\n}\n\nvec3 clipColor(vec3 c) {\n float l = lum(c);\n float n = min(min(c.r, c.g), c.b);\n float x = max(max(c.r, c.g), c.b);\n\n if (n < 0.0) {\n c = l + ((c - l) * l) / (l - n);\n }\n if (x > 1.0) {\n c = l + ((c - l) * (1.0 - l)) / (x - l);\n }\n\n return c;\n}\n\nvec3 setLum(vec3 c, float l) {\n return clipColor(c + (l - lum(c)));\n}\n\nfloat sat(vec3 c) {\n return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b);\n}\n\n// Map the channels so min → 0, max → s, mid → proportional (W3C SetSat result).\nvec3 setSat(vec3 c, float s) {\n float mn = min(min(c.r, c.g), c.b);\n float mx = max(max(c.r, c.g), c.b);\n\n return mx > mn ? (c - mn) * (s / (mx - mn)) : vec3(0.0);\n}\n\nvec3 blendNonSeparable(int mode, vec3 cb, vec3 cs) {\n if (mode == MODE_HUE) {\n return setLum(setSat(cs, sat(cb)), lum(cb));\n }\n if (mode == MODE_SATURATION) {\n return setLum(setSat(cb, sat(cs)), lum(cb));\n }\n if (mode == MODE_COLOR) {\n return setLum(cs, lum(cb));\n }\n return setLum(cb, lum(cs)); // default: Luminosity\n}\n\nvec3 blendAdvanced(int mode, vec3 cb, vec3 cs) {\n return mode >= MODE_HUE ? blendNonSeparable(mode, cb, cs) : blendSeparable(mode, cb, cs);\n}\n\nvoid main(void) {\n vec4 src = texture(u_source, v_texcoord);\n // The backdrop is captured from the framebuffer (bottom-left origin), so its\n // V axis is flipped relative to the source/quad UVs.\n vec4 dst = texture(u_backdrop, vec2(v_texcoord.x, 1.0 - v_texcoord.y));\n\n float alphaSource = src.a;\n float alphaBackdrop = max(dst.a, u_opaqueBackdrop);\n vec3 colorSource = unpremultiply(src);\n vec3 colorBackdrop = unpremultiply(dst);\n\n vec3 blended = blendAdvanced(u_mode, colorBackdrop, colorSource);\n // Cs' = (1 - αb)·Cs + αb·B(Cb, Cs)\n vec3 mixedSource = mix(colorSource, blended, alphaBackdrop);\n\n // Premultiplied blended source; GPU source-over composites it over backdrop.\n fragColor = vec4(mixedSource * alphaSource, alphaSource);\n}\n");_vertexData=new ArrayBuffer(64);_float32View=new Float32Array(this._vertexData);_sourceSamplerSlot=new Int32Array([0]);_backdropSamplerSlot=new Int32Array([1]);_modeValue=new Int32Array([0]);_opaqueValue=new Float32Array([0]);_connection=null;connect(t){if(null!==this._connection)return;const i=t.context,n=i.createVertexArray();if(null===n)throw new Error("WebGl2BackdropBlendCompositor: could not create vertex array object.");this._shader.connect(ts(i));const r=new Map,s=new Hr(e.BufferTypes.ElementArrayBuffer,ho,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(i,r)),o=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,r));this._shader.sync();const a=(new ns).addIndex(s).addAttribute(o,this._shader.getAttribute("a_position"),i.FLOAT,!1,16,0).addAttribute(o,this._shader.getAttribute("a_texcoord"),i.FLOAT,!1,16,8).connect(this._createVaoRuntime(i,n));this._connection={gl:i,vaoHandle:n,vao:a,indexBuffer:s,vertexBuffer:o,bufferHandles:r}}disconnect(){const e=this._connection;null!==e&&(e.indexBuffer.destroy(),e.vertexBuffer.destroy(),e.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(e,t,i,n,r,s,o){if(null===this._connection)throw new Error("WebGl2BackdropBlendCompositor: not connected.");if(r<=0||s<=0)return;const a=e.context,h=e.renderTarget,l=h.root&&h.width>0?a.drawingBufferWidth/h.width:1,u=h.root&&h.height>0?a.drawingBufferHeight/h.height:1,c=Math.max(0,Math.floor(i*l)),d=Math.max(0,Math.floor(a.drawingBufferHeight-(n+s)*u)),_=e.acquireRenderTexture(r,s),f=Math.min(_.width,Math.max(0,Math.round(r*l))),p=Math.min(_.height,Math.max(0,Math.round(s*u))),m=h.root&&!a.getContextAttributes()?.alpha;try{a.bindFramebuffer(a.READ_FRAMEBUFFER,e._renderTargetFramebuffer(h)),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e._renderTargetFramebuffer(_)),a.blitFramebuffer(c,d,c+f,d+p,0,0,f,p,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,null),e._rebindActiveTarget(),this._drawBlend(e,t,_,i,n,r,s,o,m)}finally{e.releaseRenderTexture(_)}}_drawBlend(t,i,n,r,s,o,a,h,l){const u=this._connection;if(null===u)throw new Error("WebGl2BackdropBlendCompositor: not connected.");this._writeQuadVertices(r,s,r+o,s+a),t.bindShader(this._shader);const c=t.view.getTransform().toArray(!1);this._modeValue[0]=h,this._opaqueValue[0]=l?1:0,this._shader.getUniform("u_projection").setValue(c),this._shader.getUniform("u_source").setValue(this._sourceSamplerSlot),this._shader.getUniform("u_backdrop").setValue(this._backdropSamplerSlot),this._shader.getUniform("u_mode").setValue(this._modeValue),this._shader.getUniform("u_opaqueBackdrop").setValue(this._opaqueValue),this._shader.sync(),t.bindTexture(i,0),t.bindTexture(n,1),t.setBlendMode(e.BlendModes.Normal),t.bindVertexArrayObject(u.vao),u.vertexBuffer.upload(this._float32View),u.vao.draw(6,0),t.stats.batches++,t.stats.drawCalls++,t.bindTexture(null,1)}_writeQuadVertices(e,t,i,n){const r=this._float32View;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("WebGl2BackdropBlendCompositor: could not create render buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:n=>{const r=n.data;e.bindBuffer(n.type,i),e.bufferData(n.type,r,n.usage),t.set(n,i)},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}const uo=new Uint16Array([0,1,2,0,2,3]);class co{_shader=new Yr("#version 300 es\nprecision lowp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\n\nuniform mat3 u_projection;\n\nout vec2 v_texcoord;\n\nvoid main(void) {\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n}\n","#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_content;\nuniform sampler2D u_mask;\n\nin vec2 v_texcoord;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 contentColor = texture(u_content, v_texcoord);\n float maskAlpha = texture(u_mask, v_texcoord).a;\n\n fragColor = vec4(contentColor.rgb * maskAlpha, contentColor.a * maskAlpha);\n}\n");_vertexData=new ArrayBuffer(64);_float32View=new Float32Array(this._vertexData);_contentSamplerSlot=new Int32Array([0]);_maskSamplerSlot=new Int32Array([1]);_connection=null;connect(t){if(null!==this._connection)return;const i=t.context,n=i.createVertexArray();if(null===n)throw new Error("WebGl2MaskCompositor: could not create vertex array object.");this._shader.connect(ts(i));const r=new Map,s=new Hr(e.BufferTypes.ElementArrayBuffer,uo,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(i,r),t.accountant),o=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,r),t.accountant);this._shader.sync();const a=(new ns).addIndex(s).addAttribute(o,this._shader.getAttribute("a_position"),i.FLOAT,!1,16,0).addAttribute(o,this._shader.getAttribute("a_texcoord"),i.FLOAT,!1,16,8).connect(this._createVaoRuntime(i,n));this._connection={gl:i,vaoHandle:n,vao:a,indexBuffer:s,vertexBuffer:o,bufferHandles:r}}disconnect(){const e=this._connection;null!==e&&(e.indexBuffer.destroy(),e.vertexBuffer.destroy(),e.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(e,t,i,n,r,s,o,a){const h=this._connection;if(null===h)throw new Error("WebGl2MaskCompositor: not connected.");this._writeQuadVertices(n,r,n+s,r+o),e.bindShader(this._shader);const l=e.view.getTransform().toArray(!1);this._shader.getUniform("u_projection").setValue(l),this._shader.getUniform("u_content").setValue(this._contentSamplerSlot),this._shader.getUniform("u_mask").setValue(this._maskSamplerSlot),this._shader.sync(),e.bindTexture(t,0),e.bindTexture(i,1),e.setBlendMode(a),e.bindVertexArrayObject(h.vao),h.vertexBuffer.upload(this._float32View),h.vao.draw(6,0),e.stats.batches++,e.stats.drawCalls++,e.bindTexture(null,1)}_writeQuadVertices(e,t,i,n){const r=this._float32View;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("WebGl2MaskCompositor: could not create render buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:n=>{const r=n.data;e.bindBuffer(n.type,i),e.bufferData(n.type,r,n.usage),t.set(n,i)},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}class _o{_backend;_stencilEnabled=!1;constructor(e){this._backend=e}get activeTarget(){return this._backend.renderTarget}get activeView(){return this._backend.view}hasActivePass=!0;beginPass(e){this._backend.setRenderTarget(e.target),this._backend.setView(e.view),this._stencilEnabled=e.stencil===xi.Enabled,"clear"===e.load&&this._backend.clear(e.clearColor??void 0)}endPass(){this._backend.flush()}withChildPass(e,t){const i=this._backend.renderTarget,n=this._backend.view,r=this._stencilEnabled;this.beginPass(e);try{t()}finally{this._backend.setRenderTarget(i),this._backend.setView(n),this._stencilEnabled=r}}pushScissorRect(e){this._backend.pushScissorRect(e)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(e,t){this._backend.pushStencilClip(e,t)}popStencilClip(){this._backend.popStencilClip()}resolveLoad(e,t){return t?"clear":"load"}}const fo=new Set(["a_position","position"]);class po{_shader=new Yr("#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\n\nuniform mat3 u_matrix;\n\nvoid main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n}\n","#version 300 es\nprecision lowp float;\n\nlayout(location = 0) out vec4 fragColor;\n\n// Color writes are masked off while the stencil silhouette is drawn, so this\n// output is discarded; it exists only to make the program link.\nvoid main(void) {\n fragColor = vec4(0.0);\n}\n");_matrix=new At;_positions=new Float32Array(64);_connection=null;connect(t){if(null!==this._connection)return;const i=t.context,n=i.createVertexArray();if(null===n)throw new Error("WebGl2StencilClipper: could not create vertex array object.");this._shader.connect(ts(i)),this._shader.sync();const r=new Hr(e.BufferTypes.ArrayBuffer,this._positions,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i),t.accountant),s=new ns(e.RenderingPrimitives.Triangles).addAttribute(r,this._shader.getAttribute("a_position"),i.FLOAT,!1,8,0).connect(this._createVaoRuntime(i,n));this._connection={gl:i,vao:s,vertexBuffer:r}}disconnect(){const e=this._connection;null!==e&&(e.vertexBuffer.destroy(),e.vao.destroy(),this._shader.disconnect(),this._connection=null)}draw(t,i,n){const r=this._connection;if(null===r)throw new Error("WebGl2StencilClipper: not connected.");const s=this._extractPositions(i);if(0===s)return;this._matrix.copy(n).combine(t.view.getTransform()),t.bindShader(this._shader),this._shader.getUniform("u_matrix").setValue(this._matrix.toArray(!1)),this._shader.sync(),t.bindVertexArrayObject(r.vao),r.vertexBuffer.upload(this._positions.subarray(0,2*s));const o="triangle-strip"===i.topology?e.RenderingPrimitives.TriangleStrip:e.RenderingPrimitives.Triangles;r.vao.draw(s,0,o),t.stats.drawCalls++}_extractPositions(e){const t=this._resolvePositionAttribute(e.attributes);if("f32"!==t.type)throw new Error(`Stencil clipShape position attribute "${t.name}" must be of type f32 (got "${t.type}").`);const{stride:i,vertexData:n,indices:r}=e,s=n instanceof Float32Array?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),o=null!==r?r.length:e.vertexCount;this._ensureCapacity(o);const a=this._positions;for(let e=0;e<o;e++){const n=(null!==r?r[e]:e)*i+t.offset;a[2*e]=s.getFloat32(n,!0),a[2*e+1]=s.getFloat32(n+4,!0)}return o}_resolvePositionAttribute(e){const t=e.find(e=>fo.has(e.name));if(t)return t;const i=e.find(e=>e.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensureCapacity(e){const t=2*e;this._positions.length<t&&(this._positions=new Float32Array(Math.max(t,2*this._positions.length)))}_createBufferRuntime(e){const t=e.createBuffer();if(null===t)throw new Error("WebGl2StencilClipper: could not create render buffer.");return{bind:i=>{e.bindBuffer(i.type,t)},upload:i=>{e.bindBuffer(i.type,t),e.bufferData(i.type,i.data,i.usage)},destroy:i=>{e.deleteBuffer(t),i.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}class mo{backendType=e.RenderBackendType.WebGl2;rendererRegistry=new ro;onContextLost=new x;onContextRestored=new x;_context;_rootRenderTarget;_onContextLostHandler;_onContextRestoredHandler;_textureStates=new Map;_renderTargetStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_clipBoundsStack=[];_clipPixelStack=[];_clipPointA=new it;_clipPointB=new it;_maskCompositor=new co;_maskCompositorConnected=!1;_backdropBlendCompositor=new lo;_backdropBlendCompositorConnected=!1;_stencilClipper=new po;_stencilStates=new Map;_stencilClipperConnected=!1;_passCoordinatorInstance=null;_canvas;_contextLost;_renderTarget;_snapTransform=new At;_renderer=null;_shader=null;_blendMode=null;_texture=null;_textureUnit=0;_vao=null;_clearColor=new Tt;_boundFramebuffer=null;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0,rawFrameDeltaMs:0,gpuMemoryBytes:0,textureUploadBytes:0,bufferUploadBytes:0,downloadBytes:0,downloadCount:0};_accountant=new Js(this._stats);_transformBuffer=new ao;_transformTexture=null;_transformTextureHash=0;_transformTextureCount=-1;_activeDrawCommand=null;_drawPlanDepth=0;_planBaseStack=[];_planHashStack=[];constructor(t){const i=t.options.canvas??{},n=t.options.rendering??{},r=i.width??800,s=i.height??600,o=t.options.clearColor,a=n.webglAttributes;n.debug,this._canvas=t.canvas;const h=this._createContext(a);if(!h)throw new Error("This browser or hardware does not support WebGL.");this._context=h,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),o&&this.clearColor.copy(o),this._rootRenderTarget=new di(r,s,!0),this._renderTarget=this._rootRenderTarget,this._onContextLostHandler=this._onContextLost.bind(this),this._onContextRestoredHandler=this._onContextRestored.bind(this),this._setupContext(),this._addEvents(),this.rendererRegistry.connect(this),this._bindRenderTarget(this._renderTarget),this.setBlendMode(e.BlendModes.Normal),this.resize(r,s)}get context(){return this._context}get renderTarget(){return this._renderTarget}get view(){return this._renderTarget.view}get clearColor(){return this._clearColor}get stats(){return this._stats}get accountant(){return this._accountant}get activeDrawCommand(){return this._activeDrawCommand}get _passCoordinator(){return this._passCoordinatorInstance??=new _o(this)}async initialize(){return this}resetStats(){return Qs(this._stats),this._transformBuffer.begin(),this}get transformBufferCount(){return this._transformBuffer.count}_beginDrawPlan(e){this._planBaseStack.push(this._transformBuffer.count),this._planHashStack.push(this._transformBuffer.frameHash),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(e,t,i){const n=t+i;for(let i=t;i<n;i++){const t=e[i];if(t.kind!==Yt.Draw)continue;const n=t.command;ii(n,this)?this._writeTransformCommand(n):this._transformBuffer.recordSkippedWrite()}}_prepareDrawCommand(e){this._activeDrawCommand=e}_writeTransformCommand(e){const t=e.drawable;this._transformBuffer.write(e.nodeIndex,this._resolveSnapTransform(t),t.tint)}_resolveSnapTransform(e){const t=this._renderTarget,i=t.root?this._canvas.width:t.width,n=t.root?this._canvas.height:t.height;return kn(e,t.view,i,n,this._snapTransform)}_getSnapPixelSize(){const e=this._renderTarget;return{width:e.root?this._canvas.width:e.width,height:e.root?this._canvas.height:e.height}}_pushTransform(e){return this._transformBuffer.push(this._resolveSnapTransform(e),e.tint)}_endDrawPlan(){this._activeDrawCommand=null;const e=this._planBaseStack.pop()??0,t=this._planHashStack.pop()??0;this._drawPlanDepth>0&&this._drawPlanDepth--,this._drawPlanDepth>0&&(this._flushActiveRenderer(),this._transformBuffer.rewindTo(e,t)),0===this._drawPlanDepth&&this._assertBalancedStencil()}_assertBalancedStencil(){let e=0;for(const t of this._stencilStates.values())e+=t.stack.length;if(0===e)return;for(const e of this._stencilStates.values())e.depth=0,e.stack.length=0;const t=this._context;throw t.stencilFunc(t.ALWAYS,0,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.disable(t.STENCIL_TEST),new Error(`Unbalanced stencil clip stack at end of frame (${e} unpopped clip(s)).`)}draw(e){const t=this.rendererRegistry.resolve(e);return this._setActiveRenderer(t),t.render(e),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(e,t,i,n){if(n<=0||0===e.vertexCount)return this;if(t.length<n||i.length<n)throw new Error(`drawInstanced requires ${n} transforms and tints (got ${t.length}/${i.length}).`);const r=this.rendererRegistry.resolve(e);if(!(r instanceof ss))throw new Error("drawInstanced requires a mesh handled by the WebGL2 mesh renderer.");this._setActiveRenderer(r);const s=this._transformBuffer.push(t[0],i[0]);for(let e=1;e<n;e++)this._transformBuffer.push(t[e],i[e]);return r.drawInstancedBatch(e,s,n),this._activeDrawCommand=null,this._stats.submittedNodes+=n,this}execute(e){return this._flushActiveRenderer(),this._stats.renderPasses++,e.execute(this),this}setRenderTarget(e){const t=e||this._rootRenderTarget,i=this._renderTarget!==t;return i&&(this._flushActiveRenderer(),this._renderTarget=t,this._stats.renderTargetChanges++),this._bindRenderTarget(t),i&&this._applyStencilState(t),this}pushScissorRect(e){this._flushActiveRenderer(),this._clipBoundsStack.push(e.clone());const t=this._toClipPixels(e),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,n=i?this._intersectClips(i,t):t;return this._clipPixelStack.push(n),this._applyClipState(),this}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const e=this._clipBoundsStack.pop();return e&&e.destroy(),this._clipPixelStack.pop(),this._applyClipState(),this}pushStencilClip(e,t){const i=this._renderTarget,n=this._getStencilState(i);if(n.depth>=255)throw new Error("Stencil clip nesting exceeds the 255-level limit.");this._flushActiveRenderer(),this._setActiveRenderer(null),this._stencilClipperConnected||(this._stencilClipper.connect(this),this._stencilClipperConnected=!0);const r=this._context,s=n.depth;return 0===s&&(this._ensureTargetStencil(),r.enable(r.STENCIL_TEST),r.disable(r.SCISSOR_TEST),r.clearStencil(0),r.clear(r.STENCIL_BUFFER_BIT),this._applyClipState()),r.colorMask(!1,!1,!1,!1),r.stencilFunc(r.EQUAL,s,255),r.stencilOp(r.KEEP,r.KEEP,r.INCR),this._stencilClipper.draw(this,e,t),r.colorMask(!0,!0,!0,!0),n.depth=s+1,n.stack.push({shape:e,transform:(new At).copy(t)}),r.stencilFunc(r.EQUAL,n.depth,255),r.stencilOp(r.KEEP,r.KEEP,r.KEEP),this}popStencilClip(){const e=this._renderTarget,t=this._getStencilState(e),i=t.stack.pop();if(void 0===i)return this;this._flushActiveRenderer(),this._setActiveRenderer(null);const n=this._context,r=t.depth;return n.colorMask(!1,!1,!1,!1),n.stencilFunc(n.EQUAL,r,255),n.stencilOp(n.KEEP,n.KEEP,n.DECR),this._stencilClipper.draw(this,i.shape,i.transform),n.colorMask(!0,!0,!0,!0),t.depth=r-1,this._applyStencilState(e),this}composeWithAlphaMask(e,t,i,n,r,s,o){return r<=0||s<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._maskCompositorConnected||(this._maskCompositor.connect(this),this._maskCompositorConnected=!0),this._maskCompositor.compose(this,e,t,i,n,r,s,o)),this}composeWithBackdropBlend(e,t,i,n,r,s){return n<=0||r<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._backdropBlendCompositorConnected||(this._backdropBlendCompositor.connect(this),this._backdropBlendCompositorConnected=!0),this._backdropBlendCompositor.compose(this,e,t,i,n,r,s)),this}_renderTargetFramebuffer(e){return this._prepareRenderTarget(e).framebuffer}_rebindActiveTarget(){this._bindRenderTarget(this._renderTarget)}acquireRenderTexture(e,t){for(let i=0;i<this._temporaryRenderTextures.length;i++){const n=this._temporaryRenderTextures[i];if(n.width===e&&n.height===t)return this._temporaryRenderTextures.splice(i,1),n}return new _i(e,t)}releaseRenderTexture(e){return this._temporaryRenderTextures.includes(e)||(e.setView(null),this._temporaryRenderTextures.push(e)),this}setView(e){return this._renderTarget.view!==e&&this._flushActiveRenderer(),this._renderTarget.setView(e),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(e){return this._vao!==e&&(e?e.bind():this._vao?.unbind(),this._vao=e),this}bindShader(e){return this._shader!==e&&(this._shader&&(this._shader.unbind(),this._shader=null),e&&e.bind(),this._shader=e),this}bindTexture(e,t){if(void 0!==t&&this._setTextureUnit(t),null===e)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(e);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=e,this}setActiveTextureUnit(e){return this._setTextureUnit(e),this}bindTransformBufferTexture(e,t){const i=Math.max(1,t),n=this._transformTexture;n?.height===this._transformBuffer.capacity&&n.buffer===this._transformBuffer.data||(n?.destroy(),this._transformTexture=new kr({width:3,height:this._transformBuffer.capacity,format:"rgba32f",data:this._transformBuffer.data}),this._transformTextureHash=0,this._transformTextureCount=-1);const r=this._transformBuffer.commitSnapshot(i),s=this._transformTexture;if(null===s)throw new Error("Transform texture must be initialized before binding.");if(r.changed||r.count!==this._transformTextureCount||r.hash!==this._transformTextureHash){const{firstRow:e,rowCount:t}=this._transformBuffer.consumeDirtyRange(r.count);t>0&&(s.commitRect(0,e,3,t),this._transformBuffer.recordUpload(t)),this._transformTextureCount=r.count,this._transformTextureHash=r.hash}return this.bindTexture(s,e)}setBlendMode(t){if(t!==this._blendMode){const i=this._context;switch(this._blendMode=t,t){case e.BlendModes.Additive:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ONE);break;case e.BlendModes.Subtract:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ZERO,i.ONE_MINUS_SRC_COLOR);break;case e.BlendModes.Multiply:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA);break;case e.BlendModes.Screen:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_COLOR);break;default:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(e){if(this._textureUnit!==e){const t=this._context;this._textureUnit=e,t.activeTexture(t.TEXTURE0+e)}}setClearColor(e){if(!this._clearColor.equals(e)){const t=this._context;this._clearColor.copy(e),t.clearColor(e.r/255,e.g/255,e.b/255,e.a)}return this}clear(e){const t=this._context;return e&&this.setClearColor(e),this._bindRenderTarget(this._renderTarget),t.clear(t.COLOR_BUFFER_BIT),this}resize(e,t){return this._rootRenderTarget.resize(e,t),this._bindRenderTarget(this._renderTarget),this}flush(){return this._flushActiveRenderer(),this}destroy(){this._removeEvents(),this.onContextLost.destroy(),this.onContextRestored.destroy(),this.setRenderTarget(null),this._setActiveRenderer(null),this.bindVertexArrayObject(null),this.bindShader(null),this.bindTexture(null),this.rendererRegistry.destroy(),this._clearColor.destroy(),this._destroyManagedResources(),this._destroyTemporaryRenderTextures();for(const e of this._clipBoundsStack)e.destroy();this._clipBoundsStack.length=0,this._clipPixelStack.length=0,this._clipPointA.destroy(),this._clipPointB.destroy(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._backdropBlendCompositorConnected&&(this._backdropBlendCompositor.disconnect(),this._backdropBlendCompositorConnected=!1),this._stencilClipperConnected&&(this._stencilClipper.disconnect(),this._stencilClipperConnected=!1),this._stencilStates.clear(),this._drawPlanDepth=0,this._rootRenderTarget.destroy(),null!==this._transformTexture&&(this._transformTexture.destroy(),this._transformTexture=null),this._vao=null,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._boundFramebuffer=null,this._activeDrawCommand=null,this._transformTextureCount=-1,this._transformTextureHash=0}_createContext(e){try{return this._canvas.getContext("webgl2",{...e,stencil:!0})}catch(e){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const e=this._context,{r:t,g:i,b:n,a:r}=this._clearColor;e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.blendEquation(e.FUNC_ADD),e.clearColor(t/255,i/255,n/255,r)}_addEvents(){this._canvas.addEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.addEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_removeEvents(){this._canvas.removeEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_onContextLost(){this._contextLost=!0,this.onContextLost.dispatch(),this._restoreContext()}_onContextRestored(){this._contextLost=!1,this.onContextRestored.dispatch()}_createFramebuffer(){const e=this._context.createFramebuffer();if(null===e)throw new Error("Could not create framebuffer.");return e}_createTextureHandle(){const e=this._context.createTexture();if(null===e)throw new Error("Could not create texture.");return e}_bookTextureStorage(e,t,i){const n=eo(t.width,t.height,i,this._textureMipLevelCount(t));e.accountedBytes=this._accountant.reallocate(e.accountedBytes,n)}_textureMipLevelCount(e){if(!e.generateMipMap)return 1;const t=Math.max(e.width,e.height);return t<=1?1:Math.floor(Math.log2(t))+1}_destroyManagedResources(){for(const e of[...this._renderTargetStates.keys()])this._evictRenderTarget(e,!1);for(const e of[...this._textureStates.keys()])this._evictTexture(e,!1)}_destroyTemporaryRenderTextures(){for(const e of this._temporaryRenderTextures)e.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(e){let t=this._renderTargetStates.get(e);return t||(this._subscribeToDestroy(e,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(e,!0)}),t={framebuffer:e.root?null:this._createFramebuffer(),version:-1,attachedTexture:null,stencilRenderbuffer:null,stencilWidth:0,stencilHeight:0},this._renderTargetStates.set(e,t)),t}_getTextureState(e){let t=this._textureStates.get(e);return t||(this._subscribeToDestroy(e,this._textureDestroyHandlers,()=>{this._evictTexture(e,!0)}),t={handle:this._createTextureHandle(),version:-1,width:0,height:0,accountedBytes:0},this._textureStates.set(e,t)),t}_subscribeToDestroy(e,t,i){t.has(e)||(e.addDestroyListener(i),t.set(e,i))}_unsubscribeFromDestroy(e,t){const i=t.get(e);i&&(e.removeDestroyListener(i),t.delete(e))}_evictRenderTarget(e,t){const i=this._renderTargetStates.get(e);this._unsubscribeFromDestroy(e,this._renderTargetDestroyHandlers),e instanceof _i&&this._evictTexture(e,!1),i&&(this._boundFramebuffer===i.framebuffer&&(this._context.bindFramebuffer(this._context.FRAMEBUFFER,null),this._boundFramebuffer=null),null!==i.framebuffer&&this._context.deleteFramebuffer(i.framebuffer),null!==i.stencilRenderbuffer&&(this._context.deleteRenderbuffer(i.stencilRenderbuffer),i.stencilRenderbuffer=null),this._renderTargetStates.delete(e)),this._stencilStates.delete(e),this._renderTarget===e&&(this._renderTarget=this._rootRenderTarget,t&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(e,t){const i=this._textureStates.get(e);this._unsubscribeFromDestroy(e,this._textureDestroyHandlers),i&&(this._texture===e&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this._context.deleteTexture(i.handle),this._accountant.free(i.accountedBytes),i.accountedBytes=0,this._textureStates.delete(e)),this._texture===e&&(this._texture=null),t&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(e){const t=this._prepareRenderTarget(e);if(this._boundFramebuffer!==t.framebuffer||t.version!==e.version){const i=this._context,n=e.getViewport(),r=e.root&&e.width>0?this._canvas.width/e.width:1,s=e.root&&e.height>0?this._canvas.height/e.height:1,o=Math.floor(n.x*r),a=Math.max(0,Math.round(n.width*r)),h=Math.max(0,Math.round(n.height*s)),l=(e.root?this._canvas.height:e.height)-(Math.floor(n.y*s)+h);i.bindFramebuffer(i.FRAMEBUFFER,t.framebuffer),i.viewport(o,l,a,h),this._boundFramebuffer=t.framebuffer,t.version=e.version}this._clipPixelStack.length>0&&this._applyClipState()}_setActiveRenderer(e){this._renderer!==e&&(this._flushActiveRenderer(),this._renderer=e)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(e){const t=this._getRenderTargetState(e);if(e instanceof _i&&t.framebuffer){const i=this._boundFramebuffer,n=this._textureUnit;this._setTextureUnit(15);const r=this._syncTexture(e);if(this._setTextureUnit(n),t.attachedTexture!==r.handle){const e=this._context;e.bindFramebuffer(e.FRAMEBUFFER,t.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.handle,0),e.bindFramebuffer(e.FRAMEBUFFER,i),t.attachedTexture=r.handle}this._stencilStates.has(e)||(e.needsStencil=!1),(e.needsStencil||null!==t.stencilRenderbuffer)&&this._syncStencilAttachment(e,t)}return t}_ensureTargetStencil(){const e=this._renderTarget;e.root||(e.needsStencil=!0,this._syncStencilAttachment(e,this._getRenderTargetState(e)))}_syncStencilAttachment(e,t){if(null===t.framebuffer)return;const i=this._context,n=Math.max(1,e.width),r=Math.max(1,e.height);if(null!==t.stencilRenderbuffer&&t.stencilWidth===n&&t.stencilHeight===r)return;null===t.stencilRenderbuffer&&(t.stencilRenderbuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,t.stencilRenderbuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH24_STENCIL8,n,r),i.bindRenderbuffer(i.RENDERBUFFER,null);const s=this._boundFramebuffer;i.bindFramebuffer(i.FRAMEBUFFER,t.framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,t.stencilRenderbuffer),i.bindFramebuffer(i.FRAMEBUFFER,s),t.stencilWidth=n,t.stencilHeight=r}_getStencilState(e){let t=this._stencilStates.get(e);return void 0===t&&(t={depth:0,stack:[]},this._stencilStates.set(e,t)),t}_applyStencilState(e){const t=this._context,i=this._getStencilState(e).depth;if(0===i)return t.stencilFunc(t.ALWAYS,0,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),void t.disable(t.STENCIL_TEST);t.enable(t.STENCIL_TEST),t.stencilFunc(t.EQUAL,i,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}_syncTexture(e){const t=this._context,i=this._getTextureState(e),n=e instanceof _i?e.textureVersion:e.version;if(t.bindTexture(t.TEXTURE_2D,i.handle),i.version!==n){if(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,e.scaleMode),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,e.scaleMode),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,e.wrapMode),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,e.wrapMode),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),e instanceof kr){const n=e.format,r=function(e){const t=WebGL2RenderingContext;switch(e){case"r8":return{internalFormat:t.R8,format:t.RED,type:t.UNSIGNED_BYTE,channels:1};case"r32f":return{internalFormat:t.R32F,format:t.RED,type:t.FLOAT,channels:1};case"rgba8":return{internalFormat:t.RGBA8,format:t.RGBA,type:t.UNSIGNED_BYTE,channels:4};case"rgba32f":return{internalFormat:t.RGBA32F,format:t.RGBA,type:t.FLOAT,channels:4}}}(n),s=e._consumeDirtyRegion(),o=-1===i.version||i.width!==e.width||i.height!==e.height;t.pixelStorei(t.UNPACK_ALIGNMENT,1);const a=to(n);if(o||null===s||s.full)t.texImage2D(t.TEXTURE_2D,0,r.internalFormat,e.width,e.height,0,r.format,r.type,e.buffer),this._bookTextureStorage(i,e,a),this._accountant.recordTextureUpload(e.width*e.height*a);else{const i=r.channels,n=e.width*i,o=s.width*i,h=e.buffer instanceof Float32Array?new Float32Array(s.width*s.height*i):new Uint8Array(s.width*s.height*i);for(let t=0;t<s.height;t++){const r=(s.y+t)*n+s.x*i,a=t*o;h.set(e.buffer.subarray(r,r+o),a)}t.texSubImage2D(t.TEXTURE_2D,0,s.x,s.y,s.width,s.height,r.format,r.type,h),this._accountant.recordTextureUpload(s.width*s.height*a)}t.pixelStorei(t.UNPACK_ALIGNMENT,4)}else e instanceof _i?-1===i.version||i.width!==e.width||i.height!==e.height||null===e.source?(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,e.source),this._bookTextureStorage(i,e,go),this._accountant.recordTextureUpload(e.width*e.height*go)):(t.texSubImage2D(t.TEXTURE_2D,0,0,0,e.width,e.height,t.RGBA,t.UNSIGNED_BYTE,e.source),this._accountant.recordTextureUpload(e.width*e.height*go)):e.source&&(-1===i.version||i.width!==e.width||i.height!==e.height?(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e.source),this._bookTextureStorage(i,e,go)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,e.source),this._accountant.recordTextureUpload(e.width*e.height*go));e.generateMipMap&&(e instanceof _i||null!==e.source)&&t.generateMipmap(t.TEXTURE_2D),i.version=n,i.width=e.width,i.height=e.height}return i}_toClipPixels(e){const t=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(e.left,e.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(e.right,e.bottom)),n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),s=Math.min(t.y,i.y),o=Math.max(t.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(n))),u=Math.max(0,Math.min(a,Math.ceil(r))),c=Math.max(0,Math.min(h,Math.floor(s))),d=Math.max(0,Math.min(h,Math.ceil(o))),_=Math.max(0,u-l),f=Math.max(0,d-c);return{x:l,y:Math.max(0,h-d),width:_,height:f}}_intersectClips(e,t){const i=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.width,t.x+t.width),s=Math.min(e.y+e.height,t.y+t.height);return{x:i,y:n,width:Math.max(0,r-i),height:Math.max(0,s-n)}}_applyClipState(){const e=this._context;if(0===this._clipPixelStack.length)return void e.disable(e.SCISSOR_TEST);const t=this._clipPixelStack[this._clipPixelStack.length-1],i=this._renderTarget.root&&this._renderTarget.width>0?this._canvas.width/this._renderTarget.width:1,n=this._renderTarget.root&&this._renderTarget.height>0?this._canvas.height/this._renderTarget.height:1,r=Math.floor(t.x*i),s=Math.floor(t.y*n),o=Math.max(0,Math.round(t.width*i)),a=Math.max(0,Math.round(t.height*n));e.enable(e.SCISSOR_TEST),e.scissor(r,s,o,a)}}const go=4;class yo{_projectionData=new Float32Array(16);_vertexData=new Float32Array(16);_indexData=new Uint16Array([0,1,2,0,2,3]);_blendData=new ArrayBuffer(16);_blendModeView=new Uint32Array(this._blendData,0,1);_blendOpaqueView=new Float32Array(this._blendData,4,1);_projectionMatrix=new At;_pipelines=new Map;_device=null;_shaderModule=null;_projectionBindGroupLayout=null;_textureBindGroupLayout=null;_blendBindGroupLayout=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_projectionBuffer=null;_blendBuffer=null;_projectionBindGroup=null;_blendBindGroup=null;_backdropSampler=null;_backdropTexture=null;_backdropView=null;_backdropWidth=0;_backdropHeight=0;_backdropFormat=null;connect(e){null===this._device&&(this._device=e,this._shaderModule=e.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct BlendUniforms {\n mode: u32,\n opaqueBackdrop: f32,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(1) @binding(1)\nvar sourceSampler: sampler;\n@group(1) @binding(2)\nvar backdropTexture: texture_2d<f32>;\n@group(1) @binding(3)\nvar backdropSampler: sampler;\n\n@group(2) @binding(0)\nvar<uniform> blend: BlendUniforms;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n\n return output;\n}\n\nfn unpremultiply(color: vec4<f32>) -> vec3<f32> {\n if (color.a > 0.0) {\n return color.rgb / color.a;\n }\n\n return vec3<f32>(0.0);\n}\n\n// W3C separable blend B(Cb, Cs) for one channel (straight color in [0, 1]).\n// Mode values match the BlendModes enum (src/rendering/types.ts).\nfn blendChannel(mode: u32, cb: f32, cs: f32) -> f32 {\n switch mode {\n case 3u { return cb * cs; } // Multiply\n case 4u { return cb + cs - cb * cs; } // Screen\n case 5u { return min(cb, cs); } // Darken\n case 6u { return max(cb, cs); } // Lighten\n case 7u { return select(1.0 - 2.0 * (1.0 - cb) * (1.0 - cs), 2.0 * cb * cs, cb <= 0.5); } // Overlay\n case 8u { // ColorDodge\n if (cb <= 0.0) { return 0.0; }\n return select(min(1.0, cb / (1.0 - cs)), 1.0, cs >= 1.0);\n }\n case 9u { // ColorBurn\n if (cb >= 1.0) { return 1.0; }\n return select(1.0 - min(1.0, (1.0 - cb) / cs), 0.0, cs <= 0.0);\n }\n case 10u { return select(1.0 - 2.0 * (1.0 - cb) * (1.0 - cs), 2.0 * cb * cs, cs <= 0.5); } // HardLight\n case 11u { // SoftLight\n if (cs <= 0.5) { return cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb); }\n let d = select(sqrt(cb), ((16.0 * cb - 12.0) * cb + 4.0) * cb, cb <= 0.25);\n return cb + (2.0 * cs - 1.0) * (d - cb);\n }\n case 12u { return abs(cb - cs); } // Difference\n case 13u { return cb + cs - 2.0 * cb * cs; } // Exclusion\n default { return min(cb, cs); } // Darken\n }\n}\n\nfn blendSeparable(mode: u32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {\n return vec3<f32>(blendChannel(mode, cb.x, cs.x), blendChannel(mode, cb.y, cs.y), blendChannel(mode, cb.z, cs.z));\n}\n\n// Non-separable helpers (W3C): operate on the whole color.\nfn lum(c: vec3<f32>) -> f32 {\n return dot(c, vec3<f32>(0.3, 0.59, 0.11));\n}\n\nfn clipColor(input: vec3<f32>) -> vec3<f32> {\n var c = input;\n let l = lum(c);\n let n = min(min(c.x, c.y), c.z);\n let x = max(max(c.x, c.y), c.z);\n\n if (n < 0.0) { c = l + ((c - l) * l) / (l - n); }\n if (x > 1.0) { c = l + ((c - l) * (1.0 - l)) / (x - l); }\n\n return c;\n}\n\nfn setLum(c: vec3<f32>, l: f32) -> vec3<f32> {\n return clipColor(c + (l - lum(c)));\n}\n\nfn sat(c: vec3<f32>) -> f32 {\n return max(max(c.x, c.y), c.z) - min(min(c.x, c.y), c.z);\n}\n\n// Map the channels so min -> 0, max -> s, mid -> proportional (W3C SetSat result).\nfn setSat(c: vec3<f32>, s: f32) -> vec3<f32> {\n let mn = min(min(c.x, c.y), c.z);\n let mx = max(max(c.x, c.y), c.z);\n\n return select(vec3<f32>(0.0), (c - mn) * (s / (mx - mn)), mx > mn);\n}\n\nfn blendNonSeparable(mode: u32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {\n switch mode {\n case 14u { return setLum(setSat(cs, sat(cb)), lum(cb)); } // Hue\n case 15u { return setLum(setSat(cb, sat(cs)), lum(cb)); } // Saturation\n case 16u { return setLum(cs, lum(cb)); } // Color\n default { return setLum(cb, lum(cs)); } // Luminosity\n }\n}\n\nfn blendAdvanced(mode: u32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {\n if (mode >= 14u) { return blendNonSeparable(mode, cb, cs); }\n return blendSeparable(mode, cb, cs);\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let src = textureSample(sourceTexture, sourceSampler, input.texcoord);\n // copyTextureToTexture preserves the target's top-left orientation, so the\n // backdrop is sampled at the same UV as the quad — no V-flip (unlike the\n // WebGL2 framebuffer-blit path, which reads bottom-left order).\n let dst = textureSample(backdropTexture, backdropSampler, input.texcoord);\n\n let alphaSource = src.a;\n // An opaque target (the on-screen root canvas, alphaMode 'opaque') has an\n // unreliable captured alpha; force full backdrop coverage so the blend is\n // not skipped. Offscreen RenderTextures carry real alpha.\n let alphaBackdrop = max(dst.a, blend.opaqueBackdrop);\n let colorSource = unpremultiply(src);\n let colorBackdrop = unpremultiply(dst);\n\n let blended = blendAdvanced(blend.mode, colorBackdrop, colorSource);\n // Cs' = (1 - αb)·Cs + αb·B(Cb, Cs)\n let mixedSource = mix(colorSource, blended, alphaBackdrop);\n\n // Premultiplied blended source; the GPU source-over composites it over the\n // untouched backdrop already in the target (αs = 0 passes the backdrop through).\n return vec4<f32>(mixedSource * alphaSource, alphaSource);\n}\n"}),this._projectionBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this._blendBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this._pipelineLayout=e.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout,this._blendBindGroupLayout]}),this._vertexBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=e.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._blendBuffer=e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._backdropSampler=e.createSampler({magFilter:"nearest",minFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this._projectionBindGroup=e.createBindGroup({layout:this._projectionBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projectionBuffer}}]}),this._blendBindGroup=e.createBindGroup({layout:this._blendBindGroupLayout,entries:[{binding:0,resource:{buffer:this._blendBuffer}}]}))}disconnect(){null!==this._device&&(this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._projectionBuffer?.destroy(),this._blendBuffer?.destroy(),this._backdropTexture?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._projectionBuffer=null,this._blendBuffer=null,this._backdropTexture=null,this._backdropView=null,this._backdropWidth=0,this._backdropHeight=0,this._backdropFormat=null,this._backdropSampler=null,this._projectionBindGroup=null,this._blendBindGroup=null,this._pipelineLayout=null,this._blendBindGroupLayout=null,this._textureBindGroupLayout=null,this._projectionBindGroupLayout=null,this._shaderModule=null,this._pipelines.clear(),this._device=null)}compose(e,t,i,n,r,s,o){if(null===this._device)throw new Error("WebGpuBackdropBlendCompositor: not connected.");if(r<=0||s<=0)return;const a=this._device,h=e.renderTarget;e.flush();const l=e.renderTargetFormat,u=e._getAttachmentPixelSize(h),c=h.root&&h.width>0?u.width/h.width:1,d=h.root&&h.height>0?u.height/h.height:1,_=Math.max(0,Math.floor(i*c)),f=Math.max(0,Math.floor(n*d)),p=Math.max(0,Math.min(Math.round(r*c),u.width-_)),m=Math.max(0,Math.min(Math.round(s*d),u.height-f));if(p<=0||m<=0)return;const g=this._ensureBackdrop(a,p,m,l),y=a.createCommandEncoder();y.copyTextureToTexture({texture:e._renderTargetTexture(h),origin:{x:_,y:f,z:0}},{texture:this._backdropTexture,origin:{x:0,y:0,z:0}},{width:p,height:m,depthOrArrayLayers:1}),a.queue.submit([y.finish()]),this._drawBlend(e,t,g,i,n,r,s,o,h.root)}_ensureBackdrop(e,t,i,n){return null!==this._backdropTexture&&this._backdropWidth===t&&this._backdropHeight===i&&this._backdropFormat===n||(this._backdropTexture?.destroy(),this._backdropTexture=e.createTexture({size:{width:t,height:i},format:n,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this._backdropView=this._backdropTexture.createView(),this._backdropWidth=t,this._backdropHeight=i,this._backdropFormat=n),this._backdropView}_drawBlend(e,t,i,n,r,s,o,a,h){const l=this._device;this._writeQuadVertices(n,r,n+s,r+o),l.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(e.view.getTransform()),l.queue.writeBuffer(this._projectionBuffer,0,this._projectionData),this._blendModeView[0]=a,this._blendOpaqueView[0]=h?1:0,l.queue.writeBuffer(this._blendBuffer,0,this._blendData);const u=e.getTextureBinding(t),c=l.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:u.view},{binding:1,resource:u.sampler},{binding:2,resource:i},{binding:3,resource:this._backdropSampler}]}),d=e.renderTargetFormat,_=e._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,_),p=e._passCoordinator.acquirePass().pass;p.setPipeline(f),p.setBindGroup(0,this._projectionBindGroup),p.setBindGroup(1,c),p.setBindGroup(2,this._blendBindGroup),p.setVertexBuffer(0,this._vertexBuffer),p.setIndexBuffer(this._indexBuffer,"uint16"),p.drawIndexed(6),e.stats.batches++,e.stats.drawCalls++,e._passCoordinator.endPass()}_getOrCreatePipeline(t,i){const n=`${t}|${i?"s":"n"}`,r=this._pipelines.get(n);if(void 0!==r)return r;const s=this._device,o={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e.BlendModes.Normal)}]},primitive:{topology:"triangle-list"}};i&&(o.depthStencil=Ps());const a=s.createRenderPipeline(o);return this._pipelines.set(n,a),a}_writeQuadVertices(e,t,i,n){const r=this._vertexData;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_writeProjectionMatrix(e){const t=this._projectionMatrix.copy(e),i=this._projectionData;i[0]=t.a,i[1]=t.c,i[2]=0,i[3]=0,i[4]=t.b,i[5]=t.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=0,i[15]=1}}class wo{_projectionData=new Float32Array(16);_vertexData=new Float32Array(16);_indexData=new Uint16Array([0,1,2,0,2,3]);_projectionMatrix=new At;_pipelines=new Map;_device=null;_shaderModule=null;_projectionBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_projectionBuffer=null;_projectionBindGroup=null;connect(e){null===this._device&&(this._device=e,this._shaderModule=e.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar contentTexture: texture_2d<f32>;\n@group(1) @binding(1)\nvar contentSampler: sampler;\n@group(1) @binding(2)\nvar maskTexture: texture_2d<f32>;\n@group(1) @binding(3)\nvar maskSampler: sampler;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let contentColor = textureSample(contentTexture, contentSampler, input.texcoord);\n let maskAlpha = textureSample(maskTexture, maskSampler, input.texcoord).a;\n\n return vec4<f32>(contentColor.rgb * maskAlpha, contentColor.a * maskAlpha);\n}\n"}),this._projectionBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this._pipelineLayout=e.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout]}),this._vertexBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=e.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._projectionBindGroup=e.createBindGroup({layout:this._projectionBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projectionBuffer}}]}))}disconnect(){null!==this._device&&(this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._projectionBuffer?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._projectionBuffer=null,this._projectionBindGroup=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._projectionBindGroupLayout=null,this._shaderModule=null,this._pipelines.clear(),this._device=null)}compose(e,t,i,n,r,s,o,a){if(null===this._device)throw new Error("WebGpuMaskCompositor: not connected.");if(s<=0||o<=0)return;const h=this._device;this._writeQuadVertices(n,r,n+s,r+o),h.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(e.view.getTransform()),h.queue.writeBuffer(this._projectionBuffer,0,this._projectionData);const l=e.getTextureBinding(t),u=e.getTextureBinding(i),c=h.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:l.view},{binding:1,resource:l.sampler},{binding:2,resource:u.view},{binding:3,resource:u.sampler}]}),d=e.renderTargetFormat,_=e._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,a,_),p=e._passCoordinator.acquirePass().pass;p.setPipeline(f),p.setBindGroup(0,this._projectionBindGroup),p.setBindGroup(1,c),p.setVertexBuffer(0,this._vertexBuffer),p.setIndexBuffer(this._indexBuffer,"uint16"),p.drawIndexed(6),e.stats.batches++,e.stats.drawCalls++,e._passCoordinator.endPass()}_getOrCreatePipeline(e,t,i){const n=`${e}|${t}|${i?"s":"n"}`,r=this._pipelines.get(n);if(void 0!==r)return r;const s=this._device,o={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:Ss(t)}]},primitive:{topology:"triangle-list"}};i&&(o.depthStencil=Ps());const a=s.createRenderPipeline(o);return this._pipelines.set(n,a),a}_writeQuadVertices(e,t,i,n){const r=this._vertexData;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_writeProjectionMatrix(e){const t=this._projectionMatrix.copy(e),i=this._projectionData;i[0]=t.a,i[1]=t.c,i[2]=0,i[3]=0,i[4]=t.b,i[5]=t.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=0,i[15]=1}}class xo{_backend;_stencil=new Ts;_stencilDepths=new Map;_stencilStacks=new Map;_stencilConnected=!1;_stencilWriteInProgress=!1;_stencilLoadOp="load";_stencilRef=0;_active=null;constructor(e){this._backend=e}get activeTarget(){return this._backend.renderTarget}get activeView(){return this._backend.view}get hasActivePass(){return null!==this._active}get activePass(){return this._active}get stencilActive(){return this._stencilWriteInProgress||this._activeTargetDepth()>0}get stencilReference(){return this._stencilRef}acquirePass(){if(null!==this._active)return this._active;const e=this._backend,t=this.stencilActive,i={colorAttachments:[e.createColorAttachment()]};t&&(i.depthStencilAttachment=this._createStencilAttachment(e.renderTarget));const n=e.device.createCommandEncoder(),r=n.beginRenderPass(i);e.stats.renderPasses++;const s=e.getScissorRect();return null!==s&&s.width>0&&s.height>0&&r.setScissorRect(s.x,s.y,s.width,s.height),this._applyViewport(r),t&&r.setStencilReference(this._stencilRef),this._active={encoder:n,pass:r,targetFormat:e.renderTargetFormat,view:e.view,stencilEnabled:t,stencilRef:this._stencilRef},this._active}endPass(){const e=this._active;null!==e&&(this._active=null,e.pass.end(),this._backend.submit(e.encoder.finish()))}beginPass(e){this._backend.setRenderTarget(e.target),this._backend.setView(e.view),"clear"===e.load&&this._backend.clear(e.clearColor??void 0)}withChildPass(e,t){const i=this._backend.renderTarget,n=this._backend.view;this.beginPass(e);try{t()}finally{this._backend.setRenderTarget(i),this._backend.setView(n)}}pushScissorRect(e){this._backend.pushScissorRect(e)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(e,t){const i=this._backend.renderTarget,n=this._stencilDepths.get(i)??0;if(n>=255)throw new Error("Stencil clip nesting exceeds the 255-level limit.");this._connectStencil(),this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=n,this._stencilLoadOp=0===n?"clear":"load";const r=this.acquirePass();this._stencil.draw(r.pass,r.targetFormat,!0,e,t,r.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(i,n+1),this._stencilRef=n+1,this._getStencilStack(i).push({shape:e,transform:(new At).copy(t)})}popStencilClip(){const e=this._backend.renderTarget,t=this._stencilStacks.get(e),i=t?.pop();if(void 0===i)return;const n=this._stencilDepths.get(e)??0;this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=n,this._stencilLoadOp="load";const r=this.acquirePass();this._stencil.draw(r.pass,r.targetFormat,!1,i.shape,i.transform,r.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(e,n-1),this._stencilRef=n-1}resolveLoad(e,t){return t||!this._backend._targetHasContent(e)?"clear":"load"}releaseStencilTarget(e){this._stencilConnected&&this._stencil.releaseAttachment(e),this._stencilDepths.delete(e),this._stencilStacks.delete(e)}resetStencil(){this._stencilDepths.clear(),this._stencilStacks.clear(),this._stencilWriteInProgress=!1,this._stencilRef=0}destroyStencil(){this._stencilConnected&&(this._stencil.disconnect(),this._stencilConnected=!1),this._stencilDepths.clear(),this._stencilStacks.clear(),this._stencilWriteInProgress=!1,this._stencilRef=0}unbalancedStencilClips(){let e=0;for(const t of this._stencilStacks.values())e+=t.length;return e}_activeTargetDepth(){return this._stencilDepths.get(this._backend.renderTarget)??0}_applyViewport(e){const t=this._backend.view.viewport;if(0===t.x&&0===t.y&&1===t.width&&1===t.height)return;const{width:i,height:n}=this._backend._getAttachmentPixelSize(this._backend.renderTarget),r=Math.floor(t.x*i),s=Math.floor(t.y*n),o=Math.max(1,Math.round(t.width*i)),a=Math.max(1,Math.round(t.height*n));e.setViewport(r,s,o,a,0,1)}_connectStencil(){this._stencilConnected||(this._stencil.connect(this._backend.device),this._stencilConnected=!0)}_getStencilStack(e){let t=this._stencilStacks.get(e);return void 0===t&&(t=[],this._stencilStacks.set(e,t)),t}_createStencilAttachment(e){const{width:t,height:i}=this._backend._getAttachmentPixelSize(e),n=this._stencil.getAttachmentView(e,t,i),r=this._stencilLoadOp;return this._stencilLoadOp="load",{view:n,depthReadOnly:!0,stencilLoadOp:r,stencilStoreOp:"store",stencilClearValue:0}}}class vo{_buffer=new ao;_storageBuffer=null;_storageCapacity=0;_storageHash=0;_storageCount=-1;_needsFullUpload=!1;_accountant=null;_accountedBytes=0;get buffer(){return this._buffer}begin(e=0){this._buffer.begin(e)}writeCommand(e,t){const i=e.drawable;this._buffer.write(e.nodeIndex,t??i.getGlobalTransform(),i.tint)}recordSkippedWrite(){this._buffer.recordSkippedWrite()}push(e,t){return this._buffer.push(t??e.getGlobalTransform(),e.tint)}pushValues(e,t){return this._buffer.push(e,t)}reserve(e,t,i){this._accountant=i??this._accountant;const n=12*Math.max(1,t)*Float32Array.BYTES_PER_ELEMENT;null!==this._storageBuffer&&n<=this._storageCapacity||this._growBuffer(e,n)}getBuffer(e,t,i){this._accountant=i??this._accountant;const n=Math.max(1,t),r=12*n*Float32Array.BYTES_PER_ELEMENT,s=this._buffer.commitSnapshot(n);if((null===this._storageBuffer||r>this._storageCapacity)&&this._growBuffer(e,r),s.changed||s.hash!==this._storageHash||s.count!==this._storageCount){const{firstRow:t,rowCount:i}=this._buffer.consumeDirtyRange(s.count),n=12*Float32Array.BYTES_PER_ELEMENT;this._needsFullUpload?(e.queue.writeBuffer(this._storageBuffer,0,this._buffer.data.buffer,this._buffer.data.byteOffset,s.count*n),this._buffer.recordUpload(s.count),this._accountant?.recordBufferUpload(s.count*n),this._needsFullUpload=!1):i>0&&(e.queue.writeBuffer(this._storageBuffer,t*n,this._buffer.data.buffer,this._buffer.data.byteOffset+t*n,i*n),this._buffer.recordUpload(i),this._accountant?.recordBufferUpload(i*n)),this._storageHash=s.hash,this._storageCount=s.count}return{buffer:this._storageBuffer,count:s.count}}destroy(){this._storageBuffer?.destroy(),this._storageBuffer=null,this._storageCapacity=0,this._storageHash=0,this._storageCount=-1,this._accountedBytes>0&&(this._accountant?.free(this._accountedBytes),this._accountedBytes=0)}_growBuffer(e,t){let i=Math.max(this._storageCapacity,12*Float32Array.BYTES_PER_ELEMENT);for(;i<t;)i*=2;this._storageBuffer?.destroy(),this._storageBuffer=e.createBuffer({size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._storageCapacity=i,this._storageHash=0,this._storageCount=-1,this._needsFullUpload=!0,this._accountedBytes=this._accountant?.reallocate(this._accountedBytes,i)??this._accountedBytes}}const bo="rgba8unorm";class So{backendType=e.RenderBackendType.WebGpu;rendererRegistry=new ro;onDeviceLost=new x;onDeviceRestored=new x;_canvas;_rootRenderTarget;_clearColor=new Tt;_deviceLost=!1;_isRecovering=!1;_destroyed=!1;_recoveryAttempt=0;_maxRecoveryAttempts=5;_recoveryBackoffMs=100;_textureStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_clipBoundsStack=[];_clipPixelStack=[];_clipPointA=new it;_clipPointB=new it;_maskCompositor=new wo;_maskCompositorConnected=!1;_backdropBlendCompositor=new yo;_backdropBlendCompositorConnected=!1;_mipmapShaderModule=null;_mipmapBindGroupLayout=null;_mipmapPipelineLayout=null;_mipmapPipeline=null;_mipmapSampler=null;_context=null;_device=null;_format=null;_initializePromise=null;_renderTarget;_snapTransform=new At;_renderer=null;_texture=null;_clearRequested=!1;_hasPresentedFrame=!1;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0,rawFrameDeltaMs:0,gpuMemoryBytes:0,textureUploadBytes:0,bufferUploadBytes:0,downloadBytes:0,downloadCount:0};_accountant=new Js(this._stats);_transformStorage=new vo;_activeDrawCommand=null;_passCoordinatorInstance=null;_drawPlanDepth=0;_planBaseStack=[];_planHashStack=[];constructor(e){const t=e.options.canvas??{},i=t.width??800,n=t.height??600,r=e.options.clearColor;this._canvas=e.canvas,this._rootRenderTarget=new di(i,n,!0),this._renderTarget=this._rootRenderTarget,r&&this._clearColor.copy(r),this.resize(i,n)}get view(){return this._renderTarget.view}get renderTarget(){return this._renderTarget}get device(){if(null===this._device)throw new Error("WebGPU device is not initialized yet.");return this._device}get context(){if(null===this._context)throw new Error("WebGPU canvas context is not initialized yet.");return this._context}get format(){if(null===this._format)throw new Error("WebGPU canvas format is not initialized yet.");return this._format}get renderTargetFormat(){return this._renderTarget===this._rootRenderTarget?this.format:bo}get clearRequested(){return this._clearRequested}get stats(){return this._stats}get accountant(){return this._accountant}get activeDrawCommand(){return this._activeDrawCommand}get _passCoordinator(){return this._passCoordinatorInstance??=new xo(this)}get clearColor(){return this._clearColor}get deviceLost(){return this._deviceLost}setClearColor(e){return this._clearColor.copy(e),this}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(e=>{throw this._initializePromise=null,e})),this._initializePromise}resetStats(){return Qs(this._stats),this._getTransformStorage().buffer.begin(),this}get transformBufferCount(){return this._getTransformStorage().buffer.count}_beginDrawPlan(e){const t=this._getTransformStorage();this._planBaseStack.push(t.buffer.count),this._planHashStack.push(t.buffer.frameHash);const i=t.buffer.count+e;i>0&&null!==this._device&&!this._deviceLost&&t.reserve(this._device,i,this._accountant),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(e,t,i){const n=this._getTransformStorage(),r=t+i;for(let i=t;i<r;i++){const t=e[i];if(t.kind!==Yt.Draw)continue;const r=t.command;ii(r,this)?n.writeCommand(r,this._resolveSnapTransform(r.drawable)):n.recordSkippedWrite()}}_prepareDrawCommand(e){this._activeDrawCommand=e}_endDrawPlan(){this._activeDrawCommand=null;const e=this._planBaseStack.pop()??0,t=this._planHashStack.pop()??0;if(this._drawPlanDepth>0&&this._drawPlanDepth--,this._drawPlanDepth>0&&(this._flushActiveRenderer(),this._getTransformStorage().buffer.rewindTo(e,t)),0===this._drawPlanDepth&&null!==this._passCoordinatorInstance){const e=this._passCoordinatorInstance.unbalancedStencilClips();if(e>0)throw this._passCoordinatorInstance.resetStencil(),new Error(`Unbalanced stencil clip stack at end of frame (${e} unpopped clip(s)).`)}}draw(e){if(this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const t=this.rendererRegistry.resolve(e);return this._setActiveRenderer(t),t.render(e),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(e,t,i,n){if(n<=0||0===e.vertexCount||this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const r=this.rendererRegistry.resolve(e);if(!(r instanceof ks))throw new Error("drawInstanced requires a mesh handled by the WebGPU mesh renderer.");this._setActiveRenderer(r);const s=this._getTransformStorage(),o=s.pushValues(t[0],i[0]);for(let e=1;e<n;e++)s.pushValues(t[e],i[e]);return r.drawInstancedBatch(e,o,n),this._activeDrawCommand=null,this._stats.submittedNodes+=n,this}execute(e){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._stats.renderPasses++,e.execute(this)),this}setBlendMode(e){return this}setRenderTarget(e){const t=e??this._rootRenderTarget;return this._renderTarget!==t&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=t,this._stats.renderTargetChanges++,t!==this._rootRenderTarget&&this._subscribeRenderTarget(t)),this}pushScissorRect(e){this._flushActiveRenderer(),this._clipBoundsStack.push(e.clone());const t=this._toClipPixels(e),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,n=i?this._intersectClips(i,t):t;return this._clipPixelStack.push(n),this}composeWithAlphaMask(e,t,i,n,r,s,o){return r<=0||s<=0||this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._maskCompositorConnected||(this._maskCompositor.connect(this.device),this._maskCompositorConnected=!0),this._maskCompositor.compose(this,e,t,i,n,r,s,o)),this}composeWithBackdropBlend(e,t,i,n,r,s){return n<=0||r<=0||this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._backdropBlendCompositorConnected||(this._backdropBlendCompositor.connect(this.device),this._backdropBlendCompositorConnected=!0),this._backdropBlendCompositor.compose(this,e,t,i,n,r,s)),this}_renderTargetTexture(e){if(e===this._rootRenderTarget)return this.context.getCurrentTexture();if(e instanceof _i)return this._getTextureState(e).texture;throw new Error("WebGpuBackend._renderTargetTexture: unsupported render target type.")}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const e=this._clipBoundsStack.pop();return e&&e.destroy(),this._clipPixelStack.pop(),this}pushStencilClip(e,t){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._passCoordinator.pushStencilClip(e,t)),this}popStencilClip(){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._passCoordinator.popStencilClip()),this}getScissorRect(){if(0===this._clipPixelStack.length)return null;const e=this._clipPixelStack[this._clipPixelStack.length-1],t=this._renderTarget.root&&this._renderTarget.width>0?this._canvas.width/this._renderTarget.width:1,i=this._renderTarget.root&&this._renderTarget.height>0?this._canvas.height/this._renderTarget.height:1;return{x:Math.floor(e.x*t),y:Math.floor(e.y*i),width:Math.max(0,Math.round(e.width*t)),height:Math.max(0,Math.round(e.height*i))}}acquireRenderTexture(e,t){for(let i=0;i<this._temporaryRenderTextures.length;i++){const n=this._temporaryRenderTextures[i];if(n.width===e&&n.height===t)return this._temporaryRenderTextures.splice(i,1),n}return new _i(e,t)}releaseRenderTexture(e){return this._temporaryRenderTextures.includes(e)||(e.setView(null),this._temporaryRenderTextures.push(e)),this}setView(e){return this._renderTarget.view!==e&&this._flushActiveRenderer(),this._renderTarget.setView(e),this}clear(e){return e&&this.setClearColor(e),this._clearRequested=!0,this}resize(e,t){return this._rootRenderTarget.resize(e,t),this._hasPresentedFrame=!1,this}flush(){return this._device&&this._context?(this._renderer?this._flushActiveRenderer():this._clearRequested&&(this._passCoordinator.acquirePass(),this._passCoordinator.endPass()),this):this}destroy(){this._destroyed=!0,this.onDeviceLost.destroy(),this.onDeviceRestored.destroy(),this._setActiveRenderer(null),this.rendererRegistry.destroy(),this._destroyManagedTextures(),this._destroyTemporaryRenderTextures();for(const e of this._clipBoundsStack)e.destroy();this._clipBoundsStack.length=0,this._clipPixelStack.length=0,this._clipPointA.destroy(),this._clipPointB.destroy(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._backdropBlendCompositorConnected&&(this._backdropBlendCompositor.disconnect(),this._backdropBlendCompositorConnected=!1),this._transformStorage?.destroy(),this._transformStorage=null,this._activeDrawCommand=null,this._passCoordinatorInstance?.destroyStencil(),this._drawPlanDepth=0;for(const e of[...this._renderTargetDestroyHandlers.keys()])this._unsubscribeRenderTarget(e);this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._deviceLost=!1,this._texture=null,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._renderTarget=this._rootRenderTarget,this._clearColor.destroy(),this._rootRenderTarget.destroy()}createColorAttachment(){const e=this._renderTarget;let t;if(e===this._rootRenderTarget)t=this.context.getCurrentTexture().createView();else{if(!(e instanceof _i))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");t=this._syncTexture(e).view}const i=this._passCoordinator.resolveLoad(e,this._clearRequested);return this._clearRequested=!1,{view:t,clearValue:{r:this._clearColor.r/255,g:this._clearColor.g/255,b:this._clearColor.b/255,a:this._clearColor.a},loadOp:i,storeOp:"store"}}submit(e){if(this.device.queue.submit([e]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof _i){const e=this._syncTexture(this._renderTarget);e.hasContent=!0,e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}}_targetHasContent(e){return e===this._rootRenderTarget?this._hasPresentedFrame:e instanceof _i&&this._getTextureState(e).hasContent}_getAttachmentPixelSize(e){return e===this._rootRenderTarget?{width:this._canvas.width,height:this._canvas.height}:{width:e.width,height:e.height}}getTextureBinding(e){const t=this._syncTexture(e);return{view:t.view,sampler:t.sampler}}getTextureFormat(e){return this._getGpuTextureFormat(e)}shouldPremultiplyTextureSample(e){return!(e instanceof _i)&&e.premultiplyAlpha}getTransformStorageBuffer(e){return this._getTransformStorage().getBuffer(this.device,e,this._accountant)}_pushTransform(e){return this._getTransformStorage().push(e,this._resolveSnapTransform(e))}_resolveSnapTransform(e){const t=this._renderTarget,i=t===this._rootRenderTarget,n=i?this._canvas.width:t.width,r=i?this._canvas.height:t.height;return kn(e,t.view,n,r,this._snapTransform)}_getSnapPixelSize(){return this._getAttachmentPixelSize(this._renderTarget)}_setActiveRenderer(e){this._renderer!==e&&(this._flushActiveRenderer(),this._renderer=e)}_flushActiveRenderer(){this._renderer?.flush()}_getTransformStorage(){return null!==this._transformStorage&&void 0!==this._transformStorage||(this._transformStorage=new vo),this._transformStorage}async _initialize(){const e=this._getGpuNavigator();if(null===e)throw new Error("This browser does not support WebGPU.");if("function"!=typeof e.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof e.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");let t,i;try{t=await e.gpu.requestAdapter()}catch(e){throw this._createInitializationError("Failed to request a WebGPU adapter.",e)}if(null===t)throw new Error("Could not acquire a WebGPU adapter.");if("function"!=typeof t.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");try{i=await t.requestDevice()}catch(e){throw this._createInitializationError("Failed to request a WebGPU device.",e)}if(null===i)throw new Error("Could not acquire a WebGPU device.");const n=this._canvas.getContext("webgpu");if(null===n)throw new Error("Could not create WebGPU canvas context.");const r=e.gpu.getPreferredCanvasFormat();try{n.configure({device:i,format:r,alphaMode:"opaque",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC})}catch(e){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",e)}this._context=n,this._device=i,this._format=r,this._hasPresentedFrame=!1,this._subscribeToDeviceLoss(),this.rendererRegistry.connect(this),this.resize(this._rootRenderTarget.width,this._rootRenderTarget.height);const s=[r,bo];return await this._prewarmRendererPipelines(s),this}_subscribeToDeviceLoss(){if(!this._device)return;const e=this._device;e.lost.then(t=>{this._destroyed||this._device!==e||this._handleDeviceLoss(t)})}_handleDeviceLoss(e){this._deviceLost=!0,this.onDeviceLost.dispatch(e),"destroyed"!==e.reason&&this._attemptRecovery()}async _attemptRecovery(){if(!this._isRecovering&&!this._destroyed){this._isRecovering=!0;try{for(;this._recoveryAttempt<this._maxRecoveryAttempts&&!this._destroyed;){this._recoveryAttempt++,this._teardownDeviceState();try{if(await this._initialize(),this._destroyed)return;return this._deviceLost=!1,this._recoveryAttempt=0,this._initializePromise=Promise.resolve(this),void this.onDeviceRestored.dispatch()}catch{if(this._destroyed)return;const e=this._recoveryBackoffMs*Math.pow(2,this._recoveryAttempt-1);await new Promise(t=>{setTimeout(t,e)})}}}finally{this._isRecovering=!1}}}_teardownDeviceState(){for(const[e,t]of this._textureDestroyHandlers)e.removeDestroyListener(t);this._textureDestroyHandlers.clear(),this._textureStates.clear(),this._temporaryRenderTextures.length=0,this.rendererRegistry.disconnect(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._backdropBlendCompositorConnected&&(this._backdropBlendCompositor.disconnect(),this._backdropBlendCompositorConnected=!1),this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._transformStorage?.destroy(),this._transformStorage=null,this._activeDrawCommand=null,this._passCoordinatorInstance?.destroyStencil(),this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._hasPresentedFrame=!1}async _prewarmRendererPipelines(e){const t=[];for(const i of this.rendererRegistry.renderers()){const n=i;"function"==typeof n.prewarmPipelines&&t.push(n.prewarmPipelines(e))}await Promise.all(t)}_getGpuNavigator(){const e=navigator;return e.gpu?e:null}_createInitializationError(e,t){return t instanceof Error&&t.message.length>0?new Error(`${e} ${t.message}`):new Error(e)}_destroyManagedTextures(){for(const e of[...this._textureStates.keys()])this._evictTexture(e)}_destroyTemporaryRenderTextures(){for(const e of this._temporaryRenderTextures)e.destroy();this._temporaryRenderTextures.length=0}_getTextureState(e){let t=this._textureStates.get(e);if(!t){const i=this.device.createTexture({size:{width:Math.max(e.width,1),height:Math.max(e.height,1)},format:this._getGpuTextureFormat(e),mipLevelCount:this._getMipLevelCount(e),usage:this._getTextureUsage(e)}),n=this._getMipLevelCount(e);t={texture:i,view:i.createView(),sampler:this._createSampler(e),version:-1,width:e.width,height:e.height,mipLevelCount:n,hasContent:!1,accountedBytes:0},t.accountedBytes=this._accountant.reallocate(0,this._estimateTextureBytes(e,n));const r=()=>{this._evictTexture(e)};e.addDestroyListener(r),this._textureDestroyHandlers.set(e,r),this._textureStates.set(e,t)}return t}_syncTexture(e){if(!(e instanceof _i||e instanceof kr||null!==e.source&&0!==e.width&&0!==e.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const t=this._getTextureState(e),i=e instanceof _i?e.textureVersion:e.version,n=this._getMipLevelCount(e);if(t.version!==i){if(t.width!==e.width||t.height!==e.height||t.mipLevelCount!==n){t.texture.destroy();const i=this.device.createTexture({size:{width:e.width,height:e.height},format:this._getGpuTextureFormat(e),mipLevelCount:n,usage:this._getTextureUsage(e)});t.texture=i,t.view=i.createView(),t.width=e.width,t.height=e.height,t.mipLevelCount=n,t.hasContent=!1,t.accountedBytes=this._accountant.reallocate(t.accountedBytes,this._estimateTextureBytes(e,n))}if(t.sampler=this._createSampler(e),e instanceof kr){const i=Bo(e.format),n=e._consumeDirtyRegion();if(null===n||n.full||!t.hasContent)this.device.queue.writeTexture({texture:t.texture},e.buffer,{bytesPerRow:e.width*i.bytesPerPixel,rowsPerImage:e.height},{width:e.width,height:e.height}),this._accountant.recordTextureUpload(e.width*e.height*i.bytesPerPixel);else{const r=i.channels,s=i.bytesPerPixel,o=n.width*n.height*s,a=e.buffer instanceof Float32Array?new Float32Array(o/4):new Uint8Array(o),h=e.width*r,l=n.width*r;for(let t=0;t<n.height;t++){const i=(n.y+t)*h+n.x*r,s=t*l;a.set(e.buffer.subarray(i,i+l),s)}this.device.queue.writeTexture({texture:t.texture,origin:{x:n.x,y:n.y}},a,{bytesPerRow:n.width*s,rowsPerImage:n.height},{width:n.width,height:n.height}),this._accountant.recordTextureUpload(n.width*n.height*s)}t.hasContent=!0}else if(!(e instanceof _i)){const i=e.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:t.texture},{width:e.width,height:e.height}),this._accountant.recordTextureUpload(e.width*e.height*4),t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}t.version=i}return t}_evictTexture(e){const t=this._textureStates.get(e),i=this._textureDestroyHandlers.get(e);i&&(e.removeDestroyListener(i),this._textureDestroyHandlers.delete(e)),t&&(t.texture.destroy(),this._accountant.free(t.accountedBytes),t.accountedBytes=0,this._textureStates.delete(e)),this._texture===e&&(this._texture=null)}_subscribeRenderTarget(e){if(!this._renderTargetDestroyHandlers.has(e)){const t=()=>{this._renderTarget===e&&(this._renderTarget=this._rootRenderTarget),this._passCoordinatorInstance?.releaseStencilTarget(e),this._renderTargetDestroyHandlers.delete(e)};e.addDestroyListener(t),this._renderTargetDestroyHandlers.set(e,t)}}_unsubscribeRenderTarget(e){const t=this._renderTargetDestroyHandlers.get(e);t&&(e.removeDestroyListener(t),this._renderTargetDestroyHandlers.delete(e))}_toClipPixels(e){const t=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(e.left,e.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(e.right,e.bottom)),n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),s=Math.min(t.y,i.y),o=Math.max(t.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(n))),u=Math.max(0,Math.min(a,Math.ceil(r))),c=Math.max(0,Math.min(h,Math.floor(s))),d=Math.max(0,Math.min(h,Math.ceil(o)));return{x:l,y:c,width:Math.max(0,u-l),height:Math.max(0,d-c)}}_intersectClips(e,t){const i=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.width,t.x+t.width),s=Math.min(e.y+e.height,t.y+t.height);return{x:i,y:n,width:Math.max(0,r-i),height:Math.max(0,s-n)}}_createSampler(e){const t=e instanceof kr&&("r32f"===e.format||"rgba32f"===e.format),i=t?"nearest":this._getFilterMode(e.scaleMode);return this.device.createSampler({addressModeU:this._getAddressMode(e.wrapMode),addressModeV:this._getAddressMode(e.wrapMode),magFilter:i,minFilter:i,mipmapFilter:t?"nearest":this._getMipmapFilterMode(e.scaleMode)})}_getGpuTextureFormat(e){if(e instanceof kr){return Bo(e.format).gpuFormat}return bo}_getTextureUsage(e){const t=this._getMipLevelCount(e)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return e instanceof _i?GPUTextureUsage.COPY_SRC|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|t:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|t}_getAddressMode(t){switch(t){case e.WrapModes.Repeat:return"repeat";case e.WrapModes.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case e.ScaleModes.Nearest:case e.ScaleModes.NearestMipmapNearest:case e.ScaleModes.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case e.ScaleModes.NearestMipmapLinear:case e.ScaleModes.LinearMipmapLinear:return"linear";default:return"nearest"}}_textureBytesPerPixel(e){if(e instanceof kr){const t=e.format;return to(t)}return 4}_estimateTextureBytes(e,t){return eo(e.width,e.height,this._textureBytesPerPixel(e),t)}_getMipLevelCount(e){if(!e.generateMipMap)return 1;const t=Math.max(e.width,e.height);return t<=1?1:Math.floor(Math.log2(t))+1}_generateMipmaps(e,t){if(t<=1)return;const i=this._getMipmapResources(),n=this.device.createCommandEncoder();for(let r=1;r<t;r++){const t=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:e.createView({baseMipLevel:r-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),s=n.beginRenderPass({colorAttachments:[{view:e.createView({baseMipLevel:r,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});s.setPipeline(i.pipeline),s.setBindGroup(0,t),s.draw(3),s.end()}this.device.queue.submit([n.finish()])}_getMipmapResources(){return null!==this._mipmapShaderModule&&null!==this._mipmapBindGroupLayout&&null!==this._mipmapPipelineLayout&&null!==this._mipmapPipeline&&null!==this._mipmapSampler||(this._mipmapShaderModule=this.device.createShaderModule({code:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@group(0) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(0) @binding(1)\nvar sourceSampler: sampler;\n\n@vertex\nfn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0)\n );\n // Y is flipped vs the position array: NDC Y points up, but texture UV\n // Y points down (UV (0,0) is the top-left of the source). Matching the\n // two ensures that the output texture's top-left pixel samples from the\n // source's top-left, so every mip level has the same orientation as the\n // level above it. Prior to this, odd mip levels were rendered upside\n // down, producing visible texture flips at view-size doublings.\n var texcoords = array<vec2<f32>, 3>(\n vec2<f32>(0.0, 1.0),\n vec2<f32>(2.0, 1.0),\n vec2<f32>(0.0, -1.0)\n );\n var output: VertexOutput;\n\n output.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);\n output.texcoord = texcoords[vertexIndex];\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(sourceTexture, sourceSampler, input.texcoord);\n}\n"}),this._mipmapBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._mipmapPipelineLayout=this.device.createPipelineLayout({bindGroupLayouts:[this._mipmapBindGroupLayout]}),this._mipmapPipeline=this.device.createRenderPipeline({layout:this._mipmapPipelineLayout,vertex:{module:this._mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this._mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:bo,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}}),this._mipmapSampler=this.device.createSampler({minFilter:"linear",magFilter:"linear",mipmapFilter:"nearest"})),{bindGroupLayout:this._mipmapBindGroupLayout,pipeline:this._mipmapPipeline,sampler:this._mipmapSampler}}}function Bo(e){switch(e){case"r8":return{gpuFormat:"r8unorm",bytesPerPixel:1,channels:1};case"r32f":return{gpuFormat:"r32float",bytesPerPixel:4,channels:1};case"rgba8":return{gpuFormat:"rgba8unorm",bytesPerPixel:4,channels:4};case"rgba32f":return{gpuFormat:"rgba32float",bytesPerPixel:16,channels:4}}}class Co extends vr{onStart=new x;onStop=new x;_videoElement;_duration;_volume=1;_playbackRate=1;_loop=!1;_muted=!1;_bus=null;_audioSetup=null;_textureDirty=!0;_lastVideoTime=Number.NaN;_videoFrameCallbackHandle=null;_onMetadataHandler;_onResizeHandler;_onVideoFrameHandler;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this.setupWithAudioContext(e)};constructor(e,t,i){super(new pi(e,i));const{duration:n,volume:r,playbackRate:s,loop:o,muted:a}=e;this._videoElement=e,this._duration=n,this._volume=r,this._playbackRate=s,this._loop=o,this._muted=a,this._onMetadataHandler=this._onVideoMetadataUpdated.bind(this),this._onResizeHandler=this._onVideoMetadataUpdated.bind(this),this._onVideoFrameHandler=this._onVideoFrame.bind(this),0!==this._videoElement.videoWidth&&0!==this._videoElement.videoHeight||(this._videoElement.addEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.addEventListener("resize",this._onResizeHandler)),t&&this.applyOptions(t),U()?this.setupWithAudioContext(L()):I.add(this._onAudioContextReady),this.updateTexture(),this._requestVideoFrameCallback()}get videoElement(){return this._videoElement}get duration(){return this._duration}get progress(){const e=this.currentTime,t=this.duration;return e%t/t}get volume(){return this._volume}set volume(e){this.setVolume(e)}get loop(){return this._loop}set loop(e){this.setLoop(e)}get playbackRate(){return this._playbackRate}set playbackRate(e){this.setPlaybackRate(e)}get currentTime(){return this.getTime()}set currentTime(e){this.setTime(e)}get muted(){return this._muted}set muted(e){this.setMuted(e)}get paused(){return this._videoElement.paused}set paused(e){e?this.pause():this.play()}get playing(){return!this.paused}set playing(e){e?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}get bus(){return this._bus}set bus(e){if(this._bus!==e&&(this._audioSetup&&this._audioSetup.gainNode.disconnect(),this._bus=e,this._audioSetup)){const t=e._getInputNode();t?this._audioSetup.gainNode.connect(t):this._audioSetup.gainNode.connect(this._audioSetup.audioContext.destination)}}play(e){return e&&this.applyOptions(e),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(e){return e&&this.applyOptions(e),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(e){return this.pause(e),this.currentTime=0,this}toggle(e){return this.paused?this.play(e):this.pause(e)}applyOptions(e={}){const{volume:t,loop:i,playbackRate:n,time:r,muted:s}=e;return void 0!==t&&(this.volume=t),void 0!==i&&(this.loop=i),void 0!==n&&(this.playbackRate=n),void 0!==r&&(this.currentTime=r),void 0!==s&&(this.muted=s),this}setVolume(e){const t=Y(e,0,2);if(this._volume===t)return this;if(this._volume=t,this._audioSetup){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(this.muted?0:t,i.currentTime,.01)}return this}setLoop(e){return this._loop!==e&&(this._loop=e,this._videoElement.loop=e),this}setPlaybackRate(e){const t=Y(e,.1,20);return this._playbackRate!==t&&(this._playbackRate=t,this._videoElement.playbackRate=t),this}getTime(){return this._videoElement.currentTime}setTime(e){return this._videoElement.currentTime=Math.max(0,e),this}setMuted(e){if(this._muted!==e&&(this._muted=e,this._audioSetup)){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(e?0:this.volume,i.currentTime,.01)}return this}_collect(e,t){this.visible&&(this._markTextureDirtyOnPlaybackAdvance(),this.updateTexture()),super._collect(e,t)}updateTexture(){const e=this.texture;if(!e||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const t=this.textureFrame.width>0&&this.textureFrame.height>0;return e.updateSource(),e.width>0&&e.height>0&&this.setTextureFrame(et.temp.set(0,0,e.width,e.height),!t),this._textureDirty=!1,this}destroy(){super.destroy(),this.stop(),this._videoElement.removeEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.removeEventListener("resize",this._onResizeHandler),this._cancelVideoFrameCallback(),I.remove(this._onAudioContextReady),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null),this.onStart.destroy(),this.onStop.destroy()}_onVideoMetadataUpdated(){this._textureDirty=!0,this.updateTexture()}_onVideoFrame(e,t){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyOnPlaybackAdvance(){const e=this._videoElement.currentTime;this._lastVideoTime!==e&&(this._lastVideoTime=e,this._textureDirty=!0)}_requestVideoFrameCallback(){const e=this._videoElement;e.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=e.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const e=this._videoElement;e.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(e.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext=e=>{const t=e.createGain();t.gain.setTargetAtTime(this.muted?0:this.volume,e.currentTime,.01);const i=this.bus?._getInputNode()??null;i?t.connect(i):t.connect(e.destination);const n=e.createMediaElementSource(this._videoElement);n.connect(t),this._audioSetup={audioContext:e,gainNode:t,sourceNode:n}}}class To{_objectUrls=[];createObjectUrl(e){const t=URL.createObjectURL(e);return this._objectUrls.push(t),t}revokeObjectUrl(e){URL.revokeObjectURL(e);const t=this._objectUrls.indexOf(e);-1!==t&&this._objectUrls.splice(t,1)}destroy(){for(const e of this._objectUrls)URL.revokeObjectURL(e);this._objectUrls.length=0}}class Mo extends To{storageName="binary";async process(e){return e.arrayBuffer()}async create(e){return e}}function Po(e,t){const i=e.match(new RegExp(`\\b${t}=(-?\\d+)`));return void 0!==i?.[1]?parseInt(i[1],10):0}function Ao(e,t){const i=e.match(new RegExp(`\\b${t}="([^"]*)"`));if(void 0!==i?.[1])return i[1];const n=e.match(new RegExp(`\\b${t}=(\\S+)`));return n?.[1]??""}function Eo(e){const t=e.split(/\r?\n/),i=[],n=new Map,r=new Map;let s=0,o=0;for(const e of t){const t=e.trim();if(0===t.length)continue;switch(t.split(/\s/)[0]??""){case"common":s=Po(t,"lineHeight"),o=Po(t,"base");break;case"page":{const e=Po(t,"id"),n=Ao(t,"file");i[e]=n;break}case"char":{const e=Po(t,"id");n.set(e,{x:Po(t,"x"),y:Po(t,"y"),width:Po(t,"width"),height:Po(t,"height"),xOffset:Po(t,"xoffset"),yOffset:Po(t,"yoffset"),xAdvance:Po(t,"xadvance"),page:Po(t,"page")});break}case"kerning":{const e=Po(t,"first"),i=Po(t,"second"),n=Po(t,"amount");r.set(`${e},${i}`,n);break}}}return{pages:i,chars:n,kernings:r,lineHeight:s,base:o}}class Ro extends To{storageName="csv";async process(e){return e.text()}async create(e,t={}){const i=t.delimiter??",",n=[],r=e.replaceAll("\r\n","\n").replaceAll("\r","\n");let s=[],o="",a=!1,h=0;for(;h<r.length;){const e=r[h];a?'"'===e?'"'===r[h+1]?(o+='"',h+=2):(a=!1,h++):(o+=e,h++):'"'===e?(a=!0,h++):e===i?(s.push(o),o="",h++):"\n"===e?(s.push(o),o="",n.push(s),s=[],h++):(o+=e,h++)}return s.push(o),s.some(e=>""!==e)&&n.push(s),n}}class ko extends To{storageName="font";_addedFontFaces=[];async process(e){return e.arrayBuffer()}async create(e,t){if(!t?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:n,addToDocument:r}=t;if(e.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${e.byteLength}.`);const s=await new FontFace(i,e,n).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${e.byteLength} bytes).`)});return!1!==r&&(document.fonts.add(s),this._addedFontFaces.push(s)),s}destroy(){for(const e of this._addedFontFaces)document.fonts.delete(e);this._addedFontFaces.length=0,super.destroy()}}const Do=[{mimeType:"image/x-icon",pattern:[0,0,1,0],mask:[255,255,255,255]},{mimeType:"image/x-icon",pattern:[0,0,2,0],mask:[255,255,255,255]},{mimeType:"image/bmp",pattern:[66,77],mask:[255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,55,97],mask:[255,255,255,255,255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,57,97],mask:[255,255,255,255,255,255]},{mimeType:"image/webp",pattern:[82,73,70,70,0,0,0,0,87,69,66,80,86,80],mask:[255,255,255,255,0,0,0,0,255,255,255,255,255,255]},{mimeType:"image/png",pattern:[137,80,78,71,13,10,26,10],mask:[255,255,255,255,255,255,255,255]},{mimeType:"image/jpeg",pattern:[255,216,255],mask:[255,255,255]},{mimeType:"@/audio/basic",pattern:[46,115,110,100],mask:[255,255,255,255]},{mimeType:"@/audio/mpeg",pattern:[73,68,51],mask:[255,255,255]},{mimeType:"@/audio/wave",pattern:[82,73,70,70,0,0,0,0,87,65,86,69],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"@/audio/midi",pattern:[77,84,104,100,0,0,0,6],mask:[255,255,255,255,255,255,255,255]},{mimeType:"@/audio/aiff",pattern:[70,79,82,77,0,0,0,0,65,73,70,70],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"video/avi",pattern:[82,73,70,70,0,0,0,0,65,86,73,32],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"application/ogg",pattern:[79,103,103,83,0],mask:[255,255,255,255,255]}],Fo=e=>{const t=new Uint8Array(e);if(!t.length)throw new Error("Cannot determine mime type: No data.");for(const e of Do)if(!(t.length<e.pattern.length)&&e.pattern.every((i,n)=>((t[n]??0)&(e.mask[n]??0))===i))return e.mimeType;return(e=>{const t=new Uint8Array(e),i=new DataView(e).getUint32(0,!1);return!(t.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...t.subarray(4,11))})(e)?"video/mp4":(e=>{const t=new Uint8Array(e),i=[26,69,223,163].every((e,i)=>e===t[i]),n=t.subarray(4,4100),r=n.findIndex((e,t,i)=>66===i[t]&&130===i[t+1]);return!(!i||-1===r)&&"webm"===String.fromCharCode(...n.subarray(r+3,r+7))})(e)?"video/webm":(e=>{if(e.byteLength<12)return!1;const t=new Uint8Array(e);if("ftyp"!==String.fromCharCode(t[4]??0,t[5]??0,t[6]??0,t[7]??0))return!1;const i=String.fromCharCode(t[8]??0,t[9]??0,t[10]??0,t[11]??0);return"avif"===i||"avis"===i})(e)?"image/avif":"text/plain"};class Io extends To{storageName="image";async process(e){return e.arrayBuffer()}async create(e,t={}){const i=new Blob([e],{type:t.mimeType??Fo(e)});if("function"==typeof createImageBitmap)return createImageBitmap(i);const n=this.createObjectUrl(i);return new Promise((e,t)=>{const i=new Image,r=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{r(),e(i)},{once:!0}),i.addEventListener("error",()=>{r(),t(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),t(new Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const Lo={once:!0};class Uo extends To{storageName="music";_audioElements=[];async process(e){return e.arrayBuffer()}async create(e,t={}){const{mimeType:i,loadEvent:n,playbackOptions:r,stallTimeout:s}=t,o=new Blob([e],{type:i??Fo(e)}),a=this.createObjectUrl(o);return new Promise((e,t)=>{const i=document.createElement("audio");let o;this._audioElements.push(i);let h=!1;const l=e=>{h||(h=!0,void 0!==o&&(clearTimeout(o),o=void 0),this.revokeObjectUrl(a),e())};i.addEventListener("error",()=>l(()=>t(new Error("Error loading audio source."))),Lo),i.addEventListener("abort",()=>l(()=>t(new Error("Audio loading was canceled."))),Lo),i.addEventListener("emptied",()=>l(()=>t(new Error("Audio loading was emptied."))),Lo),i.addEventListener(n??"canplaythrough",()=>l(()=>e(new mt(i,r))),Lo),void 0!==s&&i.addEventListener("stalled",()=>{h||(void 0!==o&&clearTimeout(o),o=setTimeout(()=>l(()=>t(new Error("Audio loading stalled."))),s))}),i.preload="auto",i.src=a})}destroy(){for(const e of this._audioElements)e.pause(),e.src="",e.load();this._audioElements.length=0,super.destroy()}}class Go extends To{storageName="sound";async process(e){return e.arrayBuffer()}async create(e,t={}){const i=await G(e);return new lt(i,{...t.playbackOptions,...void 0!==t.poolSize&&{poolSize:t.poolSize},...void 0!==t.sprites&&{sprites:t.sprites}})}}const No=e=>{const t=e.split(":");let i;return i=3===t.length?3600*Number(t[0])+60*Number(t[1])+Number(t[2]):2===t.length?60*Number(t[0])+Number(t[1]):Number(t[0]),i},Oo=new Set(["start","center","end","left","right"]),Vo=new Set(["start","center","end"]),zo=new Set(["auto","line-left","center","line-right"]),qo=(e,t)=>{if(t)for(const i of t.split(/\s+/)){const t=i.indexOf(":");if(-1===t)continue;const n=i.slice(0,t),r=i.slice(t+1);switch(n){case"vertical":"rl"!==r&&"lr"!==r&&""!==r||(e.vertical=r);break;case"line":if("auto"===r)e.line="auto";else{const[t="",i]=r.split(","),n=parseFloat(t);Number.isNaN(n)||(e.line=n),void 0!==i&&Vo.has(i)&&(e.lineAlign=i)}break;case"position":{const[t="",i]=r.split(","),n=parseFloat(t);Number.isNaN(n)||(e.position=n),void 0!==i&&zo.has(i)&&(e.positionAlign=i);break}case"size":{const t=parseFloat(r);Number.isNaN(t)||(e.size=t);break}case"align":Oo.has(r)&&(e.align=r)}}},Wo=e=>{const t=e.trim().replace(",",".").split(":");return 3600*Number(t[0])+60*Number(t[1])+Number(t[2])};class Yo extends To{storageName="subtitle";async process(e){const t=await e.text();return{fmt:(e.url.split("?")[0]??e.url).toLowerCase().endsWith(".srt")?"srt":"vtt",text:t}}async create(e){return"srt"===e.fmt?(e=>{const t=[],i=e.replaceAll("\r\n","\n").replaceAll("\r","\n").split(/\n[ \t]*\n/);for(const e of i){const i=e.trim().split("\n");if(i.length<2)continue;let n=0;/^\d+$/.test((i[0]??"").trim())&&(n=1);const r=i[n];if(!r?.includes("--\x3e"))continue;const s=r.indexOf("--\x3e"),o=Wo(r.slice(0,s)),a=Wo(r.slice(s+3)),h=i.slice(n+1).join("\n");t.push(new VTTCue(o,a,h))}return t})(e.text):(e=>{const t=[],i=e.replaceAll("\r\n","\n").replaceAll("\r","\n").split("\n");let n=0;for(;n<i.length&&!(i[n]??"").includes("--\x3e");)n++;for(;n<i.length;){const e=(i[n]??"").trim();if(e.includes("--\x3e")){const r=e.indexOf("--\x3e"),s=e.slice(0,r).trim(),o=e.slice(r+3).trim().split(/\s+/),a=o[0]??"",h=o.slice(1).join(" "),l=No(s),u=No(a);n++;const c=[];for(;n<i.length;){const e=i[n];if(void 0===e||""===e.trim())break;c.push(e),n++}const d=new VTTCue(l,u,c.join("\n"));qo(d,h),t.push(d)}else n++}return t})(e.text)}}class $o extends To{storageName="svg";async process(e){return e.text()}async create(e,t={}){const{width:i,height:n}=t;let r=e;if(void 0!==i||void 0!==n){const e=r.indexOf("<svg"),t=r.indexOf(">",e);if(-1!==e&&-1!==t){const s=r.slice(0,e),o=r.slice(e+4,t),a=r.slice(t+1);r=`${s}<svg${String(o).replaceAll(/\s+width=(?:"[^"]*"|'[^']*')/g,"").replaceAll(/\s+height=(?:"[^"]*"|'[^']*')/g,"")}${(void 0!==i?` width="${i}"`:"")+(void 0!==n?` height="${n}"`:"")}>${a}`}}const s=new Blob([r],{type:"image/svg+xml"}),o=this.createObjectUrl(s);return new Promise((e,t)=>{const i=new Image,n=()=>{this.revokeObjectUrl(o)};i.addEventListener("load",()=>{n(),e(i)},{once:!0}),i.addEventListener("error",()=>{n(),t(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{n(),t(new Error("Image loading was canceled."))},{once:!0}),i.src=o})}}class Xo extends To{storageName="texture";async process(e){return e.arrayBuffer()}async create(e,t={}){const{mimeType:i,samplerOptions:n}=t,r=new Blob([e],{type:i??Fo(e)});if("function"==typeof createImageBitmap){const e=await createImageBitmap(r);return new pi(e,n)}const s=this.createObjectUrl(r);return new Promise((e,t)=>{const i=new Image,r=()=>{this.revokeObjectUrl(s)};i.addEventListener("load",()=>{r(),e(new pi(i,n))},{once:!0}),i.addEventListener("error",()=>{r(),t(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),t(new Error("Image loading was canceled."))},{once:!0}),i.src=s})}}const Ho={once:!0};class jo extends To{storageName="video";_videoElements=[];async process(e){return e.arrayBuffer()}async create(e,t={}){const{mimeType:i,loadEvent:n,playbackOptions:r,samplerOptions:s,stallTimeout:o}=t,a=new Blob([e],{type:i??Fo(e)}),h=this.createObjectUrl(a);return new Promise((e,t)=>{const i=document.createElement("video");let a;this._videoElements.push(i);let l=!1;const u=e=>{l||(l=!0,void 0!==a&&(clearTimeout(a),a=void 0),this.revokeObjectUrl(h),e())};i.addEventListener("error",()=>u(()=>t(new Error("Video loading error."))),Ho),i.addEventListener("abort",()=>u(()=>t(new Error("Video loading error: cancelled."))),Ho),i.addEventListener("emptied",()=>u(()=>t(new Error("Video loading error: emptied."))),Ho),i.addEventListener(n??"canplaythrough",()=>u(()=>e(new Co(i,r,s))),Ho),void 0!==o&&i.addEventListener("stalled",()=>{l||(void 0!==a&&clearTimeout(a),a=setTimeout(()=>u(()=>t(new Error("Video loading stalled."))),o))}),i.preload="auto",i.src=h})}destroy(){for(const e of this._videoElements)e.pause(),e.src="",e.load();this._videoElements.length=0,super.destroy()}}class Ko extends To{storageName="wasm";async process(e){return e.arrayBuffer()}async create(e){return WebAssembly.compile(e)}}class Qo extends To{storageName="xml";async process(e){return e.text()}async create(e){const t=(new DOMParser).parseFromString(e,"text/xml"),i=t.querySelector("parsererror");if(i)throw new Error(`XML parse error: ${i.textContent.trim()||"unknown error"}`);return t}}class Zo{}class Jo{}class ea{}class ta{}class ia{}class na{}class ra{}class sa{}class oa{}class aa{}function ha(e){return()=>{const t=e();return{async load({source:e,options:i},n){const r=await n.fetchArrayBuffer(e);return t.create(r,i)},createFromBytes:(e,i)=>t.create(e,i),destroy(){t.destroy()}}}}function la(e){return()=>{const t=e();return{async load({source:e,options:i},n){const r=await n.fetchText(e);return t.create(r,i)},createFromBytes:(e,i)=>t.create((new TextDecoder).decode(e),i),destroy(){t.destroy()}}}}function ua(e,t,i){return{type:e,...t,create:i}}const ca=ua(pi,{typeNames:["texture"]},ha(()=>new Xo)),da=ua(lt,{typeNames:["sound"]},ha(()=>new Go)),_a=ua(mt,{typeNames:["music"]},ha(()=>new Uo)),fa=ua(Co,{typeNames:["video"]},ha(()=>new jo)),pa=ua(Zo,{typeNames:["json"]},()=>({load:async({source:e},t)=>t.fetchJson(e),createFromBytes:e=>Promise.resolve(JSON.parse((new TextDecoder).decode(e)))})),ma=ua(Jo,{typeNames:["text"]},()=>({load:async({source:e},t)=>t.fetchText(e),createFromBytes:e=>Promise.resolve((new TextDecoder).decode(e))})),ga=ua(ea,{typeNames:["svg"]},la(()=>new $o)),ya=ua(ta,{typeNames:["vtt","srt"]},()=>{const e=new Yo;return{async load({source:t},i){const n=await i.fetchText(t),r=(t.split("?")[0]??t).toLowerCase().endsWith(".srt")?"srt":"vtt",s=await e.process({text:()=>Promise.resolve(n),url:t});return e.create({...s,fmt:r})},destroy(){e.destroy()}}}),wa=ua(ia,{typeNames:["xml"]},la(()=>new Qo)),xa=ua(na,{typeNames:["csv"]},la(()=>new Ro)),va=ua(oa,{typeNames:["binary"]},ha(()=>new Mo)),ba=ua(Sr,{typeNames:["bmFont"],extensions:["fnt"]},e=>({async load({source:t},i){const n=Eo(await i.fetchText(t)),r=await Promise.all(n.pages.map(i=>e.load(pi,function(e,t){try{return new URL(e,t).href}catch{const i="https://exojs.invalid/";return new URL(e,i+t.replace(/^\/+/,"")).href.slice(i.length)}}(i,t))));return new Sr(n,r)}})),Sa=[];"undefined"!=typeof FontFace&&Sa.push(ua(sa,{typeNames:["font"],extensions:["woff","woff2","ttf","otf"]},ha(()=>new ko))),"undefined"!=typeof HTMLImageElement&&Sa.push(ua(ra,{typeNames:["image"]},ha(()=>new Io))),"undefined"!=typeof WebAssembly&&Sa.push(ua(aa,{typeNames:["wasm"]},ha(()=>new Ko)));const Ba=Object.freeze([ca,da,_a,fa,pa,ma,ga,ya,wa,xa,va,ba,...Sa]);class Ca{_config;constructor(e){this._config=e}get type(){return this._config.type}get source(){return this._config.source}}const Ta=Ca,Ma="EXOA";function Pa(e){throw new Error(`Invalid asset container: ${e}.`)}function Aa(e){e.byteLength<12&&Pa(`buffer too small for a 12-byte header (got ${e.byteLength})`);const t=new Uint8Array(e),i=new DataView(e);for(let e=0;e<4;e++)t[e]!==Ma.charCodeAt(e)&&Pa(`bad magic (expected "${Ma}")`);const n=i.getUint32(4,!0);n>1&&Pa(`unsupported version ${n} (this build reads up to 1)`);const r=i.getUint32(8,!0),s=12+r;let o;s>e.byteLength&&Pa(`index length ${r} runs past the buffer (size ${e.byteLength})`);try{o=JSON.parse((new TextDecoder).decode(t.subarray(12,s)))}catch{Pa("index is not valid JSON")}Array.isArray(o)||Pa("index is not an array");const a=e.byteLength-s,h=o.map((e,t)=>function(e,t,i){"object"==typeof e&&null!==e||Pa(`index entry ${t} is not an object`);const n=e,{alias:r,type:s,offset:o,length:a,mime:h}=n;return"string"!=typeof r&&Pa(`index entry ${t} has a non-string "alias"`),"string"!=typeof s&&Pa(`index entry ${t} ("${r}") has a non-string "type"`),("number"!=typeof o||!Number.isFinite(o)||o<0)&&Pa(`index entry "${r}" has an invalid "offset"`),("number"!=typeof a||!Number.isFinite(a)||a<0)&&Pa(`index entry "${r}" has an invalid "length"`),o+a>i&&Pa(`index entry "${r}" runs past the data section (offset ${o} + length ${a} > ${i})`),void 0!==h&&"string"!=typeof h&&Pa(`index entry "${r}" has a non-string "mime"`),{alias:r,type:s,offset:o,length:a,..."string"==typeof h&&{mime:h},...void 0!==n.options&&{options:n.options}}}(e,t,a));return{version:n,entries:h,dataStart:s}}class Ea extends Error{bundle;failures;constructor(e,t){super(`Failed to load bundle "${e}" (${t.length} failure${1===t.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=e,this.failures=t}}function Ra(e){return function(e){if(!ka(e))throw new Error("Invalid asset manifest: manifest must be an object.");if(!ka(e.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[t,i]of Object.entries(e.bundles)){if(0===t.trim().length)throw new Error("Invalid asset manifest: bundle names must be non-empty strings.");if(!Array.isArray(i))throw new Error(`Invalid asset manifest: bundle "${t}" must be an array of entries.`);const e=new Map;for(const[n,r]of i.entries()){const i=`bundle "${t}" entry[${n}]`;if(!ka(r))throw new Error(`Invalid asset manifest: ${i} must be an object.`);if("function"!=typeof r.type)throw new Error(`Invalid asset manifest: ${i} has an invalid "type" token.`);Da(r.alias,`${i} has an invalid "alias".`),Da(r.path,`${i} has an invalid "path".`);const s=r.type,o=r.alias;e.has(s)||e.set(s,new Set);const a=e.get(s);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${Fa(s)}, "${o}") in bundle "${t}".`);a.add(o)}}}(e),e}function ka(e){return"object"==typeof e&&null!==e}function Da(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`Invalid asset manifest: ${t}`)}function Fa(e){return e.name.length>0?e.name:"(anonymous type)"}class Ia{entries;constructor(e){if(Object.hasOwn(e,"entries"))throw new Error('An Assets container may not define an asset named "entries": that name is reserved for the spread-composition helper.');const t={};for(const i of Object.keys(e)){const n=e[i],r=n instanceof Ca?n:new Ca(n);t[i]=r,Object.defineProperty(this,i,{value:r,enumerable:!0,configurable:!1,writable:!1})}this.entries=t}}const La=Ia;class Ua{async resolve(e,t){const{storageName:i,key:n,url:r,requestOptions:s,factory:o,options:a}=e;for(const e of t){const t=await e.load(i,n);if(null!=t)try{return await o.create(t,a)}catch{await e.delete(i,n)}}const h=await fetch(r,s);if(!h.ok)throw new Error(`Failed to fetch "${r}" (${h.status} ${h.statusText}).`);const l=await o.process(h),u=await o.create(l,a);for(const e of t)try{await e.save(i,n,l)}catch{}return u}}const Ga=e=>{const t=Object.getPrototypeOf(e.prototype);return t?.constructor??null};class Na{_factories=new io({walk:Ga,dispose:e=>e.destroy()});register(e,t){this._factories.set(e,t)}resolve(e){const t=this._factories.resolve(e);if(!t)throw new Error(`No factory registered for ${e.name}. Register one with loader.register() before loading.`);return t}has(e){return this._factories.has(e)}destroy(){this._factories.destroy()}}class Oa{onProgress;_progress;_promise;constructor(e,t){this.onProgress=new x,this._progress={total:t,loaded:0,pending:t,failed:0},this._promise=e}get progress(){return this._progress}_notifyItem(e){const t=this._progress,i=t.loaded+(e?1:0),n=t.failed+(e?0:1),r=i+n;this._progress={total:t.total,loaded:i,pending:Math.max(0,t.total-r),failed:n},this.onProgress.dispatch(this._progress)}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}}class Va{_registry=new Na;_assetTypeMap=new Map;_resources=new Map;_resourceKeys=new WeakMap;_manifest=new Map;_bundles=new Map;_inFlight=new Map;_typeIds=new WeakMap;_preventStoreKeys=new Set;_stores;_cacheStrategy;_aliasKeyToIdentityKey=new Map;_identityKeyToAliases=new Map;_inFlightByIdentity=new Map;_handlerFunctions=new Map;_extensionMap=new Map;_boundHandlers=[];_basePath;_fetchOptions;_concurrency;_nextTypeId=1;_fgBatchActive=0;_fgBatchLoaded=0;_fgBatchTotal=0;_backgroundQueue=[];_backgroundActive=0;_backgroundTotal=0;_backgroundLoaded=0;_backgroundResolve=null;onProgress=new x;onBundleProgress=new x;onLoaded=new x;onError=new x;onLoadStart=new x;onLoadProgress=new x;onLoadComplete=new x;onLoadError=new x;constructor(e={}){this._basePath=e.basePath??"",this._fetchOptions=e.fetchOptions??{},this._concurrency=e.concurrency??6,this._stores=e.cache?Array.isArray(e.cache)?e.cache:[e.cache]:[],this._cacheStrategy=e.cacheStrategy??new Ua}register(e,t){return this._registry.register(e,t),this}registerAssetType(e,t,i){if("function"==typeof t)this._assetTypeMap.set(e,t),i&&this._registry.register(t,i);else{const i=class{};Object.defineProperty(i,"name",{value:e}),this._assetTypeMap.set(e,i);const n=t.getIdentityKey?.bind(t);this._handlerFunctions.set(i,{load:(e,i)=>t.load(e,i),...void 0!==n&&{getIdentityKey:n}})}return this}registerExtension(e,t){return this._extensionMap.set(e.replace(/^\./,"").toLowerCase(),t),this}add(e,t){const i=e;if("string"==typeof t)this._addManifestEntry(i,t,t);else if(Array.isArray(t)){const e=t;for(const t of e)this._addManifestEntry(i,t,t)}else for(const[e,n]of Object.entries(t))this._addManifestEntry(i,e,n);return this}registerManifest(e){const t=Ra(e),i=new Map,n=new Array;for(const[e,r]of Object.entries(t.bundles)){if(this._bundles.has(e))throw new Error(`Bundle "${e}" is already registered.`);const t=new Array;for(const n of r){const r=n.type,s=this._key(r,n.alias),o=i.get(s)??this._getManifestEntry(r,n.alias);if(o&&!this._isManifestDefinitionEquivalent(o,n.path,n.options))throw new Error(`Conflicting asset definition for (${this._describeType(r)}, "${n.alias}") while registering bundle "${e}".`);i.set(s,{path:n.path,options:n.options}),t.push({type:r,alias:n.alias,path:n.path,options:n.options})}n.push([e,t])}for(const[e,t]of n){for(const e of t)this._addManifestEntry(e.type,e.alias,e.path,e.options);this._bundles.set(e,t)}return this}async loadBundle(e,t={}){const i=this._bundles.get(e);if(!i)throw new Error(`Unknown bundle "${e}".`);const n=i.length;let r=0;const s=new Array;if(0!==n){if(await Promise.all(i.map(async i=>{try{await(t.background?this._loadSingleBackground(i.type,i.alias,i.path,i.options):this._loadSingle(i.type,i.alias,i.options,i.path))}catch(e){s.push({type:i.type,alias:i.alias,error:this._normalizeError(e)})}finally{r++,this._emitBundleProgress(e,r,n,t.onProgress)}})),s.length>0)throw new Ea(e,s)}else this._emitBundleProgress(e,0,0,t.onProgress)}async loadContainer(e){const t=await this._contextFetch(e,"__ctx_binary",e=>e.arrayBuffer()),{entries:i,dataStart:n}=Aa(t),r=i.map(t=>{const i=this._assetTypeMap.get(t.type);if(!i)throw new Error(`Container "${e}" references unknown asset type "${t.type}".`);return{entry:t,type:i}});await Promise.all(r.map(({entry:e,type:i})=>{const r=n+e.offset,s=t.slice(r,r+e.length);return this._injectSource(i,e.alias,s,e.options)}))}hasBundle(e){const t=this._bundles.get(e);return!!t&&t.every(e=>this._hasResource(e.type,e.alias))}load(e,t,i){if(e instanceof Ca){const t=e,i=t._config.source;return this._createLoadingQueue([{alias:i,asset:t}],e=>e.get(i))}if(e instanceof Ia){const t=e,i=Object.entries(t.entries).map(([e,t])=>({alias:e,asset:t}));return this._createLoadingQueue(i,e=>{const t={};for(const{alias:n}of i)t[n]=e.get(n);return t})}if("string"==typeof e&&void 0===t){const t=e,i=t.match(/\.([^./?#]+)(?:[?#]|$)/)?.[1]?.toLowerCase(),n=i?this._extensionMap.get(i):void 0;if(void 0===n)throw new Error(`Loader: no type registered for extension ".${i??"?"}" in "${t}". Register one via loader.registerExtension().`);const r=n===sa?{family:(t.split("/").pop()?.split(/[?#]/)[0]??"").replace(/\.[^.]+$/,"")}:void 0;this._onFgBatchStart(t,t);let s=null;const o=this._loadSingle(n,t,r).then(e=>(s?.(!0),this._onFgBatchSettled(t,!0),e),e=>{throw s?.(!1),this._onFgBatchSettled(t,!1,this._normalizeError(e)),e}),a=new Oa(o,1);return s=a._notifyItem.bind(a),a}if("function"==typeof e){const n=e,r=t,s=i;if("string"==typeof r){this._onFgBatchStart(r,r);let e=null;const t=this._loadSingle(n,r,s).then(t=>(e?.(!0),this._onFgBatchSettled(r,!0),t),t=>{throw e?.(!1),this._onFgBatchSettled(r,!1,this._normalizeError(t)),t}),i=new Oa(t,1);return e=i._notifyItem.bind(i),i}if(Array.isArray(r)){const e=r;let t=null;const i=new Array(e.length),o=e.map((e,r)=>(this._onFgBatchStart(e,e),this._loadSingle(n,e,s).then(n=>{i[r]=n,t?.(!0),this._onFgBatchSettled(e,!0)},i=>{throw t?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(i)),i}))),a=Promise.all(o).then(()=>i),h=new Oa(a,e.length);return t=h._notifyItem.bind(h),h}const o=Object.entries(r),a={};let h=null;const l=o.map(([e,t])=>{const i="string"==typeof t?t:t.source,r="string"==typeof t?s:{...t,..."object"==typeof s&&null!==s?s:{}};return this._onFgBatchStart(e,i),this._loadSingle(n,e,r,i).then(t=>{a[e]=t,h?.(!0),this._onFgBatchSettled(e,!0)},t=>{throw h?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t})}),u=Promise.all(l).then(()=>a),c=new Oa(u,o.length);return h=c._notifyItem.bind(c),c}const n=e,r=Object.entries(n).map(([e,t])=>({alias:e,asset:t instanceof Ca?t:new Ta(t)}));return this._createLoadingQueue(r,e=>{const t={};for(const{alias:i}of r)t[i]=e.get(i);return t})}backgroundLoad(){for(const[e,t]of this._manifest)for(const[i,n]of t){if(this._hasResource(e,i))continue;const t=this._key(e,i);this._inFlight.has(t)||this._backgroundQueue.push({type:e,alias:i,path:n.path,options:n.options})}this._backgroundTotal=this._backgroundQueue.length,this._backgroundLoaded=0,this._drainBackground()}loadAll(){return new Promise(e=>{this._backgroundResolve=e,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,e())})}setConcurrency(e){return this._concurrency=e,this}get(e,t){const i=e,n=this._resources.get(i);if(!n?.has(t))throw new Error(`Missing resource "${t}" for type ${i.name}.`);return n.get(t)}peek(e,t){const i=e;return this._resources.get(i)?.get(t)??null}has(e,t){const i=e;return this._resources.get(i)?.has(t)??!1}keyFor(e){return this._resourceKeys.get(e)??null}unload(e,t){if(e instanceof Ca){const t=e,i=this._assetTypeMap.get(t.type);if(!i)return this;const n=this._resolveAssetIdentityKey(i,t),r=this._identityKeyToAliases.get(n);if(r&&r.size>0)for(const e of[...r])this._unloadOne(i,e);else this._unloadOne(i,t._config.source);return this}if(e instanceof Ia){const t=e;for(const[e,i]of Object.entries(t.entries)){const t=i,n=this._assetTypeMap.get(t.type);if(!n)continue;const r=this._resolveAssetIdentityKey(n,t),s=this._identityKeyToAliases.get(r);if(s?.has(e))for(const e of[...s])this._unloadOne(n,e);else this._unloadOne(n,e)}return this}return this._unloadOne(e,t)}_unloadOne(e,t){const i=e,n=this._key(i,t);this._resources.get(i)?.delete(t);const r=this._aliasKeyToIdentityKey.get(n);if((this._inFlight.has(n)||void 0!==r&&this._inFlightByIdentity.has(r))&&this._preventStoreKeys.add(n),void 0!==r){this._aliasKeyToIdentityKey.delete(n);const e=this._identityKeyToAliases.get(r);e&&(e.delete(t),0===e.size&&this._identityKeyToAliases.delete(r))}return this}unloadAll(e){if(e)this._resources.get(e)?.clear();else for(const e of this._resources.values())e.clear();return this}get basePath(){return this._basePath}set basePath(e){this._basePath=e}get fetchOptions(){return this._fetchOptions}set fetchOptions(e){this._fetchOptions=e}bindAsset(e,t){const i=[],n=void 0!==e.typeNames?[...e.typeNames]:[];for(const t of e.extensions??[])i.push(t.replace(/^\./,"").toLowerCase());const r=new Set;for(const e of i){if(r.has(e))throw new Error(`Duplicate extension key ".${e}" within a single asset binding.`);r.add(e)}if(this._handlerFunctions.has(e.type))throw new Error(`An asset handler is already registered for ${e.type.name}.`);for(const e of n)if(this._assetTypeMap.has(e))throw new Error(`Asset type name "${e}" is already registered.`);for(const e of i)if(this._extensionMap.has(e))throw new Error(`File extension ".${e}" is already mapped to an asset type.`);const s=e=>{const{source:t,...i}=e;return 0===Object.keys(i).length?{source:t}:{source:t,options:i}},o=t.getIdentityKey?.bind(t),a=t.createFromBytes?.bind(t);this._handlerFunctions.set(e.type,{load:(e,i)=>t.load(s(e),i),...o&&{getIdentityKey:e=>o(s(e))},...a&&{createFromBytes:(e,t)=>a(e,t)}});for(const t of n)this._assetTypeMap.set(t,e.type);for(const t of i)this._extensionMap.set(t,e.type);this._boundHandlers.push(t)}hasLoadable(e){return this._handlerFunctions.has(e)||this._registry.has(e)}hasAssetType(e){return this._assetTypeMap.has(e)}hasExtension(e){return this._extensionMap.has(e.replace(/^\./,"").toLowerCase())}destroy(){this._registry.destroy();for(const e of this._stores)e.destroy();const e=new Set;for(const t of this._boundHandlers)e.has(t)||(e.add(t),t.destroy?.());this._boundHandlers.length=0,this._resources.clear(),this._manifest.clear(),this._bundles.clear(),this._inFlight.clear(),this._preventStoreKeys.clear(),this._inFlightByIdentity.clear(),this._aliasKeyToIdentityKey.clear(),this._identityKeyToAliases.clear(),this._handlerFunctions.clear(),this._backgroundQueue.length=0,this.onProgress.destroy(),this.onBundleProgress.destroy(),this.onLoaded.destroy(),this.onError.destroy(),this.onLoadStart.destroy(),this.onLoadProgress.destroy(),this.onLoadComplete.destroy(),this.onLoadError.destroy()}async _loadSingle(e,t,i,n){if(this._hasResource(e,t)){const i=this._resources.get(e);if(!0===i?.has(t))return i.get(t)}const r=this._key(e,t);if(this._inFlight.has(r))return this._inFlight.get(r);if(this._boostFromQueue(e,t),this._inFlight.has(r))return this._inFlight.get(r);const s=this._getManifestEntry(e,t),o=n??s?.path??t,a=i??s?.options,h=this._handlerFunctions.get(e);if(h){const i=this._identityKey(e,o),n={source:o};null!=a&&"object"==typeof a&&Object.assign(n,a);const s=this._buildHandlerContext(i);return this._trackInFlight(r,this._fetchWithHandler(e,t,o,n,h.load,s))}return this._trackInFlight(r,this._fetch(e,t,o,a))}_loadSingleBackground(e,t,i,n){if(this._hasResource(e,t)){const i=this._resources.get(e);if(!0===i?.has(t))return Promise.resolve(i.get(t))}const r=this._key(e,t),s=this._inFlight.get(r);if(s)return s;this._isQueuedInBackground(e,t)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:e,alias:t,path:i,options:n}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(r);return o||this._waitForBackgroundEntry(e,t)}_createLoadingQueue(e,t){const i=new Map;let n=null;const r=e.map(({alias:e,asset:t})=>{this._onFgBatchStart(e,t.source);const r=this._assetTypeMap.get(t.type);return r?this._loadSingleAsset(r,e,t).then(t=>{i.set(e,t),n?.(!0),this._onFgBatchSettled(e,!0)},t=>{throw n?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t}):Promise.reject(new Error(`No constructor registered for asset type "${t.type}". Call registerAssetType() first.`)).then(()=>{n?.(!0)},t=>{throw n?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t})}),s=Promise.all(r).then(()=>t(i)),o=new Oa(s,e.length);return n=o._notifyItem.bind(o),o}async _loadSingleAsset(e,t,i){if(this._hasResource(e,t))return this._resources.get(e)?.get(t);const n=i.source,r=i._config,{type:s,source:o,...a}=r,h=this._handlerFunctions.get(e),l=h?.getIdentityKey?.(r)??n,u=`id:${this._getTypeId(e)}:${l}`,c=this._key(e,t);this._aliasKeyToIdentityKey.set(c,u);let d=this._identityKeyToAliases.get(u);d||(d=new Set,this._identityKeyToAliases.set(u,d)),d.add(t);const _=this._inFlightByIdentity.get(u);if(_)return _.then(i=>(this._storeResource(e,t,i),i));let f;if(h){const i={source:n,...a},r=this._buildHandlerContext(u);f=this._fetchWithHandler(e,t,n,i,h.load,r)}else{const i=Object.keys(a).length>0?a:void 0;f=this._fetch(e,t,n,i)}const p=f.finally(()=>{this._inFlightByIdentity.delete(u)}).then(e=>e,t=>{const i=this._identityKeyToAliases.get(u);if(i){for(const t of i){const i=this._key(e,t);this._aliasKeyToIdentityKey.delete(i),this._preventStoreKeys.delete(i)}this._identityKeyToAliases.delete(u)}throw t});return this._inFlightByIdentity.set(u,p),p}async _fetchWithHandler(e,t,i,n,r,s){const o=this._resolveUrl(i);try{const i=await r(n,s);return this._storeResource(e,t,i),i}catch(e){const i=e instanceof Error?e.message:String(e);throw new Error(`Failed to load "${t}" from "${o}": ${i}`,{cause:e})}}_buildHandlerContext(e){return{loader:this,identityKey:e,fetchText:e=>this._contextFetch(e,"__ctx_text",e=>e.text()),fetchArrayBuffer:e=>this._contextFetch(e,"__ctx_binary",e=>e.arrayBuffer()),fetchJson:e=>this._contextFetch(e,"__ctx_json",e=>e.json())}}_contextFetch(e,t,i){const n=this._resolveUrl(e),r={storageName:t,process:i,create:e=>Promise.resolve(e),destroy(){}};return this._cacheStrategy.resolve({storageName:t,key:e,url:n,requestOptions:this._fetchOptions,factory:r,options:void 0},this._stores)}async _injectSource(e,t,i,n){const r=this._handlerFunctions.get(e);let s;if(r?.createFromBytes)s=await r.createFromBytes(i,n);else{if(!this._registry.has(e))throw new Error(`Asset type "${e.name}" cannot be built from container bytes (no createFromBytes handler).`);s=await this._registry.resolve(e).create(i,n)}this._storeResource(e,t,s)}async _fetch(e,t,i,n){const r=this._registry.resolve(e),s=this._resolveUrl(i);try{const o=await this._cacheStrategy.resolve({storageName:r.storageName,key:i,url:s,requestOptions:this._fetchOptions,factory:r,options:n},this._stores);return this._storeResource(e,t,o),o}catch(e){const i=e instanceof Error?e.message:String(e);throw new Error(`Failed to load "${t}" from "${s}": ${i}`,{cause:e})}}_onFgBatchStart(e,t){0===this._fgBatchActive&&(this._fgBatchLoaded=0),this._fgBatchActive++,this._fgBatchTotal++,1===this._fgBatchActive&&this.onLoadStart.dispatch(e,t)}_onFgBatchSettled(e,t,i){t?this._fgBatchLoaded++:void 0!==i&&this.onLoadError.dispatch(e,i),this._fgBatchActive--,this.onLoadProgress.dispatch(this._fgBatchLoaded,this._fgBatchTotal,e),0===this._fgBatchActive&&(this._fgBatchTotal=0,this.onLoadComplete.dispatch())}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const e=this._backgroundQueue.shift();if(!e)continue;const t=this._key(e.type,e.alias);this._hasResource(e.type,e.alias)||this._inFlight.has(t)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(e)}}_boostFromQueue(e,t){const i=this._backgroundQueue.findIndex(i=>i.type===e&&i.alias===t);if(-1===i)return;const[n]=this._backgroundQueue.splice(i,1);void 0!==n&&this._startBackgroundEntry(n)}_isQueuedInBackground(e,t){return this._backgroundQueue.some(i=>i.type===e&&i.alias===t)}_waitForBackgroundEntry(e,t){if(this._hasResource(e,t)){const i=this._resources.get(e);if(!0===i?.has(t))return Promise.resolve(i.get(t))}const i=this._key(e,t),n=this._inFlight.get(i);return n||new Promise((n,r)=>{const s=(i,r,s)=>{i===e&&r===t&&(a(),n(s))},o=(i,n,s)=>{i===e&&n===t&&(a(),r(s))},a=()=>{this.onLoaded.remove(s),this.onError.remove(o)};this.onLoaded.add(s),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(n,r);if(this._hasResource(e,t)){a();const i=this._resources.get(e);n(i?.get(t))}})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const e=this._backgroundResolve;this._backgroundResolve=null,e()}}_startBackgroundEntry(e){const t=this._key(e.type,e.alias);this._backgroundActive++,this._trackInFlight(t,this._fetch(e.type,e.alias,e.path,e.options)).catch(t=>{const i=t instanceof Error?t:new Error(String(t));this.onError.dispatch(e.type,e.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(e,t){const i=t.finally(()=>{this._inFlight.delete(e),this._preventStoreKeys.delete(e)});return this._inFlight.set(e,i),i}_emitBundleProgress(e,t,i,n){this.onBundleProgress.dispatch(e,t,i),n&&n(t,i)}_addManifestEntry(e,t,i,n){this._manifest.has(e)||this._manifest.set(e,new Map);const r=this._manifest.get(e);r&&r.set(t,{path:i,options:n})}_getManifestEntry(e,t){return this._manifest.get(e)?.get(t)}_isManifestDefinitionEquivalent(e,t,i){return e.path===t&&this._areOptionsEquivalent(e.options,i)}_areOptionsEquivalent(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(null===e||null===t)return!1;if("object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!this._areOptionsEquivalent(e[i],t[i]))return!1;return!0}const i=Object.getPrototypeOf(e);if(i!==Object.getPrototypeOf(t))return!1;if(i!==Object.prototype&&null!==i)return!1;const n=e,r=t,s=Object.keys(n),o=Object.keys(r);if(s.length!==o.length)return!1;for(const e of s){if(!Object.hasOwn(r,e))return!1;if(!this._areOptionsEquivalent(n[e],r[e]))return!1}return!0}_normalizeError(e){return e instanceof Error?e:new Error(String(e))}_describeType(e){return e.name.length>0?e.name:"(anonymous type)"}_hasResource(e,t){return this._resources.get(e)?.has(t)??!1}_storeResource(e,t,i){const n=this._key(e,t);if(this._preventStoreKeys.delete(n))return;let r=this._resources.get(e);r||(r=new Map,this._resources.set(e,r)),r.set(t,i),"object"!=typeof i||null===i||this._resourceKeys.has(i)||this._resourceKeys.set(i,{type:e,source:t}),this.onLoaded.dispatch(e,t,i)}_getTypeId(e){let t=this._typeIds.get(e);return void 0===t&&(t=this._nextTypeId++,this._typeIds.set(e,t)),t}_key(e,t){return`${this._getTypeId(e)}:${t}`}_identityKey(e,t){return`id:${this._getTypeId(e)}:${t}`}_resolveAssetIdentityKey(e,t){const i=t._config,n=this._handlerFunctions.get(e),r=n?.getIdentityKey?.(i)??t.source;return`id:${this._getTypeId(e)}:${r}`}_resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//")||e.startsWith("/")?e:`${this._basePath}${e}`}}const za="undefined"!=typeof window,qa="undefined"!=typeof document,Wa="undefined"!=typeof navigator;class Ya{static _readyPromise=null;static get ready(){return null===Ya._readyPromise&&(Ya._readyPromise=Ya._detect()),Ya._readyPromise}webgl2;webgpu;webgpuAdapter;webgpuVendor;webgpuArchitecture;pointer;keyboard;gamepad;touch;maxTouchPoints;audio;fullscreen;vibration;imageBitmap;deviceMemory;offscreenCanvas;webWorkers;devicePixelRatio;constructor(e){this.webgl2=e.webgl2,this.webgpu=e.webgpu,this.webgpuAdapter=e.webgpuAdapter,this.webgpuVendor=e.webgpuVendor,this.webgpuArchitecture=e.webgpuArchitecture,this.pointer=e.pointer,this.keyboard=e.keyboard,this.gamepad=e.gamepad,this.touch=e.touch,this.maxTouchPoints=e.maxTouchPoints,this.audio=e.audio,this.fullscreen=e.fullscreen,this.vibration=e.vibration,this.imageBitmap=e.imageBitmap,this.deviceMemory=e.deviceMemory,this.offscreenCanvas=e.offscreenCanvas,this.webWorkers=e.webWorkers,this.devicePixelRatio=e.devicePixelRatio,Object.freeze(this)}static async _detect(){const[e,t]=await async function(){if(!Xa())return[null,null];const e=navigator.gpu;if(!e||"function"!=typeof e.requestAdapter)return[null,null];try{const t=await e.requestAdapter();if(!t)return[null,null];const i=t;if(i.info)return[t,i.info];if("function"==typeof i.requestAdapterInfo)try{return[t,await i.requestAdapterInfo()]}catch{return[t,null]}return[t,null]}catch{return[null,null]}}();return new Ya({webgl2:$a(),webgpu:Xa(),webgpuAdapter:e,webgpuVendor:t?.vendor??null,webgpuArchitecture:t?.architecture??null,pointer:za&&"PointerEvent"in window,keyboard:za&&"KeyboardEvent"in window,gamepad:Wa&&"function"==typeof navigator.getGamepads,touch:Ha(),maxTouchPoints:ja(),audio:Ka(),fullscreen:Qa(),vibration:Wa&&"function"==typeof navigator.vibrate,imageBitmap:"function"==typeof createImageBitmap,deviceMemory:Za(),offscreenCanvas:za&&void 0!==window.OffscreenCanvas,webWorkers:za&&"function"==typeof window.Worker,devicePixelRatio:za?window.devicePixelRatio:1})}}function $a(){if(!qa)return!1;try{const e=document.createElement("canvas");return null!==e.getContext("webgl2")}catch{return!1}}function Xa(){return Wa&&"gpu"in navigator}function Ha(){return!!za&&("ontouchstart"in window||ja()>0)}function ja(){if(!Wa)return 0;const e=navigator.maxTouchPoints;return"number"==typeof e?e:0}function Ka(){if(!za)return!1;const e=window;return void 0!==e.AudioContext||void 0!==e.webkitAudioContext}function Qa(){if(!qa)return!1;const e=document.documentElement;return"function"==typeof e.requestFullscreen||"function"==typeof e.webkitRequestFullscreen}function Za(){if(!Wa)return 0;const e=navigator.deviceMemory;return"number"==typeof e?e:0}class Ja{_stepMs;_maxSteps;_accumulatorMs=0;constructor(e,t){if(this._stepMs=e,this._maxSteps=t,!(e>0&&Number.isFinite(e)))throw new RangeError(`FixedTimestep: step must be a positive finite number of ms, received ${e}.`)}get stepMs(){return this._stepMs}get alpha(){return this._accumulatorMs/this._stepMs}advance(e){this._accumulatorMs+=e;const t=1e-9*this._stepMs;let i=0;for(;this._accumulatorMs>=this._stepMs-t&&i<this._maxSteps;)this._accumulatorMs-=this._stepMs,i++;return this._accumulatorMs>this._stepMs&&(this._accumulatorMs%=this._stepMs),this._accumulatorMs<0&&(this._accumulatorMs=0),i}reset(){this._accumulatorMs=0}}var eh;e.LogSeverity=void 0,(eh=e.LogSeverity||(e.LogSeverity={}))[eh.Debug=0]="Debug",eh[eh.Info=1]="Info",eh[eh.Warning=2]="Warning",eh[eh.Error=3]="Error";class th{_handlers=[];_warnedKeys=new Set;log(t,i,n,r){if(t<e.LogSeverity.Error)return;const s={severity:t,channel:i,message:n,...void 0!==r?.data&&{data:r.data},...void 0!==r?.error&&{error:r.error}};for(const e of this._handlers)e(s)}debug(t,i,n){this.log(e.LogSeverity.Debug,t,i,n?{data:n}:void 0)}info(t,i,n){this.log(e.LogSeverity.Info,t,i,n?{data:n}:void 0)}warn(t,i,n){this.log(e.LogSeverity.Warning,t,i,n?{data:n}:void 0)}error(t,i,n){this.log(e.LogSeverity.Error,t,i,n?{error:n}:void 0)}warnOnce(e,t,i){this._warnedKeys.has(e)||(this._warnedKeys.add(e),this.warn(t,i))}addHandler(e){return this._handlers.push(e),()=>{const t=this._handlers.indexOf(e);t>=0&&this._handlers.splice(t,1)}}_resetWarnedKeys(){this._warnedKeys.clear()}}const ih=new th;class nh extends Bi{onResize=new x;_screenWidth=0;_screenHeight=0;get screenWidth(){return this._screenWidth}get screenHeight(){return this._screenHeight}_render(e){const t=e.screenView;this._screenWidth===t.width&&this._screenHeight===t.height||(this._screenWidth=t.width,this._screenHeight=t.height,this.onResize.dispatch(t.width,t.height)),e.render(this,{view:t})}destroy(){this.onResize.destroy(),super.destroy()}}class rh{_items=new Set;_order=[];_disposed=!1;get disposed(){return this._disposed}get size(){return this._items.size}track(e){return this._disposed||this._items.has(e)||(this._items.add(e),this._order.push(e)),e}has(e){return this._items.has(e)}untrack(e){if(this._disposed||!this._items.delete(e))return!1;const t=this._order.indexOf(e);return-1!==t&&this._order.splice(t,1),!0}destroy(){if(!this._disposed){this._disposed=!0;for(let e=this._order.length-1;e>=0;e--)try{this._order[e].destroy()}catch(e){}this._items.clear(),this._order.length=0}}}function sh(e,t){"number"==typeof t.x&&(e.x=t.x),"number"==typeof t.y&&(e.y=t.y),"number"==typeof t.rotation&&(e.rotation=t.rotation),"number"==typeof t.scaleX&&(e.scale.x=t.scaleX),"number"==typeof t.scaleY&&(e.scale.y=t.scaleY),"number"==typeof t.skewX&&(e.skewX=t.skewX),"number"==typeof t.skewY&&(e.skewY=t.skewY),"number"==typeof t.originX&&(e.origin.x=t.originX),"number"==typeof t.originY&&(e.origin.y=t.originY),!1===t.visible&&(e.visible=!1),"number"==typeof t.zIndex&&(e.zIndex=t.zIndex),!1===t.cullable&&(e.cullable=!1);const i=t.cullArea;if(Array.isArray(i)&&4===i.length&&(e.cullArea=new et(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"string"==typeof t.name&&(e.name=t.name),e instanceof Si){!0===t.interactive&&(e.interactive=!0),!0===t.draggable&&(e.draggable=!0),!0===t.focusable&&(e.focusable=!0),"number"==typeof t.tabIndex&&(e.tabIndex=t.tabIndex),"string"==typeof t.cursor&&(e.cursor=t.cursor),!0===t.clip&&(e.clip=!0),!0===t.preserveDrawOrder&&(e.preserveDrawOrder=!0),!0===t.cacheAsBitmap&&(e.cacheAsBitmap=!0);const i=t.clipShape;Array.isArray(i)&&4===i.length&&(e.clipShape=new et(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3])))}if(e instanceof Fn){const i=t.tint;Array.isArray(i)&&4===i.length&&(e.tint=new Tt(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"number"==typeof t.blendMode&&(e.blendMode=t.blendMode),"string"==typeof t.pixelSnapMode&&Tn(t.pixelSnapMode)&&(e.pixelSnapMode=t.pixelSnapMode)}}function oh(e,t,i){const n=e[t];return"number"==typeof n&&Number.isFinite(n)?n:i}function ah(e,t,i,n){const r=e[t];return"string"==typeof r&&i.includes(r)?r:n}function hh(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function lh(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type?e:null}function uh(e){return Array.isArray(e)?e.map(e=>"number"==typeof e&&Number.isFinite(e)?e:0):null}const ch=["normal","bold","100","200","300","400","500","600","700","800","900"],dh=["left","center","right","justify"],_h=["stretch","repeat","mirror-repeat"],fh=["clip","round"];function ph(e,t,i,n,r,s){return(i-e)*(s-t)-(n-t)*(r-e)>0}function mh(e,t,i,n,r,s,o,a){const h=(e-r)*(n-s)-(i-r)*(t-s),l=(e-o)*(s-a)-(r-o)*(t-a),u=(e-i)*(a-n)-(o-i)*(t-n);return!((h<0||l<0||u<0)&&(h>0||l>0||u>0))&&0!==h&&0!==l&&0!==u}function gh(e,t,i,n,r,s){const o=e[2*n],a=e[2*n+1],h=e[2*r],l=e[2*r+1],u=e[2*s],c=e[2*s+1];let d=i[s];for(;d!==n;){if(d!==r){if(mh(e[2*d],e[2*d+1],o,a,h,l,u,c))return!1}d=i[d]}return!0}const yh=(e,t,i,n,r)=>{const s=[e,t,i,n],o=r/2,a=new it(e-i,t-n).perp().normalize().multiply(o),h=new it(i-e,n-t).perp().normalize().multiply(o),l=new Float32Array([e-a.x,t-a.y,e+a.x,t+a.y,i-h.x,n-h.y,i+h.x,n+h.y]);a.destroy(),h.destroy();return{vertices:l,indices:new Uint16Array([0,1,3,0,3,2]),points:s}},wh=(e,t)=>{if(e.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const i=t/2,n=new it(e[0],e[1]),r=new it(e[e.length-2],e[e.length-1]),s=e;if(n.x===r.x&&n.y===r.y){(e=[...e]).pop(),e.pop();const[t=0,i=0]=[e[e.length-2],e[e.length-1]];r.set(t,i);const s=r.x+.5*(n.x-r.x),o=r.y+.5*(n.y-r.y);e.unshift(s,o),e.push(s,o)}n.destroy(),r.destroy();const o=e.length/2,a=[];let h,l,u,c,d,_,f=e[0],p=e[1],m=e[2],g=e[3],y=-(p-g),w=f-m,x=Math.sqrt(y*y+w*w);y/=x,w/=x,y*=i,w*=i,a.push(f-y,p-w),a.push(f+y,p+w);for(let t=1;t<o-1;t++){f=e[2*(t-1)],p=e[2*(t-1)+1],m=e[2*t],g=e[2*t+1],h=e[2*(t+1)],l=e[2*(t+1)+1],y=-(p-g),w=f-m,x=Math.sqrt(y*y+w*w),y/=x,w/=x,y*=i,w*=i,u=-(g-l),c=m-h,x=Math.sqrt(u*u+c*c),u/=x,c/=x,u*=i,c*=i;const n=-w+p-(-w+g),r=-y+m-(-y+f),s=(-y+f)*(-w+g)-(-y+m)*(-w+p),o=-c+l-(-c+g),v=-u+m-(-u+h),b=(-u+h)*(-c+g)-(-u+m)*(-c+l),S=n*v-o*r;if(Math.abs(S)<.1){a.push(m-y,g-w),a.push(m+y,g+w);continue}const B=(r*b-v*s)/S,C=(o*s-n*b)/S;(B-m)*(B-m)+(C-g)*(C-g)>196*i*i?(d=y-u,_=w-c,x=Math.sqrt(d*d+_*_),d/=x,_/=x,d*=i,_*=i,a.push(m-d,g-_),a.push(m+d,g+_),a.push(m-d,g-_)):(a.push(B,C),a.push(m-(B-m),g-(C-g)))}f=e[2*(o-2)],p=e[2*(o-2)+1],m=e[2*(o-1)],g=e[2*(o-1)+1],y=-(p-g),w=f-m,x=Math.sqrt(y*y+w*w),y/=x,w/=x,y*=i,w*=i,a.push(m-y,g-w),a.push(m+y,g+w);const v=a.length/2,b=new Float32Array(a),S=v>=3?v-2:0,B=new Uint16Array(3*S);for(let e=0;e<S;e++){const t=3*e;1&e?(B[t]=e+1,B[t+1]=e,B[t+2]=e+2):(B[t]=e,B[t+1]=e+1,B[t+2]=e+2)}return{vertices:b,indices:B,points:s}},xh=(e,t,i)=>{const n=Math.floor(15*Math.sqrt(i+i)),r=2*Math.PI/n,s=[],o=new Float32Array(2*(n+1));o[0]=e,o[1]=t;for(let a=0;a<n;a++){const n=e+Math.sin(r*a)*i,h=t+Math.cos(r*a)*i;s.push(n,h);const l=2*(a+1);o[l]=n,o[l+1]=h}const a=new Uint16Array(3*n);for(let e=0;e<n;e++){const t=3*e;a[t]=0,a[t+1]=e+1,a[t+2]=e+2>n?1:e+2}return{vertices:o,indices:a,points:s}},vh=(e,t,i,n)=>{const r=Math.floor(15*Math.sqrt(i+n)),s=2*Math.PI/r,o=[],a=new Float32Array(2*(r+1));a[0]=e,a[1]=t;for(let h=0;h<r;h++){const r=e+Math.sin(s*h)*i,l=t+Math.cos(s*h)*n;o.push(r,l);const u=2*(h+1);a[u]=r,a[u+1]=l}const h=new Uint16Array(3*r);for(let e=0;e<r;e++){const t=3*e;h[t]=0,h[t+1]=e+1,h[t+2]=e+2>r?1:e+2}return{vertices:a,indices:h,points:o}},bh=e=>{if(e.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const t=e.length/2,i=function(e){const t=e.length>>1;if(t<3)return new Uint32Array(0);if(3===t)return ph(e[0],e[1],e[2],e[3],e[4],e[5])?new Uint32Array([0,1,2]):new Uint32Array([2,1,0]);const i=new Uint32Array(t),n=new Uint32Array(t);for(let e=0;e<t;e++)i[e]=(e+t-1)%t,n[e]=(e+1)%t;if(function(e){const t=e.length>>1;let i=0;for(let n=0;n<t;n++){const r=(n+1)%t,s=e[2*n],o=e[2*n+1],a=e[2*r];i+=s*e[2*r+1]-a*o}return i}(e)<0)for(let e=0;e<t;e++){const t=i[e];i[e]=n[e],n[e]=t}const r=new Uint32Array(3*(t-2));let s=0,o=t,a=0;for(;o>3;){let t=!1;const h=a;do{const h=i[a],l=n[a],u=a;if(ph(e[2*h],e[2*h+1],e[2*u],e[2*u+1],e[2*l],e[2*l+1])&&gh(e,0,n,h,u,l)){r[s++]=h,r[s++]=u,r[s++]=l,n[h]=l,i[l]=h,o--,t=!0,a=l;break}a=n[a]}while(a!==h);if(!t)break}if(3===o){const t=i[a],o=n[a];ph(e[2*t],e[2*t+1],e[2*a],e[2*a+1],e[2*o],e[2*o+1])?(r[s++]=t,r[s++]=a,r[s++]=o):(r[s++]=o,r[s++]=a,r[s++]=t)}return r.subarray(0,s)}(e),n=new Float32Array(e.length);for(let i=0;i<t;i++)n[2*i]=e[2*i],n[2*i+1]=e[2*i+1];return{vertices:n,indices:new Uint16Array(i),points:e}},Sh=(e,t,i,n)=>({vertices:new Float32Array([e,t,e+i,t,e,t+n,e+i,t+n]),indices:new Uint16Array([0,1,2,1,3,2]),points:[e,t,e+i,t,e+i,t+n,e,t+n]}),Bh=(e,t,i,n,r)=>{const s=Math.min(Math.abs(r),i/2,n/2);if(s<=0)return Sh(e,t,i,n);const o=Math.max(1,Math.floor(15*Math.sqrt(s+s)/4)),a=Math.PI/2/o,h=[[e+s,t+s,Math.PI],[e+i-s,t+s,1.5*Math.PI],[e+i-s,t+n-s,0],[e+s,t+n-s,.5*Math.PI]],l=[];for(const[e=0,t=0,i=0]of h)for(let n=0;n<=o;n++){const r=i+a*n,o=e+Math.cos(r)*s,h=t+Math.sin(r)*s,u=l.length;u>=2&&Math.abs(l[u-2]-o)<1e-4&&Math.abs(l[u-1]-h)<1e-4||l.push(o,h)}const u=l.length/2,c=new Float32Array(2*(u+1));c[0]=e+i/2,c[1]=t+n/2;for(let e=0;e<u;e++){const t=2*(e+1);c[t]=l[2*e],c[t+1]=l[2*e+1]}const d=new Uint16Array(3*u);for(let e=0;e<u;e++){const t=3*e;d[t]=0,d[t+1]=e+1,d[t+2]=e+2>u?1:e+2}return{vertices:c,indices:d,points:[...l,l[0],l[1]]}},Ch=(e,t,i,n,r=n/2,s=0)=>{const o=Math.PI/-2+s,a=2*i,h=N/a,l=[];for(let i=0;i<a;i++){const s=o+i*h,a=i%2?r:n;l.push(e+a*Math.cos(s),t+a*Math.sin(s))}return bh(l)},Th={line:yh,path:wh,circle:xh,ellipse:vh,polygon:bh,rectangle:Sh,roundedRectangle:Bh,star:Ch};class Mh extends Bi{_lineWidth=0;_fillColor=new Tt(0,0,0,0);_lineColor=new Tt;_fillStyle=this._fillColor;_strokeStyle=this._lineColor;_fillStyleTexture=null;_strokeStyleTexture=null;_ownedTextures=new Set;_currentPoint=new it(0,0);get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e}get lineColor(){return this._lineColor}set lineColor(e){this.strokeStyle=e}get fillColor(){return this._fillColor}set fillColor(e){this.fillStyle=e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=this._resolveStyle(e,this._fillColor),this._fillStyleTexture=null}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=this._resolveStyle(e,this._lineColor),this._strokeStyleTexture=null}get currentPoint(){return this._currentPoint}getChildAt(e){return super.getChildAt(e)}addChild(e){if(!(e instanceof In))throw new Error("Graphics can only contain Mesh children.");return super.addChild(e)}addChildAt(e,t){if(!(e instanceof In))throw new Error("Graphics can only contain Mesh children.");return super.addChildAt(e,t)}moveTo(e,t){return this._currentPoint.set(e,t),this}lineTo(e,t){const{x:i,y:n}=this._currentPoint;return this.drawPath([i,n,e,t]),this.moveTo(e,t),this}quadraticCurveTo(e,t,i,n){const{x:r,y:s}=this._currentPoint;return this.drawPath(Q(r,s,e,t,i,n)),this.moveTo(i,n),this}bezierCurveTo(e,t,i,n,r,s){const{x:o,y:a}=this._currentPoint;return this.drawPath(K(o,a,e,t,i,n,r,s)),this.moveTo(r,s),this}arcTo(e,t,i,n,r){const{x:s,y:o}=this._currentPoint,a=Math.abs(r);if(0===a||s===e&&o===t||e===i&&t===n)return this.lineTo(e,t);const h=e-s,l=t-o,u=i-e,c=n-t,d=Math.hypot(h,l),_=Math.hypot(u,c);if(0===d||0===_)return this.lineTo(e,t);const f=h/d,p=l/d,m=u/_,g=c/_,y=Y(f*m+p*g,-1,1),w=Math.acos(y);if(0===w||w===Math.PI)return this.lineTo(e,t);const x=a/Math.tan(w/2);if(!Number.isFinite(x)||x>d||x>_)return this.lineTo(e,t);const v=e-f*x,b=t-p*x,S=e+m*x,B=t+g*x,C=f*g-p*m>0,T=v+(C?-p:p)*a,M=b+(C?f:-f)*a,P=Math.atan2(b-M,v-T),A=Math.atan2(B-M,S-T);return this.lineTo(v,b),this.drawArc(T,M,a,P,A,C)}drawArc(e,t,i,n,r,s=!1){const o=Math.abs(i);if(0===o)return this;let a=r-n;if(!s&&a<0?a+=N:s&&a>0&&(a-=N),0===a)return this;const h=Math.max(2,Math.ceil(Math.abs(a)/(Math.PI/16))),l=[];for(let i=0;i<=h;i++){const r=n+a*(i/h);l.push(e+Math.cos(r)*o,t+Math.sin(r)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(e,t,i,n){const r=yh(e,t,i,n,this._lineWidth);return this.addChild(this._createStrokeMesh(r)),this}drawPath(e){const t=wh(e,this._lineWidth);return this.addChild(this._createStrokeMesh(t)),this}drawPolygon(e){const t=bh(e);return this._appendFill(t),this._lineWidth>0&&this.drawPath(t.points),this}drawCircle(e,t,i){const n=xh(e,t,i);return this._appendFill(n),this._lineWidth>0&&this.drawPath(n.points),this}drawEllipse(e,t,i,n){const r=vh(e,t,i,n);return this._appendFill(r),this._lineWidth>0&&this.drawPath(r.points),this}drawRectangle(e,t,i,n){const r=Sh(e,t,i,n);return this._appendFill(r),this._lineWidth>0&&this.drawPath(r.points),this}drawRoundedRectangle(e,t,i,n,r){const s=Bh(e,t,i,n,r);return this._appendFill(s),this._lineWidth>0&&this.drawPath(s.points),this}drawStar(e,t,i,n,r=n/2,s=0){const o=Ch(e,t,i,n,r,s);return this._appendFill(o),this._lineWidth>0&&this.drawPath(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._fillColor.copy(Tt.transparentBlack),this._lineColor.copy(Tt.black),this._fillStyle=this._fillColor,this._strokeStyle=this._lineColor,this._fillStyleTexture=null,this._strokeStyleTexture=null,this._destroyOwnedTextures(),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}_resolveStyle(e,t){return null===e?t:e instanceof Tt?(t.copy(e),t):e.clone()}_appendFill(e){this._fillStyle instanceof Tt&&0===this._fillStyle.a||this.addChild(this._createFillMesh(e))}_createFillMesh(e){return this._fillStyle instanceof Tt?this._createSolidMesh(e,this._fillStyle):(this._fillStyleTexture??=this._rasterizeGradient(this._fillStyle),this._createGradientMesh(e,this._fillStyleTexture))}_createStrokeMesh(e){return this._strokeStyle instanceof Tt?this._createSolidMesh(e,this._strokeStyle):(this._strokeStyleTexture??=this._rasterizeGradient(this._strokeStyle),this._createGradientMesh(e,this._strokeStyleTexture))}_createSolidMesh(e,t){const i=new In({vertices:e.vertices,indices:e.indices});return i.tint=t,i}_createGradientMesh(e,t){return new In({vertices:e.vertices,indices:e.indices,uvs:Ph(e.vertices),texture:t})}_rasterizeGradient(t){const i=t.toTexture(256,256,{samplerOptions:{scaleMode:e.ScaleModes.Linear}});return this._ownedTextures.add(i),i}_destroyOwnedTextures(){for(const e of this._ownedTextures)e.destroy();this._ownedTextures.clear()}}const Ph=e=>{let t=1/0,i=1/0,n=-1/0,r=-1/0;for(let s=0;s<e.length;s+=2){const o=e[s],a=e[s+1];o<t&&(t=o),o>n&&(n=o),a<i&&(i=a),a>r&&(r=a)}const s=n-t,o=r-i,a=s>0?1/s:0,h=o>0?1/o:0,l=new Float32Array(e.length);for(let n=0;n<e.length;n+=2)l[n]=(e[n]-t)*a,l[n+1]=(e[n+1]-i)*h;return l},Ah=-1;function Eh(e,t){if(!Number.isInteger(t)||t!==Ah&&t<1)throw new Error(`AnimatedSprite ${e} has an invalid repeat value (${t}). Must be -1 (infinite) or a positive integer.`)}class Rh extends vr{_clips=new Map;_currentClipName=null;_currentFrameIndex=0;_playing=!1;_repeatOverride=null;_elapsedFrameTimeMs=0;_completedCycles=0;onComplete=new x;onFrame=new x;constructor(e,t){super(e),t&&this.setClips(t)}get currentClip(){return this._currentClipName}get currentFrame(){return this._currentFrameIndex}get playing(){return this._playing}get repeat(){return null!==this._repeatOverride?this._repeatOverride:this._currentClipName?this._clips.get(this._currentClipName)?.repeat??Ah:Ah}set repeat(e){Eh("repeat",e),this._repeatOverride=e}setClips(e){this._clips.clear();for(const[t,i]of Object.entries(e))this.defineClip(t,i);return this}defineClip(e,t){if(0===e.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");const i=t.frames;if(!Array.isArray(t.frames)||0===i.length)throw new Error(`AnimatedSprite clip "${e}" must define at least one frame.`);const n=t.fps??12;if(!Number.isFinite(n)||n<=0)throw new Error(`AnimatedSprite clip "${e}" has an invalid fps value (${n}).`);const r=t.repeat??Ah;Eh(`clip "${e}"`,r);let s=null;if(t.frameDurations){if(t.frameDurations.length!==i.length)throw new Error(`AnimatedSprite clip "${e}" frameDurations length (${t.frameDurations.length}) must match its frame count (${i.length}).`);for(const i of t.frameDurations)if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${e}" has an invalid frameDurations value (${i}).`);s=[...t.frameDurations]}let o=null;if(t.frameOffsets){if(t.frameOffsets.length!==i.length)throw new Error(`AnimatedSprite clip "${e}" frameOffsets length (${t.frameOffsets.length}) must match its frame count (${i.length}).`);for(const i of t.frameOffsets)if(!Number.isFinite(i.x)||!Number.isFinite(i.y))throw new Error(`AnimatedSprite clip "${e}" has an invalid frameOffsets value (${JSON.stringify(i)}).`);o=t.frameOffsets.map(e=>({x:e.x,y:e.y}))}return this._clips.set(e,{frames:i.map(e=>e.clone()),frameDurationMs:1e3/n,frameDurations:s,frameOffsets:o,repeat:r}),this}_getClipDefinitions(){const e={};for(const[t,i]of this._clips)e[t]={frames:i.frames.map(e=>e.clone()),fps:1e3/i.frameDurationMs,repeat:i.repeat,...i.frameDurations?{frameDurations:[...i.frameDurations]}:{},...i.frameOffsets?{frameOffsets:i.frameOffsets.map(e=>({x:e.x,y:e.y}))}:{}};return e}removeClip(e){return this._currentClipName===e&&this.stop(),this._clips.delete(e),this}play(e,t={}){const i=this._clips.get(e);if(!i)throw new Error(`AnimatedSprite clip "${e}" is not defined.`);void 0!==t.repeat&&Eh("play() options.repeat",t.repeat);const n=this._currentClipName===e,r=t.restart??!0;return n&&!r||(this._currentClipName=e,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._completedCycles=0,this._applyFrame(i,0),this.onFrame.dispatch(e,0)),this._repeatOverride=t.repeat??this._repeatOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const e=this._clips.get(this._currentClipName);return e&&e.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(e,0),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(e){if(!this._playing||null===this._currentClipName)return this;const t=this._clips.get(this._currentClipName);if(!t||t.frames.length<=1)return this;const i="number"==typeof e?e:e.milliseconds;if(i<=0)return this;this._elapsedFrameTimeMs+=i;let n=t.frameDurations?.[this._currentFrameIndex]??t.frameDurationMs;for(;this._elapsedFrameTimeMs>=n;){this._elapsedFrameTimeMs-=n;const e=this._currentFrameIndex+1;if(e>=t.frames.length){const e=this._repeatOverride??t.repeat;let i;if(e===Ah?i=!0:(this._completedCycles++,i=this._completedCycles<e),i){this._currentFrameIndex=0,this._applyFrame(t,0),this.onFrame.dispatch(this._currentClipName,0),n=t.frameDurations?.[this._currentFrameIndex]??t.frameDurationMs;continue}this._currentFrameIndex=t.frames.length-1,this._applyFrame(t,this._currentFrameIndex),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=e,this._applyFrame(t,this._currentFrameIndex),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex),n=t.frameDurations?.[this._currentFrameIndex]??t.frameDurationMs}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const e of this._clips.values())for(const t of e.frames)t.destroy();this._clips.clear()}static fromSpritesheet(e){const t={};for(const[i,n]of e.animations)t[i]={frames:n.map(t=>e.getFrame(t))};return new Rh(e.texture,t)}_applyFrame(e,t){this.setTextureFrame(e.frames[t],!1);const i=e.frameOffsets?.[t];i&&(this.getLocalBounds().setPosition(i.x,i.y),this._invalidateBoundsCascade())}}function kh(e){const t={};for(const[i,n]of Object.entries(e))void 0!==n&&(t[i]=n);return t}const Dh=e=>[e.r,e.g,e.b,e.a],Fh=e=>Array.isArray(e)&&4===e.length?new Tt(Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])):void 0,Ih=(e,t,i,n,r)=>e.r===t&&e.g===i&&e.b===n&&e.a===r;function Lh(e){const t={};return"Arial"!==e.fontFamily&&(t.fontFamily=e.fontFamily),"normal"!==e.fontWeight&&(t.fontWeight=e.fontWeight),"normal"!==e.fontStyle&&(t.fontStyle=e.fontStyle),20!==e.fontSize&&(t.fontSize=e.fontSize),Ih(e.fillColor,255,255,255,1)||(t.fillColor=Dh(e.fillColor)),Ih(e.outlineColor,0,0,0,1)||(t.outlineColor=Dh(e.outlineColor)),0!==e.outlineWidth&&(t.outlineWidth=e.outlineWidth),"left"!==e.align&&(t.align=e.align),1.2!==e.lineHeight&&(t.lineHeight=e.lineHeight),0!==e.leading&&(t.leading=e.leading),Ih(e.shadowColor,0,0,0,1)||(t.shadowColor=Dh(e.shadowColor)),0!==e.shadowOffsetX&&(t.shadowOffsetX=e.shadowOffsetX),0!==e.shadowOffsetY&&(t.shadowOffsetY=e.shadowOffsetY),0!==e.shadowAlpha&&(t.shadowAlpha=e.shadowAlpha),0!==e.shadowBlur&&(t.shadowBlur=e.shadowBlur),null!==e.gradientColors&&(t.gradientColors=[Dh(e.gradientColors[0]),Dh(e.gradientColors[1])]),"vertical"!==e.gradientAxis&&(t.gradientAxis=e.gradientAxis),Object.keys(t).length>0?t:void 0}function Uh(e){if("object"!=typeof e||null===e)return;const t=e,i={};"string"==typeof t.fontFamily&&(i.fontFamily=t.fontFamily);const n=ah(t,"fontWeight",ch);void 0!==n&&(i.fontWeight=n),"italic"!==t.fontStyle&&"normal"!==t.fontStyle||(i.fontStyle=t.fontStyle),"number"==typeof t.fontSize&&(i.fontSize=t.fontSize);const r=Fh(t.fillColor);void 0!==r&&(i.fillColor=r);const s=Fh(t.outlineColor);void 0!==s&&(i.outlineColor=s),"number"==typeof t.outlineWidth&&(i.outlineWidth=t.outlineWidth);const o=ah(t,"align",dh);void 0!==o&&(i.align=o),"number"==typeof t.lineHeight&&(i.lineHeight=t.lineHeight),"number"==typeof t.leading&&(i.leading=t.leading);const a=Fh(t.shadowColor);if(void 0!==a&&(i.shadowColor=a),"number"==typeof t.shadowOffsetX&&(i.shadowOffsetX=t.shadowOffsetX),"number"==typeof t.shadowOffsetY&&(i.shadowOffsetY=t.shadowOffsetY),"number"==typeof t.shadowAlpha&&(i.shadowAlpha=t.shadowAlpha),"number"==typeof t.shadowBlur&&(i.shadowBlur=t.shadowBlur),Array.isArray(t.gradientColors)&&2===t.gradientColors.length){const e=Fh(t.gradientColors[0]),n=Fh(t.gradientColors[1]);void 0!==e&&void 0!==n&&(i.gradientColors=[e,n])}return"horizontal"!==t.gradientAxis&&"vertical"!==t.gradientAxis||(i.gradientAxis=t.gradientAxis),i}const Gh=["visible","clip","ellipsis"],Nh=["ltr","rtl"],Oh=["normal","pre","pre-line"];function Vh(e){if("object"!=typeof e||null===e)return;const t=e,i={},n=oh(t,"maxWidth");void 0!==n&&(i.maxWidth=n);const r=oh(t,"maxHeight");void 0!==r&&(i.maxHeight=r);const s=ah(t,"overflow",Gh);void 0!==s&&(i.overflow=s);const o=oh(t,"letterSpacing");void 0!==o&&(i.letterSpacing=o);const a=ah(t,"direction",Nh);void 0!==a&&(i.direction=a);const h=function(e,t,i){const n=e[t];return"boolean"==typeof n?n:i}(t,"breakWords");void 0!==h&&(i.breakWords=h);const l=ah(t,"whiteSpace",Oh);return void 0!==l&&(i.whiteSpace=l),Object.keys(i).length>0?i:void 0}const zh=e=>Array.isArray(e)?new Float32Array(e.map(Number)):new Float32Array,qh=e=>Array.isArray(e)?new Uint32Array(e.map(Number)):new Uint32Array,Wh=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Yh=e=>{const t=hh(e);return{left:Wh(t?.left)??0,top:Wh(t?.top)??0,right:Wh(t?.right)??0,bottom:Wh(t?.bottom)??0}},$h=e=>{const t=hh(e);if(null===t)return;const i={},n=ah(t,"edges",_h);void 0!==n&&(i.edges=n);const r=ah(t,"center",_h);void 0!==r&&(i.center=r);const s=ah(t,"top",_h);void 0!==s&&(i.top=s);const o=ah(t,"right",_h);void 0!==o&&(i.right=o);const a=ah(t,"bottom",_h);void 0!==a&&(i.bottom=a);const h=ah(t,"left",_h);void 0!==h&&(i.left=h);const l=ah(t,"edgeFit",fh);void 0!==l&&(i.edgeFit=l);const u=ah(t,"centerFit",fh);return void 0!==u&&(i.centerFit=u),i},Xh={write(e,t){const i={vertices:[...e.vertices]};null!==e.indices&&(i.indices=[...e.indices]),null!==e.uvs&&(i.uvs=[...e.uvs]),null!==e.colors&&(i.colors=[...e.colors]);const n=t.keyFor(e.texture);return null!==n&&(i.texture=n),e.material,i},read(e,t){return new In(kh({vertices:zh(e.vertices),indices:void 0!==e.indices?(i=e.indices,Array.isArray(i)?new Uint16Array(i.map(Number)):new Uint16Array):void 0,uvs:void 0!==e.uvs?zh(e.uvs):void 0,colors:void 0!==e.colors?qh(e.colors):void 0,texture:t.resolveAsset("string"==typeof e.texture?e.texture:null,pi)}));var i}},Hh={write:(e,t)=>0===e.children.length?{}:{children:e.children.map(e=>t.writeNode(e))},read(e,t){const i=new Mh,n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}},jh={write(e,t){const i={slices:{...e.slices},border:{...e.border},modes:{...e.modes},width:e.width,height:e.height},n=t.keyFor(e.texture);return null!==n&&(i.texture=n),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi);if(null===i)throw new Error("NineSliceSprite deserialize requires its texture to be pre-loaded into the Loader.");return new ur(i,kh({slices:Yh(e.slices),border:null!==hh(e.border)?Yh(e.border):void 0,modes:$h(e.modes),width:Wh(e.width),height:Wh(e.height)}))}},Kh={write(e,t){const i={width:e.width,height:e.height,modeX:e.modeX,modeY:e.modeY,fitX:e.fitX,fitY:e.fitY,offsetX:e.offsetX,offsetY:e.offsetY},n=t.keyFor(e.texture);return null!==n&&(i.texture=n),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi);if(null===i)throw new Error("RepeatingSprite deserialize requires its texture to be pre-loaded into the Loader.");return new wr(i,kh({width:Wh(e.width),height:Wh(e.height),modeX:ah(e,"modeX",_h),modeY:ah(e,"modeY",_h),fitX:ah(e,"fitX",fh),fitY:ah(e,"fitY",fh),offsetX:Wh(e.offsetX),offsetY:Wh(e.offsetY)}))}},Qh={write(e,t){const i={},n=t.keyFor(e.texture);null!==n&&(i.texture=n);const r={};for(const[t,i]of Object.entries(e._getClipDefinitions()))r[t]=kh({frames:i.frames.map(e=>[e.x,e.y,e.width,e.height]),fps:i.fps,repeat:i.repeat,frameDurations:i.frameDurations?[...i.frameDurations]:void 0,frameOffsets:i.frameOffsets?i.frameOffsets.map(e=>[e.x,e.y]):void 0});return i.clips=r,null!==e.currentClip&&(i.currentClip=e.currentClip),e.playing&&(i.playing=!0),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi),n={},r=hh(e.clips);if(null!==r)for(const[e,t]of Object.entries(r)){const i=hh(t);if(null===i)continue;const r=Array.isArray(i.frames)?i.frames.map(e=>{const t=uh(e)??[];return new et(t[0]??0,t[1]??0,t[2]??0,t[3]??0)}):[],s=Array.isArray(i.frameDurations)?uh(i.frameDurations)??void 0:void 0,o=Array.isArray(i.frameOffsets)?i.frameOffsets.map(e=>{const t=uh(e)??[];return{x:t[0]??0,y:t[1]??0}}):void 0;n[e]=kh({frames:r,fps:Wh(i.fps),repeat:Wh(i.repeat),frameDurations:s,frameOffsets:o})}const s=new Rh(i,n);return"string"==typeof e.currentClip&&e.currentClip in n&&(s.play(e.currentClip),!0!==e.playing&&s.pause()),s}},Zh={write(e,t){const i={text:e.text},n=t.keyFor(e.font);null!==n&&(i.font=n),e.msdf&&(i.msdf=!0),1!==e.fontScale&&(i.scale=e.fontScale);const r=Lh(e.style);return void 0!==r&&(i.style=r),Object.keys(e.layout).length>0&&(i.layout={...e.layout}),i},read(e,t){const i=t.resolveAsset("string"==typeof e.font?e.font:null,Sr);if(null===i)throw new Error("BitmapText deserialize requires its BmFont to be pre-loaded into the Loader.");const n=Vh(e.layout);return new Ar("string"==typeof e.text?e.text:"",i,kh({...Uh(e.style),msdf:!0===e.msdf,scale:Wh(e.scale),layout:n}))}},Jh={write(e){const t={src:e.videoElement.src};return 1!==e.volume&&(t.volume=e.volume),e.loop&&(t.loop=!0),1!==e.playbackRate&&(t.playbackRate=e.playbackRate),e.muted&&(t.muted=!0),e.currentTime>0&&(t.time=e.currentTime),t},read(e){const t=document.createElement("video");return"string"==typeof e.src&&(t.src=e.src),new Co(t,kh({volume:Wh(e.volume),loop:!0===e.loop||void 0,playbackRate:Wh(e.playbackRate),muted:!0===e.muted||void 0,time:Wh(e.time)}))}};class el extends Bi{_uiWidth=0;_uiHeight=0;_enabled=!0;_uiAnchor=null;_uiAnchorOffsetX=0;_uiAnchorOffsetY=0;_uiAnchorRoot=null;_onAnchorResize=(e,t)=>{this._applyAnchor(e,t)};get uiWidth(){return this._uiWidth}get uiHeight(){return this._uiHeight}setSize(e,t){const i=Math.max(0,e),n=Math.max(0,t);return this._uiWidth===i&&this._uiHeight===n||(this._uiWidth=i,this._uiHeight=n,this._relayout(),null!==this._uiAnchorRoot&&this._applyAnchor(this._uiAnchorRoot.screenWidth,this._uiAnchorRoot.screenHeight)),this}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._onEnabledChanged(e))}anchorIn(e,t,i=0,n=0){return this._uiAnchor=t,this._uiAnchorOffsetX=i,this._uiAnchorOffsetY=n,this._uiAnchorRoot!==e&&(this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=e,e.onResize.add(this._onAnchorResize)),this._applyAnchor(e.screenWidth,e.screenHeight),this}_applyAnchor(e,t){if(null===this._uiAnchor)return;const[i,n]=(e=>{let t=.5,i=.5;return e.endsWith("left")?t=0:e.endsWith("right")&&(t=1),e.startsWith("top")?i=0:e.startsWith("bottom")&&(i=1),[t,i]})(this._uiAnchor);this.setPosition(i*(e-this._uiWidth)+this._uiAnchorOffsetX,n*(t-this._uiHeight)+this._uiAnchorOffsetY)}_relayout(){}_onEnabledChanged(e){}destroy(){this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=null,super.destroy()}}class tl extends el{onClick=new x;_background=new Mh;_label;_colors;_cornerRadius;_state="normal";_pointerInside=!1;constructor(e={}){super(),this._colors={normal:(e.color??new Tt(54,120,220,1)).clone(),hover:(e.hoverColor??new Tt(74,140,240,1)).clone(),pressed:(e.pressedColor??new Tt(40,96,180,1)).clone(),disabled:(e.disabledColor??new Tt(70,76,90,1)).clone()},this._cornerRadius=e.cornerRadius??8,this._label=new Wr(e.label??"",{fillColor:e.textColor??Tt.white,fontSize:e.fontSize??16,align:"center"}),this.addChild(this._background),this.addChild(this._label),this.interactive=!0,this.focusable=!0,this.cursor="pointer",this.onPointerOver.add(this._onPointerOver),this.onPointerOut.add(this._onPointerOut),this.onPointerDown.add(this._onPointerDown),this.onPointerUp.add(this._onPointerUp),this.onPointerTap.add(this._activate),this.onKeyDown.add(this._onKey),this.setSize(e.width??120,e.height??40)}get label(){return this._label.text}set label(e){this._label.text=e,this._positionLabel()}get colors(){return this._colors}get cornerRadius(){return this._cornerRadius}get textColor(){return this._label.style.fillColor}get fontSize(){return this._label.style.fontSize}_onPointerOver=()=>{this._pointerInside=!0,this._refreshState()};_onPointerOut=()=>{this._pointerInside=!1,this._refreshState()};_onPointerDown=()=>{this.enabled&&(this._state="pressed",this._draw())};_onPointerUp=()=>{this._refreshState()};_activate=()=>{this.enabled&&this.onClick.dispatch(this)};_onKey=t=>{const i=t.channel;!this.enabled||i!==e.Keyboard.Enter&&i!==e.Keyboard.Space||(t.preventDefault(),this.onClick.dispatch(this))};_refreshState(){let e="normal";this.enabled?this._pointerInside&&(e="hover"):e="disabled",this._state=e,this._draw()}_onEnabledChanged(e){this.interactive=e,this._refreshState()}_relayout(){this._draw(),this._positionLabel()}_draw(){const e=this._background;e.clear(),this._uiWidth<=0||this._uiHeight<=0||(e.fillColor=this._colors[this._state],e.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_positionLabel(){const e=this._label.getLocalBounds();this._label.setPosition((this._uiWidth-e.width)/2,(this._uiHeight-e.height)/2)}}class il extends el{_text;constructor(e="",t={}){super(),this._text=new Wr(e,{fillColor:Tt.white,fontSize:16,...t}),this.addChild(this._text),this._syncSize()}get text(){return this._text.text}set text(e){this._text.text!==e&&(this._text.text=e,this._syncSize())}get textNode(){return this._text}_syncSize(){const e=this._text.getLocalBounds();this.setSize(e.width,e.height)}}class nl extends el{_background=new Mh;_color;_borderColor;_borderWidth;_cornerRadius;constructor(e={}){super(),this._color=(e.color??new Tt(30,34,45,.92)).clone(),this._borderColor=(e.borderColor??new Tt(255,255,255,.12)).clone(),this._borderWidth=e.borderWidth??0,this._cornerRadius=e.cornerRadius??8,this.addChild(this._background),this.setSize(e.width??0,e.height??0)}get background(){return this._background}get color(){return this._color}get borderColor(){return this._borderColor}get borderWidth(){return this._borderWidth}get cornerRadius(){return this._cornerRadius}_relayout(){const e=this._background;e.clear(),this._uiWidth<=0||this._uiHeight<=0||(this._borderWidth>0&&(e.lineWidth=this._borderWidth,e.lineColor=this._borderColor),e.fillColor=this._color,e.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}}class rl extends el{_track=new Mh;_fill=new Mh;_trackColor;_fillColor;_cornerRadius;_value;constructor(e={}){super(),this._value=Y(e.value??0,0,1),this._trackColor=(e.trackColor??new Tt(255,255,255,.16)).clone(),this._fillColor=(e.fillColor??new Tt(80,220,120,1)).clone(),this._cornerRadius=e.cornerRadius??4,this.addChild(this._track),this.addChild(this._fill),this.setSize(e.width??200,e.height??12)}get value(){return this._value}set value(e){const t=Y(e,0,1);this._value!==t&&(this._value=t,this._drawFill())}get trackColor(){return this._trackColor}get fillColor(){return this._fillColor}get cornerRadius(){return this._cornerRadius}_relayout(){this._drawTrack(),this._drawFill()}_drawTrack(){const e=this._track;e.clear(),this._uiWidth<=0||this._uiHeight<=0||(e.fillColor=this._trackColor,e.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_drawFill(){const e=this._fill;e.clear();const t=this._uiWidth*this._value;t<=0||this._uiHeight<=0||(e.fillColor=this._fillColor,e.drawRoundedRectangle(0,0,t,this._uiHeight,Math.min(this._cornerRadius,t/2)))}}class sl extends el{_direction;_spacing;_padding;constructor(e={}){super(),this._direction=e.direction??"column",this._spacing=e.spacing??8,this._padding=e.padding??0}get direction(){return this._direction}get spacing(){return this._spacing}get padding(){return this._padding}addItem(e){return this.addChild(e),this.layout()}layout(){const e="row"===this._direction;let t=this._padding,i=0,n=!0;for(const r of this.children){const s=r instanceof el?r.uiWidth:r.getLocalBounds().width,o=r instanceof el?r.uiHeight:r.getLocalBounds().height;n||(t+=this._spacing),n=!1,e?(r.setPosition(t,this._padding),t+=s,i=Math.max(i,o)):(r.setPosition(this._padding,t),t+=o,i=Math.max(i,s))}const r=t+this._padding,s=i+2*this._padding;return this.setSize(e?r:s,e?s:r),this}}const ol=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,al={write(e){const t={text:e.text},i=Lh(e.textNode.style);return void 0!==i&&(t.style=i),e.enabled||(t.enabled=!1),t},read(e){const t=new il("string"==typeof e.text?e.text:"",Uh(e.style));return!1===e.enabled&&(t.enabled=!1),t}},hl={write(e,t){const i={width:e.uiWidth,height:e.uiHeight,color:Dh(e.color),borderColor:Dh(e.borderColor),borderWidth:e.borderWidth,cornerRadius:e.cornerRadius};e.enabled||(i.enabled=!1);const n=e.children.filter(t=>t!==e.background);return n.length>0&&(i.children=n.map(e=>t.writeNode(e))),i},read(e,t){const i=new nl(kh({width:ol(e.width),height:ol(e.height),color:Fh(e.color),borderColor:Fh(e.borderColor),borderWidth:ol(e.borderWidth),cornerRadius:ol(e.cornerRadius)}));!1===e.enabled&&(i.enabled=!1);const n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}},ll={write(e){const t={width:e.uiWidth,height:e.uiHeight,label:e.label,cornerRadius:e.cornerRadius,color:Dh(e.colors.normal),hoverColor:Dh(e.colors.hover),pressedColor:Dh(e.colors.pressed),disabledColor:Dh(e.colors.disabled),textColor:Dh(e.textColor),fontSize:e.fontSize};return e.enabled||(t.enabled=!1),t},read(e){const t=new tl(kh({width:ol(e.width),height:ol(e.height),label:"string"==typeof e.label?e.label:void 0,cornerRadius:ol(e.cornerRadius),color:Fh(e.color),hoverColor:Fh(e.hoverColor),pressedColor:Fh(e.pressedColor),disabledColor:Fh(e.disabledColor),textColor:Fh(e.textColor),fontSize:ol(e.fontSize)}));return!1===e.enabled&&(t.enabled=!1),t}},ul={write(e){const t={width:e.uiWidth,height:e.uiHeight,value:e.value,trackColor:Dh(e.trackColor),fillColor:Dh(e.fillColor),cornerRadius:e.cornerRadius};return e.enabled||(t.enabled=!1),t},read(e){const t=new rl(kh({width:ol(e.width),height:ol(e.height),value:ol(e.value),trackColor:Fh(e.trackColor),fillColor:Fh(e.fillColor),cornerRadius:ol(e.cornerRadius)}));return!1===e.enabled&&(t.enabled=!1),t}},cl={write(e,t){const i={direction:e.direction,spacing:e.spacing,padding:e.padding};return e.enabled||(i.enabled=!1),e.children.length>0&&(i.children=e.children.map(e=>t.writeNode(e))),i},read(e,t){const i=new sl(kh({direction:"row"===e.direction||"column"===e.direction?e.direction:void 0,spacing:ol(e.spacing),padding:ol(e.padding)}));!1===e.enabled&&(i.enabled=!1);const n=e.children;if(Array.isArray(n)){for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}i.layout()}return i}},dl={write:(e,t)=>e.children.length>0?{children:e.children.map(e=>t.writeNode(e))}:{},read(e,t){const i=new nh,n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}};const _l={write:(e,t)=>0===e.children.length?{}:{children:e.children.map(e=>t.writeNode(e))},read(e,t){const i=new Bi,n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}},fl={write(e,t){const i={},n=t.keyFor(e.texture);null!==n&&(i.texture=n),e.material;const r=e.texture,s=e.textureFrame;return null===r||0===s.x&&0===s.y&&s.width===r.width&&s.height===r.height||(i.frame=[s.x,s.y,s.width,s.height]),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi),n=new vr(i),r=e.frame;return null!==i&&Array.isArray(r)&&4===r.length&&n.setTextureFrame(et.temp.set(Number(r[0]),Number(r[1]),Number(r[2]),Number(r[3]))),n}},pl={write(e){const t={text:e.text},i=Lh(e.style);return void 0!==i&&(t.style=i),Object.keys(e.layout).length>0&&(t.layout={...e.layout}),e.colorGlyphs&&(t.colorGlyphs=!0),8!==e.sdfRadius&&(t.sdfRadius=e.sdfRadius),t},read(e){const t=Vh(e.layout);return new Wr("string"==typeof e.text?e.text:"",kh({...Uh(e.style),...t,colorGlyphs:!0===e.colorGlyphs,sdfRadius:"number"==typeof e.sdfRadius?e.sdfRadius:void 0}))}};function ml(e){e.register("Container",Bi,_l),e.register("Sprite",vr,fl),e.register("Text",Wr,pl),function(e){e.register("Mesh",In,Xh),e.register("Graphics",Mh,Hh),e.register("NineSliceSprite",ur,jh),e.register("RepeatingSprite",wr,Kh),e.register("AnimatedSprite",Rh,Qh),e.register("BitmapText",Ar,Zh),e.register("Video",Co,Jh)}(e),function(e){e.register("Label",il,al),e.register("Panel",nl,hl),e.register("Button",tl,ll),e.register("ProgressBar",rl,ul),e.register("Stack",sl,cl),e.register("UIRoot",nh,dl)}(e)}const gl=e=>{const t=Object.getPrototypeOf(e);return"function"==typeof t&&t!==Function.prototype?t:null};class yl{_fallback;_byCtor=new io({walk:gl});_byName=new Map;constructor(e=null){this._fallback=e}register(e,t,i){const n=this._byName.get(e);if(void 0!==n&&n.ctor!==t)throw new Error(`A serializer for type name "${e}" is already registered for a different constructor.`);const r={typeName:e,ctor:t,serializer:i};this._byCtor.set(t,r),this._byName.set(e,r)}resolveByNode(e){return this._byCtor.resolve(e.constructor)??this._fallback?.resolveByNode(e)}resolveByName(e){return this._byName.get(e)??this._fallback?.resolveByName(e)}hasType(e){return this._byName.has(e)||(this._fallback?.hasType(e)??!1)}clear(){this._byName.clear(),this._byCtor.destroy()}}const wl=new yl;let xl=!1;function vl(){xl||(xl=!0,ml(wl))}function bl(e,t,i){const n={version:t,loader:e,readNode:e=>Bl(e,n,i),resolveAsset:(t,i)=>{if(null==t||null===e)return null;return e.peek(i,t)}};return n}function Sl(t,i,n){const r=n.resolveByNode(t);if(void 0===r)throw new Error(`No serializer registered for node type "${t.constructor.name}". Register one via registerSerializer().`);const s={type:r.typeName};return function(t,i){if(0!==t.x&&(i.x=t.x),0!==t.y&&(i.y=t.y),0!==t.rotation&&(i.rotation=t.rotation),1!==t.scale.x&&(i.scaleX=t.scale.x),1!==t.scale.y&&(i.scaleY=t.scale.y),0!==t.skewX&&(i.skewX=t.skewX),0!==t.skewY&&(i.skewY=t.skewY),0!==t.origin.x&&(i.originX=t.origin.x),0!==t.origin.y&&(i.originY=t.origin.y),t.visible||(i.visible=!1),0!==t.zIndex&&(i.zIndex=t.zIndex),t.cullable||(i.cullable=!1),null!==t.cullArea&&(i.cullArea=[t.cullArea.x,t.cullArea.y,t.cullArea.width,t.cullArea.height]),null!==t.name&&(i.name=t.name),t instanceof Si){t.interactive&&(i.interactive=!0),t.draggable&&(i.draggable=!0),t.focusable&&(i.focusable=!0),0!==t.tabIndex&&(i.tabIndex=t.tabIndex),null!==t.cursor&&(i.cursor=t.cursor),t.clip&&(i.clip=!0),t.preserveDrawOrder&&(i.preserveDrawOrder=!0),t.cacheAsBitmap&&(i.cacheAsBitmap=!0);const e=t.clipShape;e instanceof et&&(i.clipShape=[e.x,e.y,e.width,e.height])}if(t instanceof Fn){const n=t.tint;255===n.r&&255===n.g&&255===n.b&&1===n.a||(i.tint=[n.r,n.g,n.b,n.a]),t.blendMode!==e.BlendModes.Normal&&(i.blendMode=t.blendMode),"none"!==t.pixelSnapMode&&(i.pixelSnapMode=t.pixelSnapMode)}}(t,s),Object.assign(s,r.serializer.write(t,i)),s}function Bl(e,t,i){const n=i.resolveByName(e.type);if(void 0===n)throw new Error(`No serializer registered for type "${e.type}". Register one via registerSerializer().`);const r=n.serializer.read(e,t);return sh(r,e),r}function Cl(e,t=null,i=wl){return vl(),Sl(e,function(e,t){const i={version:1,loader:e,writeNode:e=>Sl(e,i,t),keyFor:t=>{if(null==t||"object"!=typeof t||null===e)return null;const i=e.keyFor(t);return null===i?null:i.source}};return i}(t,i),i)}function Tl(e,t,i=null,n=wl){vl();const r=bl(i,1,n);e.removeChildren(),sh(e,t);const s=t.children;if(Array.isArray(s))for(const t of s){const i=lh(t);null!==i&&e.addChild(r.readNode(i))}}class Ml{_systems=[];_set=new Set;_pending=[];_ticking=!1;_sorted=!0;onAdd=new x;onRemove=new x;add(e){return this._ticking?this._pending.push({add:!0,system:e}):this._insert(e),e}remove(e){return this._ticking?!!this._set.has(e)&&(this._pending.push({add:!1,system:e}),!0):this._delete(e)}has(e){return this._set.has(e)}get size(){return this._set.size}_tick(e){if(0!==this._systems.length){this._sorted||(this._systems.sort((e,t)=>(e.order??0)-(t.order??0)),this._sorted=!0),this._ticking=!0;for(const t of this._systems)t.update(e);this._ticking=!1,this._drainPending()}}destroy(){for(let e=this._systems.length-1;e>=0;e--)this._systems[e].destroy();this._systems.length=0,this._set.clear(),this._pending.length=0,this.onAdd.destroy(),this.onRemove.destroy()}_insert(e){this._set.has(e)||(this._set.add(e),this._systems.push(e),this._sorted=!1,this.onAdd.dispatch(e))}_delete(e){if(!this._set.delete(e))return!1;const t=this._systems.indexOf(e);return-1!==t&&this._systems.splice(t,1),this.onRemove.dispatch(e),!0}_drainPending(){if(0!==this._pending.length){for(const{add:e,system:t}of this._pending)e?this._insert(t):this._delete(t);this._pending.length=0}}}class Pl{_scene;_bindings=new Set;constructor(e){this._scene=e}onStart(e,t,i){return this._track(this._scene.app.input.onStart(e,t,i))}onActive(e,t,i){return this._track(this._scene.app.input.onActive(e,t,i))}onStop(e,t,i){return this._track(this._scene.app.input.onStop(e,t,i))}onTrigger(e,t,i){return this._track(this._scene.app.input.onTrigger(e,t,i))}destroy(){for(const e of this._bindings)e.unbind();this._bindings.clear()}_track(e){return this._bindings.add(e),e}}class Al{_scene;_tweens=new Set;constructor(e){this._scene=e}create(e){const t=this._scene.app.tweens.create(e);return this._tweens.add(t),t}add(e){return this._scene.app.tweens.add(e),this._tweens.add(e),this}destroy(){for(const e of this._tweens)e.stop();this._tweens.clear()}}class El{_app=null;_root=new Bi;paused=!1;onLoad=new x;onUnload=new x;_inputs=null;_tweens=null;_systems=null;_disposal=new rh;get app(){return this._app}set app(e){this._app=e}get root(){return this._root}get inputs(){if(null===this._inputs){if(null===this._app)throw new Error("Scene.inputs is unavailable before the scene is attached to an Application.");this._inputs=this._disposal.track(new Pl(this))}return this._inputs}get tweens(){if(null===this._tweens){if(null===this._app)throw new Error("Scene.tweens is unavailable before the scene is attached to an Application.");this._tweens=this._disposal.track(new Al(this))}return this._tweens}track(e){return this._disposal.track(e)}get systems(){return null===this._systems&&(this._systems=this._disposal.track(new Ml)),this._systems}_tickSystems(e){this._systems?._tick(e)}_ui=null;get ui(){return null===this._ui&&(this._ui=this._disposal.track(new nh),null!==this._root._getStage()&&this._app?.interaction.attachUIRoot(this._ui)),this._ui}_peekUI(){return this._ui}addChild(e){return this._root.addChild(e),this}removeChild(e){return this._root.removeChild(e),this}serialize(){const e=this._app?.loader??null,t=this._app?.serializers,i={version:1,root:Cl(this._root,e,t)},n=this._peekUI();return null!==n&&(i.ui=Cl(n,e,t)),i}deserialize(e){const t=function(e){const t=hh(e);if(null===t)throw new Error("Cannot deserialize scene: the document is not an object.");const i="number"==typeof t.version?t.version:0;if(i>1)throw new Error(`Cannot deserialize scene: data version ${i} is newer than the supported version 1.`);const n=lh(t.root);if(null===n)throw new Error("Cannot deserialize scene: the document has no valid root node.");const r=lh(t.ui);return null!==r?{version:i,root:n,ui:r}:{version:i,root:n}}(e),i=this._app?.loader??null,n=this._app?.serializers;return Tl(this._root,t.root,i,n),void 0!==t.ui&&Tl(this.ui,t.ui,i,n),this}load(e){}init(e){}update(e){}fixedUpdate(e){}draw(e){}unload(e){}destroy(){this._disposal.destroy(),this._inputs=null,this._tweens=null,this._systems=null,this.onLoad.destroy(),this.onUnload.destroy(),this._root.destroy(),this._app=null}}class Rl extends In{render(e){return this.visible&&e.draw(this),this}}class kl{_app;_activeScene=null;_transitionOverlay=(()=>new Rl({vertices:new Float32Array([0,0,1,0,0,1,1,1]),indices:new Uint16Array([0,1,2,1,3,2])}))();_transition=null;onChangeScene=new x;onStartScene=new x;onUpdateScene=new x;onStopScene=new x;_asyncUpdateWarned=new WeakSet;_asyncDrawWarned=new WeakSet;constructor(e){this._app=e}get currentScene(){return this._activeScene}set currentScene(e){this.setScene(e)}async setScene(e,t={}){return await this._runWithTransition(async()=>{if(e===this._activeScene)return;null!==e&&await this._prepareScene(e);const t=this._activeScene;this._activeScene=e,null!==t&&await this._disposeScene(t),this.onChangeScene.dispatch(e),null!==e&&this.onStartScene.dispatch(e)},t.transition),this}update(e){this._advanceTransition(e.milliseconds);const t=this._activeScene;if(null!==t){if(!t.paused){const i=t.update(e);!this._asyncUpdateWarned.has(t)&&i instanceof Promise&&(this._asyncUpdateWarned.add(t),ih.warn("scene","Scene.update() returned a Promise. update() must be synchronous — async logic here breaks frame timing and silently drops errors. Move async work into load() or init() instead.")),t._tickSystems(e)}const i=t.draw(this._app.rendering);!this._asyncDrawWarned.has(t)&&i instanceof Promise&&(this._asyncDrawWarned.add(t),ih.warn("scene","Scene.draw() returned a Promise. draw() must be synchronous — an async draw() produces incomplete frames and silently drops errors.")),t._peekUI()?._render(this._app.rendering)}const i=this._getTransitionAlpha();return i>0&&this._renderTransitionOverlay(i),null!==t&&this.onUpdateScene.dispatch(t),this}fixedUpdate(e){const t=this._activeScene;return null===t||t.paused||t.fixedUpdate(e),this}destroy(){if(this._transition){const e=this._transition;this._transition=null,e.color.destroy(),e.reject(new Error("SceneManager was destroyed while a transition was active."))}this._unloadActiveSceneOnDestroy(),this._transitionOverlay.destroy(),this.onChangeScene.destroy(),this.onStartScene.destroy(),this.onUpdateScene.destroy(),this.onStopScene.destroy()}async _prepareScene(e){e.app=this._app;try{await e.load(this._app.loader),await e.init(this._app.loader),e.root.children.length>0&&e.draw===El.prototype.draw&&ih.warn("scene",`Scene.root has ${e.root.children.length} child(ren) after init() but draw() is not overridden. Scene.root is not auto-rendered — call context.render(this.root) inside draw().`),this._app.interaction.attachRoot(e.root);const t=e._peekUI();null!==t&&this._app.interaction.attachUIRoot(t),e.onLoad.dispatch()}catch(t){let i=null;try{await e.unload(this._app.loader)}catch(e){i=e}if(e.destroy(),e.app=null,i){const e=t instanceof Error?t.message:String(t);let n="unknown cleanup error";throw i instanceof Error?n=i.message:"string"==typeof i&&(n=i),new Error(`Failed to initialize scene: ${e}. Cleanup also failed: ${n}.`,{cause:t})}throw t}}async _disposeScene(e){e.onUnload.dispatch(),this.onStopScene.dispatch(e),await e.unload(this._app.loader);const t=e._peekUI();null!==t&&this._app.interaction.detachUIRoot(t),this._app.interaction.detachRoot(e.root),e.destroy(),e.app=null}async _unloadActiveSceneOnDestroy(){const e=this._activeScene;if(null!==e){this._activeScene=null;try{await this._disposeScene(e)}catch(e){ih.error("scene","SceneManager.destroy() failed to unload the active scene.",e instanceof Error?e:void 0)}}}async _runWithTransition(e,t){if("fade"!==t?.type)return void await e();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,t.duration??220);0!==i?await new Promise((n,r)=>{this._transition={type:"fade",durationMs:i,action:e,resolve:n,reject:r,color:(t.color??Tt.black).clone(),elapsedMs:0,phase:"out"}}):await e()}_advanceTransition(e){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,e)),void(this._transition.elapsedMs>=this._transition.durationMs&&(this._transition.phase="switching",this._executeTransitionAction()))):void("in"===this._transition.phase&&(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,e)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const e=this._transition;if("switching"===e?.phase){try{await e.action()}catch(t){return void(this._transition===e&&(this._transition=null,e.color.destroy(),e.reject(t)))}this._transition===e&&(e.phase="in",e.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const e=this._transition;this._transition=null,e.color.destroy(),e.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const e=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?e:1-e}_renderTransitionOverlay(e){const t=this._transition,i=t?t.color:Tt.black,n=this._app.backend,r=n.view.getBounds(),s=this._transitionOverlay,o=s.vertices;o[0]=r.left,o[1]=r.top,o[2]=r.right,o[3]=r.top,o[4]=r.left,o[5]=r.bottom,o[6]=r.right,o[7]=r.bottom,s.tint.set(i.r,i.g,i.b,Math.max(0,Math.min(1,e))),s.render(n)}}var Dl;e.ApplicationStatus=void 0,(Dl=e.ApplicationStatus||(e.ApplicationStatus={}))[Dl.Loading=1]="Loading",Dl[Dl.Running=2]="Running",Dl[Dl.Halting=3]="Halting",Dl[Dl.Stopped=4]="Stopped";const Fl=1e3/60,Il={type:"auto"},Ll=800,Ul=600,Gl=1,Nl=-1,Ol={method:"GET",mode:"cors",cache:"default"},Vl={debug:!1,spriteRendererBatchSize:4096,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1}},zl={gamepadDefinitions:[],gamepadSlotStrategy:"sticky",pointerDistanceThreshold:10};const ql=Object.freeze({version:"0.15.0",revision:"18cadeb",development:!1});const Wl={decodeBase64:function(e){const t=e.replaceAll(/\s+/g,""),i=atob(t),n=i.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=i.charCodeAt(e);return r},decompress:async function(e,t){if("undefined"==typeof DecompressionStream)throw new Error("Codec.decompress requires the native DecompressionStream API.");const i=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(t)).getReader(),n=[];let r=0;for(;;){const{done:e,value:t}=await i.read();if(e)break;n.push(t),r+=t.length}const s=new Uint8Array(r);let o=0;for(const e of n)s.set(e,o),o+=e.length;return s}},Yl="undefined"!=typeof performance,$l={mark:e=>{Yl&&"function"==typeof performance.mark&&performance.mark(e)},measure:(e,t,i)=>{if(Yl&&"function"==typeof performance.measure)try{return performance.measure(e,t,i)}catch{return}},clearMarks:e=>{Yl&&"function"==typeof performance.clearMarks&&performance.clearMarks(e)},clearMeasures:e=>{Yl&&"function"==typeof performance.clearMeasures&&performance.clearMeasures(e)}};class Xl{_descriptor;constructor(e){this._descriptor=e}static from(e,t=null,i){return new Xl(Cl(e,t,i))}static fromJSON(e){return new Xl(e)}instantiate(e=null,t){return function(e,t=null,i=wl){return vl(),Bl(e,bl(t,1,i),i)}(this._descriptor,e,t)}toJSON(){return this._descriptor}}const Hl=new Map([["DPad",[.22,.58]],["DPadUp",[.22,.5]],["DPadDown",[.22,.66]],["DPadLeft",[.14,.58]],["DPadRight",[.3,.58]],["ButtonNorth",[.78,.5]],["ButtonWest",[.7,.58]],["ButtonEast",[.86,.58]],["ButtonSouth",[.78,.66]],["LeftShoulder",[.28,.28]],["RightShoulder",[.72,.28]],["LeftTrigger",[.2,.16]],["RightTrigger",[.8,.16]],["Select",[.46,.5]],["Start",[.54,.5]],["LeftStick",[.38,.66]],["RightStick",[.62,.66]]]),jl=new Map([["ButtonNorth",Li.North],["ButtonWest",Li.West],["ButtonEast",Li.East],["ButtonSouth",Li.South],["LeftShoulder",Li.LeftShoulder],["RightShoulder",Li.RightShoulder],["LeftTrigger",Li.LeftTrigger],["RightTrigger",Li.RightTrigger],["Select",Li.Select],["Start",Li.Start],["LeftStick",Li.LeftStick],["RightStick",Li.RightStick],["DPadUp",Li.DPadUp],["DPadDown",Li.DPadDown],["DPadLeft",Li.DPadLeft],["DPadRight",Li.DPadRight]]),Kl=new Map([["ButtonNorth","North"],["ButtonWest","West"],["ButtonEast","East"],["ButtonSouth","South"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Select"],["Start","Start"],["LeftStick","L3"],["RightStick","R3"]]),Ql=new Map([["ButtonNorth","Y"],["ButtonWest","X"],["ButtonEast","B"],["ButtonSouth","A"],["LeftShoulder","LB"],["RightShoulder","RB"],["LeftTrigger","LT"],["RightTrigger","RT"],["Select","View"],["Start","Menu"],["LeftStick","L3"],["RightStick","R3"]]),Zl=new Map([["ButtonNorth","Triangle"],["ButtonWest","Square"],["ButtonEast","Circle"],["ButtonSouth","Cross"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Create"],["Start","Options"],["LeftStick","L3"],["RightStick","R3"]]),Jl=new Map([["ButtonNorth","X"],["ButtonWest","Y"],["ButtonEast","A"],["ButtonSouth","B"],["LeftShoulder","L"],["RightShoulder","R"],["LeftTrigger","ZL"],["RightTrigger","ZR"],["Select","Minus"],["Start","Plus"],["LeftStick","L3"],["RightStick","R3"]]),eu=new Map([[e.GamepadMappingFamily.GenericDualAnalog,Kl],[e.GamepadMappingFamily.Xbox,Ql],[e.GamepadMappingFamily.PlayStation,Zl],[e.GamepadMappingFamily.SwitchPro,Jl],[e.GamepadMappingFamily.JoyConLeft,Jl],[e.GamepadMappingFamily.JoyConRight,Jl],[e.GamepadMappingFamily.GameCube,Kl],[e.GamepadMappingFamily.SteamController,Kl],[e.GamepadMappingFamily.SteamDeck,Kl],[e.GamepadMappingFamily.ArcadeStick,Kl]]);let tu=null;class iu{static collisionSegments=32;collisionType=e.CollisionType.Circle;_position;_collisionVertices=null;_verticesDirty=!0;_normals=null;_normalsDirty=!0;_radius;constructor(e=0,t=0,i=0){this._position=new it(e,t),this._radius=i}get position(){return this._position}set position(e){this._position.copy(e),this._verticesDirty=!0,this._normalsDirty=!0}get x(){return this._position.x}set x(e){this._position.x!==e&&(this._position.x=e,this._verticesDirty=!0,this._normalsDirty=!0)}get y(){return this._position.y}set y(e){this._position.y!==e&&(this._position.y=e,this._verticesDirty=!0,this._normalsDirty=!0)}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,this._verticesDirty=!0,this._normalsDirty=!0)}setPosition(e,t){return this._position.set(e,t),this._verticesDirty=!0,this._normalsDirty=!0,this}setRadius(e){return this._radius!==e&&(this._radius=e,this._verticesDirty=!0,this._normalsDirty=!0),this}set(e,t,i){return this._position.set(e,t),this._radius=i,this._verticesDirty=!0,this._normalsDirty=!0,this}copy(e){return this._position.copy(e.position),this._radius=e.radius,this._verticesDirty=!0,this._normalsDirty=!0,this}clone(){return new iu(this.x,this.y,this.radius)}equals({x:e,y:t,radius:i}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t||void 0!==i&&this.radius!==i)}getBounds(){return new et(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){if(this._normalsDirty){const e=this.getCollisionVertices();null===this._normals&&(this._normals=e.map(()=>new it));for(let t=0;t<e.length;t++){const i=e[t],n=e[(t+1)%e.length];this._normals[t].set(n.x-i.x,n.y-i.y).rperp().normalize()}this._normalsDirty=!1}return this._normals}project(e,t=new me){const i=e.dot(this.x,this.y),n=this.radius*e.length;return t.set(i-n,i+n)}contains(e,t){return ve(it.temp.set(e,t),this)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Ee(t.getBounds(),this);case e.CollisionType.Rectangle:return Ee(t,this);case e.CollisionType.Polygon:return Ge(this,t);case e.CollisionType.Circle:return De(this,t);case e.CollisionType.Ellipse:return Fe(this,t);case e.CollisionType.Line:return Te(t,this);case e.CollisionType.Point:return ve(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return We(this,t.getBounds());case e.CollisionType.Rectangle:return We(this,t);case e.CollisionType.Polygon:return Xe(t,this,!0);case e.CollisionType.Circle:return qe(this,t);case e.CollisionType.Ellipse:return $e(t,this,!0);default:return null}}destroy(){if(this._position.destroy(),null!==this._collisionVertices){for(const e of this._collisionVertices)e.destroy();this._collisionVertices=null}if(null!==this._normals){for(const e of this._normals)e.destroy();this._normals=null}}getCollisionVertices(){if(this._verticesDirty){const e=iu.collisionSegments;if(null===this._collisionVertices){this._collisionVertices=new Array(e);for(let t=0;t<e;t++)this._collisionVertices[t]=new it}for(let t=0;t<e;t++){const i=2*t*Math.PI/e-Math.PI/2,n=Math.cos(i)*this._radius,r=Math.sin(i)*this._radius;this._collisionVertices[t].set(this._radius+n,this._radius+r)}this._verticesDirty=!1}return this._collisionVertices}static get temp(){return null===tu&&(tu=new iu),tu}}class nu{collisionType=e.CollisionType.Ellipse;_position;_radius;constructor(e=0,t=0,i=0,n=i){this._position=new it(e,t),this._radius=new it(i,n)}get position(){return this._position}set position(e){this._position.copy(e)}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get radius(){return this._radius}set radius(e){this._radius.copy(e)}get rx(){return this._radius.x}set rx(e){this._radius.x=e}get ry(){return this._radius.y}set ry(e){this._radius.y=e}setPosition(e,t){return this._position.set(e,t),this}setRadius(e,t=e){return this._radius.set(e,t),this}set(e,t,i,n){return this._position.set(e,t),this._radius.set(i,n),this}copy(e){return this._position.copy(e.position),this._radius.copy(e.radius),this}clone(){return new nu(this.x,this.y,this.rx,this.ry)}getBounds(){return new et(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(e,t=new me){const i=this.x*e.x+this.y*e.y,n=Math.sqrt((this.rx*e.x)**2+(this.ry*e.y)**2);return t.set(i-n,i+n)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Re(t.getBounds(),this);case e.CollisionType.Rectangle:return Re(t,this);case e.CollisionType.Polygon:return Oe(this,t);case e.CollisionType.Circle:return Fe(t,this);case e.CollisionType.Ellipse:return Ne(this,t);case e.CollisionType.Line:return Me(t,this);case e.CollisionType.Point:return be(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Ye(this,t.getBounds());case e.CollisionType.Rectangle:return Ye(this,t);case e.CollisionType.Circle:return $e(this,t);case e.CollisionType.Polygon:return je(this,t);case e.CollisionType.Ellipse:return He(this,t);default:return null}}contains(e,t){return be(it.temp.set(e,t),this)}equals({x:e,y:t,rx:i,ry:n}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t||void 0!==i&&this.rx!==i||void 0!==n&&this.ry!==n)}destroy(){this._position.destroy(),this._radius.destroy()}}let ru=null;class su{collisionType=e.CollisionType.Line;_fromPosition;_toPosition;constructor(e=0,t=0,i=0,n=0){this._fromPosition=new it(e,t),this._toPosition=new it(i,n)}get fromPosition(){return this._fromPosition}set fromPosition(e){this._fromPosition.copy(e)}get fromX(){return this._fromPosition.x}set fromX(e){this._fromPosition.x=e}get fromY(){return this._fromPosition.y}set fromY(e){this._fromPosition.y=e}get toPosition(){return this._toPosition}set toPosition(e){this._toPosition.copy(e)}get toX(){return this._toPosition.x}set toX(e){this._toPosition.x=e}get toY(){return this._toPosition.y}set toY(e){this._toPosition.y=e}set(e,t,i,n){return this._fromPosition.set(e,t),this._toPosition.set(i,n),this}copy(e){return this._fromPosition.copy(e.fromPosition),this.toPosition.copy(e.toPosition),this}clone(){return new su(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:e,fromY:t,toX:i,toY:n}=this,r=Math.min(e,i),s=Math.min(t,n);return new et(r,s,Math.max(e,i)-r,Math.max(t,n)-s)}getNormals(){return[]}project(e,t=new me){return t}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Ce(this,t.getBounds());case e.CollisionType.Rectangle:return Ce(this,t);case e.CollisionType.Polygon:return Pe(this,t);case e.CollisionType.Circle:return Te(this,t);case e.CollisionType.Ellipse:return Me(this,t);case e.CollisionType.Line:return Be(this,t);case e.CollisionType.Point:return we(t,this);default:return!1}}collidesWith(e){return null}contains(e,t,i=.1){return we(it.temp.set(e,t),this,i)}equals({fromX:e,fromY:t,toX:i,toY:n}={}){return!(void 0!==e&&this.fromX!==e||void 0!==t&&this.fromY!==t||void 0!==i&&this.toX!==i||void 0!==n&&this.toY!==n)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===ru&&(ru=new su),ru}}class ou{radius;phi;constructor(e=0,t=0){this.radius=e,this.phi=t}static fromVector(e){return new ou(e.length,e.angle)}toVector(){return it.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}let au=null;class hu{_startPoint;_endPoint;constructor(e=0,t=0,i=0,n=0){this._startPoint=new it(e,t),this._endPoint=new it(i,n)}get startPoint(){return this._startPoint}set startPoint(e){this._startPoint.copy(e)}get startX(){return this._startPoint.x}set startX(e){this._startPoint.x=e}get startY(){return this._startPoint.y}set startY(e){this._startPoint.y=e}get endPoint(){return this._endPoint}set endPoint(e){this._endPoint.copy(e)}get endX(){return this._endPoint.x}set endX(e){this._endPoint.x=e}get endY(){return this._endPoint.y}set endY(e){this._endPoint.y=e}set(e,t,i,n){return this._startPoint.set(e,t),this._endPoint.set(i,n),this}copy(e){return this._startPoint.copy(e.startPoint),this._endPoint.copy(e.endPoint),this}clone(){return new hu(this.startX,this.startY,this.endX,this.endY)}equals({startX:e,startY:t,endX:i,endY:n}={}){return!(void 0!==e&&this.startX!==e||void 0!==t&&this.startY!==t||void 0!==i&&this.endX!==i||void 0!==n&&this.endY!==n)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===au&&(au=new hu),au}}function lu(e,t,i,n){const r=e.x,s=e.x+e.width,o=e.y,a=e.y+e.height,h=n.x,l=n.x+n.width,u=n.y,c=n.y+n.height;let d=-1/0,_=1/0;if(t>0)d=(h-s)/t,_=(l-r)/t;else if(t<0)d=(l-r)/t,_=(h-s)/t;else if(s<=h||r>=l)return null;let f=-1/0,p=1/0;if(i>0)f=(u-a)/i,p=(c-o)/i;else if(i<0)f=(c-o)/i,p=(u-a)/i;else if(a<=u||o>=c)return null;const m=Math.max(d,f),g=Math.min(_,p);if(m>g||g<0||m>1)return null;const y=Math.max(0,m),w=e.x+t*y,x=e.y+i*y;let v=0,b=0;if(m<=0){Math.min(s-h,l-r)<Math.min(a-u,c-o)?v=r<h?-1:1:b=o<u?-1:1}else d>f?v=t>0?-1:1:b=i>0?-1:1;return{t:y,x:w,y:x,normalX:v,normalY:b}}function uu(e,t,i,n){const r=e.x-n.x,s=e.y-n.y,o=e.radius+n.radius,a=t*t+i*i,h=2*(r*t+s*i),l=r*r+s*s-o*o;if(l<=0){const t=Math.sqrt(r*r+s*s),i=t>0?r/t:1,n=t>0?s/t:0;return{t:0,x:e.x,y:e.y,normalX:i,normalY:n}}if(0===a)return null;const u=h*h-4*a*l;if(u<0)return null;const c=(-h-Math.sqrt(u))/(2*a);if(c<0||c>1)return null;const d=e.x+t*c,_=e.y+i*c;return{t:c,x:d,y:_,normalX:(d-n.x)/o,normalY:(_-n.y)/o}}const cu={rectangle:lu,circleVsRectangle:function(e,t,i,n){const r=e.radius,s=e.x,o=e.y,a=n.x,h=n.x+n.width,l=n.y,u=n.y+n.height,c=s-Math.max(a,Math.min(s,h)),d=o-Math.max(l,Math.min(o,u));if(c*c+d*d<=r*r){const e=Math.sqrt(c*c+d*d);if(e>0)return{t:0,x:s,y:o,normalX:c/e,normalY:d/e};const t=s-a,i=h-s,n=o-l,r=u-o;return Math.min(t,i)<=Math.min(n,r)?{t:0,x:s,y:o,normalX:t<i?-1:1,normalY:0}:{t:0,x:s,y:o,normalX:0,normalY:n<r?-1:1}}if(0===t&&0===i)return null;let _=1/0,f=0,p=0;const m=(e,t,i)=>{e>=0&&e<=1&&e<_&&(_=e,f=t,p=i)};if(0!==t){const e=(a-r-s)/t;if(e>=0&&e<=1){const t=o+i*e;t>=l&&t<=u&&m(e,-1,0)}const n=(h+r-s)/t;if(n>=0&&n<=1){const e=o+i*n;e>=l&&e<=u&&m(n,1,0)}}if(0!==i){const e=(l-r-o)/i;if(e>=0&&e<=1){const i=s+t*e;i>=a&&i<=h&&m(e,0,-1)}const n=(u+r-o)/i;if(n>=0&&n<=1){const e=s+t*n;e>=a&&e<=h&&m(n,0,1)}}const g=t*t+i*i,y=[a,h,a,h],w=[l,l,u,u];for(let e=0;e<4;e++){const n=y[e],a=w[e],h=s-n,l=o-a,u=2*(h*t+l*i),c=u*u-4*g*(h*h+l*l-r*r);if(c<0)continue;const d=(-u-Math.sqrt(c))/(2*g);if(d<0||d>1)continue;m(d,(s+t*d-n)/r,(o+i*d-a)/r)}return _>1?null:{t:_,x:s+t*_,y:o+i*_,normalX:f,normalY:p}},circleVsCircle:uu,rectangleAgainst:function(e,t,i,n){if(0===n.length)return null;const r=Math.min(e.x,e.x+t),s=Math.max(e.x+e.width,e.x+e.width+t),o=Math.min(e.y,e.y+i),a=Math.max(e.y+e.height,e.y+e.height+i);let h=null;for(const l of n){if(s<=l.x||r>=l.x+l.width||a<=l.y||o>=l.y+l.height)continue;const n=lu(e,t,i,l);null!==n&&(null===h||n.t<h.t)&&(h=n)}return h},circleAgainst:function(e,t,i,n){if(0===n.length)return null;const r=Math.min(e.x,e.x+t)-e.radius,s=Math.max(e.x,e.x+t)+e.radius,o=Math.min(e.y,e.y+i)-e.radius,a=Math.max(e.y,e.y+i)+e.radius;let h=null;for(const l of n){if(s<=l.x-l.radius||r>=l.x+l.radius||a<=l.y-l.radius||o>=l.y+l.radius)continue;const n=uu(e,t,i,l);null!==n&&(null===h||n.t<h.t)&&(h=n)}return h},substep:function*(e,t,i,n,r){const s=Math.hypot(i,n),o=Math.max(1,Math.ceil(s/r));for(let r=0;r<=o;r++){const s=r/o;yield{x:e+i*s,y:t+n*s,t:s}}}};class du{_context;target;view;constructor(e,t,i){this._context=e,this.target=t,this.view=i}get backend(){return this._context.backend}clear(e){this._context.clear(e)}render(e,t){this._context.render(e,{view:t?.view??this.view})}renderTo(e,t){this._context.renderTo(e,t)}drawGeometry(e,t,i){this._context.drawGeometry(e,t,{...i,view:i?.view??this.view})}drawBatch(e,t){this._context.drawBatch(e,{...t,view:t?.view??this.view})}}class _u{enabled;label;_pipelineOwner=null;constructor(e){this.enabled=e?.enabled??!0,this.label=e?.label??new.target.name}resize(e,t){}destroy(){}}class fu extends _u{_passes=[];_executing=!1;_destroyed=!1;constructor(e){super(e)}get size(){return this._passes.length}addPass(e){return this._admit(e),this._passes.push(e),e._pipelineOwner=this,this}insertPass(e,t){this._admit(e);const i=Math.max(0,Math.min(t,this._passes.length));return this._passes.splice(i,0,e),e._pipelineOwner=this,this}removePass(e){this._assertLive(),this._assertNotExecuting();const t=this._passes.indexOf(e);return-1!==t&&(this._passes.splice(t,1),e._pipelineOwner=null,!0)}clear(){this._assertLive(),this._assertNotExecuting();for(const e of this._passes)e._pipelineOwner=null;return this._passes.length=0,this}hasPass(e){return e._pipelineOwner===this}indexOf(e){return this._passes.indexOf(e)}at(e){return this._passes[e]}[Symbol.iterator](){return this._passes[Symbol.iterator]()}execute(e){if(this.enabled){if(this._assertLive(),this._executing)throw new Error("RenderPipeline.execute is not re-entrant.");this._executing=!0;try{for(const t of this._passes)t.enabled&&t.execute(e)}finally{this._executing=!1}}}resize(e,t){for(const i of this._passes)i.resize(e,t)}destroy(){if(this._destroyed)return;this._assertNotExecuting(),this._destroyed=!0;const e=this._passes.splice(0,this._passes.length),t=[];for(const i of e){i._pipelineOwner=null;try{i.destroy()}catch(e){t.push(e)}}if(t.length>0)throw t[0]}_admit(e){if(this._assertLive(),this._assertNotExecuting(),null!==e._pipelineOwner)throw new Error("RenderPass already belongs to a RenderPipeline; remove it from its current pipeline first.");if(e instanceof fu&&e._reaches(this))throw new Error("RenderPipeline cannot contain itself, directly or indirectly (cycle).")}_reaches(e){if(this===e)return!0;for(const t of this._passes)if(t instanceof fu&&t._reaches(e))return!0;return!1}_assertLive(){if(this._destroyed)throw new Error("RenderPipeline has been destroyed and can no longer be used.")}_assertNotExecuting(){if(this._executing)throw new Error("RenderPipeline cannot be mutated while it is executing.")}}class pu{destroy(){}}const mu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);class gu extends pu{uniforms;_fragmentSource;_vertexSource;_shader=null;_connection=null;constructor(e){if(super(),!e.fragmentSource)throw new Error("WebGl2ShaderFilter requires fragmentSource for the WebGL2 backend.");const t=!1!==e.autoUpgrade;var i;this._fragmentSource=t?(i=e.fragmentSource,/^\s*#version\s+300\s+es/.test(i)?i:"#version 300 es\nprecision highp float;\nout vec4 fragColor;\n"+i.replace(/^\s*#version[^\n]*\n/,"").replaceAll(/\bgl_FragColor\b/g,"fragColor").replaceAll(/\btexture2D(?=\s*\()/g,"texture").replaceAll(/\btextureCube(?=\s*\()/g,"texture").replaceAll(/\btexture2DProj(?=\s*\()/g,"textureProj").replaceAll(/\bvarying\b/g,"in")):e.fragmentSource,this._vertexSource=e.vertexSource??"#version 300 es\nin vec2 aPosition;\nin vec2 aUv;\nout vec2 vUv;\nvoid main() {\n vUv = aUv;\n gl_Position = vec4(aPosition, 0.0, 1.0);\n}\n",this.uniforms={...e.uniforms??{}}}apply(t,i,n){if(t.backendType===e.RenderBackendType.WebGpu)throw new Error("WebGl2ShaderFilter requires the WebGL2 backend. Use WebGpuShaderFilter on WebGPU.");const r=t;this._ensureConnected(r);const s=this._shader;t.execute(new vi(t=>{const r=t;r.bindShader(s),r.bindTexture(i,0),s.uniforms.has("uTexture")&&s.getUniform("uTexture").setValue(new Int32Array([0])),s.uniforms.has("uResolution")&&s.getUniform("uResolution").setValue(new Float32Array([n.width,n.height]));let o=1;for(const[e,t]of Object.entries(this.uniforms)){if(!s.uniforms.has(e))continue;const i=s.getUniform(e);t instanceof pi?(r.bindTexture(t,o),i.setValue(new Int32Array([o])),o++):i.setValue(this._marshalValue(t))}s.sync();const a=this._connection;r.bindVertexArrayObject(a.vao),a.vao.draw(4,0,e.RenderingPrimitives.TriangleStrip)},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){null!==this._connection&&(this._connection.vertexBuffer.destroy(),this._connection.vao.destroy(),this._connection=null),null!==this._shader&&(this._shader.destroy(),this._shader=null);for(const e of Object.keys(this.uniforms))delete this.uniforms[e]}_ensureConnected(e){if(null!==this._shader)return;const t=e.context,i=new Yr(this._vertexSource,this._fragmentSource);i.connect(ts(t)),i.sync();const n=t.createVertexArray();if(null===n)throw new Error("WebGl2ShaderFilter: could not create vertex array object.");const r=this._createVertexBuffer(t),s=this._createVao(t,n,i,r);this._shader=i,this._connection={gl:t,vertexBuffer:r,vao:s}}_createVertexBuffer(t){const i=t.createBuffer();if(null===i)throw new Error("WebGl2ShaderFilter: could not create vertex buffer.");const n=new Hr(e.BufferTypes.ArrayBuffer,mu,e.BufferUsage.StaticDraw);return n.connect({bind:()=>{t.bindBuffer(t.ARRAY_BUFFER,i)},upload:(e,n)=>{t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,e.data,e.usage)},destroy:e=>{t.deleteBuffer(i),e.disconnect()}}),n}_createVao(t,i,n,r){let s=-1;const o=new ns(e.RenderingPrimitives.TriangleStrip);return n.attributes.has("aPosition")&&o.addAttribute(r,n.getAttribute("aPosition"),t.FLOAT,!1,16,0),n.attributes.has("aUv")&&o.addAttribute(r,n.getAttribute("aUv"),t.FLOAT,!1,16,8),o.connect({bind:e=>{if(t.bindVertexArray(i),s!==e.version){let i=null;for(const n of e.attributes){const e=n.buffer;i!==e&&(e.bind(),i=e),t.vertexAttribPointer(n.location,n.size,n.type,n.normalized,n.stride,n.start),t.enableVertexAttribArray(n.location)}s=e.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,r)=>{t.drawArrays(r,n,i)},destroy:e=>{t.deleteVertexArray(i),e.disconnect()}}),o}_marshalValue(e){return e instanceof Float32Array||e instanceof Int32Array?e:"number"==typeof e?new Float32Array([e]):new Float32Array(e)}}const yu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);function wu(e){return e instanceof pi||"object"==typeof e&&null!==e&&"width"in e&&"height"in e&&!(e instanceof Float32Array)&&!(e instanceof Int32Array)&&!Array.isArray(e)}class xu extends pu{uniforms;_fragmentSource;_vertexSource;_connection=null;constructor(e){if(super(),!e.fragmentSource)throw new Error("WebGpuShaderFilter requires fragmentSource.");this._fragmentSource=e.fragmentSource,this._vertexSource=e.vertexSource??"\nstruct VsOut {\n @builtin(position) position: vec4<f32>,\n @location(0) vUv: vec2<f32>,\n};\n\n@vertex\nfn main(@location(0) aPosition: vec2<f32>, @location(1) aUv: vec2<f32>) -> VsOut {\n var out: VsOut;\n out.position = vec4<f32>(aPosition, 0.0, 1.0);\n out.vUv = aUv;\n return out;\n}\n",this.uniforms={...e.uniforms??{}}}apply(t,i,n){if(t.backendType!==e.RenderBackendType.WebGpu)throw new Error("WebGpuShaderFilter requires the WebGPU backend. Use WebGl2ShaderFilter on WebGL2.");const r=t;this._ensureConnected(r,n);const s=this._connection;t.execute(new vi(e=>{const t=e,r=s.device,o=new Float32Array([n.width,n.height,0,0]);r.queue.writeBuffer(s.resolutionBuffer,0,o);const a=t.getTextureBinding(i),h=r.createBindGroup({layout:s.autoBindGroupLayout,entries:[{binding:0,resource:{buffer:s.resolutionBuffer}},{binding:1,resource:a.view},{binding:2,resource:s.sampler}]}),l=this._buildUserBindGroup(t,s),u=t._passCoordinator.acquirePass().pass;u.setPipeline(s.pipeline),u.setVertexBuffer(0,s.vertexBuffer),u.setBindGroup(0,h),u.setBindGroup(1,l),u.draw(4),t.stats.drawCalls++,t._passCoordinator.endPass()},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){null!==this._connection&&(this._connection.vertexBuffer.destroy(),this._connection.resolutionBuffer.destroy(),this._connection.userUniformBuffer?.destroy(),this._connection=null);for(const e of Object.keys(this.uniforms))delete this.uniforms[e]}_ensureConnected(e,t){if(null!==this._connection)return;const i=e.device,n=i.createShaderModule({code:this._vertexSource}),r=i.createShaderModule({code:this._fragmentSource}),s=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT|GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),o=this._buildUserBindGroupLayout(i),a=i.createPipelineLayout({bindGroupLayouts:[s,o]}),h=e.getTextureFormat(t),l=i.createRenderPipeline({layout:a,vertex:{module:n,entryPoint:"main",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:r,entryPoint:"main",targets:[{format:h}]},primitive:{topology:"triangle-strip"}}),u=i.createBuffer({size:yu.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});i.queue.writeBuffer(u,0,yu);const c=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),d=i.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"});this._connection={device:i,vertexBuffer:u,resolutionBuffer:c,autoBindGroupLayout:s,userBindGroupLayout:o,pipelineLayout:a,pipeline:l,sampler:d,userUniformBuffer:null}}_buildUserBindGroupLayout(e){const t=[];Object.values(this.uniforms).some(e=>!wu(e))&&t.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});let i=1;for(const e of Object.values(this.uniforms))wu(e)&&(t.push({binding:i,visibility:GPUShaderStage.FRAGMENT,texture:{}}),i++,t.push({binding:i,visibility:GPUShaderStage.FRAGMENT,sampler:{}}),i++);return 0===t.length&&t.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),e.createBindGroupLayout({entries:t})}_buildUserBindGroup(e,t){const i=t.device,n=[],r=Object.entries(this.uniforms).filter(([,e])=>!wu(e));if(r.length>0){const e=16*r.length,s=new Float32Array(e/4);let o=0;for(const[,e]of r){const t=4*o;if("number"==typeof e)s[t]=e;else if(e instanceof Float32Array)s.set(e,t);else if(e instanceof Int32Array)for(let i=0;i<e.length;i++)s[t+i]=e[i];else{const i=e;for(let e=0;e<i.length;e++)s[t+e]=i[e]}o++}(null===t.userUniformBuffer||t.userUniformBuffer.size<e)&&(t.userUniformBuffer?.destroy(),t.userUniformBuffer=i.createBuffer({size:e,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),i.queue.writeBuffer(t.userUniformBuffer,0,s),n.push({binding:0,resource:{buffer:t.userUniformBuffer}})}else null===t.userUniformBuffer&&(t.userUniformBuffer=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),n.push({binding:0,resource:{buffer:t.userUniformBuffer}});let s=1;for(const[,t]of Object.entries(this.uniforms)){if(!wu(t))continue;const i=e.getTextureBinding(t);n.push({binding:s,resource:i.view}),s++,n.push({binding:s,resource:i.sampler}),s++}return i.createBindGroup({layout:t.userBindGroupLayout,entries:n})}}class vu extends pu{static identityLut1D(t=256){const i=document.createElement("canvas");i.width=t,i.height=1;const n=i.getContext("2d");if(null===n)throw new Error("LutFilter.identityLut1D: 2D canvas context unavailable.");const r=n.createImageData(t,1);for(let e=0;e<t;e++){const i=Math.round(e/(t-1)*255),n=4*e;r.data[n]=i,r.data[n+1]=i,r.data[n+2]=i,r.data[n+3]=255}return n.putImageData(r,0,0),new pi(i,{scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,generateMipMap:!1})}static identityLut3D(t=17){const i=t*t,n=document.createElement("canvas");n.width=i,n.height=t;const r=n.getContext("2d");if(null===r)throw new Error("LutFilter.identityLut3D: 2D canvas context unavailable.");const s=r.createImageData(i,t),o=t-1;for(let e=0;e<t;e++){const n=Math.round(e/o*255);for(let r=0;r<t;r++){const a=Math.round(r/o*255);for(let h=0;h<t;h++){const l=Math.round(h/o*255),u=4*(r*i+(e*t+h));s.data[u]=l,s.data[u+1]=a,s.data[u+2]=n,s.data[u+3]=255}}}return r.putImageData(s,0,0),new pi(n,{scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,generateMipMap:!1})}static fromImage(t){return new pi(t,{scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,generateMipMap:!1})}_mode;_size;_lut;_backendFilter=null;constructor(e={}){super(),this._mode=e.mode??"3d",this._size=Math.max(2,Math.floor(e.size??17)),this._lut="1d"===this._mode?vu.identityLut1D():vu.identityLut3D(this._size)}get mode(){return this._mode}get size(){return this._size}get lut(){return this._lut}setLut(e){return this._lut=e,null!==this._backendFilter&&(this._backendFilter.uniforms.uLut=e),this}apply(e,t,i){null===this._backendFilter&&(this._backendFilter=this._createBackendFilter(e)),this._backendFilter.apply(e,t,i)}destroy(){null!==this._backendFilter&&(this._backendFilter.destroy(),this._backendFilter=null)}_createBackendFilter(t){const i="3d"===this._mode,n={uLut:this._lut};return i&&(n.uLutSize=this._size),t.backendType===e.RenderBackendType.WebGpu?new xu({fragmentSource:i?"\nstruct Uniforms {\n uLutSize: f32,\n};\n\n@group(0) @binding(1) var uTexture: texture_2d<f32>;\n@group(0) @binding(2) var uSampler: sampler;\n@group(1) @binding(0) var<uniform> uniforms: Uniforms;\n@group(1) @binding(1) var uLut: texture_2d<f32>;\n\nfn sampleLut3d(c: vec3<f32>) -> vec3<f32> {\n let n = uniforms.uLutSize;\n let scaled = clamp(c.b, 0.0, 1.0) * (n - 1.0);\n let bLow = floor(scaled);\n let bHigh = min(bLow + 1.0, n - 1.0);\n let bFrac = scaled - bLow;\n let invN2 = 1.0 / (n * n);\n let invN = 1.0 / n;\n let halfPx = 0.5 / (n * n);\n let halfRow = 0.5 / n;\n let rOff = clamp(c.r, 0.0, 1.0) * (n - 1.0) * invN2;\n let gOff = clamp(c.g, 0.0, 1.0) * (n - 1.0) * invN + halfRow;\n let uLow = bLow * invN + rOff + halfPx;\n let uHigh = bHigh * invN + rOff + halfPx;\n let lo = textureSample(uLut, uSampler, vec2<f32>(uLow, gOff)).rgb;\n let hi = textureSample(uLut, uSampler, vec2<f32>(uHigh, gOff)).rgb;\n return mix(lo, hi, bFrac);\n}\n\n@fragment\nfn fragMain(@location(0) vUv: vec2<f32>) -> @location(0) vec4<f32> {\n let src = textureSample(uTexture, uSampler, vUv);\n return vec4<f32>(sampleLut3d(src.rgb), src.a);\n}\n":"\n@group(0) @binding(1) var uTexture: texture_2d<f32>;\n@group(0) @binding(2) var uSampler: sampler;\n@group(1) @binding(1) var uLut: texture_2d<f32>;\n\n@fragment\nfn fragMain(@location(0) vUv: vec2<f32>) -> @location(0) vec4<f32> {\n let src = textureSample(uTexture, uSampler, vUv);\n let graded = textureSample(uLut, uSampler, vec2<f32>(src.r, 0.5)).rgb;\n return vec4<f32>(graded, src.a);\n}\n",uniforms:n}):new gu({fragmentSource:i?"#version 300 es\nprecision mediump float;\nuniform sampler2D uTexture;\nuniform sampler2D uLut;\nuniform float uLutSize;\nin vec2 vUv;\nout vec4 fragColor;\n\nvec3 sampleLut3d(vec3 c) {\n float n = uLutSize;\n float scaled = clamp(c.b, 0.0, 1.0) * (n - 1.0);\n float bLow = floor(scaled);\n float bHigh = min(bLow + 1.0, n - 1.0);\n float bFrac = scaled - bLow;\n float invN2 = 1.0 / (n * n);\n float invN = 1.0 / n;\n float halfPx = 0.5 / (n * n);\n float halfRow = 0.5 / n;\n float rOff = clamp(c.r, 0.0, 1.0) * (n - 1.0) * invN2;\n float gOff = clamp(c.g, 0.0, 1.0) * (n - 1.0) * invN + halfRow;\n float uLow = bLow * invN + rOff + halfPx;\n float uHigh = bHigh * invN + rOff + halfPx;\n vec3 lo = texture(uLut, vec2(uLow, gOff)).rgb;\n vec3 hi = texture(uLut, vec2(uHigh, gOff)).rgb;\n return mix(lo, hi, bFrac);\n}\n\nvoid main() {\n vec4 src = texture(uTexture, vUv);\n fragColor = vec4(sampleLut3d(src.rgb), src.a);\n}\n":"#version 300 es\nprecision mediump float;\nuniform sampler2D uTexture;\nuniform sampler2D uLut;\nin vec2 vUv;\nout vec4 fragColor;\nvoid main() {\n vec4 src = texture(uTexture, vUv);\n vec3 graded = texture(uLut, vec2(src.r, 0.5)).rgb;\n fragColor = vec4(graded, src.a);\n}\n",uniforms:n})}}const bu={f32:4,u8:1,u16:2,u32:4,i32:4},Su=new Set(["triangle-list","triangle-strip"]),Bu=new Set(["static","dynamic","stream"]),Cu=new Set(["a_position","position"]),Tu=new WeakMap;let Mu=1;const Pu=(e,t)=>{const{byteLength:i}=e;if(i%t!==0)throw new Error(`Geometry vertexData byteLength ${i} must be divisible by stride ${t}.`);return i/t},Au=(e,t,i,n)=>{switch(t){case"f32":return e.getFloat32(i,!0);case"u8":{const t=e.getUint8(i);return n?t/255:t}case"u16":{const t=e.getUint16(i,!0);return n?t/65535:t}case"u32":{const t=e.getUint32(i,!0);return n?t/4294967295:t}case"i32":{const t=e.getInt32(i,!0);return n?Math.max(t/2147483647,-1):t}default:return 0}};const Eu=(e,t)=>e.offset-t.offset;class Ru{_stops;_sample=new Float32Array(4);constructor(e){this._stops=Ru._normalizeStops(e)}get stops(){return this._stops}copy(e){return this._stops=e._stops.map(e=>({offset:e.offset,color:e.color.clone()})),this._copyGeometry(e),this}equals(e){if(this===e)return!0;if(this.type!==e.type||this._stops.length!==e._stops.length)return!1;for(let t=0;t<this._stops.length;t++){const i=this._stops[t],n=e._stops[t];if(i.offset!==n.offset||!i.color.equals(n.color))return!1}return this._geometryEquals(e)}toTexture(e,t,i={}){if(!Number.isInteger(e)||!Number.isInteger(t)||e<=0||t<=0)throw new Error("Gradient.toTexture() width/height must be positive integers.");return"rgba32f"===i.format?this._toRgba32fTexture(e,t,i):this._toRgba8Texture(e,t,i)}destroy(){for(const e of this._stops)e.color.destroy();this._stops=[]}sampleAt(e,t){const i=Y(e,0,1),n=this._stops[0];let r=n.offset,s=n.color;for(let e=1;e<this._stops.length;e++){const n=this._stops[e];if(i<=n.offset){const e=Math.max(n.offset-r,1e-6),o=Y((i-r)/e,0,1);return t[0]=s.r/255+(n.color.r/255-s.r/255)*o,t[1]=s.g/255+(n.color.g/255-s.g/255)*o,t[2]=s.b/255+(n.color.b/255-s.b/255)*o,void(t[3]=s.a+(n.color.a-s.a)*o)}r=n.offset,s=n.color}t[0]=s.r/255,t[1]=s.g/255,t[2]=s.b/255,t[3]=s.a}static _normalizeStops(e){if(e.length<2)throw new Error("Gradient requires at least 2 color stops.");return e.map(e=>{if(!Number.isFinite(e.offset))throw new Error("Gradient stop offset must be a finite number.");return{offset:Y(e.offset,0,1),color:e.color.clone()}}).sort(Eu)}_toRgba8Texture(e,t,i){const n=new kr({width:e,height:t,format:"rgba8",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),r=n.buffer;let s=0;for(let i=0;i<t;i++){const n=1===t?0:i/(t-1);for(let t=0;t<e;t++){const i=1===e?0:t/(e-1);this.sampleAt(this.resolveT(i,n),this._sample),r[s]=ku(this._sample[0]),r[s+1]=ku(this._sample[1]),r[s+2]=ku(this._sample[2]),r[s+3]=ku(this._sample[3]),s+=4}}return n.commit(),n}_toRgba32fTexture(e,t,i){const n=new kr({width:e,height:t,format:"rgba32f",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),r=n.buffer;let s=0;for(let i=0;i<t;i++){const n=1===t?0:i/(t-1);for(let t=0;t<e;t++){const i=1===e?0:t/(e-1);this.sampleAt(this.resolveT(i,n),this._sample),r[s]=this._sample[0],r[s+1]=this._sample[1],r[s+2]=this._sample[2],r[s+3]=this._sample[3],s+=4}}return n.commit(),n}}const ku=e=>255*Y(e,0,1)+.5|0;class Du extends Ru{type="linear";_start;_end;constructor(e,t=[0,0],i=[1,0]){super(e),this._start=[t[0],t[1]],this._end=[i[0],i[1]]}get start(){return[this._start[0],this._start[1]]}get end(){return[this._end[0],this._end[1]]}clone(){return new Du(this.stops,this._start,this._end)}resolveT(e,t){const i=this._end[0]-this._start[0],n=this._end[1]-this._start[1],r=i*i+n*n;return r<=1e-6?0:((e-this._start[0])*i+(t-this._start[1])*n)/r}_copyGeometry(e){this._start=[e._start[0],e._start[1]],this._end=[e._end[0],e._end[1]]}_geometryEquals(e){return e instanceof Du&&this._start[0]===e._start[0]&&this._start[1]===e._start[1]&&this._end[0]===e._end[0]&&this._end[1]===e._end[1]}}class Fu extends Ru{type="radial";_center;_radius;constructor(e,t=[.5,.5],i=.5){super(e),this._center=[t[0],t[1]],this._radius=Math.max(0,i)}get center(){return[this._center[0],this._center[1]]}get radius(){return this._radius}clone(){return new Fu(this.stops,this._center,this._radius)}resolveT(e,t){if(this._radius<=1e-6)return 1;const i=e-this._center[0],n=t-this._center[1];return Math.sqrt(i*i+n*n)/this._radius}_copyGeometry(e){this._center=[e._center[0],e._center[1]],this._radius=e._radius}_geometryEquals(e){return e instanceof Fu&&this._center[0]===e._center[0]&&this._center[1]===e._center[1]&&this._radius===e._radius}}const Iu=new WeakMap;let Lu=1;const Uu=e=>{const t=Iu.get(e);if(void 0!==t)return t;const i=Lu++;return Iu.set(e,i),i},Gu=new Map;let Nu=1;const Ou=new Map;let Vu=1;const zu=(e,t,i)=>{const n=e.get(t);if(void 0!==n)return n;const r=i();return e.set(t,r),r},qu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&!ArrayBuffer.isView(e);let Wu=1;class Yu{shader;uniforms;textures;blendMode;sampler;_id;_disposeCallbacks=new Set;constructor(t){if(void 0===t.shader||null===t.shader)throw new Error("Material requires a `shader` ShaderSource.");this.shader=t.shader,this.uniforms={...t.uniforms??{}},this.textures={...t.textures??{}},this.blendMode=t.blendMode??e.BlendModes.Normal,this.sampler=t.sampler??null,this._id=Wu++}get pipelineKey(){return((e,t,i)=>{const n=`${e}|${t}|${(e=>null===e?"-":[e.scaleMode,e.wrapMode,e.premultiplyAlpha?1:0,e.generateMipMap?1:0,e.flipY?1:0].join(":"))(i)}`;return zu(Gu,n,()=>Nu++)})(this.shader.id,this.blendMode,this.sampler)}get bindKey(){return((e,t,i)=>{const n=[];for(const e of Object.keys(i))n.push(`t:${e}=${Uu(i[e])}`);for(const e of Object.keys(t)){const i=t[e];qu(i)&&n.push(`u:${e}=${Uu(i)}`)}n.sort();const r=`${e}|${n.join(",")}`;return zu(Ou,r,()=>Vu++)})(this._id,this.uniforms,this.textures)}setUniform(e,t){return this.uniforms[e]=t,this}setTexture(e,t){return this.textures[e]=t,this}destroy(){for(const e of this._disposeCallbacks)e();this._disposeCallbacks.clear()}_onDispose(e){this._disposeCallbacks.add(e)}}let $u=1;class Xu{glsl;wgsl;_id;constructor(e){if(void 0===e.glsl&&void 0===e.wgsl)throw new Error("ShaderSource requires at least one of `glsl` or `wgsl`.");if(void 0!==e.glsl){if("string"!=typeof e.glsl.vertex||0===e.glsl.vertex.length)throw new Error("ShaderSource.glsl.vertex must be a non-empty string.");if("string"!=typeof e.glsl.fragment||0===e.glsl.fragment.length)throw new Error("ShaderSource.glsl.fragment must be a non-empty string.")}if(void 0!==e.wgsl&&("string"!=typeof e.wgsl||0===e.wgsl.length))throw new Error("ShaderSource.wgsl must be a non-empty string.");this.glsl=e.glsl??null,this.wgsl=e.wgsl??null,this._id=$u++}get id(){return this._id}getDeclaredUniforms(){return{glsl:null!==this.glsl?Zu(this.glsl.vertex,this.glsl.fragment):{},wgsl:null!==this.wgsl?Ju(this.wgsl):{}}}detectUniformDrift(){if(null===this.glsl||null===this.wgsl)return{onlyInGlsl:[],onlyInWgsl:[]};const e=this.getDeclaredUniforms(),t=new Set(Object.keys(e.glsl).filter(e=>!Hu.has(e))),i=new Set(Object.keys(e.wgsl).filter(e=>!Hu.has(e))),n=[],r=[];for(const e of t)i.has(e)||n.push(e);for(const e of i)t.has(e)||r.push(e);return{onlyInGlsl:n,onlyInWgsl:r}}}const Hu=new Set(["u_projection","u_translation","u_tint","u_texture","u_mesh"]),ju=/\buniform\s+(?:mediump\s+|highp\s+|lowp\s+|)(\w+)\s+(\w+)[^;]*;/g,Ku=/@group\(\s*2\s*\)\s*@binding\(\s*\d+\s*\)\s*var(?:<[^>]+>|)\s+(\w+)\s*:\s*([^;]+);/g;function Qu(e){return e.replaceAll(/\/\*[\s\S]*?\*\//g,"").replaceAll(/\/\/[^\n]*/g,"")}function Zu(e,t){const i={};for(const n of[e,t]){const e=Qu(n);let t;for(ju.lastIndex=0;null!==(t=ju.exec(e));){const[,e,n]=t;void 0!==e&&void 0!==n&&(i[n]=e)}}return i}function Ju(e){const t={},i=Qu(e);let n;for(Ku.lastIndex=0;null!==(n=Ku.exec(i));){const[,e,i]=n;void 0!==e&&void 0!==i&&(t[e]=i.trim())}return t}class ec extends Yu{target="mesh";constructor(e){super(e)}static from(e,t,i){if(e instanceof Xu){return new ec({shader:e,...void 0!==t?t:{}})}const n=new Xu({glsl:{vertex:e,fragment:t},...void 0!==i?.wgsl?{wgsl:i.wgsl}:{}});return new ec({shader:n,...void 0!==i?.uniforms?{uniforms:i.uniforms}:{},...void 0!==i?.blendMode?{blendMode:i.blendMode}:{},...void 0!==i?.sampler?{sampler:i.sampler}:{}})}}class tc extends Yu{target="sprite";constructor(e){super(e)}static from(e,t,i){if(e instanceof Xu){return new tc({shader:e,...void 0!==t?t:{}})}const n=new Xu({glsl:{vertex:e,fragment:t},...void 0!==i?.wgsl?{wgsl:i.wgsl}:{}});return new tc({shader:n,...void 0!==i?.uniforms?{uniforms:i.uniforms}:{},...void 0!==i?.blendMode?{blendMode:i.blendMode}:{},...void 0!==i?.sampler?{sampler:i.sampler}:{}})}}const ic={woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};class nc extends Bi{_html;_css;_width;_height;_resolution;_canvas;_ctx;_texture;_mesh;_destroyed=!1;_renderVersion=0;_activeRender=null;_fonts=[];constructor(e,t={}){super(),this._html=e,this._css=t.css??"",this._width=t.width??256,this._height=t.height??128,this._resolution=t.resolution??1;const[i,n]=nc._makeCanvas(Math.ceil(this._width*this._resolution),Math.ceil(this._height*this._resolution));this._canvas=i,this._ctx=n,this._texture=new pi(i),this._texture.setSize(this._width,this._height),this._mesh=this._buildMesh(),this.addChild(this._mesh),e.length>0&&this._schedule()}get html(){return this._html}set html(e){this._html!==e&&(this._html=e,this._schedule())}get css(){return this._css}set css(e){this._css!==e&&(this._css=e,this._schedule())}get width(){return this._width}set width(e){this.resize(e,this._height)}get height(){return this._height}set height(e){this.resize(this._width,e)}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this._resizeCanvas(),this._schedule())}get ready(){return this._activeRender??Promise.resolve()}addFont(e,t,i="woff2"){const n=`data:${ic[i]};base64,${nc._toBase64(t)}`,r=this._fonts.findIndex(t=>t.family===e);return r>=0?this._fonts[r]={family:e,dataUri:n}:this._fonts.push({family:e,dataUri:n}),this._schedule(),this}removeFont(e){const t=this._fonts.findIndex(t=>t.family===e);return t>=0&&(this._fonts.splice(t,1),this._schedule()),this}resize(e,t){return this._width===e&&this._height===t||(this._width=e,this._height=t,this._resizeCanvas(),this._rebuildMesh(),this._schedule()),this}destroy(){this._destroyed=!0,this._renderVersion++,this._activeRender=null,this._texture.destroy(),super.destroy()}_schedule(){const t=++this._renderVersion;this._activeRender=this._render(t).catch(t=>{ih.log(e.LogSeverity.Warning,"rendering","HTMLText render failed.",t instanceof Error?{error:t}:void 0)})}async _render(e){if("undefined"==typeof Blob||"undefined"==typeof Image)return;const t=new Blob([this._buildSvg()],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(t),n=new Image;try{await new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(new Error("HTMLText: SVG render failed")),n.src=i})}finally{URL.revokeObjectURL(i)}if(this._destroyed||e!==this._renderVersion)return;const r=Math.ceil(this._width*this._resolution),s=Math.ceil(this._height*this._resolution);this._ctx.clearRect(0,0,r,s),this._ctx.drawImage(n,0,0,r,s),this._texture.updateSource()}_buildSvg(){const e=this._width,t=this._height,i=this._fonts.map(({family:e,dataUri:t})=>`@font-face{font-family:'${e.replaceAll("\\","\\\\").replaceAll("'","\\'")}';src:url('${t}');}`).join(""),n=this._css.replaceAll(/<\/style>/gi,"<\\/style>");return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="width:${e}px;height:${t}px;overflow:hidden;box-sizing:border-box;">${i||n?`<style>${i}${n}</style>`:""}${this._html}</div></foreignObject></svg>`}_buildMesh(){const e=this._width,t=this._height;return new In({vertices:new Float32Array([0,0,e,0,e,t,0,t]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint16Array([0,1,2,0,2,3]),texture:this._texture})}_rebuildMesh(){this.removeChild(this._mesh),this._mesh.destroy(),this._mesh=this._buildMesh(),this.addChild(this._mesh)}_resizeCanvas(){const e=Math.ceil(this._width*this._resolution),t=Math.ceil(this._height*this._resolution);this._canvas.width=e,this._canvas.height=t,this._texture.updateSource()}static _toBase64(e){const t=new Uint8Array(e);let i="";for(let e=0;e<t.length;e++)i+=String.fromCharCode(t[e]);return btoa(i)}static _makeCanvas(e,t){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(e,t),n=i.getContext("2d");if(!n)throw new Error("HTMLText: could not obtain 2D context.");return[i,n]}const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");if(!n)throw new Error("HTMLText: could not obtain 2D context.");return[i,n]}}const rc=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"];class sc{name;version;_storeNames;_migrations;_onCloseHandler=this.disconnect.bind(this);_connected=!1;_database=null;get connected(){return this._connected}constructor(e,t=1,i=rc,n){if(!f)throw new Error("This browser does not support indexedDB!");this.name=e,this.version=t,this._storeNames=i,this._migrations=n}async getObjectStore(e,t="readonly"){return await this.connect(),this._database.transaction([e],t).objectStore(e)}async connect(){return!(!this._connected||!this._database)||new Promise((e,t)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",e=>{const n=i.result,r=i.transaction,s=[...r.objectStoreNames],{oldVersion:o,newVersion:a}=e;if(n.addEventListener("error",()=>t(new Error("An error occurred while opening the database."))),n.addEventListener("abort",()=>t(new Error("The database opening was aborted."))),this._migrations){const e=Object.keys(this._migrations).map(Number).filter(e=>e>o&&e<=(a??this.version)).sort((e,t)=>e-t);for(const t of e){const e=this._migrations[t];if(void 0===e)continue;if(!e(n,r))return void r.abort()}}else{for(const e of s)this._storeNames.includes(e)||n.deleteObjectStore(e);for(const e of this._storeNames)s.includes(e)||n.createObjectStore(e,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,e(!0)}),i.addEventListener("error",()=>t(new Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>t(new Error("The request for the database connection has been blocked.")))})}async disconnect(){return this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close(),this._database=null,this._connected=!1),!0}async load(e,t){const i=await this.getObjectStore(e);return new Promise((e,n)=>{const r=i.get(t);r.addEventListener("success",()=>e(r.result?.data??null)),r.addEventListener("error",()=>n(new Error("An error occurred while loading an item.")))})}async save(e,t,i){const n=await this.getObjectStore(e,"readwrite");return new Promise((e,r)=>{const s=n.put({name:t,data:i});s.addEventListener("success",()=>e()),s.addEventListener("error",()=>r(new Error("An error occurred while saving an item.")))})}async delete(e,t){const i=await this.getObjectStore(e,"readwrite");return new Promise((e,n)=>{const r=i.delete(t);r.addEventListener("success",()=>e(!0)),r.addEventListener("error",()=>n(new Error("An error occurred while deleting an item.")))})}async clearStorage(e){const t=await this.getObjectStore(e,"readwrite");return new Promise((e,i)=>{const n=t.clear();n.addEventListener("success",()=>e(!0)),n.addEventListener("error",()=>i(new Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((e,t)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>e(!0)),i.addEventListener("error",()=>t(new Error("An error occurred while deleting a storage.")))})}destroy(){this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close()),this._database=null,this._connected=!1}}class oc{_db;constructor(e){const t="string"==typeof e?{name:e}:e;this._db=new sc(t.name,t.version??1,t.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"],t.migrations)}async load(e,t){return this._db.load(e,t)}async save(e,t,i){return this._db.save(e,t,i)}async delete(e,t){return this._db.delete(e,t)}async clear(e){return this._db.clearStorage(e)}destroy(){this._db.destroy()}}return e.AbstractAssetFactory=To,e.AbstractText=br,e.AnimatedSprite=Rh,e.Application=class{options;canvas;loader;input;focus;interaction;scene;random;tweens=new a;systems=new Ml;serializers=new yl(wl);onResize=new x;onFrame=new x;onFixedFrame=new x;onCanvasFocusChange=new x;onVisibilityChange=new x;onBackendLost=new x;onBackendRestored=new x;onError=new x;pauseOnHidden=!1;_updateHandler;_startupClock=new ki;_activeClock=new ki;_frameClock=new ki;_fixed;_fixedTime;_frameAlpha=0;_status=e.ApplicationStatus.Stopped;_pixelRatio=Gl;_designWidth=Ll;_designHeight=Ul;_frameCount=0;_frameRequest=0;_backendType;_backend;_rendering;_snapshot;_capabilities=null;_documentVisible=!0;_cursor="default";_visibilityChangeHandler=this._onDocumentVisibilityChange.bind(this);_resizeObserver=null;_sizingMode="fixed";_audio=new ft;constructor(e={}){const t=e.canvas??{},i=e.loader??{},n=e.rendering??{},r=e.input??{},s=t.element??document.createElement("canvas"),o=t.width??Ll,a=t.height??Ul;this._pixelRatio=t.pixelRatio??(()=>{const e=globalThis.devicePixelRatio;return"number"==typeof e&&e>0?Math.min(e,2):1})(),this._designWidth=o,this._designHeight=a,this.canvas=s,this._applyCanvasSize(o,a),void 0!==t.tabIndex?this.canvas.tabIndex=t.tabIndex:this.canvas.hasAttribute("tabindex")||(this.canvas.tabIndex=Nl),void 0!==t.imageRendering&&(this.canvas.style.imageRendering=t.imageRendering),this._mountCanvas(t.mount),this._sizingMode=t.sizingMode??"fixed",this._applySizingMode(this._sizingMode),this.options={clearColor:e.clearColor??Tt.cornflowerBlue,backend:e.backend??Il,canvas:{element:this.canvas,width:o,height:a,pixelRatio:this._pixelRatio,tabIndex:this.canvas.tabIndex,...void 0!==t.imageRendering&&{imageRendering:t.imageRendering}},loader:{basePath:i.basePath??"",fetchOptions:i.fetchOptions??{...Ol},...void 0!==i.cache&&{cache:i.cache},...void 0!==i.cacheStrategy&&{cacheStrategy:i.cacheStrategy},...void 0!==i.concurrency&&{concurrency:i.concurrency}},rendering:{debug:n.debug??Vl.debug,webglAttributes:n.webglAttributes??Vl.webglAttributes,spriteRendererBatchSize:n.spriteRendererBatchSize??Vl.spriteRendererBatchSize},input:{gamepadDefinitions:r.gamepadDefinitions??[...zl.gamepadDefinitions],gamepadSlotStrategy:r.gamepadSlotStrategy??zl.gamepadSlotStrategy,pointerDistanceThreshold:r.pointerDistanceThreshold??zl.pointerDistanceThreshold}},this._snapshot=void 0===e.extensions?function(){if(0===bt?.revision)return bt.snapshot;const e=vt([...St.values()]);return bt={revision:0,snapshot:e},e}():vt([...e.extensions??[]]),this.loader=new Va(this.options.loader);try{!function(e,t){const i=new Set,n=new Set,r=new Set;for(const s of t){if(i.has(s.type)||e.hasLoadable(s.type))throw new Error(`An asset handler is already registered for ${s.type.name}.`);for(const t of s.typeNames??[]){if(n.has(t)||e.hasAssetType(t))throw new Error(`Asset type name "${t}" is already registered. Remove the conflicting binding.`);n.add(t)}for(const t of s.extensions??[]){const i=t.replace(/^\./,"").toLowerCase();if(r.has(i)||e.hasExtension(i))throw new Error(`File extension ".${i}" is already mapped to an asset type. Remove the conflicting binding.`);r.add(i)}i.add(s.type)}for(const i of t){const t=i.create(e);e.bindAsset({type:i.type,...void 0!==i.typeNames&&{typeNames:i.typeNames},...void 0!==i.extensions&&{extensions:i.extensions}},t)}}(this.loader,[...Ba,...this._snapshot.assets]),function(e,t){for(const i of t)e.register(i.typeName,i.target,i.serializer)}(this.serializers,this._snapshot.serializers)}catch(e){try{this.loader.destroy()}catch{}throw e}this._backendType=this.resolveInitialBackendType(),this._backend=this.createBackend(this._backendType,this._snapshot),this._rendering=new Zs(this._backend),this.input=new yn(this),this.focus=new Ai(this),this.interaction=new vn(this),this.scene=new kl(this),this.random=new Bn(this.options.seed),this._updateHandler=this.update.bind(this);const h=void 0!==this.options.fixedTimeStep?1e3*this.options.fixedTimeStep:Fl;this._fixed=new Ja(h,5),this._fixedTime=new Ri(h),this.systems.add(this.input),this.systems.add(this.interaction),this.systems.add(this._audio),this.systems.add(this.tweens),this.systems.add(this._rendering),this._startupClock.start(),"undefined"!=typeof document&&(this._documentVisible="visible"===document.visibilityState,document.addEventListener("visibilitychange",this._visibilityChangeHandler)),this.input.onCanvasFocusChange.add(e=>{this.onCanvasFocusChange.dispatch(e)}),this.onVisibilityChange.add(e=>{this._audio._applyVisibility(e)})}get status(){return this._status}get startupTime(){return this._startupClock.elapsedTime}get activeTime(){return this._activeClock.elapsedTime}get frameTime(){return this._frameClock.elapsedTime}get frameCount(){return this._frameCount}get frameAlpha(){return this._frameAlpha}get fixedTimeStep(){return this._fixed.stepMs/1e3}get backend(){return this._backend}get rendering(){return this._rendering}get capabilities(){if(null===this._capabilities)throw new Error("Application.capabilities is unavailable before start() resolves. Use `await Capabilities.ready` for pre-start checks.");return this._capabilities}get canvasFocused(){return this.input.canvasFocused}get documentVisible(){return this._documentVisible}get cursor(){return this._cursor}set cursor(e){this.setCursor(e)}get sizingMode(){return this._sizingMode}set sizingMode(e){e!==this._sizingMode&&(this._resizeObserver?.disconnect(),this._resizeObserver=null,this._sizingMode=e,this._applySizingMode(e))}get clearColor(){return this._backend.clearColor}set clearColor(e){this._backend.clearColor.copy(e)}get audio(){return this._audio}get width(){return this._designWidth}get height(){return this._designHeight}get pixelRatio(){return this._pixelRatio}screenToWorld(e,t){return this._rendering.view.screenToWorld(e,t)}_backingStoreToDesign(e,t){const i=this.canvas.width||1,n=this.canvas.height||1;return{x:e/i*this._designWidth,y:t/n*this._designHeight}}async start(t){if(this._status===e.ApplicationStatus.Stopped){this._status=e.ApplicationStatus.Loading;const i=Ya.ready;try{await this.initializeBackend(),this._capabilities=await i,await this.scene.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._fixed.reset(),this._activeClock.start(),this._status=e.ApplicationStatus.Running}catch(t){throw this._status=e.ApplicationStatus.Stopped,t}}return this}update(){if(this._status===e.ApplicationStatus.Running){if(this.pauseOnHidden&&!this._documentVisible)return this._frameClock.restart(),this._fixed.reset(),this._frameRequest=requestAnimationFrame(this._updateHandler),this;const e=this._frameClock.elapsedTime.milliseconds,t=Math.min(e,100),i=Ri.temp.set(t),n=performance.now();this.backend.resetStats(),this.backend.stats.rawFrameDeltaMs=e,this.systems._tick(i);const r=this._fixed.advance(t);for(let e=0;e<r;e++)this.scene.fixedUpdate(this._fixedTime),this.onFixedFrame.dispatch(this._fixedTime);this._frameAlpha=this._fixed.alpha,this.scene.update(i),this.onFrame.dispatch(i),this.backend.flush(),this.backend.stats.frameTimeMs=performance.now()-n,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===e.ApplicationStatus.Running&&(this._status=e.ApplicationStatus.Halting,cancelAnimationFrame(this._frameRequest),this.scene.setScene(null).catch(e=>{ih.error("core","Application.stop() failed to unload the active scene.",e instanceof Error?e:void 0),this.onError?.dispatch(e instanceof Error?e:new Error(String(e)))}),this._activeClock.stop(),this._frameClock.stop(),this._status=e.ApplicationStatus.Stopped),this}resize(e,t){return this._designWidth=e,this._designHeight=t,this._applyCanvasSize(e,t),this.options.canvas={...this.options.canvas??{},width:e,height:t,pixelRatio:this._pixelRatio},this.backend.resize(e,t),this._rendering.resize(e,t),this.onResize.dispatch(e,t,this),this}_mountCanvas(e){if(void 0===e||"undefined"==typeof document)return;const t="string"==typeof e?document.querySelector(e):e;t?.append(this.canvas)}_applySizingMode(e){const t=this.canvas.style;switch(e){case"fill":{const e=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!e)break;this._resizeObserver=new ResizeObserver(()=>{const t=e.clientWidth,i=e.clientHeight;t>0&&i>0&&this.resize(t,i)}),this._resizeObserver.observe(e);break}case"letterbox":{const e=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!e)break;const t=e.style;t.display="flex",t.alignItems="center",t.justifyContent="center",t.overflow="hidden",t.background="#000",this._resizeObserver=new ResizeObserver(()=>{const t=e.clientWidth,i=e.clientHeight;t>0&&i>0&&this._applyLetterboxLayout(t,i)}),this._resizeObserver.observe(e);break}case"fit":t.width="100%",t.height="100%",t.objectFit="contain";break;case"shrink":t.maxWidth="100%",t.maxHeight="100%",t.objectFit="contain"}}_applyLetterboxLayout(e,t){const i=((e,t,i,n,r)=>{const s=Math.min(e/i,t/n),o=i*s,a=n*s;return{contentWidthCss:o,contentHeightCss:a,backingWidth:Math.max(1,Math.round(o*r)),backingHeight:Math.max(1,Math.round(a*r))}})(e,t,this._designWidth,this._designHeight,this._pixelRatio);this.canvas.width=i.backingWidth,this.canvas.height=i.backingHeight,this.canvas.style.width=`${i.contentWidthCss}px`,this.canvas.style.height=`${i.contentHeightCss}px`}setCursor(e){const t=e instanceof pi?e.source:e;if(null===t)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof t?t:`url(${w(t)}), auto`,this.canvas.style.cursor=this._cursor,this}capture(e,t){return this._rendering.capture(e,t)}destroy(){"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this._visibilityChangeHandler),this._resizeObserver?.disconnect(),this._resizeObserver=null,this.stop(),this.loader.destroy(),this.focus.destroy(),this.systems.destroy(),this._backend.destroy(),this.scene.destroy(),this._startupClock.destroy(),this._activeClock.destroy(),this._frameClock.destroy(),this.onResize.destroy(),this.onFrame.destroy(),this.onFixedFrame.destroy(),this.onCanvasFocusChange.destroy(),this.onVisibilityChange.destroy(),this.onBackendLost.destroy(),this.onBackendRestored.destroy(),this.onError.destroy()}_onDocumentVisibilityChange(){const e="visible"===document.visibilityState;e!==this._documentVisible&&(this._documentVisible=e,this.onVisibilityChange.dispatch(e))}resolveInitialBackendType(){const e=this.options.backend?.type;return"webgl2"===e?"webgl2":"webgpu"===e||this.canUseWebGpu()?"webgpu":"webgl2"}createBackend(t,i){const n=function(t){const i=t.spriteRendererBatchSize??4096,n={[e.RenderBackendType.WebGl2]:()=>new ys(i),[e.RenderBackendType.WebGpu]:()=>new Ws},r={[e.RenderBackendType.WebGl2]:()=>new ss,[e.RenderBackendType.WebGpu]:()=>new ks},s={[e.RenderBackendType.WebGl2]:()=>new vs,[e.RenderBackendType.WebGpu]:()=>new Hs},o={[e.RenderBackendType.WebGl2]:()=>new hs(i),[e.RenderBackendType.WebGpu]:()=>new Us},a={[e.RenderBackendType.WebGl2]:()=>new ps(i),[e.RenderBackendType.WebGpu]:()=>new Os};return[{targets:[vr],create:e=>n[e.backendType]?.()},{targets:[In],create:e=>r[e.backendType]?.()},{targets:[Wr,Ar],create:e=>s[e.backendType]?.()},{targets:[ur],create:e=>o[e.backendType]?.()},{targets:[wr],create:e=>a[e.backendType]?.()}]}(this.options.rendering??{}),r=[...n,...i.renderers];if("webgpu"===t){const e=new So(this);e.onDeviceLost.add(()=>{this.onBackendLost.dispatch()}),e.onDeviceRestored.add(()=>{this.onBackendRestored.dispatch()});try{Bt(e,r)}catch(t){try{e.destroy()}catch{}throw t}return e}const s=new mo(this);s.onContextLost.add(()=>{this.onBackendLost.dispatch()}),s.onContextRestored.add(()=>{this.onBackendRestored.dispatch()});try{Bt(s,r)}catch(e){try{s.destroy()}catch{}throw e}return s}async initializeBackend(){try{await this._backend.initialize()}catch(e){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw e;this._backend.destroy(),this._backendType="webgl2",this._backend=this.createBackend(this._backendType,this._snapshot);const t=this._rendering;this.systems.remove(t),t.destroy(),this._rendering=new Zs(this._backend),this.systems.add(this._rendering),await this._backend.initialize()}}canUseWebGpu(){return!!navigator.gpu}_applyCanvasSize(e,t){const i=Math.round(e*this._pixelRatio),n=Math.round(t*this._pixelRatio);this.canvas.width=i,this.canvas.height=n,this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`}},e.ArcadeStickGamepadMapping=Oi,e.Asset=Ta,e.Assets=La,e.AudioBus=J,e.AudioEffect=ee,e.AudioGenerator=ut,e.AudioInput=ct,e.AudioListener=dt,e.AudioManager=ft,e.AudioStream=mt,e.BinaryAsset=oa,e.BinaryFactory=Mo,e.BiquadEffect=class extends ee{_node=null;_type;_frequency;_resonance;_gain;_detune;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(e={}){super(),this._type=e.type??"lowpass",this._frequency=e.frequency??1e3,this._resonance=e.resonance??1,this._gain=e.gain??0,this._detune=e.detune??0,U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._node)throw new Error("BiquadEffect not yet initialized.");return this._node}get outputNode(){if(!this._node)throw new Error("BiquadEffect not yet initialized.");return this._node}get type(){return this._type}set type(e){this._type=e,this._node&&(this._node.type=e)}get frequency(){return this._frequency}set frequency(e){this._frequency=e,this._node&&this._node.frequency.setTargetAtTime(e,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(e){this._resonance=e,this._node&&this._node.Q.setTargetAtTime(e,this._node.context.currentTime,.01)}get gain(){return this._gain}set gain(e){this._gain=e,this._node&&this._node.gain.setTargetAtTime(e,this._node.context.currentTime,.01)}get detune(){return this._detune}set detune(e){this._detune=e,this._node&&this._node.detune.setTargetAtTime(e,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(e){const t=e.createBiquadFilter();t.type=this._type,t.frequency.setValueAtTime(this._frequency,e.currentTime),t.Q.setValueAtTime(this._resonance,e.currentTime),t.gain.setValueAtTime(this._gain,e.currentTime),t.detune.setValueAtTime(this._detune,e.currentTime),this._node=t}},e.BitmapText=Ar,e.BlurFilter=class extends pu{_sprite=new vr(null);_sampleTint=Tt.white.clone();_radius=2;_quality=1;constructor(e={}){super(),this._radius=Math.max(0,e.radius??2),this._quality=Math.max(1,Math.floor(e.quality??1))}get radius(){return this._radius}set radius(e){this._radius=Math.max(0,e)}get quality(){return this._quality}set quality(e){this._quality=Math.max(1,Math.floor(e))}apply(t,i,n){const r=this._radius,s=this._quality,o=Math.max(1,2*s+1),a=1/(r<=0?1:2*o);this._sampleTint.set(255,255,255,a),this._sprite.setTexture(i).setBlendMode(e.BlendModes.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=n.width,this._sprite.height=n.height,t.execute(new vi(()=>{if(r<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<o;e++){const i=(2*(1===o?0:e/(o-1))-1)*r;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}},e.BmFont=Sr,e.BmFontAdapter=Pr,e.BmFontLoaderFactory=class extends To{storageName="bmfont";_loader;constructor(e){super(),this._loader=e}async process(e){return{text:await e.text(),url:e.url}}async create(e){const{text:t,url:i}=e,n=Eo(t),r=await Promise.all(n.pages.map(e=>this._loader.load(pi,new URL(e,i).href)));return new Sr(n,r)}},e.Bounds=kt,e.BundleLoadError=Ea,e.Button=tl,e.CacheFirstStrategy=Ua,e.CallbackRenderPass=class extends _u{_callback;_clear;_target;_view;_redirect;_activeContext=null;_executing=!1;constructor(e,t){super(t),this._callback=e,this._clear=t?.clear??null,this._target=t?.target??null,this._view=t?.view??null,this._redirect=null!==this._target?new vi(()=>this._runCallback(),{target:this._target,view:this._view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(e){if(this._executing)throw new Error("CallbackRenderPass.execute is not re-entrant.");this._executing=!0;try{if(null!==this._redirect){this._activeContext=e;try{e.backend.execute(this._redirect)}finally{this._activeContext=null}return}null!==this._clear&&e.backend.clear(this._clear),this._callback(new du(e,e.backend.renderTarget,e.backend.view))}finally{this._executing=!1}}_runCallback(){null!==this._activeContext&&null!==this._target&&this._callback(new du(this._activeContext,this._target,this._view??this._target.view))}},e.Capabilities=Ya,e.Circle=iu,e.Clock=ki,e.Codec=Wl,e.Collision=Ke,e.Color=Tt,e.ColorFilter=class extends pu{_color;_sprite=new vr(null);constructor(e=Tt.white){super(),this._color=e.clone()}get color(){return this._color}apply(t,i,n){this._sprite.setTexture(i).setBlendMode(e.BlendModes.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=n.width,this._sprite.height=n.height,t.execute(new vi(()=>{this._sprite.render(t)},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}},e.Container=Bi,e.CsvAsset=na,e.CsvFactory=Ro,e.DataTexture=kr,e.DisposalScope=rh,e.Drawable=Fn,e.Ease=i,e.Ellipse=nu,e.Envelope=class{attackMs;decayMs;sustainLevel;releaseMs;constructor(e={}){this.attackMs=Math.max(0,e.attackMs??10),this.decayMs=Math.max(0,e.decayMs??100),this.sustainLevel=Math.max(0,Math.min(1,e.sustainLevel??.7)),this.releaseMs=Math.max(0,e.releaseMs??200)}trigger(e,t){const i=t+this.attackMs/1e3,n=i+this.decayMs/1e3;e.cancelScheduledValues(t),e.setValueAtTime(0,t),e.linearRampToValueAtTime(1,i),e.linearRampToValueAtTime(this.sustainLevel,n)}release(e,t){this.releaseMs,e.cancelScheduledValues(t),e.setTargetAtTime(0,t,this.releaseMs/1e3/3)}get totalDurationMs(){return this.attackMs+this.decayMs+this.releaseMs}destroy(){}},e.Filter=pu,e.Flags=Mt,e.FocusManager=Ai,e.FontAsset=sa,e.FontFactory=ko,e.GameCubeGamepadMapping=Wi,e.Gamepad=Ii,e.GamepadAxis=Vi,e.GamepadButton=Li,e.GamepadMapping=Ni,e.GamepadPromptLayouts=class{static controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];static getControlPosition(e){return Hl.get(e)??[.5,.5]}static getControlLabels(e){return eu.get(e)??Kl}static getControlChannelMap(){return jl}},e.GenericDualAnalogGamepadMapping=qi,e.Geometry=class{attributes;stride;topology;usage;indices;vertexData;_version=0;_localBounds=new et;_localBoundsDirty=!0;_positionAttribute;_disposeCallbacks=new Set;constructor(e){const{attributes:t,vertexData:i,stride:n,indices:r=null,topology:s="triangle-list",usage:o="static"}=e;if(0===t.length)throw new Error("Geometry attributes must be a non-empty array.");if(!Number.isInteger(n)||n<=0)throw new Error(`Geometry stride must be a positive integer (got ${n}).`);if(!Su.has(s))throw new Error(`Geometry topology must be one of: triangle-list, triangle-strip (got ${String(s)}).`);if(!Bu.has(o))throw new Error(`Geometry usage must be one of: static, dynamic, stream (got ${String(o)}).`);const a=[],h=new Set;for(const e of t){if("string"!=typeof e.name||0===e.name.length)throw new Error("Geometry attribute name must be a non-empty string.");if(h.has(e.name))throw new Error(`Geometry attribute "${e.name}" is declared more than once.`);if(h.add(e.name),!Number.isInteger(e.size)||e.size<1||e.size>4)throw new Error(`Geometry attribute "${e.name}" size must be an integer in [1..4] (got ${e.size}).`);if(!Number.isInteger(e.offset)||e.offset<0)throw new Error(`Geometry attribute "${e.name}" offset must be a non-negative integer (got ${e.offset}).`);const t=bu[e.type],i=e.offset+t*e.size;if(i>n)throw new Error(`Geometry attribute "${e.name}" range [${e.offset}, ${i}) exceeds stride ${n}.`);for(const t of a)if(e.offset<t.end&&i>t.start)throw new Error(`Geometry attribute "${e.name}" overlaps attribute "${t.name}" in the interleaved layout.`);a.push({name:e.name,start:e.offset,end:i})}const l=(e=>{const t=e.find(e=>Cu.has(e.name));if(t)return t;const i=e.find(e=>e.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Geometry requires a position attribute named `a_position` or `position`.")})(t);if(l.size<2)throw new Error(`Geometry position attribute "${l.name}" must declare at least 2 components.`);const u=Pu(i,n);if(null!==r)for(let e=0;e<r.length;e++){const t=r[e];if(t>=u)throw new Error(`Geometry index ${t} at position ${e} is out of range for vertex count ${u}.`)}this.attributes=(e=>e.map(e=>({...e})))(t),this.vertexData=i,this.stride=n,this.indices=r,this.topology=s,this.usage=o,this._positionAttribute={...l}}get vertexCount(){return Pu(this.vertexData,this.stride)}get indexCount(){return this.indices?.length??this.vertexCount}get version(){return this._version}get id(){return(e=>{const t=Tu.get(e);if(void 0!==t)return t;const i=Mu++;return Tu.set(e,i),i})(this)}invalidate(){return this._version++,this._localBoundsDirty=!0,this}getLocalBounds(e=this._localBounds){return this._localBoundsDirty&&this.recomputeLocalBounds(),e===this._localBounds?this._localBounds:e.copy(this._localBounds)}recomputeLocalBounds(){const e=this.vertexCount;if(0===e)return this._localBounds.set(0,0,0,0),this._localBoundsDirty=!1,this;const t=this.vertexData instanceof Float32Array?new DataView(this.vertexData.buffer,this.vertexData.byteOffset,this.vertexData.byteLength):new DataView(this.vertexData),i=bu[this._positionAttribute.type];let n=1/0,r=1/0,s=-1/0,o=-1/0;for(let a=0;a<e;a++){const e=a*this.stride+this._positionAttribute.offset,h=Au(t,this._positionAttribute.type,e,this._positionAttribute.normalized),l=Au(t,this._positionAttribute.type,e+i,this._positionAttribute.normalized);h<n&&(n=h),h>s&&(s=h),l<r&&(r=l),l>o&&(o=l)}return this._localBounds.set(n,r,s-n,o-r),this._localBoundsDirty=!1,this}destroy(){for(const e of this._disposeCallbacks)e();this._disposeCallbacks.clear()}_onDispose(e){this._disposeCallbacks.add(e)}},e.GlyphAtlas=Or,e.Gradient=Ru,e.Graphics=Mh,e.HTMLText=nc,e.HighpassFilter=class extends ee{_node=null;_frequency;_resonance;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(e={}){super(),this._frequency=e.frequency??1e3,this._resonance=e.resonance??1,U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._node)throw new Error("HighpassFilter not yet initialized.");return this._node}get outputNode(){if(!this._node)throw new Error("HighpassFilter not yet initialized.");return this._node}get frequency(){return this._frequency}set frequency(e){this._frequency=Math.max(20,Math.min(2e4,e)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(e){this._resonance=Math.max(1e-4,e),this._node&&this._node.Q.setTargetAtTime(this._resonance,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(e){const t=e.createBiquadFilter();t.type="highpass",t.frequency.setValueAtTime(this._frequency,e.currentTime),t.Q.setValueAtTime(this._resonance,e.currentTime),this._node=t}},e.ImageAsset=ra,e.ImageFactory=Io,e.IndexedDbDatabase=sc,e.IndexedDbKeyValueStore=class{_storeName;_store;constructor(e="exojs-kv-store"){const t="string"==typeof e?{name:e}:e,i=t.storeName??"__kv_store";this._storeName=i,this._store=new oc({name:t.name,...void 0!==t.version&&{version:t.version},...void 0!==t.migrations&&{migrations:t.migrations},storeNames:[i]})}async get(e){return await this._store.load(this._storeName,e)}async set(e,t){await this._store.save(this._storeName,e,t)}async has(e){return null!==await this._store.load(this._storeName,e)}async delete(e){return this._store.delete(this._storeName,e)}async clear(){return this._store.clear(this._storeName)}destroy(){this._store.destroy()}},e.IndexedDbStore=oc,e.InputBinding=Fi,e.InputManager=yn,e.InteractionEvent=xn,e.InteractionManager=vn,e.Interval=me,e.JoyConLeftGamepadMapping=Yi,e.JoyConRightGamepadMapping=$i,e.Json=Zo,e.JsonFactory=class extends To{storageName="json";async process(e){return e.json()}async create(e){return e}},e.KeyEvent=Ci,e.Label=il,e.Line=su,e.LinearGradient=Du,e.Loader=Va,e.LoadingQueue=Oa,e.Logger=th,e.LowpassFilter=class extends ee{_node=null;_frequency;_resonance;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(e={}){super(),this._frequency=e.frequency??1e3,this._resonance=e.resonance??1,U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._node)throw new Error("LowpassFilter not yet initialized.");return this._node}get outputNode(){if(!this._node)throw new Error("LowpassFilter not yet initialized.");return this._node}get frequency(){return this._frequency}set frequency(e){this._frequency=Math.max(20,Math.min(2e4,e)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(e){this._resonance=Math.max(1e-4,e),this._node&&this._node.Q.setTargetAtTime(this._resonance,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(e){const t=e.createBiquadFilter();t.type="lowpass",t.frequency.setValueAtTime(this._frequency,e.currentTime),t.Q.setValueAtTime(this._resonance,e.currentTime),this._node=t}},e.LutFilter=vu,e.Material=Yu,e.MathUtils=Z,e.Matrix=At,e.MemoryStore=class{_map=new Map;get(e){return Promise.resolve(this._map.has(e)?this._map.get(e):null)}set(e,t){return this._map.set(e,t),Promise.resolve()}has(e){return Promise.resolve(this._map.has(e))}delete(e){return Promise.resolve(this._map.delete(e))}clear(){return this._map.clear(),Promise.resolve(!0)}},e.Mesh=In,e.MeshBuilder=Th,e.MeshMaterial=ec,e.MusicFactory=Uo,e.NetworkOnlyStrategy=class{async resolve(e,t){const{url:i,requestOptions:n,factory:r,options:s}=e,o=await fetch(i,n);if(!o.ok)throw new Error(`Failed to fetch "${i}" (${o.status} ${o.statusText}).`);const a=await r.process(o);return r.create(a,s)}},e.NineSliceSprite=ur,e.ObservableSize=li,e.ObservableVector=Qe,e.Panel=nl,e.PassContext=du,e.Perf=$l,e.PlayStationGamepadMapping=Xi,e.Pointer=pn,e.PolarVector=ou,e.Polygon=Rt,e.Prefab=Xl,e.ProgressBar=rl,e.Quadtree=wn,e.RadialGradient=Fu,e.Random=Bn,e.Rectangle=et,e.RenderBatch=class{geometry;material;_transforms=[];_tints=[];_count=0;constructor(e,t=null){if("static"!==e.usage)throw new Error(`RenderBatch requires geometry with usage='static' (got '${e.usage}').`);if(null!==t&&"mesh"!==t.target)throw new Error(`RenderBatch material must target 'mesh' (got '${String(t.target)}').`);this.geometry=e,this.material=t}get count(){return this._count}add(e,t=null){let i=this._transforms[this._count];void 0===i&&(i=new At,this._transforms[this._count]=i),i.copy(e);let n=this._tints[this._count];return void 0===n&&(n=new Tt,this._tints[this._count]=n),n.copy(t??Tt.white),this._count++,this}clear(){return this._count=0,this}destroy(){for(const e of this._transforms)e.destroy();for(const e of this._tints)e.destroy();this._transforms.length=0,this._tints.length=0,this._count=0}get _instanceTransforms(){return this._transforms}get _instanceTints(){return this._tints}},e.RenderNode=Si,e.RenderNodePass=class extends _u{_node;_target;_clear;_renderOptions;_redirect;constructor(e,t){super(t),this._node=e,this._target=t?.target??null,this._clear=t?.clear??null,this._renderOptions=void 0!==t?.view?{view:t.view}:{},this._redirect=null!==this._target?new vi(e=>wi(this._node,e),{target:this._target,view:t?.view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(e){null===this._redirect?(null!==this._clear&&e.backend.clear(this._clear),e.render(this._node,this._renderOptions)):e.backend.execute(this._redirect)}},e.RenderPass=_u,e.RenderPipeline=fu,e.RenderTarget=di,e.RenderTexture=_i,e.RenderingContext=Zs,e.RepeatingSprite=wr,e.SERIALIZATION_VERSION=1,e.Sampler=class{_context;_sampler;_scaleMode;_wrapMode;constructor(e,t){const{scaleMode:i,wrapMode:n}=t;this._context=e,this._sampler=e.createSampler(),this._scaleMode=i,this._wrapMode=n,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(e){this.setScaleMode(e)}get wrapMode(){return this._wrapMode}set wrapMode(e){this.setWrapMode(e)}setScaleMode(e){return this._scaleMode!==e&&(this._scaleMode=e,this.updateScaleModeParameters()),this}setWrapMode(e){return this._wrapMode!==e&&(this._wrapMode=e,this.updateWrapModeParameters()),this}bind(e){return this._context.bindSampler(e,this._sampler),this}destroy(){this._context.deleteSampler(this._sampler)}updateScaleModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const e=this._context;e.samplerParameteri(this._sampler,e.TEXTURE_MAG_FILTER,this._scaleMode),e.samplerParameteri(this._sampler,e.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const e=this._context;e.samplerParameteri(this._sampler,e.TEXTURE_WRAP_S,this._wrapMode),e.samplerParameteri(this._sampler,e.TEXTURE_WRAP_T,this._wrapMode)}},e.Scene=El,e.SceneManager=kl,e.SceneNode=Lt,e.ScrollContainer=class extends el{content;_direction;_scrollX=0;_scrollY=0;_onWheel=e=>{const t=this._stage?.app?.input.getPrimaryPointerPosition();if(null==t)return;this.getBounds().contains(t.x,t.y)&&this.scrollBy("vertical"!==this._direction?e.x:0,"horizontal"!==this._direction?e.y:0)};constructor(e){super(),this._direction=e.direction??"vertical",this.content=new Bi,this.clip=!0,this.interactive=!0,this.addChild(this.content),this.setSize(e.width,e.height)}get scrollX(){return this._scrollX}get scrollY(){return this._scrollY}scrollBy(e,t){this.scrollTo(this._scrollX+e,this._scrollY+t)}scrollTo(e,t){const i=this.content.getBounds(),n=Math.max(0,i.width-this._uiWidth),r=Math.max(0,i.height-this._uiHeight);this._scrollX=Math.max(0,Math.min(e,n)),this._scrollY=Math.max(0,Math.min(t,r)),this.content.setPosition(-this._scrollX,-this._scrollY)}_relayout(){this.scrollTo(this._scrollX,this._scrollY)}_setStage(e){const t=this._stage?.app,i=e?.app;super._setStage(e),t!==i&&(t?.input.onMouseWheel.remove(this._onWheel),i?.input.onMouseWheel.add(this._onWheel))}destroy(){this._stage?.app?.input.onMouseWheel.remove(this._onWheel),super.destroy()}},e.Segment=hu,e.SerializationRegistry=yl,e.Shader=Yr,e.ShaderAttribute=Qr,e.ShaderSource=Xu,e.ShaderUniform=Zr,e.Signal=x,e.Size=l,e.Sound=lt,e.SoundFactory=Go,e.Sprite=vr,e.SpriteMaterial=tc,e.Spritesheet=class{texture;frames=new Map;sprites=new Map;animations=new Map;constructor(e,t){this.texture=e,this.parse(t)}parse(e,t=!1){t||this.clear();for(const[t,i]of Object.entries(e.frames))this.addFrame(t,i);if(e.animations)for(const[t,i]of Object.entries(e.animations))this.defineAnimation(t,i)}addFrame(e,t){const{x:i,y:n,w:r,h:s}=t.frame,o=new et(i,n,r,s),a=new vr(this.texture);a.setTextureFrame(o),this.frames.set(e,o),this.sprites.set(e,a)}defineAnimation(e,t){if(0===e.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(0===t.length)throw new Error(`Spritesheet animation "${e}" must reference at least one frame.`);for(const i of t)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${e}" references missing frame "${i}".`);return this.animations.set(e,[...t]),this}getFrame(e){const t=this.frames.get(e);if(!t)throw new Error(`Spritesheet frame named ${e} is not available!`);return t}getAnimationFrameNames(e){const t=this.animations.get(e);if(!t)throw new Error(`Spritesheet animation named ${e} is not available!`);return t}getFrameSprite(e){const t=this.sprites.get(e);if(!t)throw new Error(`Spritesheet frame named ${e} is not available!`);return t}clear(){for(const e of this.frames.values())e.destroy();this.frames.clear();for(const e of this.sprites.values())e.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}},e.Stack=sl,e.SteamControllerGamepadMapping=Hi,e.SteamDeckGamepadMapping=ji,e.SubtitleAsset=ta,e.SubtitleFactory=Yo,e.SvgAsset=ea,e.SvgFactory=$o,e.Sweep=cu,e.SwitchProGamepadMapping=Ki,e.SystemRegistry=Ml,e.Text=Wr,e.TextAsset=Jo,e.TextFactory=class extends To{storageName="text";async process(e){return e.text()}async create(e){return e}},e.TextStyle=Mr,e.Texture=pi,e.TextureFactory=Xo,e.TextureRegion=Wn,e.Time=Ri,e.Timer=Di,e.Tooltip=class{_target;_offsetX;_offsetY;_delayMs;_background;_textColor;_padding;_fontSize;_text;_node=null;_timer=null;_onPointerOver=e=>{this._scheduleShow(e.worldX,e.worldY)};_onPointerOut=()=>{this._hide()};constructor(e,t){this._target=e,this._text=t.text,this._offsetX=t.offsetX??12,this._offsetY=t.offsetY??-28,this._delayMs=1e3*(t.delay??.3),this._background=t.background??2236962,this._textColor=t.textColor??16777215,this._padding=t.padding??6,this._fontSize=t.fontSize??12,e.onPointerOver.add(this._onPointerOver),e.onPointerOut.add(this._onPointerOut)}destroy(){this._hide(),this._target.onPointerOver.remove(this._onPointerOver),this._target.onPointerOut.remove(this._onPointerOut)}_scheduleShow(e,t){this._cancelTimer(),this._timer=setTimeout(()=>{this._show(e,t)},this._delayMs)}_show(e,t){this._removeNode();const i=this._findUIRoot();if(null===i)return;const n=e=>new Tt(e>>16&255,e>>8&255,255&e,1),r=new Wr(this._text,{fillColor:n(this._textColor),fontSize:this._fontSize}),s=r.getLocalBounds(),o=s.width+2*this._padding,a=s.height+2*this._padding,h=new Mh;h.fillColor=n(this._background),h.drawRoundedRectangle(0,0,o,a,4),r.setPosition(this._padding,this._padding);const l=new Bi;l.addChild(h),l.addChild(r),l.setPosition(e+this._offsetX,t+this._offsetY),this._node=l,i.addChild(l)}_hide(){this._cancelTimer(),this._removeNode()}_removeNode(){if(null!==this._node){const e=this._node.parent;null!==e&&e.removeChild(this._node),this._node=null}}_cancelTimer(){null!==this._timer&&(clearTimeout(this._timer),this._timer=null)}_findUIRoot(){let e=this._target.parent;for(;null!==e;){if(e instanceof nh)return e;e=e.parent}return null}},e.Tween=s,e.TweenManager=a,e.TweenSequencer=o,e.UIRoot=nh,e.Vector=it,e.Video=Co,e.VideoFactory=jo,e.View=ci,e.WasmAsset=aa,e.WasmFactory=Ko,e.WebGl2ShaderFilter=gu,e.WebGpuShaderFilter=xu,e.WebStorageStore=class{_storage;_prefix;constructor(e,t={}){this._storage=e,this._prefix=t.prefix??""}get(e){const t=this._storage.getItem(this._prefix+e);if(null===t)return Promise.resolve(null);try{return Promise.resolve(JSON.parse(t))}catch{return Promise.reject(new Error(`WebStorageStore.get() failed: stored value for key "${e}" is not valid JSON.`))}}set(e,t){let i;try{i=JSON.stringify(t)}catch{return Promise.reject(new Error("WebStorageStore.set() failed: value is not JSON-serializable."))}return this._storage.setItem(this._prefix+e,i),Promise.resolve()}has(e){return Promise.resolve(null!==this._storage.getItem(this._prefix+e))}delete(e){const t=this._prefix+e,i=null!==this._storage.getItem(t);return this._storage.removeItem(t),Promise.resolve(i)}clear(){if(""===this._prefix)return this._storage.clear(),Promise.resolve(!0);const e=[];for(let t=0;t<this._storage.length;t++){const i=this._storage.key(t);!0===i?.startsWith(this._prefix)&&e.push(i)}for(const t of e)this._storage.removeItem(t);return Promise.resolve(!0)}},e.Widget=el,e.WorkletEffect=class extends ee{_inputGain=null;_outputGain=null;_dryGain=null;_wetGain=null;_dryDelay=null;_workletNode=null;_ready=null;_wet=1;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};get _workletOptions(){return{numberOfInputs:1,numberOfOutputs:1}}get _dryLatencySeconds(){return 0}get _wetMakeupGain(){return 1}get _sampleRate(){return this._outputGain?.context.sampleRate??48e3}constructor(){super(),U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._inputGain)throw new Error(`${this.constructor.name}: input node accessed before audio context is ready.`);return this._inputGain}get outputNode(){if(!this._outputGain)throw new Error(`${this.constructor.name}: output node accessed before audio context is ready.`);return this._outputGain}get wet(){return this._wet}set wet(e){if(this._wet=Math.max(0,Math.min(1,e)),this._dryGain&&this._wetGain){const e=this._wetGain.context;this._dryGain.gain.setTargetAtTime(1-this._wet,e.currentTime,.01),this._wetGain.gain.setTargetAtTime(this._wet*this._wetMakeupGain,e.currentTime,.01)}}get ready(){return this._ready??Promise.resolve()}destroy(){I.remove(this._onAudioContextReady),this._workletNode?.disconnect(),this._inputGain?.disconnect(),this._outputGain?.disconnect(),this._dryGain?.disconnect(),this._wetGain?.disconnect(),this._dryDelay?.disconnect(),this._workletNode=null,this._inputGain=null,this._outputGain=null,this._dryGain=null,this._wetGain=null,this._dryDelay=null,this._ready=null}_setAudioParam(e,t){if(!this._workletNode)return;const i=this._workletNode.parameters.get(e);i&&i.setTargetAtTime(t,this._workletNode.context.currentTime,.01)}_setup(e){const t=e.createGain(),i=e.createGain(),n=e.createGain(),r=e.createGain();this._inputGain=t,this._outputGain=i,t.connect(n),n.connect(i),n.gain.setValueAtTime(1,e.currentTime),r.gain.setValueAtTime(0,e.currentTime),r.connect(i),this._dryGain=n,this._wetGain=r,this._ready=wt(e,this._workletName,this._workletSource).then(()=>{if(!this._inputGain||!this._dryGain||!this._wetGain)return;const t=this._dryLatencySeconds;if(t>0){const i=e.createDelay(Math.max(1,2*t));i.delayTime.setValueAtTime(t,e.currentTime),this._dryDelay=i,this._inputGain.disconnect(this._dryGain),this._inputGain.connect(i),i.connect(this._dryGain)}const i=new AudioWorkletNode(e,this._workletName,this._workletOptions);this._workletNode=i,this._inputGain.connect(i),i.connect(this._wetGain),this.wet=this._wet,this._onWorkletReady?.(e)})}},e.XboxGamepadMapping=Qi,e.XmlAsset=ia,e.XmlFactory=Qo,e.buildInfo=ql,e.createRenderStats=Ks,e.crossFade=async function(e,t,i,n={}){const r=Y(n.toVolume??1,0,1),s=n.stopAfter??!0;return t.fade(r,i),s?e.stop(i):e.fade(0,i),new Promise(e=>{setTimeout(e,Math.max(0,i))})},e.decodeAudioData=G,e.defineAssetManifest=Ra,e.getAudioContext=L,e.getOfflineAudioContext=()=>E(),e.isAdvancedBlendMode=Gt,e.isAudioContextReady=U,e.logger=ih,e.maxPointers=16,e.onAudioContextReady=I,e.pointerSlotSize=16,e.registerAudioWorkletProcessor=wt,e.registerSerializer=function(e,t,i,n=wl){n.register(e,t,i)},e.resetRenderStats=Qs,e}({});
1
+ var Exo=function(e){"use strict";const t=e=>{const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375};class i{static linear=e=>e;static quadIn=e=>e*e;static quadOut=e=>e*(2-e);static quadInOut=e=>e<.5?2*e*e:(4-2*e)*e-1;static cubicIn=e=>e*e*e;static cubicOut=e=>--e*e*e+1;static cubicInOut=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;static quartIn=e=>e*e*e*e;static quartOut=e=>1- --e*e*e*e;static quartInOut=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;static quintIn=e=>e*e*e*e*e;static quintOut=e=>1+--e*e*e*e*e;static quintInOut=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;static sineIn=e=>1-Math.cos(e*Math.PI/2);static sineOut=e=>Math.sin(e*Math.PI/2);static sineInOut=e=>-(Math.cos(Math.PI*e)-1)/2;static expoIn=e=>0===e?0:Math.pow(2,10*e-10);static expoOut=e=>1===e?1:1-Math.pow(2,-10*e);static expoInOut=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;static circIn=e=>1-Math.sqrt(1-Math.pow(e,2));static circOut=e=>Math.sqrt(1-Math.pow(e-1,2));static circInOut=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;static backIn=e=>{const t=1.70158;return 2.70158*e*e*e-t*e*e};static backOut=e=>{const t=1.70158;return 1+2.70158*Math.pow(e-1,3)+t*Math.pow(e-1,2)};static backInOut=e=>{const t=2.5949095;return e<.5?Math.pow(2*e,2)*(7.189819*e-t)/2:(Math.pow(2*e-2,2)*((t+1)*(2*e-2)+t)+2)/2};static bounceOut=t;static bounceIn=e=>1-t(1-e);static bounceInOut=e=>e<.5?(1-t(1-2*e))/2:(1+t(2*e-1))/2;static elasticIn=e=>{if(0===e)return 0;if(1===e)return 1;const t=2*Math.PI/3;return-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*t)};static elasticOut=e=>{if(0===e)return 0;if(1===e)return 1;const t=2*Math.PI/3;return Math.pow(2,-10*e)*Math.sin((10*e-.75)*t)+1};static elasticInOut=e=>{if(0===e)return 0;if(1===e)return 1;const t=2*Math.PI/4.5;return e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*t)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*t)/2+1}}var n,r;e.TweenState=void 0,(n=e.TweenState||(e.TweenState={})).Idle="idle",n.Active="active",n.Paused="paused",n.Complete="complete",n.Stopped="stopped";class s{_target;_state=e.TweenState.Idle;_properties={};_startValues=null;_duration=0;_delay=0;_easing=i.linear;_elapsed=0;_delayElapsed=0;_repeatCount=0;_repeatTotal=0;_yoyo=!1;_direction=1;_onStart=null;_onUpdate=null;_onComplete=null;_onRepeat=null;_chained=null;_manager=null;_startFired=!1;constructor(e){this._target=e}get target(){return this._target}get state(){return this._state}get progress(){if(0===this._duration)return 1;const e=Math.min(this._elapsed/this._duration,1),t=1===this._direction?e:1-e;return this._easing(t)}to(e,t){return this._properties={...e},this._duration=t,this._startValues=null,this}delay(e){return this._delay=e,this}easing(e){return this._easing=e,this}repeat(e){return this._repeatTotal=e,this}yoyo(e=!0){return this._yoyo=e,this}onStart(e){return this._onStart=e,this}onUpdate(e){return this._onUpdate=e,this}onComplete(e){return this._onComplete=e,this}onRepeat(e){return this._onRepeat=e,this}start(){return this._state=e.TweenState.Active,this._elapsed=0,this._delayElapsed=0,this._startValues=null,this._startFired=!1,this._direction=1,this._repeatCount=this._repeatTotal,this._manager?.add(this),this}pause(){return this._state===e.TweenState.Active&&(this._state=e.TweenState.Paused),this}resume(){return this._state===e.TweenState.Paused&&(this._state=e.TweenState.Active),this}stop(){return this._state!==e.TweenState.Active&&this._state!==e.TweenState.Paused||(this._state=e.TweenState.Stopped,this._manager?.remove(this)),this}chain(e){return this._chained=e,e}_attachManager(e){this._manager=e}update(t){if(this._state!==e.TweenState.Active)return;if(this._delayElapsed<this._delay){if(this._delayElapsed+=t,this._delayElapsed<this._delay)return;const e=this._delayElapsed-this._delay;this._delayElapsed=this._delay,t=e}null===this._startValues&&this._captureStartValues(),this._startFired||(this._startFired=!0,this._onStart?.()),this._elapsed+=t;const i=this._elapsed-this._duration;if(i>=0&&(this._elapsed=this._duration),this._applyProgress(),this._elapsed>=this._duration){-1===this._repeatCount||this._repeatCount>0?(-1!==this._repeatCount&&this._repeatCount--,this._onRepeat?.(),this._yoyo&&(this._direction=1===this._direction?-1:1),this._elapsed=i>0?Math.min(i,this._duration):0,i>0&&this._applyProgress()):this._complete()}}_captureStartValues(){const e={},t=Object.keys(this._properties);for(const i of t){const t=this._target[i];"number"==typeof t&&(e[String(i)]=t)}this._startValues=e}_applyProgress(){if(null===this._startValues)return;const e=0===this._duration?1:Math.min(this._elapsed/this._duration,1),t=1===this._direction?e:1-e,i=this._easing(t),n=Object.keys(this._startValues),r=this._properties;for(const e of n){const t=this._startValues[e],n=r[e];void 0!==t&&void 0!==n&&(this._target[e]=t+(n-t)*i)}this._onUpdate?.(i)}_complete(){this._elapsed=this._duration,this._applyProgress(),this._state=e.TweenState.Complete,this._manager?.remove(this),this._onComplete?.(),this._chained?.start()}}e.TweenSequencerState=void 0,(r=e.TweenSequencerState||(e.TweenSequencerState={})).Idle="idle",r.Active="active",r.Paused="paused",r.Complete="complete",r.Stopped="stopped";class o{_stages=[];_state=e.TweenSequencerState.Idle;_manager;_currentStageIndex=0;_direction=1;_repeatCount=0;_repeatTotal=0;_yoyo=!1;_delayElapsed=0;_onStartCb=null;_onCompleteCb=null;_startFired=!1;constructor(e){this._manager=e??null}get state(){return this._state}get progress(){const e=this._stages.length;return 0===e?1:Math.min(this._currentStageIndex/e,1)}then(e){const t=Array.isArray(e)?e:[e];return this._stages.push({type:"tweens",tweens:t}),this}wait(e){return this._stages.push({type:"delay",seconds:e}),this}repeat(e){return this._repeatTotal=e,this}yoyo(e=!0){return this._yoyo=e,this}onStart(e){return this._onStartCb=e,this}onComplete(e){return this._onCompleteCb=e,this}start(){return this._state=e.TweenSequencerState.Active,this._currentStageIndex=0,this._direction=1,this._repeatCount=this._repeatTotal,this._startFired=!1,this._manager?.addTicker(this),this._startCurrentStage(),this}pause(){return this._state===e.TweenSequencerState.Active&&(this._state=e.TweenSequencerState.Paused,this._pauseCurrentStageTweens()),this}resume(){return this._state===e.TweenSequencerState.Paused&&(this._state=e.TweenSequencerState.Active,this._resumeCurrentStageTweens()),this}stop(){return this._state!==e.TweenSequencerState.Active&&this._state!==e.TweenSequencerState.Paused||(this._state=e.TweenSequencerState.Stopped,this._stopCurrentStageTweens(),this._manager?.removeTicker(this)),this}update(t){if(this._state!==e.TweenSequencerState.Active)return;if(this._startFired||(this._startFired=!0,this._onStartCb?.()),0===this._stages.length)return void this._finish();const i=this._getActualStageIndex(),n=this._stages[i];if(void 0!==n)if("delay"===n.type)this._delayElapsed+=t,this._delayElapsed>=n.seconds&&this._advanceStage();else{if(null===this._manager)for(const i of n.tweens)i.state===e.TweenState.Active&&i.update(t);n.tweens.every(t=>t.state===e.TweenState.Complete||t.state===e.TweenState.Stopped)&&this._advanceStage()}}_getActualStageIndex(){return 1===this._direction?this._currentStageIndex:this._stages.length-1-this._currentStageIndex}_startCurrentStage(){const e=this._getActualStageIndex(),t=this._stages[e];if(void 0!==t&&(this._delayElapsed=0,"tweens"===t.type))for(const e of t.tweens)null!==this._manager&&this._manager.add(e),e.start()}_advanceStage(){if(this._currentStageIndex++,this._currentStageIndex>=this._stages.length){-1===this._repeatCount||this._repeatCount>0?(-1!==this._repeatCount&&this._repeatCount--,this._yoyo&&(this._direction=1===this._direction?-1:1),this._currentStageIndex=0,this._startCurrentStage()):this._finish()}else this._startCurrentStage()}_finish(){this._state=e.TweenSequencerState.Complete,this._manager?.removeTicker(this),this._onCompleteCb?.()}_getCurrentStageTweens(){if(0===this._stages.length)return[];const e=this._getActualStageIndex(),t=this._stages[e];return"tweens"===t?.type?t.tweens:[]}_pauseCurrentStageTweens(){for(const e of this._getCurrentStageTweens())e.pause()}_resumeCurrentStageTweens(){for(const e of this._getCurrentStageTweens())e.resume()}_stopCurrentStageTweens(){for(const e of this._getCurrentStageTweens())e.stop()}}class a{order=400;_tweens=[];_tickers=[];_destroyed=!1;create(e){const t=new s(e);return t._attachManager(this),this._tweens.push(t),t}sequence(e){const[t]=e;if(void 0===t)throw new Error("[ExoJS] TweenManager.sequence() requires at least one tween.");for(let t=0;t<e.length-1;t++){const i=e[t],n=e[t+1];void 0!==i&&void 0!==n&&i.chain(n)}for(const t of e)this.add(t);return t}createSequencer(){return new o(this)}add(e){return e._attachManager(this),this._tweens.includes(e)||this._tweens.push(e),this}remove(e){const t=this._tweens.indexOf(e);return-1!==t&&this._tweens.splice(t,1),this}addTicker(e){return this._tickers.includes(e)||this._tickers.push(e),this}removeTicker(e){const t=this._tickers.indexOf(e);return-1!==t&&this._tickers.splice(t,1),this}update(e){if(this._destroyed)return;const t=[...this._tweens];for(const i of t)i.update(e.seconds);const i=[...this._tickers];for(const t of i)t.update(e.seconds)}clear(){return this._tweens=[],this._tickers=[],this}destroy(){this.clear(),this._destroyed=!0}}let h=null;class l{_width;_height;constructor(e=0,t=0){this._width=e,this._height=t}get width(){return this._width}set width(e){this._width=e}get height(){return this._height}set height(e){this._height=e}set(e,t=e){return this._width=e,this._height=t,this}add(e,t=e){return this._width+=e,this._height+=t,this}subtract(e,t=e){return this._width-=e,this._height-=t,this}scale(e,t=e){return this._width*=e,this._height*=t,this}divide(e,t=e){return this._width/=e,this._height/=t,this}copy(e){return this._width=e.width,this._height=e.height,this}clone(){return new l(this._width,this._height)}equals({width:e,height:t}={}){return!(void 0!==e&&this.width!==e||void 0!==t&&this.height!==t)}destroy(){}static zero=new l(0,0);static get temp(){return null===h&&(h=new l),h}}let u=null,c=null;const d=()=>{if("undefined"==typeof document)throw new Error("Canvas operations require a document context.");return null===u&&(u=document.createElement("canvas")),u},_=e=>{e.preventDefault(),e.stopImmediatePropagation()},f="undefined"!=typeof indexedDB,p=()=>performance.now(),m=new ArrayBuffer(0),g=(e,t,i)=>{if(t<e.length&&i>0){const n=t+i>e.length?e.length-t:i,r=e.length-n;for(let i=t;i<r;i++)e[i]=e[i+n];e.length=r}return e},y=e=>{const t=e;return e instanceof HTMLImageElement?l.temp.set(e.naturalWidth,e.naturalHeight):e instanceof HTMLVideoElement?l.temp.set(e.videoWidth,e.videoHeight):e instanceof SVGElement?l.temp.copy(e.getBoundingClientRect()):"number"==typeof t.displayWidth&&"number"==typeof t.displayHeight?l.temp.set(t.displayWidth,t.displayHeight):"number"==typeof t.width&&"number"==typeof t.height?l.temp.set(t.width,t.height):l.zero},w=e=>{const{width:t,height:i}=y(e),n=d();return n.width=t,n.height=i,(()=>{if(null===c){const e=d().getContext("2d");if(!e)throw new Error("Could not create a 2D canvas context.");c=e}return c})().drawImage(e,0,0,t,i),n.toDataURL()};class x{_handlers=[];_dispatching=!1;_pendingRemoves=null;get count(){return this._handlers.length}has(e){return this._handlers.includes(e)}add(e){return this._handlers.includes(e)||this._handlers.push(e),this}once(e){const t=(...i)=>{this.remove(t),e(...i)};return this._handlers.push(t),this}remove(e){if(this._dispatching)(this._pendingRemoves??=[]).push(e);else{const t=this._handlers.indexOf(e);-1!==t&&g(this._handlers,t,1)}return this}clear(){return this._dispatching?this._pendingRemoves=[...this._handlers]:this._handlers.length=0,this}dispatch(...e){const t=this._handlers.length;if(!t)return this;this._dispatching=!0;for(let i=0;i<t&&!1!==this._handlers[i](...e);i++);if(this._dispatching=!1,null!==this._pendingRemoves){for(const e of this._pendingRemoves){const t=this._handlers.indexOf(e);-1!==t&&g(this._handlers,t,1)}this._pendingRemoves=null}return this}destroy(){this._handlers.length=0,this._pendingRemoves=null}}const v=["mousedown","touchstart","touchend","keydown"];let b=null,S=null,B=!1,C=!1,T=!1;const M=()=>"undefined"!=typeof document,P=()=>b,A=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===b&&(b=new AudioContext),b},E=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===S){const e=A();S=new OfflineAudioContext(1,2,e.sampleRate)}return S},k=()=>{const e=P();"running"!==e?.state||T||(T=!0,(()=>{if(B&&M()){for(const e of v)document.removeEventListener(e,F,!1);B=!1}})(),I.dispatch(e))},R=()=>{k()},D=()=>{const e=A();C||"function"!=typeof e.addEventListener||(e.addEventListener("statechange",R),C=!0),k(),T||(()=>{if(!B&&M()){for(const e of v)document.addEventListener(e,F,!1);B=!0}})()},F=()=>{const e=A();"running"!==e.state?e.resume().then(()=>{k()}):k()};const I=new class extends x{add(e){return super.add(e),D(),this}once(e){return super.once(e),D(),this}},L=()=>{const e=A();return D(),e},U=()=>{const e=P();return null!==e&&"running"===e.state},G=async e=>E().decodeAudioData(e),N=2*Math.PI,O=Math.PI/180,V=180/Math.PI;var z;!function(e){e[e.left=-1]="left",e[e.middle=0]="middle",e[e.right=1]="right"}(z||(z={}));const q=e=>{const t=e%360;return t<0?t+360:t},W=e=>e*O,Y=(e,t,i)=>Math.min(i,Math.max(t,e)),$=(e,t,i)=>(1-i)*e+i*t,X=e=>0!==e&&!(e&e-1),H=(e,t,i)=>e>=Math.min(t,i)&&e<=Math.max(t,i),j=(e,t,i,n)=>{const r=e-i,s=t-n;return Math.sqrt(r*r+s*s)},K=(e,t,i,n,r,s,o,a,h=[],l=20)=>{h.push(e,t);for(let u=1;u<=l;u++){const c=u/l,d=1-c,_=d*d,f=_*d,p=c*c,m=p*c;h.push(f*e+3*_*c*i+3*d*p*r+m*o,f*t+3*_*c*n+3*d*p*s+m*a)}return h},Q=(e,t,i,n,r,s,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push($($(e,i,l),$(i,r,l),l),$($(t,n,l),$(n,s,l),l))}return o},Z={tau:N,clamp:Y,sign:e=>e&&(e<0?-1:1),lerp:$,inRange:H,isPowerOfTwo:X,distance:j,trimRotation:q,degreesToRadians:W,radiansToDegrees:e=>e*V,bezierCurveTo:K,quadraticCurveTo:Q};class J{name;_parent;_volume;_muted;_pan;_effects=[];_setup=null;_scheduledStopId=null;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setupAudio(e)};constructor(e,t={}){if(!e||"string"!=typeof e)throw new Error("AudioBus requires a non-empty string name.");this.name=e,this._parent=t.parent??null,this._volume=Y(t.volume??1,0,2),this._muted=t.muted??!1,this._pan=Y(t.pan??0,-1,1),t.effects&&this._effects.push(...t.effects),U()?this._setupAudio(L()):I.add(this._onAudioContextReady)}get parent(){return this._parent}get volume(){return this._volume}set volume(e){const t=Y(e,0,2);this._volume!==t&&(this._volume=t,this._applyVolume())}get muted(){return this._muted}set muted(e){this._muted!==e&&(this._muted=e,this._applyVolume())}get pan(){return this._pan}set pan(e){const t=Y(e,-1,1);this._pan!==t&&(this._pan=t,this._setup&&this._setup.panNode.pan.setTargetAtTime(t,this._setup.audioContext.currentTime,.01))}get inputNode(){return this._setup?.inputNode??null}addEffect(e){return this._effects.push(e),this._rebuildEffectChain(),this}removeEffect(e){const t=this._effects.indexOf(e);return-1!==t&&(this._effects.splice(t,1),this._rebuildEffectChain()),this}fadeIn(e){if(this._clearScheduledStop(),e<=0||!this._setup)return this;const t=this._setup.audioContext,i=this._setup.outputNode,n=this._muted?0:this._volume;return i.gain.cancelScheduledValues(t.currentTime),i.gain.setValueAtTime(0,t.currentTime),i.gain.linearRampToValueAtTime(n,t.currentTime+e/1e3),this}fadeOut(e,t={}){const i=t.stopAfter??!0;if(this._clearScheduledStop(),e<=0||!this._setup)return i&&(this.muted=!0),this;const n=this._setup.audioContext,r=this._setup.outputNode;return r.gain.cancelScheduledValues(n.currentTime),r.gain.setValueAtTime(r.gain.value,n.currentTime),r.gain.linearRampToValueAtTime(0,n.currentTime+e/1e3),i&&(this._scheduledStopId=setTimeout(()=>{this._scheduledStopId=null,this.muted=!0},e)),this}destroy(){I.remove(this._onAudioContextReady),this._clearScheduledStop();for(const e of this._effects)e.destroy();this._effects.length=0,this._setup&&(this._setup.inputNode.disconnect(),this._setup.outputNode.disconnect(),this._setup.panNode.disconnect(),this._setup=null)}_getInputNode(){return this._setup?.inputNode??null}_getOutputNode(){return this._setup?.outputNode??null}_setupAudio(e){const t=e.createGain(),i=e.createStereoPanner(),n=e.createGain();n.gain.setTargetAtTime(this._muted?0:this._volume,e.currentTime,.01),i.pan.setTargetAtTime(this._pan,e.currentTime,.01),this._setup={audioContext:e,inputNode:t,outputNode:n,panNode:i},this._rebuildEffectChain(),this._connectUpstream()}_connectUpstream(){if(this._setup)if(this._parent){const e=this._parent._getInputNode();e?this._setup.outputNode.connect(e):this._parent.onceSetup(()=>{if(this._setup&&this._parent){const e=this._parent._getInputNode();e&&this._setup.outputNode.connect(e)}})}else this._setup.outputNode.connect(this._setup.audioContext.destination)}onceSetup(e){this._setup?e():I.once(()=>{this._setup&&e()})}_rebuildEffectChain(){if(!this._setup)return;const{inputNode:e,panNode:t}=this._setup;e.disconnect();for(const e of this._effects)e.inputNode.disconnect(),e.outputNode.disconnect();t.disconnect();let i=e;for(const e of this._effects)i.connect(e.inputNode),i=e.outputNode;i.connect(t),t.connect(this._setup.outputNode)}_applyVolume(){if(!this._setup)return;const e=this._muted?0:this._volume;this._setup.outputNode.gain.setTargetAtTime(e,this._setup.audioContext.currentTime,.01)}_clearScheduledStop(){null!==this._scheduledStopId&&(clearTimeout(this._scheduledStopId),this._scheduledStopId=null)}}class ee{get ready(){return Promise.resolve()}}class te{get angle(){return Math.atan2(this.y,this.x)}set angle(e){const t=this.length;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(e){const t=this.angle;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(e){this.length=Math.sqrt(e)}set(e,t=e){return this.x=e,this.y=t,this}equals({x:e,y:t}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t)}add(e,t=e){return this.x+=e,this.y+=t,this}subtract(e,t=e){return this.x-=e,this.y-=t,this}multiply(e,t=e){return this.x*=e,this.y*=t,this}divide(e,t=e){return 0!==e&&0!==t&&(this.x/=e,this.y/=t),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(e){return this.set(this.x*e.a+this.y*e.b+e.x,this.x*e.c+this.y*e.d+e.y)}transformInverse(e){const t=e.a*e.d-e.b*e.c,i=this.x-e.x,n=this.y-e.y;return this.set((e.d*i-e.b*n)/t,(e.a*n-e.c*i)/t)}perp(){return this.set(-this.y,this.x)}rperp(){return this.set(this.y,-this.x)}min(){return Math.min(this.x,this.y)}max(){return Math.max(this.x,this.y)}dot(e,t){return this.x*e+this.y*t}cross(e){return this.x*e.y-this.y*e.x}distanceTo(e){return j(this.x,this.y,e.x,e.y)}}var ie;e.CollisionType=void 0,(ie=e.CollisionType||(e.CollisionType={}))[ie.Point=0]="Point",ie[ie.Line=1]="Line",ie[ie.Rectangle=2]="Rectangle",ie[ie.Circle=3]="Circle",ie[ie.Ellipse=4]="Ellipse",ie[ie.Polygon=5]="Polygon",ie[ie.SceneNode=6]="SceneNode";const ne=1e-10,re=(e,t=e)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(e,t)))),se=({x:e,y:t,rx:i,ry:n})=>{if(i<=0||n<=0)return[];const r=re(i,n),s=2*Math.PI/r,o=[];for(let a=0;a<r;a++){const r=a*s;o.push({x:e+Math.cos(r)*i,y:t+Math.sin(r)*n})}return o},oe=({x:e,y:t},{x:i,y:n},{x:r,y:s})=>e<=Math.max(i,r)+ne&&e>=Math.min(i,r)-ne&&t<=Math.max(n,s)+ne&&t>=Math.min(n,s)-ne,ae=({x:e,y:t},{x:i,y:n},{x:r,y:s})=>{const o=(n-t)*(r-i)-(i-e)*(s-n);return Math.abs(o)<=ne?0:o>0?1:2},he=(e,t,i,n)=>{const r=ae(e,t,i),s=ae(e,t,n),o=ae(i,n,e),a=ae(i,n,t);return r!==s&&o!==a||(!(0!==r||!oe(i,e,t))||(!(0!==s||!oe(n,e,t))||(!(0!==o||!oe(e,i,n))||!(0!==a||!oe(t,i,n)))))},le=({x:e,y:t},i)=>{const n=i.length;if(n<3)return!1;let r=!1;for(let s=0,o=n-1;s<n;o=s++){const n=i[o],a=i[s];a.y>t!=n.y>t&&e<(n.x-a.x)*((t-a.y)/(n.y-a.y))+a.x&&(r=!r)}return r},ue=(e,t)=>{if(0===e.length||0===t.length)return!1;for(let i=0;i<e.length;i++){const n=e[i],r=e[(i+1)%e.length];for(let e=0;e<t.length;e++){const i=t[e],s=t[(e+1)%t.length];if(he(n,r,i,s))return!0}}return le(e[0],t)||le(t[0],e)},ce=({x:e,y:t},{x:i,y:n},{x:r,y:s},o=.1)=>{const a=j(e,t,i,n),h=j(e,t,r,s),l=j(i,n,r,s);return a+h>=l-o&&a+h<=l+o},de=(e,t,i,n)=>{const r=(t.x-e.x)*(n.y-i.y)-(n.x-i.x)*(t.y-e.y);if(Math.abs(r)<=ne)return!1;const s=((n.x-i.x)*(e.y-i.y)-(n.y-i.y)*(e.x-i.x))/r,o=((t.x-e.x)*(e.y-i.y)-(t.y-e.y)*(e.x-i.x))/r;return s>=0&&s<=1&&o>=0&&o<=1},_e=(e,t)=>Math.sqrt(e*e+t*t),fe=(e,t,i,n)=>{const r=i*e+n*t;const s=(o=e)*o+(a=t)*a;var o,a;return r<0?z.left:r>s?z.right:z.middle};let pe=null;class me{min;max;constructor(e=0,t=e){this.min=e,this.max=t}set(e,t){return this.min=e,this.max=t,this}copy(e){return this.set(e.min,e.max)}clone(){return new me(this.min,this.max)}containsInterval(e){return e.min>this.min&&e.max<this.max}includes(e){return e<=this.max&&e>=this.min}overlaps(e){return!(this.min>e.max||e.min>this.max)}getOverlap(e){return this.max<e.max?this.max-e.min:e.max-this.min}destroy(){}static zero=new me(0,0);static get temp(){return null===pe&&(pe=new me),pe}}const ge=(e,t)=>{const i=e.getNormals(),n=t.getNormals(),r=new me,s=new me;for(const n of i)if(e.project(n,r),t.project(n,s),!r.overlaps(s))return!1;for(const i of n)if(e.project(i,r),t.project(i,s),!r.overlaps(s))return!1;return!0},ye=(e,t,i=0)=>(({x:e,y:t},{x:i,y:n},r=0)=>j(e,t,i,n)<=r)(e,t,i),we=(e,t,i=.1)=>ce(e,t.fromPosition,t.toPosition,i),xe=(e,t)=>(({x:e,y:t},{x:i,y:n,width:r,height:s})=>H(e,i,i+r)&&H(t,n,n+s))(e,t),ve=(e,t)=>(({x:e,y:t},{x:i,y:n,radius:r})=>r>0&&j(e,t,i,n)<=r)(e,t),be=(e,t)=>(({x:e,y:t},{x:i,y:n,rx:r,ry:s})=>{if(r<=0||s<=0)return!1;const o=(e-i)/r,a=(t-n)/s;return o*o+a*a<=1})(e,t),Se=(e,t)=>((e,{x:t,y:i,points:n})=>le({x:e.x-t,y:e.y-i},n))(e,t),Be=(e,t)=>de(e.fromPosition,e.toPosition,t.fromPosition,t.toPosition),Ce=(e,t)=>{const{x:i,y:n,width:r,height:s}=t,o={x:i,y:n},a={x:i+r,y:n},h={x:i,y:n+s},l={x:i+r,y:n+s};return de(e.fromPosition,e.toPosition,o,h)||de(e.fromPosition,e.toPosition,a,l)||de(e.fromPosition,e.toPosition,o,a)||de(e.fromPosition,e.toPosition,h,l)},Te=(e,t)=>{if(ve(e.fromPosition,t)||ve(e.toPosition,t))return!0;const{fromX:i,fromY:n,toX:r,toY:s}=e,{x:o,y:a,radius:h}=t,l=j(i,n,r,s);if(0===l)return!1;const u=((o-i)*(r-i)+(a-n)*(s-n))/(l*l),c=i+u*(r-i),d=n+u*(s-n);return!!ce({x:c,y:d},e.fromPosition,e.toPosition)&&j(c,d,o,a)<=h},Me=(e,t)=>{const{x:i,y:n,rx:r,ry:s}=t;if(r<=0||s<=0)return!1;const o=(e.fromX-i)/r,a=(e.fromY-n)/s,h=(e.toX-i)/r-o,l=(e.toY-n)/s-a,u=h*h+l*l,c=2*(o*h+a*l),d=o*o+a*a-1;if(d<=0)return!0;if(u<=Number.EPSILON)return!1;const _=c*c-4*u*d;if(_<0)return!1;const f=Math.sqrt(_),p=(-c-f)/(2*u),m=(-c+f)/(2*u);return p>=0&&p<=1||m>=0&&m<=1},Pe=(e,t)=>{const{x:i,y:n,points:r}=t,s=r.length;for(let t=0;t<s;t++){const o=r[t],a=r[(t+1)%s];if(de(e.fromPosition,e.toPosition,{x:o.x+i,y:o.y+n},{x:a.x+i,y:a.y+n}))return!0}return!1},Ae=(e,t)=>(({x:e,y:t,width:i,height:n},{x:r,y:s,width:o,height:a})=>!(r>e+i||s>t+n||e>r+o||t>s+a))(e,t),Ee=({x:e,y:t,width:i,height:n},{x:r,y:s,radius:o})=>{const a=Y(r,e,e+i),h=Y(s,t,t+n);return j(r,s,a,h)<=o},ke=(e,t)=>ue((({x:e,y:t,width:i,height:n})=>[{x:e,y:t},{x:e+i,y:t},{x:e+i,y:t+n},{x:e,y:t+n}])(e),se(t)),Re=(e,t)=>ge(e,t),De=({x:e,y:t,radius:i},{x:n,y:r,radius:s})=>j(e,t,n,r)<=i+s,Fe=(e,t)=>ue((({x:e,y:t,radius:i})=>{if(i<=0)return[];const n=re(i),r=2*Math.PI/n,s=[];for(let o=0;o<n;o++){const n=o*r;s.push({x:e+Math.cos(n)*i,y:t+Math.sin(n)*i})}return s})(e),se(t)),Ie=(e,t,i,n,r,s,o,a,h)=>{if(fe(a,h,r,s)!==z.left)return!1;return fe(n.x,n.y,e-i.x,t-i.y)===z.right&&_e(r,s)>o},Le=(e,t,i,n,r,s,o,a,h)=>{if(fe(a,h,r,s)!==z.right)return!1;const l=e-i.x,u=t-i.y;return fe(n.x,n.y,l,u)===z.left&&_e(l,u)>o},Ue=(e,t,i,n,r)=>{const s=r,o=-n,a=_e(s,o);if(0===a)return!1;const h=(e*s+t*o)/a;return h>0&&Math.abs(h)>i},Ge=({x:e,y:t,radius:i},{x:n,y:r,points:s,edges:o})=>{const a=e-n,h=t-r,l=s.length;for(let e=0;e<l;e++){const t=s[e],n=a-t.x,r=h-t.y,u=0===e?l-1:e-1,c=(e+1)%l,d=o[e];if(Ie(a,h,s[u],o[u],n,r,i,d.x,d.y))return!1;if(Le(a,h,s[c],o[c],n,r,i,d.x,d.y))return!1;if(Ue(n,r,i,d.x,d.y))return!1}return!0},Ne=(e,t)=>ue(se(e),se(t)),Oe=(e,t)=>ue(se(e),(({x:e,y:t,points:i})=>i.map(({x:i,y:n})=>({x:i+e,y:n+t})))(t)),Ve=(e,t)=>ge(e,t),ze=(e,t)=>{if(t.left>e.right||t.top>e.bottom)return null;if(e.left>t.right||e.top>t.bottom)return null;const i=Math.min(e.right,t.right)-Math.max(e.left,t.left),n=Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top),r=e.left+.5*e.width,s=e.top+.5*e.height,o=t.left+.5*t.width,a=t.top+.5*t.height;let h,l,u;i<n?(u=i,h=o<r?-1:1,l=0):(u=n,h=0,l=a<s?-1:1);const c=new it(h,l),d=new it(h*u,l*u);return{shapeA:e,shapeB:t,overlap:u,shapeAinB:t.containsRect(e),shapeBinA:e.containsRect(t),projectionN:c,projectionV:d}},qe=(e,t)=>{const i=t.position.clone().subtract(e.x,e.y),n=i.length,r=e.radius+t.radius-n;if(r<0)return i.destroy(),null;const s=i.normalize(),o=s.clone().multiply(r);return{shapeA:e,shapeB:t,overlap:r,shapeAinB:e.radius<=t.radius&&n<=t.radius-e.radius,shapeBinA:t.radius<=e.radius&&n<=e.radius-t.radius,projectionN:s,projectionV:o}},We=(e,t,i=!1)=>{const n=e.radius,r=Math.max(t.left,Math.min(e.x,t.right)),s=Math.max(t.top,Math.min(e.y,t.bottom)),o=e.x-r,a=e.y-s,h=o*o+a*a;if(h>n*n)return null;const l=Math.sqrt(h),u=n-l,c=t.width/2,d=t.height/2,_=Math.min(c,d),f=Math.max(c,d),p=j(e.x,e.y,t.left+c,t.top+d),m=n<=_&&p<=_-n,g=f<=n&&p<=n-f;let y,w;if(l>0)y=o/l,w=a/l;else{const i=e.x-t.left,n=t.right-e.x,r=e.y-t.top,s=t.bottom-e.y;Math.min(i,n)<Math.min(r,s)?(y=i<n?-1:1,w=0):(y=0,w=r<s?-1:1)}const x=i?-y:y,v=i?-w:w,b=e.position.clone().set(x,v),S=e.position.clone().set(x*u,v*u);return{shapeA:i?t:e,shapeB:i?e:t,overlap:u,shapeAinB:i?g:m,shapeBinA:i?m:g,projectionN:b,projectionV:S}},Ye=(e,t,i=!1)=>{if(!ke(t,e))return null;const n=Math.max(t.left,Math.min(e.x,t.right)),r=Math.max(t.top,Math.min(e.y,t.bottom)),s=e.x-n,o=e.y-r,a=Math.sqrt(s*s+o*o);let h,l,u;if(a>0){h=s/a,l=o/a;u=1/Math.sqrt(h*h/(e.rx*e.rx)+l*l/(e.ry*e.ry))-a}else{const i=e.x-t.left,n=t.right-e.x,r=e.y-t.top,s=t.bottom-e.y,o=Math.min(i,n),a=Math.min(r,s);o<a?(h=i<n?-1:1,l=0,u=o+e.rx):(h=0,l=r<s?-1:1,u=a+e.ry)}const c=i?-h:h,d=i?-l:l,_=e.position.clone().set(c,d),f=e.position.clone().set(c*u,d*u);return{shapeA:i?t:e,shapeB:i?e:t,overlap:u,shapeAinB:!1,shapeBinA:!1,projectionN:_,projectionV:f}},$e=(e,t,i=!1)=>{if(!Fe(t,e))return null;const n=e.x-t.x,r=e.y-t.y,s=Math.sqrt(n*n+r*r);let o,a,h;if(s>0){o=n/s,a=r/s;h=1/Math.sqrt(o*o/(e.rx*e.rx)+a*a/(e.ry*e.ry))+t.radius-s}else e.rx<=e.ry?(o=1,a=0,h=e.rx+t.radius):(o=0,a=1,h=e.ry+t.radius);const l=i?-o:o,u=i?-a:a,c=e.position.clone().set(l,u),d=e.position.clone().set(l*h,u*h);return{shapeA:i?t:e,shapeB:i?e:t,overlap:h,shapeAinB:!1,shapeBinA:!1,projectionN:c,projectionV:d}},Xe=(e,t,i=!1)=>{const n=t.radius,r=e.points,s=t.x-e.x,o=t.y-e.y,a=t.position.clone().set(0,0),h=r.length;let l=!0,u=!0,c=1/0;for(let e=0;e<h;e++){const t=r[e],i=r[(e+1)%h],d=i.x-t.x,_=i.y-t.y,f=s-t.x,p=o-t.y,m=fe(d,_,f,p),g=_e(f,p);if(g>n&&(l=!1),m===z.left){const i=r[0===e?h-1:e-1],l=t.x-i.x,d=t.y-i.y,_=s-i.x,m=o-i.y;if(fe(l,d,_,m)===z.right){if(g>n)return a.destroy(),null;const e=n-g;Math.abs(e)<Math.abs(c)&&(c=e,a.set(f,p).normalize()),u=!1}}else if(m===z.right){const t=r[(e+2)%h],l=t.x-i.x,d=t.y-i.y,_=s-i.x,f=o-i.y,p=_e(_,f);if(fe(l,d,_,f)===z.left){if(p>n)return a.destroy(),null;const e=n-p;Math.abs(e)<Math.abs(c)&&(c=e,a.set(_,f).normalize()),u=!1}}else{const e=_,t=-d,i=_e(e,t),r=0===i?0:(f*e+p*t)/i;if(r>0&&Math.abs(r)>n)return a.destroy(),null;(r>=0||n-r<2*n)&&(u=!1);const s=n-r;Math.abs(s)<Math.abs(c)&&(c=s,a.set(e,t).normalize())}}const d=a.clone().multiply(c);return{shapeA:i?t:e,shapeB:i?e:t,overlap:c,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:d}},He=(e,t)=>{if(!Ne(e,t))return null;const i=e.x-t.x,n=e.y-t.y,r=Math.sqrt(i*i+n*n);let s,o,a;if(r>0){s=i/r,o=n/r;a=Math.sqrt((s*e.rx)**2+(o*e.ry)**2)+Math.sqrt((s*t.rx)**2+(o*t.ry)**2)-r}else e.rx<=e.ry?(s=1,o=0,a=e.rx+t.rx):(s=0,o=1,a=e.ry+t.ry);if(a<=0)return null;const h=e.position.clone().set(s,o),l=e.position.clone().set(s*a,o*a);return{shapeA:e,shapeB:t,overlap:a,shapeAinB:!1,shapeBinA:!1,projectionN:h,projectionV:l}},je=(e,t)=>{const i=e.getNormals(),n=t.getNormals(),r=(i[0]||n[0]).clone(),s=new me,o=new me;let a,h,l,u=1/0,c=!0,d=!0;for(const n of i){if(e.project(n,s),t.project(n,o),!s.overlaps(o))return r.destroy(),null;l=s.getOverlap(o),a=o.containsInterval(s),h=s.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(s.min-o.min),Math.abs(s.max-o.max))),l<u&&(u=l,r.copy(n))}for(const i of n){if(e.project(i,s),t.project(i,o),!s.overlaps(o))return r.destroy(),null;l=s.getOverlap(o),a=o.containsInterval(s),h=s.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(s.min-o.min),Math.abs(s.max-o.max))),l<u&&(u=l,r.copy(i))}const _=r.clone().multiply(u,u);return{shapeA:e,shapeB:t,overlap:u,shapeAinB:c,shapeBinA:d,projectionN:r,projectionV:_}},Ke={intersects:{circleCircle:De,circleEllipse:Fe,circlePoly:Ge,ellipseEllipse:Ne,ellipsePoly:Oe,lineCircle:Te,lineEllipse:Me,lineLine:Be,linePoly:Pe,lineRect:Ce,pointCircle:ve,pointEllipse:be,pointLine:we,pointPoint:ye,pointPoly:Se,pointRect:xe,polyPoly:Ve,rectCircle:Ee,rectEllipse:ke,rectPoly:Re,rectRect:Ae},resolve:{circleCircle:qe,circleRectangle:We,ellipseCircle:$e,ellipseEllipse:He,ellipseRectangle:Ye,polygonCircle:Xe,rectangleRectangle:ze}};class Qe extends te{_x;_y;_owner;_channel;constructor(e,t=0,i=0,n=0){super(),this._x=i,this._y=n,this._owner=e,this._channel=t}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._owner?._onObservableChange(this._channel))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._owner?._onObservableChange(this._channel))}get angle(){return Math.atan2(this._y,this._x)}set angle(e){const t=this.length;this.set(Math.cos(e)*t,Math.sin(e)*t)}get length(){return Math.sqrt(this._x*this._x+this._y*this._y)}set length(e){const t=this.angle;this.set(Math.cos(t)*e,Math.sin(t)*e)}set(e=this._x,t=this._y){return this._x===e&&this._y===t||(this._x=e,this._y=t,this._owner?._onObservableChange(this._channel)),this}add(e,t=e){return this.set(this._x+e,this._y+t)}subtract(e,t=e){return this.set(this._x-e,this._y-t)}scale(e,t=e){return this.set(this._x*e,this._y*t)}divide(e,t=e){return 0!==e&&0!==t?this.set(this._x/e,this._y/t):this}clone(){return new Qe(this._owner,this._channel,this._x,this._y)}copy(e){return this.set(e.x,e.y)}destroy(){this._owner=null}}let Ze=null;const Je=new Qe(null);class et{collisionType=e.CollisionType.Rectangle;_position;_size;_normals=null;_normalsDirty=!1;constructor(e=0,t=e,i=0,n=i){this._position=new Qe(this,0,e,t),this._size=new l(i,n)}_onObservableChange(){this._normalsDirty=!0}get position(){return this._position}set position(e){this._position.copy(e)}get x(){return this._position.x}set x(e){this._position.x=e,this._normalsDirty=!0}get y(){return this._position.y}set y(e){this._position.y=e,this._normalsDirty=!0}get size(){return this._size}set size(e){this._size.copy(e),this._normalsDirty=!0}get width(){return this._size.width}set width(e){this._size.width=e,this._normalsDirty=!0}get height(){return this._size.height}set height(e){this._size.height=e,this._normalsDirty=!0}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}setPosition(e,t){return this._position.set(e,t),this._normalsDirty=!0,this}setSize(e,t){return this._size.set(e,t),this._normalsDirty=!0,this}set(e,t,i,n){return this.setPosition(e,t),this.setSize(i,n),this}copy(e){return this.position=e.position,this.size=e.size,this}clone(){return new et(this.x,this.y,this.width,this.height)}equals({x:e,y:t,width:i,height:n}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t||void 0!==i&&this.width!==i||void 0!==n&&this.height!==n)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new it,new it,new it,new it])),this._normalsDirty=!1),this._normals}project(e,t=new me){const i=e.dot(this.left,this.top),n=e.dot(this.right,this.top),r=e.dot(this.right,this.bottom),s=e.dot(this.left,this.bottom);return t.set(Math.min(i,n,r,s),Math.max(i,n,r,s))}transform(e,t=this){const i=Je.set(this.left,this.top).transform(e);let n=i.x,r=i.x,s=i.y,o=i.y;return i.set(this.left,this.bottom).transform(e),n=Math.min(n,i.x),s=Math.min(s,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(e),n=Math.min(n,i.x),s=Math.min(s,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(e),n=Math.min(n,i.x),s=Math.min(s,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),t.set(n,s,r-n,o-s)}contains(e,t){return xe(Je.set(e,t),this)}containsRect(e){return H(e.left,this.left,this.right)&&H(e.right,this.left,this.right)&&H(e.top,this.top,this.bottom)&&H(e.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return t.isAlignedBox?Ae(this,t.getBounds()):ge(this,t);case e.CollisionType.Rectangle:return Ae(this,t);case e.CollisionType.Polygon:return Re(this,t);case e.CollisionType.Circle:return Ee(this,t);case e.CollisionType.Ellipse:return ke(this,t);case e.CollisionType.Line:return Ce(t,this);case e.CollisionType.Point:return xe(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return t.isAlignedBox?ze(this,t.getBounds()):je(this,t);case e.CollisionType.Rectangle:return ze(this,t);case e.CollisionType.Polygon:return je(this,t);case e.CollisionType.Circle:return We(t,this,!0);case e.CollisionType.Ellipse:return Ye(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(e){e[0].set(this.right-this.left,0).rperp().normalize(),e[1].set(0,this.bottom-this.top).rperp().normalize(),e[2].set(this.left-this.right,0).rperp().normalize(),e[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===Ze&&(Ze=new et),Ze}}let tt=null;class it extends te{collisionType=e.CollisionType.Point;x;y;constructor(e=0,t=0){super(),this.x=e,this.y=t}clone(){return new it(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return xe(this,t.getBounds());case e.CollisionType.Rectangle:return xe(this,t);case e.CollisionType.Polygon:return Se(this,t);case e.CollisionType.Circle:return ve(this,t);case e.CollisionType.Ellipse:return be(this,t);case e.CollisionType.Line:return we(this,t);case e.CollisionType.Point:return ye(this,t);default:return!1}}collidesWith(e){return null}getBounds(){return et.temp.set(this.x,this.y,0,0)}contains(e,t){return ye(it.temp.set(e,t),this)}getNormals(){return[this.clone().rperp().normalize()]}project(e,t=new me){return t}destroy(){}static get temp(){return null===tt&&(tt=new it),tt}static zero=new it(0,0);static one=new it(1,1);static add(e,t){return new it(e.x+t.x,e.y+t.y)}static subtract(e,t){return new it(e.x-t.x,e.y-t.y)}static multiply(e,t){return new it(e.x*t.x,e.y*t.y)}static divide(e,t){return new it(e.x/t.x,e.y/t.y)}}const nt={distanceModel:"linear",refDistance:50,maxDistance:1e3,rolloffFactor:1};class rt{_audioContext;_output;_manager;_bus;_volume;_ended=!1;_stopTimer=null;onEnd=new x;_spatialConfig;_panner=null;_position=null;_followNode=null;_spatialRegistered=!1;_effects=[];constructor(e){this._audioContext=e.audioContext,this._output=e.output,this._bus=e.bus,this._manager=e.manager,this._volume=Y(e.volume,0,1),this._spatialConfig={...nt,...e.spatial},this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01),!1!==e.autoConnect&&this._connectOutput()}get ended(){return this._ended}get output(){return this._output}get volume(){return this._volume}set volume(e){this._volume=Y(e,0,1),this._ended||this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01)}get bus(){return this._bus}set bus(e){e!==this._bus&&(this._ended?this._bus=e:(this._tail().disconnect(),this._bus=e,this._connectOutput()))}addEffect(e){return this._ended||(this._effects.push(e),this._rebuildEffectChain()),this}removeEffect(e){const t=this._effects.indexOf(e);return-1!==t&&(this._effects.splice(t,1),e.outputNode.disconnect(),this._rebuildEffectChain()),this}fade(e,t){if(this._ended)return;const i=Y(e,0,1);this._volume=i;const n=this._audioContext,r=this._output;t<=0?r.gain.setTargetAtTime(i,n.currentTime,.01):(r.gain.cancelScheduledValues(n.currentTime),r.gain.setValueAtTime(r.gain.value,n.currentTime),r.gain.linearRampToValueAtTime(i,n.currentTime+t/1e3))}stop(e){if(!this._ended){if(void 0!==e&&e>0){const t=this._audioContext,i=this._output;return i.gain.cancelScheduledValues(t.currentTime),i.gain.setValueAtTime(i.gain.value,t.currentTime),i.gain.linearRampToValueAtTime(0,t.currentTime+e/1e3),this._clearStopTimer(),void(this._stopTimer=setTimeout(()=>{this._stopTimer=null,this._finish()},e))}this._finish()}}get position(){return this._position}set position(e){this._ended||(null!==e?(null===this._position?this._position=new it(e.x,e.y):this._position.set(e.x,e.y),this._ensurePanner(),this._tickSpatial()):null!==this._position&&(this._position.destroy(),this._position=null))}follow(e){this._ended||(this._followNode=e,null!==e&&(this._ensurePanner(),this._tickSpatial()))}_tickSpatial(){if(null===this._panner||this._ended)return;let e,t;if(null!==this._followNode){const i=this._followNode.getGlobalTransform();e=i.x,t=i.y}else{if(null===this._position)return;e=this._position.x,t=this._position.y}const i=this._panner,n=this._audioContext.currentTime;i.positionX?(i.positionX.setValueAtTime(e,n),i.positionY.setValueAtTime(t,n),i.positionZ.setValueAtTime(0,n)):i.setPosition&&i.setPosition(e,t,0)}_tail(){const e=this._effects[this._effects.length-1];return void 0!==e?e.outputNode:this._output}_connectOutput(){this._connectTail(this._tail())}_connectTail(e){const t=this._bus._getInputNode();null===t?(e.connect(this._audioContext.destination),this._bus.onceSetup(()=>{if(this._ended)return;const e=this._bus._getInputNode();if(null!==e){const t=this._tail();t.disconnect(),t.connect(e)}})):e.connect(t)}_rebuildEffectChain(){if(this._ended)return;this._output.disconnect();for(const e of this._effects)e.outputNode.disconnect();let e=this._output;for(const t of this._effects)e.connect(t.inputNode),e=t.outputNode;this._connectTail(e)}_clearStopTimer(){null!==this._stopTimer&&(clearTimeout(this._stopTimer),this._stopTimer=null)}_ensurePanner(){if(null!==this._panner||this._ended)return;const e=this._audioContext.createPanner();e.panningModel="equalpower",e.distanceModel=this._spatialConfig.distanceModel,e.refDistance=this._spatialConfig.refDistance,e.maxDistance=this._spatialConfig.maxDistance,e.rolloffFactor=this._spatialConfig.rolloffFactor,this._routeThroughPanner(e),this._panner=e,this._spatialRegistered||(this._spatialRegistered=!0,this._manager._registerSpatial(this))}_finish(){if(!this._ended){this._ended=!0,this._clearStopTimer(),this._teardownSource(),this._panner?.disconnect(),this._output.disconnect();for(const e of this._effects)e.outputNode.disconnect();this._effects.length=0,null!==this._position&&(this._position.destroy(),this._position=null),this._followNode=null,this.onEnd.dispatch(),this.onEnd.destroy()}}}class st extends rt{_oscillator;_envelopeGain;_envelope;_frequency;_type;_detune;_playbackRate=1;constructor(e){super(e);const t=this._audioContext,i=t.currentTime;this._frequency=e.frequency,this._type=e.type,this._detune=e.detune,this._envelope=e.envelope,this._envelopeGain=t.createGain(),this._envelopeGain.connect(this._output);const n=t.createOscillator();n.type=e.type,n.frequency.value=e.frequency,n.detune.value=e.detune,n.connect(this._envelopeGain),n.onended=()=>this._finish(),this._envelope?this._envelope.trigger(this._envelopeGain.gain,i):this._envelopeGain.gain.value=1,n.start(i),this._oscillator=n}get frequency(){return this._frequency}set frequency(e){this._frequency=e,this._ended||this._oscillator.frequency.setTargetAtTime(e,this._audioContext.currentTime,.01)}get type(){return this._type}set type(e){this._type=e,this._ended||(this._oscillator.type=e)}get playbackRate(){return this._playbackRate}set playbackRate(e){this._playbackRate=e}get detune(){return this._detune}set detune(e){this._detune=e,this._ended||this._oscillator.detune.setTargetAtTime(e,this._audioContext.currentTime,.01)}stop(e){if(!this._ended)if(void 0!==e&&e>0)super.stop(e);else{if(this._envelope){const e=this._audioContext.currentTime;this._envelope.release(this._envelopeGain.gain,e);const t=e+this._envelope.releaseMs/1e3;try{this._oscillator.stop(t)}catch{}return}super.stop()}}_routeThroughPanner(e){this._envelopeGain.disconnect(),this._envelopeGain.connect(e),e.connect(this._output)}_teardownSource(){this._oscillator.onended=null;try{this._oscillator.stop(0)}catch{}this._oscillator.disconnect(),this._envelopeGain.disconnect()}}class ot{onEnd=new x;_bus;_output=null;constructor(e){this._bus=e}get ended(){return!0}get output(){return this._output??=L().createGain()}get volume(){return 0}set volume(e){}get bus(){return this._bus}set bus(e){}fade(e,t){}stop(e){}addEffect(e){return this}removeEffect(e){return this}}class at extends rt{_buffer;_window;_source;_loop;_playbackRate;_detune;_offsetAtStart;_startedAt;constructor(e){super(e),this._buffer=e.buffer,this._window=e.window,this._loop=e.loop,this._playbackRate=e.playbackRate,this._detune=e.detune,this._offsetAtStart=e.offset,this._startedAt=this._audioContext.currentTime,this._source=this._startSource(e.offset)}get duration(){return this._window.end-this._window.base}get time(){if(this._ended)return 0;const e=this.duration,t=(this._audioContext.currentTime-this._startedAt)*this._playbackRate;let i=this._offsetAtStart-this._window.base+t;return this._loop&&e>0&&(i%=e,i<0&&(i+=e)),Y(i,0,e)}set time(e){this.seek(e)}seek(e){if(this._ended)return;const t=this._window.base+Y(e,0,this.duration);this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect(),this._source=this._startSource(t),this._offsetAtStart=t,this._startedAt=this._audioContext.currentTime}get loop(){return this._loop}set loop(e){this._loop===e||this._ended?this._loop=e:(this._loop=e,this._source.loop=e,e&&(this._source.loopStart=this._window.loopStart,this._source.loopEnd=this._window.loopEnd))}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Y(e,.1,20);if(this._playbackRate===t||this._ended)return void(this._playbackRate=t);const i=this.time;this._playbackRate=t,this._offsetAtStart=this._window.base+i,this._startedAt=this._audioContext.currentTime,this._source.playbackRate.setTargetAtTime(t,this._audioContext.currentTime,.01)}get detune(){return this._detune}set detune(e){this._detune=e,this._ended||this._source.detune.setTargetAtTime(e,this._audioContext.currentTime,.01)}_routeThroughPanner(e){this._source.disconnect(),this._source.connect(e),e.connect(this._output)}_teardownSource(){this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect()}_startSource(e){const t=this._audioContext.createBufferSource();t.buffer=this._buffer,t.loop=this._loop,t.playbackRate.value=this._playbackRate,t.detune.value=this._detune,this._loop&&(t.loopStart=this._window.loopStart,t.loopEnd=this._window.loopEnd),t.connect(this._panner??this._output),t.onended=()=>this._finish();const i=this._loop?void 0:this._window.end-e;return!this._loop&&void 0!==i&&i>0?t.start(0,e,i):t.start(0,e),t}}var ht;e.SoundPoolStrategy=void 0,(ht=e.SoundPoolStrategy||(e.SoundPoolStrategy={})).FirstInFirstOut="fifo",ht.LeastRecentlyUsed="lru",ht.LowestPriority="priority";class lt{_audioBuffer;_sprites=new Map;_clipStart=0;_clipEnd=0;volume;loop;playbackRate;muted;_poolSize;_poolStrategy;_priority;_position=null;_velocity=null;_distanceModel="linear";_refDistance=50;_maxDistance=1e3;_rolloffFactor=1;_activeVoices=[];get audioBuffer(){return this._audioBuffer}get duration(){return this._clipEnd-this._clipStart}get poolSize(){return this._poolSize}set poolSize(e){this.setPoolSize(e)}get poolStrategy(){return this._poolStrategy}set poolStrategy(e){this._poolStrategy=e}get priority(){return this._priority}set priority(e){this._priority=e}get position(){return this._position}set position(e){null!==e?null===this._position?this._position=new it(e.x,e.y):this._position.set(e.x,e.y):null!==this._position&&(this._position.destroy(),this._position=null)}get velocity(){return this._velocity}set velocity(e){null===e?null!==this._velocity&&(this._velocity.destroy(),this._velocity=null):null===this._velocity?this._velocity=new it(e.x,e.y):this._velocity.set(e.x,e.y)}get distanceModel(){return this._distanceModel}set distanceModel(e){this._distanceModel=e}get refDistance(){return this._refDistance}set refDistance(e){this._refDistance=Math.max(0,e)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance=Math.max(0,e)}get rolloffFactor(){return this._rolloffFactor}set rolloffFactor(e){this._rolloffFactor=Math.max(0,e)}constructor(t,i={}){this._audioBuffer=t,this._clipEnd=t.duration;const{poolSize:n,poolStrategy:r,priority:s,sprites:o,volume:a,loop:h,playbackRate:l,muted:u,distanceModel:c,refDistance:d,maxDistance:_,rolloffFactor:f}=i;this.volume=Y(a??1,0,1),this.loop=h??!1,this.playbackRate=Y(l??1,.1,20),this.muted=u??!1,this._poolSize=Math.max(1,Math.floor(n??8)),this._poolStrategy=r??e.SoundPoolStrategy.FirstInFirstOut,this._priority=s??0,void 0!==c&&(this._distanceModel=c),void 0!==d&&(this._refDistance=Math.max(0,d)),void 0!==_&&(this._maxDistance=Math.max(0,_)),void 0!==f&&(this._rolloffFactor=Math.max(0,f)),o&&this.setSprites(o)}setPoolSize(e){const t=Math.max(1,Math.floor(e));return this._poolSize===t||(this._poolSize=t,this._trimActiveVoices()),this}setSprites(e){this._sprites.clear();for(const[t,i]of Object.entries(e))this.defineSprite(t,i);return this}defineSprite(e,t){if(0===e.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=t.start,n=t.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${e}" has an invalid start time (${i}).`);if(!Number.isFinite(n)||n<=i)throw new Error(`Sound sprite "${e}" has an invalid end time (${n}).`);if(n>this.duration)throw new Error(`Sound sprite "${e}" ends at ${n}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(e,{start:i,end:n,loop:t.loop??!1}),this}hasSprite(e){return this._sprites.has(e)}removeSprite(e){return this._sprites.delete(e),this}clip(e,t){const i=Y(e,0,this._audioBuffer.duration),n=Y(i+t,i,this._audioBuffer.duration),r=new lt(this._audioBuffer,{volume:this.volume,loop:this.loop,playbackRate:this.playbackRate,muted:this.muted,poolSize:this._poolSize,poolStrategy:this._poolStrategy,priority:this._priority,distanceModel:this._distanceModel,refDistance:this._refDistance,maxDistance:this._maxDistance,rolloffFactor:this._rolloffFactor});return r._clipStart=i,r._clipEnd=n,r}_createVoice(e,t){const i=this._clipStart+Math.max(0,t.time??0);return i>=this._clipEnd?new ot(t.bus??e.sound):this._buildVoice(e,t,i,{base:this._clipStart,end:this._clipEnd,loopStart:this._clipStart,loopEnd:this._clipEnd})}_createSpriteVoice(e,t,i={}){const n=this._sprites.get(t);if(!n)throw new Error(`Sound sprite "${t}" is not defined.`);const r=Math.max(0,i.time??0),s=n.start+r;if(s>=n.end)throw new Error(`Sound sprite "${t}" offset (${r}s) exceeds clip duration (${n.end-n.start}s).`);const o=i.loop??n.loop;return this._buildVoice(e,{...i,loop:o},s,{base:n.start,end:n.end,loopStart:n.start,loopEnd:n.end})}_buildVoice(e,t,i,n){const r=t.loop??this.loop,s=Y(t.playbackRate??this.playbackRate,.1,20),o=t.detune??0,a=Y(t.muted?0:t.volume??(this.muted?0:this.volume),0,1),h=t.bus??e.sound;if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const e=this._pickEvictionVictim(),t=this._activeVoices[e];t&&(this._activeVoices.splice(e,1),t.voice.stop())}const l=L(),u=l.createGain(),c=new at({audioContext:l,output:u,bus:h,manager:e,volume:a,spatial:{distanceModel:this._distanceModel,refDistance:this._refDistance,maxDistance:this._maxDistance,rolloffFactor:this._rolloffFactor},buffer:this._audioBuffer,loop:r,playbackRate:s,detune:o,offset:i,window:n});null!==this._position&&(c.position=this._position);const d={voice:c,startedAt:l.currentTime,effectiveDuration:r?1/0:n.end-i};return c.onEnd.add(()=>{const e=this._activeVoices.indexOf(d);-1!==e&&this._activeVoices.splice(e,1)}),this._activeVoices.push(d),c}_stopAllVoices(){const e=[...this._activeVoices];this._activeVoices.length=0;for(const t of e)t.voice.stop()}destroy(){this._stopAllVoices(),this._sprites.clear(),null!==this._position&&(this._position.destroy(),this._position=null),null!==this._velocity&&(this._velocity.destroy(),this._velocity=null)}_pruneEndedVoices(){for(let e=this._activeVoices.length-1;e>=0;e--)!0===this._activeVoices[e]?.voice.ended&&this._activeVoices.splice(e,1)}_pickEvictionVictim(){switch(this._poolStrategy){case e.SoundPoolStrategy.LeastRecentlyUsed:return this._pickClosestToEnd();case e.SoundPoolStrategy.LowestPriority:case e.SoundPoolStrategy.FirstInFirstOut:default:return 0}}_pickClosestToEnd(){const e=U()?L().currentTime:0;let t=1/0,i=0;for(let n=0;n<this._activeVoices.length;n++){const r=this._activeVoices[n];if(void 0===r)continue;const s=e-r.startedAt,o=r.effectiveDuration-s;o<t&&(t=o,i=n)}return i}_trimActiveVoices(){for(;this._activeVoices.length>this._poolSize;){const e=this._pickEvictionVictim(),t=this._activeVoices[e];if(!t)break;this._activeVoices.splice(e,1),t.voice.stop()}}}class ut{frequency;type;detune;envelope;volume;muted;_poolSize;_poolStrategy;priority;_activeVoices=[];get poolSize(){return this._poolSize}set poolSize(e){this._poolSize=Math.max(1,Math.floor(e))}get poolStrategy(){return this._poolStrategy}set poolStrategy(e){this._poolStrategy=e}constructor(t={}){this.frequency=t.frequency??440,this.type=t.type??"sine",this.detune=t.detune??0,this.envelope=t.envelope??null,this.volume=Y(t.volume??1,0,1),this.muted=t.muted??!1,this._poolSize=Math.max(1,Math.floor(t.poolSize??8)),this._poolStrategy=t.poolStrategy??e.SoundPoolStrategy.FirstInFirstOut,this.priority=t.priority??0}setNote(e){return this.frequency=ut.midiToFrequency(e),this}static midiToFrequency(e){return 440*Math.pow(2,(e-69)/12)}_createVoice(e,t){const i=t.bus??e.sound;if(!U())return new ot(i);if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const e=this._pickEvictionVictim(),t=this._activeVoices[e];t&&(this._activeVoices.splice(e,1),t.voice.stop())}const n=L(),r=n.createGain(),s=t.detune??this.detune,o=Y(t.muted?0:t.volume??(this.muted?0:this.volume),0,1),a=new st({audioContext:n,output:r,bus:i,manager:e,volume:o,frequency:this.frequency,type:this.type,detune:s,envelope:this.envelope}),h={voice:a,startedAt:n.currentTime};return a.onEnd.add(()=>{const e=this._activeVoices.indexOf(h);-1!==e&&this._activeVoices.splice(e,1)}),this._activeVoices.push(h),a}stopAll(){const e=[...this._activeVoices];this._activeVoices.length=0;for(const t of e)t.voice.stop();return this}destroy(){this.stopAll()}_pruneEndedVoices(){for(let e=this._activeVoices.length-1;e>=0;e--)!0===this._activeVoices[e]?.voice.ended&&this._activeVoices.splice(e,1)}_pickEvictionVictim(){if(this._poolStrategy===e.SoundPoolStrategy.LeastRecentlyUsed){let e=0,t=1/0;for(let i=0;i<this._activeVoices.length;i++){const n=this._activeVoices[i];void 0!==n&&n.startedAt<t&&(t=n.startedAt,e=i)}return e}return 0}}class ct{_stream;constructor(e){this._stream=e}get stream(){return this._stream}static async open(e={}){if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("AudioInput.open: getUserMedia is not available in this environment.");const t={};void 0!==e.deviceId&&(t.deviceId=e.deviceId),void 0!==e.echoCancellation&&(t.echoCancellation=e.echoCancellation),void 0!==e.noiseSuppression&&(t.noiseSuppression=e.noiseSuppression),void 0!==e.autoGainControl&&(t.autoGainControl=e.autoGainControl);const i=await navigator.mediaDevices.getUserMedia({audio:!(Object.keys(t).length>0)||t});return new ct(i)}close(){for(const e of this._stream.getTracks())e.stop()}}class dt{position=new it(0,0);velocity=new it(0,0);target=null;_audioListener=null;_ctx=null;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(){U()?this._setup(L()):I.add(this._onAudioContextReady)}_tick(){if(null!==this.target&&this._readTargetPosition(),null!==this._audioListener&&null!==this._ctx){const e=this._ctx.currentTime,t=this._audioListener;t.positionX&&t.positionY&&t.positionZ?(t.positionX.setValueAtTime(this.position.x,e),t.positionY.setValueAtTime(this.position.y,e),t.positionZ.setValueAtTime(0,e)):t.setPosition&&t.setPosition(this.position.x,this.position.y,0)}}destroy(){I.remove(this._onAudioContextReady),this.position.destroy(),this.velocity.destroy(),this.target=null,this._audioListener=null,this._ctx=null}_readTargetPosition(){const e=this.target;if(null===e)return;const t=e;if("function"==typeof t.getGlobalTransform){const e=t.getGlobalTransform();return void this.position.set(e.x,e.y)}const i=e;if(void 0!==i.center&&"object"==typeof i.center)return void this.position.set(i.center.x,i.center.y);const n=e;this.position.set(n.x,n.y)}_setup(e){this._ctx=e,this._audioListener=e.listener;const t=e.currentTime,i=e.listener;i.forwardX&&i.forwardY&&i.forwardZ&&i.upX&&i.upY&&i.upZ?(i.forwardX.setValueAtTime(0,t),i.forwardY.setValueAtTime(0,t),i.forwardZ.setValueAtTime(-1,t),i.upX.setValueAtTime(0,t),i.upY.setValueAtTime(1,t),i.upZ.setValueAtTime(0,t)):i.setOrientation&&i.setOrientation(0,0,-1,0,1,0)}}class _t extends rt{_sourceNode;_stream;constructor(e){super({...e,autoConnect:!1}),this._sourceNode=e.sourceNode,this._stream=e.stream,this._sourceNode.connect(this._output)}routeTo(e){return this._ended||(this._tail().disconnect(),this._bus=e,this._connectOutput()),this}async record(e){const t=new MediaRecorder(this._stream),i=[];return t.addEventListener("dataavailable",e=>{e.data.size>0&&i.push(e.data)}),new Promise((n,r)=>{t.addEventListener("stop",()=>{(async()=>{try{const e=new Blob(i,{type:t.mimeType||"audio/webm"}),r=await G(await e.arrayBuffer());n(new lt(r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}})()}),t.addEventListener("error",()=>r(new Error("Recording failed."))),t.start(),setTimeout(()=>{"inactive"!==t.state&&t.stop()},Math.max(0,e))})}_routeThroughPanner(e){this._sourceNode.disconnect(),this._sourceNode.connect(e),e.connect(this._output)}_teardownSource(){this._sourceNode.disconnect()}}class ft{order=300;master;music;sound;listener;onUnlock=new x;_registered=new Map;_spatial=new Set;_muteOnHidden=!1;constructor(){this.master=new J("master",{parent:null}),this.music=new J("music",{parent:this.master}),this.sound=new J("sound",{parent:this.master}),this.listener=new dt,this._registered.set("master",this.master),this._registered.set("music",this.music),this._registered.set("sound",this.sound),U()?queueMicrotask(()=>this.onUnlock.dispatch()):I.add(()=>{this.onUnlock.dispatch()})}get muteOnHidden(){return this._muteOnHidden}set muteOnHidden(e){this._muteOnHidden=e}get locked(){return!U()}play(e,t){return e._createVoice(this,t??{})}open(e){const t=L(),i=t.createMediaStreamSource(e.stream),n=t.createGain();return new _t({audioContext:t,output:n,bus:this.sound,manager:this,volume:1,sourceNode:i,stream:e.stream})}update(e){this.listener._tick();for(const e of this._spatial)e.ended?this._spatial.delete(e):e._tickSpatial()}_registerSpatial(e){this._spatial.add(e)}_applyVisibility(e){this._muteOnHidden&&(this.master.muted=!e)}registerBus(e){if(this._registered.has(e.name))throw new Error(`Audio bus "${e.name}" is already registered.`);return this._registered.set(e.name,e),this}unregisterBus(e){if(e===this.master||e===this.music||e===this.sound)throw new Error(`Cannot unregister built-in bus "${e.name}".`);return this._registered.get(e.name)!==e||(this._registered.delete(e.name),e.destroy()),this}getBus(e){const t=this._registered.get(e);if(!t)throw new Error(`Audio bus "${e}" is not registered.`);return t}hasBus(e){return this._registered.has(e)}destroy(){this.listener.destroy(),this._spatial.clear();for(const e of this._registered.values())e.destroy();this._registered.clear()}}class pt extends rt{_element;_sourceNode;_detune=0;_onEnded=()=>this._finish();_unlockHandler=null;constructor(e){super(e),this._element=e.element,this._sourceNode=e.sourceNode,this._sourceNode.connect(this._output),this._element.loop=e.loop,this._element.playbackRate=e.playbackRate,void 0!==e.startTime&&(this._element.currentTime=Math.max(0,e.startTime)),this._element.addEventListener("ended",this._onEnded),this._startPlayback()}get duration(){return this._element.duration}get time(){return this._element.currentTime}set time(e){this.seek(e)}seek(e){this._ended||(this._element.currentTime=Math.max(0,e))}pause(){this._ended||this._element.pause()}resume(){this._ended||this._element.play()}get paused(){return this._element.paused}get loop(){return this._element.loop}set loop(e){this._element.loop=e}get playbackRate(){return this._element.playbackRate}set playbackRate(e){this._element.playbackRate=Y(e,.1,20)}get detune(){return this._detune}set detune(e){this._detune=e}_routeThroughPanner(e){this._sourceNode.disconnect(),this._sourceNode.connect(e),e.connect(this._output)}_teardownSource(){this._element.removeEventListener("ended",this._onEnded),this._clearUnlockHandler(),this._element.pause(),this._sourceNode.disconnect()}_startPlayback(){U()?this._element.play():(this._unlockHandler=()=>{this._clearUnlockHandler(),this._ended||this._element.play()},I.add(this._unlockHandler))}_clearUnlockHandler(){null!==this._unlockHandler&&(I.remove(this._unlockHandler),this._unlockHandler=null)}}class mt{_audioElement;volume;loop;playbackRate;muted;_sourceNode=null;_activeVoice=null;constructor(e,t){this._audioElement=e,this.volume=Y(t?.volume??1,0,1),this.loop=t?.loop??!1,this.playbackRate=Y(t?.playbackRate??1,.1,20),this.muted=t?.muted??!1,void 0!==t?.time&&(this._audioElement.currentTime=Math.max(0,t.time))}get audioElement(){return this._audioElement}get duration(){return this._audioElement.duration}_createVoice(e,t){const i=t.bus??e.music,n=L();null===this._activeVoice||this._activeVoice.ended||this._activeVoice.stop(),null===this._sourceNode?this._sourceNode=n.createMediaElementSource(this._audioElement):this._sourceNode.disconnect();const r=n.createGain(),s=t.loop??this.loop,o=Y(t.playbackRate??this.playbackRate,.1,20),a=Y(t.muted?0:t.volume??(this.muted?0:this.volume),0,1),h=new pt({audioContext:n,output:r,bus:i,manager:e,volume:a,element:this._audioElement,sourceNode:this._sourceNode,loop:s,playbackRate:o,...void 0!==t.time&&{startTime:t.time}});return this._activeVoice=h,h.onEnd.add(()=>{this._activeVoice===h&&(this._activeVoice=null)}),h}destroy(){null!==this._activeVoice&&(this._activeVoice.stop(),this._activeVoice=null),null!==this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=null)}}const gt=new WeakMap,yt=new WeakMap;async function wt(e,t,i){let n=gt.get(e);if(n||(n=new Set,gt.set(e,n)),n.has(t))return;let r=yt.get(e);r||(r=new Map,yt.set(e,r));const s=r.get(t);if(s)return s;const o=new Blob([i],{type:"application/javascript"}),a=URL.createObjectURL(o),h=e.audioWorklet.addModule(a).finally(()=>{URL.revokeObjectURL(a)}).then(()=>{n.add(t),r.delete(t)}).catch(e=>{throw r.delete(t),e});return r.set(t,h),h}const xt=Object.freeze({extensions:Object.freeze([]),renderers:Object.freeze([]),assets:Object.freeze([]),serializers:Object.freeze([])});function vt(e){if(0===e.length)return xt;const t=new Map,i=new Set,n=new Set,r=[],s=[];function o(e){const a=t.get(e.id);if(void 0!==a&&a!==e)throw new Error(`Extension "${e.id}" was provided by multiple descriptor objects.`);if(void 0===a&&t.set(e.id,e),!n.has(e)){if(i.has(e)){const t=[...r.slice(r.indexOf(e)),e].map(e=>e.id).join(" → ");throw new Error(`Extension dependency cycle detected: ${t}`)}i.add(e),r.push(e);for(const t of e.dependencies??[])o(t);r.pop(),i.delete(e),n.add(e),s.push(e)}}for(const t of e)o(t);const a=[],h=[],l=[];for(const e of s){if(e.renderers)for(const t of e.renderers)a.push(t);if(e.assets)for(const t of e.assets)h.push(t);if(e.serializers)for(const t of e.serializers)l.push(t)}return Object.freeze({extensions:Object.freeze(s),renderers:Object.freeze(a),assets:Object.freeze(h),serializers:Object.freeze(l)})}let bt,St=new Map;function Bt(e,t){const i=new Set;for(const n of t){if(0===n.targets.length)throw new Error("A RendererBinding must declare at least one target.");for(const e of n.targets){if(i.has(e))throw new Error(`Two bindings target the same drawable type ${e.name}. Remove one of the conflicting bindings.`);i.add(e)}const t=n.create(e);void 0!==t&&e.rendererRegistry.bindRenderer(n.targets,t)}}const Ct=e=>0|Y(e,0,255);class Tt{_r;_g;_b;_a;_rgba=null;_array=null;constructor(e=0,t=0,i=0,n=1){this._r=Ct(e),this._g=Ct(t),this._b=Ct(i),this._a=Y(n,0,1)}get r(){return this._r}set r(e){this._r=Ct(e),this._rgba=null}get g(){return this._g}set g(e){this._g=Ct(e),this._rgba=null}get b(){return this._b}set b(e){this._b=Ct(e),this._rgba=null}get a(){return this._a}set a(e){this._a=Y(e,0,1),this._rgba=null}set(e=this._r,t=this._g,i=this._b,n=this._a){return this._r=Ct(e),this._g=Ct(t),this._b=Ct(i),this._a=Y(n,0,1),this._rgba=null,this}copy(e){return this.set(e.r,e.g,e.b,e.a)}clone(){return new Tt(this._r,this._g,this._b,this._a)}equals({r:e,g:t,b:i,a:n}={}){return!(void 0!==e&&this.r!==e||void 0!==t&&this.g!==t||void 0!==i&&this.b!==i||void 0!==n&&this.a!==n)}toArray(e=!1){return this._array||(this._array=new Float32Array(4)),e?(this._array[0]=this._r/255,this._array[1]=this._g/255,this._array[2]=this._b/255,this._array[3]=this._a):(this._array[0]=this._r,this._array[1]=this._g,this._array[2]=this._b,this._array[3]=this._a),this._array}toString(e=!0){return`${e?"#":""}${(1<<24|this._r<<16|this._g<<8|this._b).toString(16).substr(1)}`}toRgba(){return null===this._rgba&&(this._rgba=(255*this._a<<24|this._b<<16|this._g<<8|this._r)>>>0),this._rgba}destroy(){this._array&&(this._array=null)}static aliceBlue=new Tt(240,248,255,1);static antiqueWhite=new Tt(250,235,215,1);static aqua=new Tt(0,255,255,1);static aquamarine=new Tt(127,255,212,1);static azure=new Tt(240,255,255,1);static beige=new Tt(245,245,220,1);static bisque=new Tt(255,228,196,1);static black=new Tt(0,0,0,1);static blanchedAlmond=new Tt(255,235,205,1);static blue=new Tt(0,0,255,1);static blueViolet=new Tt(138,43,226,1);static brown=new Tt(165,42,42,1);static burlyWood=new Tt(222,184,135,1);static cadetBlue=new Tt(95,158,160,1);static chartreuse=new Tt(127,255,0,1);static chocolate=new Tt(210,105,30,1);static coral=new Tt(255,127,80,1);static cornflowerBlue=new Tt(100,149,237,1);static cornsilk=new Tt(255,248,220,1);static crimson=new Tt(220,20,60,1);static cyan=new Tt(0,255,255,1);static darkBlue=new Tt(0,0,139,1);static darkCyan=new Tt(0,139,139,1);static darkGoldenrod=new Tt(184,134,11,1);static darkGray=new Tt(169,169,169,1);static darkGreen=new Tt(0,100,0,1);static darkKhaki=new Tt(189,183,107,1);static darkMagenta=new Tt(139,0,139,1);static darkOliveGreen=new Tt(85,107,47,1);static darkOrange=new Tt(255,140,0,1);static darkOrchid=new Tt(153,50,204,1);static darkRed=new Tt(139,0,0,1);static darkSalmon=new Tt(233,150,122,1);static darkSeaGreen=new Tt(143,188,139,1);static darkSlateBlue=new Tt(72,61,139,1);static darkSlateGray=new Tt(47,79,79,1);static darkTurquoise=new Tt(0,206,209,1);static darkViolet=new Tt(148,0,211,1);static deepPink=new Tt(255,20,147,1);static deepSkyBlue=new Tt(0,191,255,1);static dimGray=new Tt(105,105,105,1);static dodgerBlue=new Tt(30,144,255,1);static firebrick=new Tt(178,34,34,1);static floralWhite=new Tt(255,250,240,1);static forestGreen=new Tt(34,139,34,1);static fuchsia=new Tt(255,0,255,1);static gainsboro=new Tt(220,220,220,1);static ghostWhite=new Tt(248,248,255,1);static gold=new Tt(255,215,0,1);static goldenrod=new Tt(218,165,32,1);static gray=new Tt(128,128,128,1);static green=new Tt(0,128,0,1);static greenYellow=new Tt(173,255,47,1);static honeydew=new Tt(240,255,240,1);static hotPink=new Tt(255,105,180,1);static indianRed=new Tt(205,92,92,1);static indigo=new Tt(75,0,130,1);static ivory=new Tt(255,255,240,1);static khaki=new Tt(240,230,140,1);static lavender=new Tt(230,230,250,1);static lavenderBlush=new Tt(255,240,245,1);static lawnGreen=new Tt(124,252,0,1);static lemonChiffon=new Tt(255,250,205,1);static lightBlue=new Tt(173,216,230,1);static lightCoral=new Tt(240,128,128,1);static lightCyan=new Tt(224,255,255,1);static lightGoldenrodYellow=new Tt(250,250,210,1);static lightGray=new Tt(211,211,211,1);static lightGreen=new Tt(144,238,144,1);static lightPink=new Tt(255,182,193,1);static lightSalmon=new Tt(255,160,122,1);static lightSeaGreen=new Tt(32,178,170,1);static lightSkyBlue=new Tt(135,206,250,1);static lightSlateGray=new Tt(119,136,153,1);static lightSteelBlue=new Tt(176,196,222,1);static lightYellow=new Tt(255,255,224,1);static lime=new Tt(0,255,0,1);static limeGreen=new Tt(50,205,50,1);static linen=new Tt(250,240,230,1);static magenta=new Tt(255,0,255,1);static maroon=new Tt(128,0,0,1);static mediumAquamarine=new Tt(102,205,170,1);static mediumBlue=new Tt(0,0,205,1);static mediumOrchid=new Tt(186,85,211,1);static mediumPurple=new Tt(147,112,219,1);static mediumSeaGreen=new Tt(60,179,113,1);static mediumSlateBlue=new Tt(123,104,238,1);static mediumSpringGreen=new Tt(0,250,154,1);static mediumTurquoise=new Tt(72,209,204,1);static mediumVioletRed=new Tt(199,21,133,1);static midnightBlue=new Tt(25,25,112,1);static mintCream=new Tt(245,255,250,1);static mistyRose=new Tt(255,228,225,1);static moccasin=new Tt(255,228,181,1);static navajoWhite=new Tt(255,222,173,1);static navy=new Tt(0,0,128,1);static oldLace=new Tt(253,245,230,1);static olive=new Tt(128,128,0,1);static oliveDrab=new Tt(107,142,35,1);static orange=new Tt(255,165,0,1);static orangeRed=new Tt(255,69,0,1);static orchid=new Tt(218,112,214,1);static paleGoldenrod=new Tt(238,232,170,1);static paleGreen=new Tt(152,251,152,1);static paleTurquoise=new Tt(175,238,238,1);static paleVioletRed=new Tt(219,112,147,1);static papayaWhip=new Tt(255,239,213,1);static peachPuff=new Tt(255,218,185,1);static peru=new Tt(205,133,63,1);static pink=new Tt(255,192,203,1);static plum=new Tt(221,160,221,1);static powderBlue=new Tt(176,224,230,1);static purple=new Tt(128,0,128,1);static red=new Tt(255,0,0,1);static rosyBrown=new Tt(188,143,143,1);static royalBlue=new Tt(65,105,225,1);static saddleBrown=new Tt(139,69,19,1);static salmon=new Tt(250,128,114,1);static sandyBrown=new Tt(244,164,96,1);static seaGreen=new Tt(46,139,87,1);static seaShell=new Tt(255,245,238,1);static sienna=new Tt(160,82,45,1);static silver=new Tt(192,192,192,1);static skyBlue=new Tt(135,206,235,1);static slateBlue=new Tt(106,90,205,1);static slateGray=new Tt(112,128,144,1);static snow=new Tt(255,250,250,1);static springGreen=new Tt(0,255,127,1);static steelBlue=new Tt(70,130,180,1);static tan=new Tt(210,180,140,1);static teal=new Tt(0,128,128,1);static thistle=new Tt(216,191,216,1);static tomato=new Tt(255,99,71,1);static transparentBlack=new Tt(0,0,0,0);static transparentWhite=new Tt(255,255,255,0);static turquoise=new Tt(64,224,208,1);static violet=new Tt(238,130,238,1);static wheat=new Tt(245,222,179,1);static white=new Tt(255,255,255,1);static whiteSmoke=new Tt(245,245,245,1);static yellow=new Tt(255,255,0,1);static yellowGreen=new Tt(154,205,50,1)}class Mt{_value=0;get value(){return this._value}constructor(...e){e.length&&this.push(...e)}push(...e){for(const t of e)this._value|=t;return this}pop(e){const t=this.has(e);return this.remove(e),t}remove(...e){for(const t of e)this._value&=~t;return this}has(...e){return e.some(e=>0!==(this._value&e))}clear(){return this._value=0,this}destroy(){this.clear()}}let Pt=null;class At{a;b;x;c;d;y;e;f;z;_array=null;constructor(e=1,t=0,i=0,n=0,r=1,s=0,o=0,a=0,h=1){this.a=e,this.b=t,this.x=i,this.c=n,this.d=r,this.y=s,this.e=o,this.f=a,this.z=h}set(e=this.a,t=this.b,i=this.x,n=this.c,r=this.d,s=this.y,o=this.e,a=this.f,h=this.z){return this.a=e,this.b=t,this.x=i,this.c=n,this.d=r,this.y=s,this.e=o,this.f=a,this.z=h,this}copy(e){return this.a=e.a,this.b=e.b,this.x=e.x,this.c=e.c,this.d=e.d,this.y=e.y,this.e=e.e,this.f=e.f,this.z=e.z,this}clone(){return new At(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:e,b:t,x:i,c:n,d:r,y:s,e:o,f:a,z:h}={}){return!(void 0!==e&&this.a!==e||void 0!==t&&this.b!==t||void 0!==i&&this.x!==i||void 0!==n&&this.c!==n||void 0!==r&&this.d!==r||void 0!==s&&this.y!==s||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(e){return this.set(this.a*e.a+this.c*e.b+this.e*e.x,this.b*e.a+this.d*e.b+this.f*e.x,this.x*e.a+this.y*e.b+this.z*e.x,this.a*e.c+this.c*e.d+this.e*e.y,this.b*e.c+this.d*e.d+this.f*e.y,this.x*e.c+this.y*e.d+this.z*e.y,this.a*e.e+this.c*e.f+this.e*e.z,this.b*e.e+this.d*e.f+this.f*e.z,this.x*e.e+this.y*e.f+this.z*e.z)}getInverse(e=this){const t=this.a*(this.z*this.d-this.y*this.f)-this.b*(this.z*this.c-this.y*this.e)+this.x*(this.f*this.c-this.d*this.e);return 0===t?e.copy(At.identity):e.set((this.d*this.z-this.y*this.f)/t,(this.x*this.f-this.b*this.z)/t,(this.b*this.y-this.x*this.d)/t,(this.y*this.e-this.c*this.z)/t,(this.a*this.z-this.x*this.e)/t,(this.x*this.c-this.a*this.y)/t,(this.c*this.f-this.d*this.e)/t,(this.b*this.e-this.a*this.f)/t,(this.a*this.d-this.b*this.c)/t)}translate(e,t=e){return this.combine(At.temp.set(1,0,e,0,1,t,0,0,1))}rotate(e,t=0,i=t){const n=W(e),r=Math.cos(n),s=Math.sin(n);return this.combine(At.temp.set(r,-s,t*(1-r)+i*s,s,r,i*(1-r)-t*s,0,0,1))}scale(e,t=e,i=0,n=i){return this.combine(At.temp.set(e,0,i*(1-e),0,t,n*(1-t),0,0,1))}toArray(e=!1){const t=this._array||(this._array=new Float32Array(9));return e?(t[0]=this.a,t[1]=this.b,t[2]=this.x,t[3]=this.c,t[4]=this.d,t[5]=this.y,t[6]=this.e,t[7]=this.f,t[8]=this.z):(t[0]=this.a,t[1]=this.c,t[2]=this.e,t[3]=this.b,t[4]=this.d,t[5]=this.f,t[6]=this.x,t[7]=this.y,t[8]=this.z),t}destroy(){this._array&&(this._array=null)}static identity=new At(1,0,0,0,1,0,0,0,1);static get temp(){return null===Pt&&(Pt=new At),Pt}}let Et=null;class kt{collisionType=e.CollisionType.Polygon;_position;_points=[];_edges=[];_cachedNormals=null;_normalsDirty=!0;constructor(e=[],t=0,i=0){this._position=new it(t,i),this.setPoints(e)}get position(){return this._position}set position(e){this._position.copy(e),this._normalsDirty=!0}get x(){return this._position.x}set x(e){this._position.x=e,this._normalsDirty=!0}get y(){return this._position.y}set y(e){this._position.y=e,this._normalsDirty=!0}get points(){return this._points}set points(e){this.setPoints(e)}get edges(){return this._edges}setPosition(e,t){return this._position.set(e,t),this._normalsDirty=!0,this}setPoints(e){const t=this._points.length,i=e.length,n=t-i,r=Math.min(t,i);for(let t=0;t<r;t++)this._points[t].copy(e[t]);if(n>0){for(const e of this._points.splice(i))e.destroy();for(const e of this._edges.splice(i))e.destroy();if(null!==this._cachedNormals&&this._cachedNormals.length>i){const e=this._cachedNormals.splice(i);for(const t of e)t.destroy()}}else if(n<0)for(let n=t;n<i;n++)this._points.push(e[n].clone()),this._edges.push(e[n].clone());for(let e=0;e<i;e++){const t=this._points[e],n=this._points[(e+1)%i];this._edges[e].set(n.x-t.x,n.y-t.y)}return this._normalsDirty=!0,this}set(e,t,i){return this._position.set(e,t),this.setPoints(i),this._normalsDirty=!0,this}copy(e){return this._position.copy(e.position),this.setPoints(e.points),this._normalsDirty=!0,this}clone(){return new kt(this.points,this.x,this.y)}equals({x:e,y:t,points:i}={}){return(void 0===e||this.x===e)&&(void 0===t||this.y===t)&&(void 0===i||this.points.length===i.length&&this.points.every((e,t)=>e.equals(i[t])))}getBounds(){let e=1/0,t=1/0,i=-1/0,n=-1/0;for(const r of this._points)e=Math.min(r.x,e),t=Math.min(r.y,t),i=Math.max(r.x,i),n=Math.max(r.y,n);return new et(this.x+e,this.y+t,i-e,n-t)}getNormals(){if(this._normalsDirty){const e=this._points.length;for(null===this._cachedNormals&&(this._cachedNormals=[]);this._cachedNormals.length<e;)this._cachedNormals.push(new it);for(let t=0;t<e;t++)this._cachedNormals[t].copy(this._edges[t]).rperp().normalize();this._normalsDirty=!1}return this._cachedNormals}project(e,t=new me){const i=Math.sqrt(e.x*e.x+e.y*e.y)||1,n=e.x/i,r=e.y/i,s=n*this._position.x+r*this._position.y,o=this._points;let a=1/0,h=-1/0;for(let e=0;e<o.length;e++){const t=o[e],i=n*t.x+r*t.y;i<a&&(a=i),i>h&&(h=i)}return t.set(a+s,h+s)}contains(e,t){return Se(it.temp.set(e,t),this)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Re(t.getBounds(),this);case e.CollisionType.Rectangle:return Re(t,this);case e.CollisionType.Polygon:return Ve(this,t);case e.CollisionType.Circle:return Ge(t,this);case e.CollisionType.Ellipse:return Oe(t,this);case e.CollisionType.Line:return Pe(t,this);case e.CollisionType.Point:return Se(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:case e.CollisionType.Rectangle:case e.CollisionType.Polygon:case e.CollisionType.Ellipse:return je(this,t);case e.CollisionType.Circle:return Xe(this,t);default:return null}}destroy(){for(const e of this._points)e.destroy();for(const e of this._edges)e.destroy();if(null!==this._cachedNormals){for(const e of this._cachedNormals)e.destroy();this._cachedNormals=null}this._position.destroy(),this._points.length=0,this._edges.length=0}static get temp(){return null===Et&&(Et=new kt),Et}}class Rt{_minX=1/0;_minY=1/0;_maxX=-1/0;_maxY=-1/0;_dirty=!0;_rect=new et;get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(e,t){return this._minX=Math.min(this._minX,e),this._minY=Math.min(this._minY,t),this._maxX=Math.max(this._maxX,e),this._maxY=Math.max(this._maxY,t),this._dirty=!0,this}addRect(e,t){return t&&(e=e.transform(t,et.temp)),this.addCoords(e.left,e.top).addCoords(e.right,e.bottom)}getRect(){return this._dirty&&(this._rect.set(this._minX,this._minY,this._maxX-this._minX,this._maxY-this._minY),this._dirty=!1),this._rect}reset(){return this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this}destroy(){this._rect.destroy()}}var Dt,Ft;!function(e){e[e.None=0]="None",e[e.Translation=1]="Translation",e[e.Rotation=2]="Rotation",e[e.Scaling=4]="Scaling",e[e.Origin=8]="Origin",e[e.Skew=32]="Skew",e[e.Transform=47]="Transform",e[e.TransformInverse=16]="TransformInverse",e[e.GlobalTransform=256]="GlobalTransform",e[e.BoundsRect=512]="BoundsRect"}(Dt||(Dt={})),function(e){e[e.Position=0]="Position",e[e.Scale=1]="Scale",e[e.Origin=2]="Origin",e[e.Anchor=3]="Anchor"}(Ft||(Ft={}));const It=[new it,new it,new it,new it];class Lt{collisionType=e.CollisionType.SceneNode;flags=new Mt(Dt.Transform|Dt.GlobalTransform|Dt.BoundsRect);_bounds=new Rt;_transform=new At;_position=new Qe(this,Ft.Position,0,0);_scale=new Qe(this,Ft.Scale,1,1);_origin=new Qe(this,Ft.Origin,0,0);_rotation=0;_skewX=0;_skewY=0;_sin=0;_cos=1;_stage=null;_visible=!0;_globalTransform=new At;_localBounds=new et;_anchor=new Qe(this,Ft.Anchor,0,0);_parentNode=null;_zIndex=0;_cullable=!0;_cullArea=null;_orientedBounds=null;name=null;get position(){return this._position}set position(e){this._position.copy(e)}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get rotation(){return this._rotation}set rotation(e){this.setRotation(e)}get scale(){return this._scale}set scale(e){this._scale.copy(e)}get origin(){return this._origin}set origin(e){this._origin.copy(e)}get anchor(){return this._anchor}set anchor(e){this._anchor.copy(e)}get parent(){return this._parentNode}set parent(e){this._parentNode=e}get visible(){return this._visible}set visible(e){this._visible=e}get zIndex(){return this._zIndex}set zIndex(e){this._zIndex!==e&&(this._zIndex=e)}get cullable(){return this._cullable}set cullable(e){this._cullable=e}get cullArea(){return this._cullArea}set cullArea(e){this._cullArea=e}get skewX(){return this._skewX}set skewX(e){this._skewX!==e&&(this._skewX=e,this._setSkewDirty())}get skewY(){return this._skewY}set skewY(e){this._skewY!==e&&(this._skewY=e,this._setSkewDirty())}get isAlignedBox(){return this.rotation%90==0&&0===this._skewX&&0===this._skewY}setPosition(e,t=e){return this._position.set(e,t),this}setRotation(e){const t=q(e);return this._rotation!==t&&(this._rotation=t,this._setRotationDirty()),this}setScale(e,t=e){return this._scale.set(e,t),this}setSkew(e,t=e){return this.skewX=e,this.skewY=t,this}setOrigin(e,t=e){return this._origin.set(e,t),this}move(e,t){return this.setPosition(this.x+e,this.y+t)}rotate(e){return this.setRotation(this._rotation+e)}getTransform(){return this.flags.has(Dt.Transform)&&(this.updateTransform(),this.flags.remove(Dt.Transform)),this._transform}updateTransform(){if(this.flags.has(Dt.Rotation)){const e=W(this._rotation);this._cos=Math.cos(e),this._sin=Math.sin(e)}if(this.flags.has(Dt.Rotation|Dt.Scaling|Dt.Skew)){const{x:e,y:t}=this._scale;if(0!==this._skewX||0!==this._skewY){const i=Math.tan(W(this._skewX)),n=Math.tan(W(this._skewY));this._transform.a=e*this._cos+i*this._sin,this._transform.b=t*this._sin+n*this._cos,this._transform.c=-e*this._sin+i*this._cos,this._transform.d=-n*this._sin+t*this._cos}else this._transform.a=e*this._cos,this._transform.b=t*this._sin,this._transform.c=-e*this._sin,this._transform.d=t*this._cos}if(this._rotation||0!==this._skewX||0!==this._skewY){const{x:e,y:t}=this._origin;this._transform.x=e*-this._transform.a-t*this._transform.b+this._position.x,this._transform.y=e*-this._transform.c-t*this._transform.d+this._position.y}else this._transform.x=this._origin.x*-this._scale.x+this._position.x,this._transform.y=this._origin.y*-this._scale.y+this._position.y;return this}setAnchor(e,t=e){return this._anchor.set(e,t),this}getLocalBounds(){return this._localBounds}getBounds(){return this.flags.has(Dt.BoundsRect)&&(this.updateBounds(),this.flags.remove(Dt.BoundsRect)),this._bounds.getRect()}updateBounds(){return this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform()),this}updateParentTransform(){return this._parentNode&&this._parentNode.updateParentTransform(),this.updateTransform(),this}getGlobalTransform(){return this.flags.has(Dt.GlobalTransform)&&(this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this.flags.remove(Dt.GlobalTransform)),this._globalTransform}getNormals(){return this._isWorldAligned()?this.getBounds().getNormals():this._orientedBoundsPolygon().getNormals()}project(e,t=new me){return this._isWorldAligned()?this.getBounds().project(e,t):this._orientedBoundsPolygon().project(e,t)}_orientedBoundsPolygon(){const e=this.getLocalBounds(),t=this.getGlobalTransform();return It[0].set(e.left,e.top).transform(t),It[1].set(e.right,e.top).transform(t),It[2].set(e.right,e.bottom).transform(t),It[3].set(e.left,e.bottom).transform(t),(this._orientedBounds??=new kt).setPoints(It)}_isWorldAligned(){const e=this.getGlobalTransform(),t=1e-9;return Math.abs(e.b)<t&&Math.abs(e.c)<t||Math.abs(e.a)<t&&Math.abs(e.d)<t}intersectsWith(t){if(this._isWorldAligned())return this.getBounds().intersectsWith(t);switch(t.collisionType){case e.CollisionType.SceneNode:case e.CollisionType.Rectangle:case e.CollisionType.Polygon:return ge(this,t);case e.CollisionType.Circle:return Ee(this.getBounds(),t);case e.CollisionType.Ellipse:return ke(this.getBounds(),t);case e.CollisionType.Line:return Ce(t,this.getBounds());case e.CollisionType.Point:return xe(t,this.getBounds());default:return!1}}collidesWith(t){if(this._isWorldAligned())return this.getBounds().collidesWith(t);switch(t.collisionType){case e.CollisionType.SceneNode:case e.CollisionType.Rectangle:case e.CollisionType.Polygon:case e.CollisionType.Circle:return je(this,t);default:return null}}contains(e,t){if(this._isWorldAligned())return this.getBounds().contains(e,t);const i=this.getGlobalTransform(),n=i.a*i.d-i.b*i.c;if(0===n)return!1;const r=e-i.x,s=t-i.y,o=(i.d*r-i.b*s)/n,a=(i.a*s-i.c*r)/n;return this.getLocalBounds().contains(o,a)}inView(e){if(!this._cullable)return!0;const t=this._cullArea??this.getBounds();return e.getBounds().intersectsWith(t)}destroy(){this._transform.destroy(),this._position.destroy(),this._scale.destroy(),this._origin.destroy(),this.flags.destroy(),this._globalTransform.destroy(),this._localBounds.destroy(),this._bounds.destroy(),this._anchor.destroy(),this._orientedBounds?.destroy()}_setStage(e){this._stage=e}_getStage(){return this._stage}_onObservableChange(e){switch(e){case Ft.Position:this._setPositionDirty();break;case Ft.Scale:this._setScalingDirty();break;case Ft.Origin:this._setOriginDirty();break;case Ft.Anchor:this._updateOrigin()}}_invalidateSubtreeTransform(){this.flags.push(Dt.GlobalTransform|Dt.BoundsRect),this._invalidateChildrenTransform()}_invalidateChildrenTransform(){}_invalidateBoundsCascade(){this.flags.push(Dt.BoundsRect),this._stage?.interaction._notifyBoundsInvalidated(this);let e=this._parentNode;for(;null!==e&&!e.flags.has(Dt.BoundsRect);)e.flags.push(Dt.BoundsRect),e._stage?.interaction._notifyBoundsInvalidated(e),e=e.parent}_setPositionDirty(){this.flags.push(Dt.Translation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setRotationDirty(){this.flags.push(Dt.Rotation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setScalingDirty(){this.flags.push(Dt.Scaling),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setOriginDirty(){this.flags.push(Dt.Origin),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setSkewDirty(){this.flags.push(Dt.Skew),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_updateOrigin(){const{x:e,y:t}=this._anchor,{width:i,height:n}=this.getLocalBounds();this.setOrigin(i*e,n*t)}}var Ut;e.BlendModes=void 0,(Ut=e.BlendModes||(e.BlendModes={}))[Ut.Normal=0]="Normal",Ut[Ut.Additive=1]="Additive",Ut[Ut.Subtract=2]="Subtract",Ut[Ut.Multiply=3]="Multiply",Ut[Ut.Screen=4]="Screen",Ut[Ut.Darken=5]="Darken",Ut[Ut.Lighten=6]="Lighten",Ut[Ut.Overlay=7]="Overlay",Ut[Ut.ColorDodge=8]="ColorDodge",Ut[Ut.ColorBurn=9]="ColorBurn",Ut[Ut.HardLight=10]="HardLight",Ut[Ut.SoftLight=11]="SoftLight",Ut[Ut.Difference=12]="Difference",Ut[Ut.Exclusion=13]="Exclusion",Ut[Ut.Hue=14]="Hue",Ut[Ut.Saturation=15]="Saturation",Ut[Ut.Color=16]="Color",Ut[Ut.Luminosity=17]="Luminosity";const Gt=t=>t>=e.BlendModes.Darken;var Nt,Ot,Vt,zt,qt,Wt,Yt;e.ScaleModes=void 0,(Nt=e.ScaleModes||(e.ScaleModes={}))[Nt.Nearest=9728]="Nearest",Nt[Nt.Linear=9729]="Linear",Nt[Nt.NearestMipmapNearest=9984]="NearestMipmapNearest",Nt[Nt.LinearMipmapNearest=9985]="LinearMipmapNearest",Nt[Nt.NearestMipmapLinear=9986]="NearestMipmapLinear",Nt[Nt.LinearMipmapLinear=9987]="LinearMipmapLinear",e.WrapModes=void 0,(Ot=e.WrapModes||(e.WrapModes={}))[Ot.Repeat=10497]="Repeat",Ot[Ot.ClampToEdge=33071]="ClampToEdge",Ot[Ot.MirroredRepeat=33648]="MirroredRepeat",e.RenderingPrimitives=void 0,(Vt=e.RenderingPrimitives||(e.RenderingPrimitives={}))[Vt.Points=0]="Points",Vt[Vt.Lines=1]="Lines",Vt[Vt.LineLoop=2]="LineLoop",Vt[Vt.LineStrip=3]="LineStrip",Vt[Vt.Triangles=4]="Triangles",Vt[Vt.TriangleStrip=5]="TriangleStrip",Vt[Vt.TriangleFan=6]="TriangleFan",e.BufferTypes=void 0,(zt=e.BufferTypes||(e.BufferTypes={}))[zt.ArrayBuffer=34962]="ArrayBuffer",zt[zt.ElementArrayBuffer=34963]="ElementArrayBuffer",zt[zt.CopyReadBuffer=36662]="CopyReadBuffer",zt[zt.CopyWriteBuffer=36663]="CopyWriteBuffer",zt[zt.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",zt[zt.UniformBuffer=35345]="UniformBuffer",zt[zt.PixelPackBuffer=35051]="PixelPackBuffer",zt[zt.PixelUnpackBuffer=35052]="PixelUnpackBuffer",e.BufferUsage=void 0,(qt=e.BufferUsage||(e.BufferUsage={}))[qt.StaticDraw=35044]="StaticDraw",qt[qt.StaticRead=35045]="StaticRead",qt[qt.StaticCopy=35046]="StaticCopy",qt[qt.DynamicDraw=35048]="DynamicDraw",qt[qt.DynamicRead=35049]="DynamicRead",qt[qt.DynamicCopy=35050]="DynamicCopy",qt[qt.StreamDraw=35040]="StreamDraw",qt[qt.StreamRead=35041]="StreamRead",qt[qt.StreamCopy=35042]="StreamCopy",e.ShaderPrimitives=void 0,(Wt=e.ShaderPrimitives||(e.ShaderPrimitives={}))[Wt.Int=5124]="Int",Wt[Wt.IntVec2=35667]="IntVec2",Wt[Wt.IntVec3=35668]="IntVec3",Wt[Wt.IntVec4=35669]="IntVec4",Wt[Wt.UnsignedInt=5125]="UnsignedInt",Wt[Wt.UnsignedIntVec2=36294]="UnsignedIntVec2",Wt[Wt.UnsignedIntVec3=36295]="UnsignedIntVec3",Wt[Wt.UnsignedIntVec4=36296]="UnsignedIntVec4",Wt[Wt.Float=5126]="Float",Wt[Wt.FloatVec2=35664]="FloatVec2",Wt[Wt.FloatVec3=35665]="FloatVec3",Wt[Wt.FloatVec4=35666]="FloatVec4",Wt[Wt.Bool=35670]="Bool",Wt[Wt.BoolVec2=35671]="BoolVec2",Wt[Wt.BoolVec3=35672]="BoolVec3",Wt[Wt.BoolVec4=35673]="BoolVec4",Wt[Wt.FloatMat2=35674]="FloatMat2",Wt[Wt.FloatMat3=35675]="FloatMat3",Wt[Wt.FloatMat4=35676]="FloatMat4",Wt[Wt.Sampler2D=35678]="Sampler2D",function(e){e[e.Draw=0]="Draw",e[e.Group=1]="Group",e[e.Barrier=2]="Barrier"}(Yt||(Yt={}));const $t=new WeakMap,Xt=new WeakMap,Ht=new WeakMap,jt=new WeakMap;let Kt=1,Qt=1,Zt=1;const Jt=(e,t,i)=>{const n=e.get(t);if(void 0!==n)return n;const r=i();return e.set(t,r),r},ei=e=>e.material??null,ti=(e,t,i)=>{const n=((e,t)=>{const i=t?.rendererRegistry;if(i&&"function"==typeof i.resolve)try{const t=i.resolve(e);if(t&&"object"==typeof t)return Jt($t,t,()=>Kt++)}catch{}const n=e.constructor;return n&&"function"==typeof n?Jt(Xt,n,()=>Kt++):0})(t,i),r=t.blendMode,s=(e=>{const t=e.texture;return t&&"object"==typeof t?Jt(Ht,t,()=>Qt++):-1})(t),o=(e=>{const t=e.shader;return t&&"object"==typeof t?Jt(jt,t,()=>Zt++):-1})(t),a=ei(t);return e.rendererId=n,e.blendMode=r,e.textureId=s,e.shaderId=o,e.pipelineKey=null!==a?a.pipelineKey:31*n+r,e.bindKey=null!==a?a.bindKey:31*n+(s>0?s:0),e},ii=(e,t)=>{const i=t.rendererRegistry;if(!i||"function"!=typeof i.resolve)return!0;try{return!1!==i.resolve(e.drawable)._consumesSharedTransform}catch{return!0}};class ni{passes=[];nodeCount=0;reset(){this.passes.length=0,this.nodeCount=0}}var ri;!function(e){e[e.None=0]="None",e[e.Rect=1]="Rect",e[e.Stencil=2]="Stencil"}(ri||(ri={}));class si{static _available=[];static _active=[];static acquire(){const e=si._available.pop()??new si;return si._active.push(e),e}static release(e){const t=si._active.lastIndexOf(e);-1!==t&&(si._active.splice(t,1),e._resetRuntimeState(),si._available.push(e))}backend;_view=null;_plan=new ni;_groupPool=[];_scopeStack=[];_groupPoolCursor=0;_commandPool=[];_commandPoolCursor=0;_drawEntryPool=[];_drawEntryPoolCursor=0;_groupEntryPool=[];_groupEntryPoolCursor=0;_barrierEntryPool=[];_barrierEntryPoolCursor=0;_reservedSeq=0;_reservedZ=0;_hasPending=!1;_pendingSeq=0;_pendingZ=0;_nodeIndex=0;build(e,t){this.backend=t,this._view=null,this._plan.reset(),this._groupPoolCursor=0,this._drawEntryPoolCursor=0,this._groupEntryPoolCursor=0,this._barrierEntryPoolCursor=0,this._scopeStack.length=0,this._hasPending=!1;const i=t.transformBufferCount??0;this._nodeIndex=i,this._commandPoolCursor=i;const n=this._acquireGroupScope(!1);return this._scopeStack.push(n),e._collect(this),this._scopeStack.pop(),n.entries.length>0&&this._plan.passes.push({target:null,view:this.view,clearColor:null,root:n}),this._plan.nodeCount=this._nodeIndex-i,this._plan}get view(){return null===this._view&&(this._view=this.backend.view),this._view}emitNode(e,t){this._reserveEntryPlacement(t,e.zIndex);const i=this._reservedSeq,n=this._reservedZ;if(e._renderPlanHasBarrierEffects()){const t=this._createEffectDescriptor(e),r=null!==t.maskSource&&!(t.maskSource instanceof et);let s=0,o=0,a=0,h=0;if(t.cacheAsBitmap||t.filters.length>0||r||(t.needsBackdropBlend??!1)){const t=e.getBounds();if(t.width<=0||t.height<=0)return;s=Math.floor(t.left),o=Math.floor(t.top),a=Math.max(1,Math.ceil(t.width)),h=Math.max(1,Math.ceil(t.height))}const l=t.cacheAsBitmap&&e._renderPlanCanReuseBitmapCache(s,o,a,h)?null:this._acquireGroupScope(this._resolvePreserveDrawOrder(e)),u={kind:Yt.Barrier,node:e,effect:t,childPlan:l,left:s,top:o,width:a,height:h};if(this._pushBarrierEntry(i,n,u),null!==l){this._scopeStack.push(l);try{e._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}return}if(e._isDrawableForRenderPlan()){this._hasPending=!0,this._pendingSeq=i,this._pendingZ=n;try{e._collectForRenderPlan(this)}finally{this._hasPending=!1}return}const r=this._acquireGroupScope(this._resolvePreserveDrawOrder(e));this._pushGroupEntry(i,n,r),this._scopeStack.push(r);try{e._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}emitDraw(e,t){const i=this._hasPending,n=this._pendingSeq,r=this._pendingZ;i&&(this._hasPending=!1);const s=i?r:e.zIndex;this._reserveEntryPlacement(t??(i?n:void 0),s);const o=this._reservedSeq,a=this._reservedZ,h=e.getBounds(),l=this._acquireDrawCommand();l.drawable=e,l.nodeIndex=this._nodeIndex++,l.seq=o,l.zIndex=a,l.groupIndex=void 0,l.material=e._getOrComputeMaterialKey(this.backend),l.minX=h.left,l.minY=h.top,l.maxX=h.right,l.maxY=h.bottom,this._pushDrawEntry(o,a,l)}_resetRuntimeState(){this._scopeStack.length=0,this._hasPending=!1,this._groupPoolCursor=0,this._commandPoolCursor=0,this._drawEntryPoolCursor=0,this._groupEntryPoolCursor=0,this._barrierEntryPoolCursor=0,this._view=null,this._nodeIndex=0}_acquireGroupScope(e){const t=this._groupPool[this._groupPoolCursor]??{kind:Yt.Group,entries:[],hasMixedZ:!1,preserveDrawOrder:!1,_nextSeq:0,firstZ:null};return this._groupPool[this._groupPoolCursor]=t,this._groupPoolCursor++,t.entries.length=0,t.hasMixedZ=!1,t.preserveDrawOrder=e,t._nextSeq=0,t.firstZ=null,t}_acquireDrawCommand(){const e=this._commandPool[this._commandPoolCursor];if(void 0!==e)return this._commandPoolCursor++,e;const t={kind:Yt.Draw,drawable:void 0,nodeIndex:0,seq:0,zIndex:0,material:void 0,groupIndex:void 0,minX:0,minY:0,maxX:0,maxY:0};return this._commandPool[this._commandPoolCursor]=t,this._commandPoolCursor++,t}_pushDrawEntry(e,t,i){let n=this._drawEntryPool[this._drawEntryPoolCursor];void 0===n?(n={kind:Yt.Draw,seq:e,zIndex:t,command:i},this._drawEntryPool[this._drawEntryPoolCursor]=n):(n.seq=e,n.zIndex=t,n.command=i),this._drawEntryPoolCursor++,this._currentScope().entries.push(n)}_pushGroupEntry(e,t,i){let n=this._groupEntryPool[this._groupEntryPoolCursor];void 0===n?(n={kind:Yt.Group,seq:e,zIndex:t,scope:i},this._groupEntryPool[this._groupEntryPoolCursor]=n):(n.seq=e,n.zIndex=t,n.scope=i),this._groupEntryPoolCursor++,this._currentScope().entries.push(n)}_pushBarrierEntry(e,t,i){let n=this._barrierEntryPool[this._barrierEntryPoolCursor];void 0===n?(n={kind:Yt.Barrier,seq:e,zIndex:t,scope:i},this._barrierEntryPool[this._barrierEntryPoolCursor]=n):(n.seq=e,n.zIndex=t,n.scope=i),this._barrierEntryPoolCursor++,this._currentScope().entries.push(n)}_reserveEntryPlacement(e,t){const i=this._currentScope(),n=e??i._nextSeq;n>=i._nextSeq&&(i._nextSeq=n+1),null===i.firstZ?i.firstZ=t:i.hasMixedZ||i.firstZ===t||(i.hasMixedZ=!0),this._reservedSeq=n,this._reservedZ=t}_currentScope(){const e=this._scopeStack[this._scopeStack.length-1];if(!e)throw new Error("RenderPlanBuilder scope stack is empty.");return e}_resolvePreserveDrawOrder(e){return e.preserveDrawOrder}_createEffectDescriptor(e){const t=e._renderPlanGetMaskSource();let i=ri.None,n=null;if(e.clip){const t=e.clipShape;null===t||t instanceof et?(i=ri.Rect,n=t):(i=ri.Stencil,n=t)}const r=e._renderPlanGetBlendMode();return{filters:e._renderPlanGetFilters(),clip:i,clipShape:n,maskSource:t,cacheAsBitmap:e.cacheAsBitmap,blendMode:r,needsBackdropBlend:Gt(r)}}}const oi=e=>`${e.pipelineKey}:${e.bindKey}`,ai=(e,t)=>e.minX<t.maxX&&e.maxX>t.minX&&e.minY<t.maxY&&e.maxY>t.minY;class hi{static optimize(e){for(const t of e.passes)this._optimizeGroup(t.root)}static _optimizeGroup(e){if(e.hasMixedZ){const t=e.entries.map((e,t)=>({entry:e,index:t}));t.sort((e,t)=>e.entry.zIndex-t.entry.zIndex||e.entry.seq-t.entry.seq||e.index-t.index);for(let i=0;i<t.length;i++)e.entries[i]=t[i].entry}this._applyMaterialGrouping(e);for(const t of e.entries)t.kind===Yt.Group?this._optimizeGroup(t.scope):t.kind===Yt.Barrier&&null!==t.scope.childPlan&&this._optimizeGroup(t.scope.childPlan)}static _applyMaterialGrouping(e){const t=e.entries,i=t.length;if(0===i)return;let n=0;for(let r=0;r<=i;r++){const s=r<i?t[r]:null,o=null===s||s.kind===Yt.Group||s.kind===Yt.Barrier;if(o&&r>n){const i=r;i-n>=1&&this._materialGroupSegment(t,n,i,e.preserveDrawOrder),n=r+1}else o&&(n=r+1)}this._assignGroupIndices(e)}static _assignGroupIndices(e){let t=1,i=null,n=null;for(const r of e.entries){if(r.kind!==Yt.Draw){i=null,n=null;continue}const e=oi(r.command.material),s=r.zIndex;null!==i&&null!==n&&e===i&&s===n||(t++,i=e,n=s),r.command.groupIndex=t}}static _materialGroupSegment(e,t,i,n){if(i-t<=1)return;const r=[];for(let n=t;n<i;n++){const t=e[n];t.kind===Yt.Draw&&r.push({entry:t,origIdx:n})}if(!(r.length<=1||n)){const n=new Map;for(const e of r){const t=e.entry.zIndex,i=n.get(t)??[];i.push(e),n.set(t,i)}for(const r of n.values())r.length>1&&this._overlapAwareGroup(r,e,t,i)}}static _overlapAwareGroup(e,t,i,n){const r=new Map;for(const t of e){const e=oi(t.entry.command.material),i=r.get(e)??[];i.push(t),r.set(e,i)}if(r.size<=1)return;const s=new Map;for(let e=i;e<n;e++)s.set(t[e],e);for(const e of r.values()){if(e.length<=1)continue;const r=[];for(const t of e){const e=s.get(t.entry);void 0!==e&&r.push(e)}if(r.sort((e,t)=>e-t),0===r.length)continue;const o=r[0],a=r[r.length-1];if(a-o+1===r.length)continue;let h=!1;for(let i=o+1;i<a&&!h;i++){const n=t[i];if(n.kind!==Yt.Draw)continue;if(oi(n.command.material)!==oi(e[0].entry.command.material))for(const t of e)if(ai(t.entry.command,n.command)){h=!0;break}}if(h)continue;const l=[];for(let e=i;e<o;e++)l.push(t[e]);const u=[];for(let e=a+1;e<n;e++)u.push(t[e]);const c=new Set(e.map(e=>e.entry)),d=[];for(let e=o;e<=a;e++){const i=t[e];c.has(i)||d.push(i)}const _=e.map(e=>e.entry),f=[...l,..._,...d,...u];for(let e=i;e<n;e++)t[e]=f[e-i];break}}}class li extends l{_callback;constructor(e,t=0,i=0){super(t,i),this._callback=e}get width(){return this._width}set width(e){this._width!==e&&(this._width=e,this._callback())}get height(){return this._height}set height(e){this._height!==e&&(this._height=e,this._callback())}set(e=this._width,t=this._height){return this._width===e&&this._height===t||(this._width=e,this._height=t,this._callback()),this}add(e,t=e){return this.set(this._width+e,this._height+t)}subtract(e,t=e){return this.set(this._width-e,this._height-t)}scale(e,t=e){return this.set(this._width*e,this._height*t)}divide(e,t=e){return this.set(this._width/e,this._height/t)}copy(e){return this.set(e.width,e.height)}clone(){return new li(this._callback,this._width,this._height)}}var ui;e.ViewFlags=void 0,(ui=e.ViewFlags||(e.ViewFlags={}))[ui.None=0]="None",ui[ui.Translation=1]="Translation",ui[ui.Rotation=2]="Rotation",ui[ui.Scaling=4]="Scaling",ui[ui.Origin=8]="Origin",ui[ui.Transform=15]="Transform",ui[ui.TransformInverse=16]="TransformInverse",ui[ui.BoundingBox=32]="BoundingBox",ui[ui.TextureCoords=64]="TextureCoords",ui[ui.VertexTint=128]="VertexTint";class ci{_center;_size;_viewport=new et(0,0,1,1);_transform=new At;_inverseTransform=new At;_bounds=new Rt;_flags=new Mt;_rotation=0;_sin=0;_cos=1;_zoomLevel=1;_zoomBaseWidth;_zoomBaseHeight;_followTarget=null;_followLerp=1;_followOffsetX=0;_followOffsetY=0;_boundsConstraint=null;_shakeIntensity=0;_shakeDurationMs=0;_shakeElapsedMs=0;_shakeFrequency=16;_shakeDecay=!0;_shakePhase=0;_shakeOffsetX=0;_shakeOffsetY=0;_updateId=0;constructor(t,i,n,r){this._center=new Qe(this,0,t,i),this._size=new li(this._setScalingDirty.bind(this),n,r),this._zoomBaseWidth=n,this._zoomBaseHeight=r,this._flags.push(e.ViewFlags.Transform,e.ViewFlags.TransformInverse,e.ViewFlags.BoundingBox)}static from(e={}){const t=new ci(e.center?.x??0,e.center?.y??0,e.size?.width??0,e.size?.height??0);return e.viewport&&(t.viewport=e.viewport),e.rotation&&0!==e.rotation&&(t.rotation=e.rotation),void 0!==e.zoom&&1!==e.zoom&&t.setZoom(e.zoom),t}_onObservableChange(){this._setPositionDirty()}get center(){return this._center}set center(e){this._center.copy(e)}get size(){return this._size}set size(e){this._size.copy(e)}get width(){return this._size.width}set width(e){this._size.width=e}get height(){return this._size.height}set height(e){this._size.height=e}get rotation(){return this._rotation}set rotation(e){this.setRotation(e)}get viewport(){return this._viewport}set viewport(e){this._viewport.equals(e)||(this._viewport.copy(e),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(e,t){return this._center.set(e,t),this}resize(e,t){return this._zoomBaseWidth=e,this._zoomBaseHeight=t,this._zoomLevel=1,this._size.set(e,t),this}setRotation(e){const t=q(e);return this._rotation!==t&&(this._rotation=t,this._setRotationDirty()),this}setViewport(e,t,i,n){return this._viewport.x===e&&this._viewport.y===t&&this._viewport.width===i&&this._viewport.height===n||(this._viewport.set(e,t,i,n),this._setDirty()),this}move(e,t){return this.setCenter(this._center.x+e,this._center.y+t),this}zoom(e){return this.resize(this._size.width*e,this._size.height*e),this}setZoom(e){const t=Math.max(1e-4,e);return this._zoomLevel=t,this._size.set(this._zoomBaseWidth/t,this._zoomBaseHeight/t),this}zoomIn(e=.1){return this.setZoom(this._zoomLevel+e)}zoomOut(e=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-e))}follow(e,t={}){return this._followTarget=e,this._followLerp=Y(t.lerp??1,0,1),this._followOffsetX=t.offsetX??0,this._followOffsetY=t.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(e){return null===e?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=e.clone():this._boundsConstraint.copy(e),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(e,t,i={}){return this._shakeIntensity=Math.max(0,e),this._shakeDurationMs=Math.max(0,t),this._shakeElapsedMs=0,this._shakeFrequency=Math.max(0,i.frequency??16),this._shakeDecay=i.decay??!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty(),this}stopShake(){return this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakePhase=0,0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()),this}update(e){return this._updateFollowTarget(),this._updateShake(e),this._applyBoundsConstraint(),this}rotate(e){return this.setRotation(this._rotation+e),this}reset(t,i,n,r){return this._zoomBaseWidth=n,this._zoomBaseHeight=r,this._zoomLevel=1,this._size.set(n,r),this._center.set(t,i),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(e.ViewFlags.Transform),this}getTransform(){return this._flags.has(e.ViewFlags.Transform)&&(this.updateTransform(),this._flags.remove(e.ViewFlags.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,i=this._center.y+this._shakeOffsetY,n=2/this.width,r=-2/this.height;if(this._flags.has(e.ViewFlags.Rotation)){const e=W(this._rotation);this._cos=Math.cos(e),this._sin=Math.sin(e)}return this._flags.has(e.ViewFlags.Rotation|e.ViewFlags.Scaling)&&(this._transform.a=n*this._cos,this._transform.b=n*this._sin,this._transform.c=-r*this._sin,this._transform.d=r*this._cos),this._transform.x=n*-this._transform.a-r*this._transform.b+-n*t,this._transform.y=n*-this._transform.c-r*this._transform.d+-r*i,this}getInverseTransform(){return this._flags.has(e.ViewFlags.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(e.ViewFlags.TransformInverse)),this._inverseTransform}screenToWorld(e,t,i,n){let r,s;if(void 0===i||void 0===n){r=e/(this.width||1)*2-1,s=1-t/(this.height||1)*2}else{const o=this._viewport.width*i,a=this._viewport.height*n;r=(e-this._viewport.x*i)/o*2-1,s=1-(t-this._viewport.y*n)/a*2}const o=this.getTransform(),a=o.a*o.d-o.b*o.c;if(0===a)return{x:0,y:0};const h=r-o.x,l=s-o.y;return{x:(h*o.d-l*o.b)/a,y:(l*o.a-h*o.c)/a}}worldToScreen(e,t,i,n){const r=this.getTransform(),s=r.a*e+r.b*t+r.x,o=r.c*e+r.d*t+r.y;if(void 0===i||void 0===n)return{x:(s+1)/2*this.width,y:(1-o)/2*this.height};const a=this._viewport.x*i,h=this._viewport.y*n;return{x:a+(s+1)/2*this._viewport.width*i,y:h+(1-o)/2*this._viewport.height*n}}getBounds(){return this._flags.has(e.ViewFlags.BoundingBox)&&(this.updateBounds(),this._flags.remove(e.ViewFlags.BoundingBox)),this._bounds.getRect()}updateBounds(){const e=this._center.x+this._shakeOffsetX,t=this._center.y+this._shakeOffsetY,i=this.width/2,n=this.height/2;return this._bounds.reset().addCoords(e-i,t-n).addCoords(e+i,t+n),this}destroy(){this.stopShake(),this.clearFollow(),this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this._center.destroy(),this._size.destroy(),this._viewport.destroy(),this._transform.destroy(),this._inverseTransform.destroy(),this._bounds.destroy(),this._flags.destroy()}_setDirty(){this._flags.push(e.ViewFlags.TransformInverse,e.ViewFlags.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(e.ViewFlags.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(e.ViewFlags.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(e.ViewFlags.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;let e,t;if(this._followTarget instanceof Lt){const i=this._followTarget.getGlobalTransform();e=i.x+this._followOffsetX,t=i.y+this._followOffsetY}else e=this._followTarget.x+this._followOffsetX,t=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(e,t):this.setCenter(this._center.x+(e-this._center.x)*this._followLerp,this._center.y+(t-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const e=this._boundsConstraint,t=this.width/2,i=this.height/2,n=e.left+t,r=e.right-t,s=e.top+i,o=e.bottom-i,a=n>r?(e.left+e.right)/2:Y(this._center.x,n,r),h=s>o?(e.top+e.bottom)/2:Y(this._center.y,s,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(e){if(this._shakeDurationMs<=0||this._shakeIntensity<=0)return void(0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()));this._shakeElapsedMs=Math.min(this._shakeDurationMs,this._shakeElapsedMs+Math.max(0,e));const t=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-t):this._shakeIntensity;this._shakePhase+=Math.max(0,e)/1e3*this._shakeFrequency*Math.PI*2;const n=Math.sin(1.7*this._shakePhase)*i,r=Math.cos(1.3*this._shakePhase)*i;n===this._shakeOffsetX&&r===this._shakeOffsetY||(this._shakeOffsetX=n,this._shakeOffsetY=r,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}class di{needsStencil=!1;_root;_destroyListeners=new Set;_version=0;_size;_viewport=new et;_defaultView;_view;constructor(e,t,i=!1){this._size=new l(e,t),this._root=i,this._defaultView=new ci(e/2,t/2,e,t),this._view=this._defaultView}get view(){return this._view}set view(e){this.setView(e)}get size(){return this._size}set size(e){this.resize(e.width,e.height)}get width(){return this._size.width}set width(e){this.resize(e,this.height)}get height(){return this._size.height}set height(e){this.resize(this.width,e)}get root(){return this._root}get version(){return this._version}addDestroyListener(e){return this._destroyListeners.add(e),this}removeDestroyListener(e){return this._destroyListeners.delete(e),this}setView(e){const t=e||this._defaultView;return this._view!==t&&(this._view=t,this._touch()),this}resize(e,t){return this._size.equals({width:e,height:t})||(this._size.set(e,t),this._touch()),this}getViewport(e=this._view){const{x:t,y:i,width:n,height:r}=e.viewport;return this._viewport.set(Math.round(t*this.width),Math.round(i*this.height),Math.round(n*this.width),Math.round(r*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(e,t=this._view){const i=this.getViewport(t);return new it(2*(e.x-i.left)/i.width-1,1-2*(e.y-i.top)/i.height).transform(t.getInverseTransform())}mapCoordsToPixel(e,t=this._view){const i=this.getViewport(t),n=e.clone().transform(t.getTransform());return n.set((n.x+1)/2*i.width+i.left|0,(1-n.y)/2*i.height+i.top|0)}destroy(){for(const e of[...this._destroyListeners])e();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}class _i extends di{static defaultSamplerOptions={scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};_source=null;_textureVersion=0;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;constructor(e,t,i){super(e,t,!1);const{scaleMode:n,wrapMode:r,premultiplyAlpha:s,generateMipMap:o,flipY:a}={..._i.defaultSamplerOptions,...i};this._scaleMode=n,this._wrapMode=r,this._premultiplyAlpha=s,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(e){this.setSource(e)}get scaleMode(){return this._scaleMode}set scaleMode(e){this.setScaleMode(e)}get wrapMode(){return this._wrapMode}set wrapMode(e){this.setWrapMode(e)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(e){this.setPremultiplyAlpha(e)}get generateMipMap(){return this._generateMipMap}set generateMipMap(e){this._generateMipMap=e}get flipY(){return this._flipY}set flipY(e){this._flipY=e}get powerOfTwo(){return X(this.width)&&X(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(e){return this._scaleMode!==e&&(this._scaleMode=e,this._touchTexture()),this}setWrapMode(e){return this._wrapMode!==e&&(this._wrapMode=e,this._touchTexture()),this}setPremultiplyAlpha(e){return this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._touchTexture()),this}setSource(e){return this._source!==e&&(this._source=e,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(e,t){return this._size.equals({width:e,height:t})||(this._size.set(e,t),this._defaultView.resize(e,t),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}const fi=(e={})=>{const{canvas:t,fillStyle:i,width:n,height:r}=e,s=t??document.createElement("canvas"),o=s.getContext("2d");return s.width=n??10,s.height=r??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,s.width,s.height),s};class pi{static _black=null;static _white=null;static defaultSamplerOptions={scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1};static empty=new pi(null);static get black(){return null===pi._black&&(pi._black=new pi(fi({fillStyle:"#000"}))),pi._black}static get white(){return null===pi._white&&(pi._white=new pi(fi({fillStyle:"#fff"}))),pi._white}_version=0;_source=null;_size=new l(0,0);_destroyListeners=new Set;_scaleMode;_wrapMode;_premultiplyAlpha=!1;_generateMipMap=!1;_flipY=!1;constructor(e=null,t){const{scaleMode:i,wrapMode:n,premultiplyAlpha:r,generateMipMap:s,flipY:o}={...pi.defaultSamplerOptions,...t};this._scaleMode=i,this._wrapMode=n,this._premultiplyAlpha=r,this._generateMipMap=s,this._flipY=o,null!==e&&this.setSource(e)}get source(){return this._source}set source(e){this.setSource(e)}get size(){return this._size}set size(e){this.setSize(e.width,e.height)}get width(){return this._size.width}set width(e){this.setSize(e,this.height)}get height(){return this._size.height}set height(e){this.setSize(this.width,e)}get scaleMode(){return this._scaleMode}set scaleMode(e){this.setScaleMode(e)}get wrapMode(){return this._wrapMode}set wrapMode(e){this.setWrapMode(e)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(e){this.setPremultiplyAlpha(e)}get generateMipMap(){return this._generateMipMap}set generateMipMap(e){this._generateMipMap=e}get flipY(){return this._flipY}set flipY(e){this._flipY=e}get powerOfTwo(){return X(this.width)&&X(this.height)}get version(){return this._version}_bumpVersion(){this._version++}addDestroyListener(e){return this._destroyListeners.add(e),this}removeDestroyListener(e){return this._destroyListeners.delete(e),this}setScaleMode(e){return this._scaleMode!==e&&(this._scaleMode=e,this._touch()),this}setWrapMode(e){return this._wrapMode!==e&&(this._wrapMode=e,this._touch()),this}setPremultiplyAlpha(e){return this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this._touch()),this}setSource(e){return this._source!==e&&(this._source=e,this.updateSource()),this}updateSource(){const{width:e,height:t}=null===(i=this._source)?l.zero:y(i);var i;return this.setSize(e,t),this._touch(),this}setSize(e,t){return this._size.equals({width:e,height:t})||(this._size.set(e,t),this._touch()),this}destroy(){for(const e of[...this._destroyListeners])e();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}class mi{static play(e,t,i){const{node:n,effect:r}=e,s=r.filters.length>0,o=r.cacheAsBitmap,{left:a,top:h,width:l,height:u}=e;if(!s&&!o&&!r.needsBackdropBlend)return void this._withClip(n,t,e,()=>{null!==e.childPlan&&i(e.childPlan)});if(o&&null===e.childPlan){const i=n._renderPlanGetCacheTexture();return void(null!==i&&this._withClip(n,t,e,()=>{n._renderPlanDrawTexture(t,i,a,h,l,u,r.blendMode)}))}const c=o?n._renderPlanEnsureCacheTexture(l,u):null;let d=null;try{const _=o&&!s?c:t.acquireRenderTexture(l,u);_!==c&&(d=_),n._renderPlanRenderToTexture(t,_,a,h,l,u,()=>{null!==e.childPlan&&i(e.childPlan)});let f=_;if(s)for(let e=0;e<r.filters.length;e++){const i=e===r.filters.length-1&&o?c:t.acquireRenderTexture(l,u);try{r.filters[e].apply(t,f,i)}catch(e){throw i!==c&&t.releaseRenderTexture(i),e}null!==d&&(t.releaseRenderTexture(d),d=null),f=i,i!==c&&(d=i)}o&&n._renderPlanStoreCacheTexture(c,a,h,l,u),this._withClip(n,t,e,()=>{r.needsBackdropBlend?t.composeWithBackdropBlend(f,a,h,l,u,r.blendMode):n._renderPlanDrawTexture(t,f,a,h,l,u,r.blendMode)})}finally{null!==d&&t.releaseRenderTexture(d)}}static _withClip(e,t,i,n){if(i.effect.clip!==ri.Stencil)this._withRectClip(e,t,i,n);else{t.pushStencilClip(i.effect.clipShape,e.getGlobalTransform());try{this._withRectClip(e,t,i,n)}finally{t.popStencilClip()}}}static _withRectClip(e,t,i,n){if(i.effect.clip===ri.Rect){const r=i.effect.clipShape??e.getBounds();if(r.width<=0||r.height<=0)return;t.pushScissorRect(r);try{this._withMask(e,t,i,n)}finally{t.popScissorRect()}return}this._withMask(e,t,i,n)}static _withMask(e,t,i,n){const r=i.effect.maskSource;if(null===r)return void n();if(r instanceof et){if(r.width<=0||r.height<=0)return;t.pushScissorRect(r);try{n()}finally{t.popScissorRect()}return}const s=t.acquireRenderTexture(i.width,i.height),o=[s];try{e._renderPlanRenderToTexture(t,s,i.left,i.top,i.width,i.height,n);const a=this._resolveMaskTexture(e,t,r,i,o);t.composeWithAlphaMask(s,a,i.left,i.top,i.width,i.height,i.effect.blendMode)}finally{for(const e of o)t.releaseRenderTexture(e)}}static _resolveMaskTexture(e,t,i,n,r){if(!(i instanceof pi||i instanceof _i)){const s=t.acquireRenderTexture(n.width,n.height);return r.push(s),e._renderPlanRenderToTexture(t,s,n.left,n.top,n.width,n.height,()=>{i.render(t)}),s}return i}}const gi=(e,t)=>{const i=e[t].command.groupIndex;if(void 0===i)return 1;let n=1;for(let r=t+1;r<e.length;r++){const t=e[r];if(t.kind!==Yt.Draw||t.command.groupIndex!==i)break;n++}return n};class yi{static play(e,t){const i=t;i._beginDrawPlan?.(e.nodeCount);try{for(const n of e.passes)null!==n.target&&t.renderTarget!==n.target&&t.setRenderTarget(n.target),t.view!==n.view&&t.setView(n.view),null!==n.clearColor&&t.clear(n.clearColor),this._playScope(n.root,t,i,this._createPlaybackContext())}finally{i._endDrawPlan?.()}}static playScope(e,t){const i=t;this._playScope(e,t,i,this._createPlaybackContext())}static _playScope(e,t,i,n){e.kind!==Yt.Barrier?this._playGroup(e,t,i,n):mi.play(e,t,e=>{this._playScope(e,t,i,n)})}static _playGroup(e,t,i,n){const r=e.entries;if(void 0!==i._prepareRenderGroupUpload){let e=n.passInstructionIndex,t=0;for(let s=0;s<r.length;){if(r[s].kind!==Yt.Draw){s++;continue}const o=gi(r,s);i._prepareRenderGroupUpload(r,s,o,this._createRenderGroupPlaybackContext(o,e,n.passGroupIndex+t)),e+=o,t++,s+=o}}let s=-1,o=0,a=0;for(let e=0;e<r.length;e++){const h=r[e];if(h.kind===Yt.Draw){if(-1===s&&(s=e,o=gi(r,e),a=0,i._beginRenderGroup?.(r,s,o),n.passGroupIndex++),void 0!==i._prepareRenderInstructionSlot){const e=this._createRenderInstructionSlot(a,n.passInstructionIndex);i._prepareRenderInstructionSlot(h.command,e)}i._prepareDrawCommand?.(h.command),t.draw(h.command.drawable),a++,n.passInstructionIndex++,a===o&&(i._endRenderGroup?.(r,s,o),s=-1,o=0,a=0)}else h.kind===Yt.Group?this._playGroup(h.scope,t,i,n):mi.play(h.scope,t,e=>{this._playScope(e,t,i,n)})}}static _createPlaybackContext(){return{passInstructionIndex:0,passGroupIndex:0}}static _createRenderGroupPlaybackContext(e,t,i){return Object.freeze({groupInstructionCount:e,firstPassInstructionIndex:t,lastPassInstructionIndex:t+e-1,passGroupIndex:i})}static _createRenderInstructionSlot(e,t){return Object.freeze({groupInstructionIndex:e,passInstructionIndex:t})}}function wi(e,t){const i=si.acquire();try{const n=i.build(e,t);hi.optimize(n),yi.play(n,t)}finally{si.release(i)}}var xi;!function(e){e[e.None=0]="None",e[e.Enabled=1]="Enabled"}(xi||(xi={}));class vi{_callback;_target;_view;_clearColor;constructor(e,t={}){this._callback=e,this._target=t.target??null,this._view=t.view??null,this._clearColor=t.clearColor??null}execute(e){const t=e._passCoordinator;if(t)return void t.withChildPass({target:this._target,view:this._view,load:null!==this._clearColor?"clear":"load",clearColor:this._clearColor,stencil:xi.None},()=>{this._callback(e)});const i=e.renderTarget,n=e.view;e.setRenderTarget(this._target),e.setView(this._view),null!==this._clearColor&&e.clear(this._clearColor);try{this._callback(e)}finally{e.setRenderTarget(i),e.setView(n)}}}const bi=e=>"destroy"in e&&"function"==typeof e.destroy;class Si extends Lt{static _spriteFactory=null;_interactive=!1;cursor=null;get interactive(){return this._interactive}set interactive(e){this._interactive!==e&&(this._interactive=e,this._stage?.interaction._notifyInteractiveChanged(this,e))}draggable=!1;preserveDrawOrder=!1;clip=!1;clipShape=null;_signals=null;get onPointerDown(){return this._interactionSignal("pointerdown")}get onPointerUp(){return this._interactionSignal("pointerup")}get onPointerMove(){return this._interactionSignal("pointermove")}get onPointerOver(){return this._interactionSignal("pointerover")}get onPointerOut(){return this._interactionSignal("pointerout")}get onPointerTap(){return this._interactionSignal("pointertap")}get onDragStart(){return this._interactionSignal("dragstart")}get onDrag(){return this._interactionSignal("drag")}get onDragEnd(){return this._interactionSignal("dragend")}_interactionSignal(e){const t=this._signals??=new Map;let i=t.get(e);return void 0===i&&(i=new x,t.set(e,i)),i}_peekInteractionSignal(e){return this._signals?.get(e)??null}focusable=!1;tabIndex=0;_onFocus=null;_onBlur=null;_onKeyDown=null;_onKeyUp=null;get onFocus(){return this._onFocus??=new x}get onBlur(){return this._onBlur??=new x}get onKeyDown(){return this._onKeyDown??=new x}get onKeyUp(){return this._onKeyUp??=new x}_peekFocusSignal(e){return"focus"===e?this._onFocus:this._onBlur}_peekKeySignal(e){return"keydown"===e?this._onKeyDown:this._onKeyUp}focus(){return this._stage?.focus.focus(this),this}blur(){return this._stage?.focus.blur(this),this}_filters=[];_cacheBounds=new et;_cacheSprite=null;_captureView=null;_mask=null;_cacheAsBitmap=!1;_cacheDirty=!0;_cacheTexture=null;get filters(){return this._filters}set filters(e){this._filters.length=0,this._filters.push(...e),this.invalidateCache()}get mask(){return this._mask}set mask(e){if(e===this)throw new Error("A RenderNode cannot use itself as its own mask source.");this._mask!==e&&(this._mask=e,this.invalidateCache())}render(e){return wi(this,e),this}_collect(e,t){this.visible&&(this.inView(e.view)?e.emitNode(this,t):e.backend.stats.culledNodes++)}_collectForRenderPlan(e){this._collectContent(e)}_isDrawableForRenderPlan(){return!1}_collectContent(e){}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(e){this._cacheAsBitmap!==e&&(this._cacheAsBitmap=e,this.invalidateCache(),e||this._destroyCacheTexture())}addFilter(e){return this._filters.push(e),this.invalidateCache()}removeFilter(e){const t=this._filters.indexOf(e);return-1!==t&&(this._filters.splice(t,1),this.invalidateCache()),this}static setInternalSpriteFactory(e){Si._spriteFactory=e}clearFilters(){return this._filters.length>0&&(this._filters.length=0,this.invalidateCache()),this}invalidateCache(){return this._cacheDirty=!0,this}_renderPlanHasBarrierEffects(){return this._filters.length>0||null!==this._mask||this._cacheAsBitmap||this.clip||Gt(this._renderPlanGetBlendMode())}_renderPlanGetMaskSource(){return this._mask}_renderPlanGetFilters(){return this._filters}_renderPlanGetBlendMode(){return e.BlendModes.Normal}_renderPlanCanReuseBitmapCache(e,t,i,n){return this._cacheAsBitmap&&!this._cacheDirty&&null!==this._cacheTexture&&this._cacheBounds.equals({x:e,y:t,width:i,height:n})}_renderPlanGetCacheTexture(){return this._cacheTexture}_renderPlanEnsureCacheTexture(e,t){return this._ensureCacheTexture(e,t)}_renderPlanStoreCacheTexture(e,t,i,n,r){this._cacheTexture=e,this._cacheBounds.set(t,i,n,r),this._cacheDirty=!1}_renderPlanRenderToTexture(e,t,i,n,r,s,o){this._renderContentToTexture(e,t,i,n,r,s,o)}_renderPlanDrawTexture(e,t,i,n,r,s,o){this._drawTexture(e,t,i,n,r,s,o)}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const e of this._filters)bi(e)&&e.destroy();if(this._filters.length=0,this._mask=null,null!==this._signals){for(const e of this._signals.values())e.destroy();this._signals.clear(),this._signals=null}this._onFocus?.destroy(),this._onBlur?.destroy(),this._onKeyDown?.destroy(),this._onKeyUp?.destroy(),this._onFocus=this._onBlur=this._onKeyDown=this._onKeyUp=null}_renderContentToTexture(e,t,i,n,r,s,o){null===this._captureView?this._captureView=new ci(i+r/2,n+s/2,r,s):this._captureView.reset(i+r/2,n+s/2,r,s),e.execute(new vi(()=>{o()},{target:t,view:this._captureView,clearColor:Tt.transparentBlack}))}_drawTexture(e,t,i,n,r,s,o){const a=this._getCacheSprite();a.setTexture(t).setBlendMode(o).setTint(Tt.white).setPosition(i,n).setRotation(0).setScale(1,1),a.width=r,a.height=s,a.render(e)}_ensureCacheTexture(e,t){return null===this._cacheTexture?this._cacheTexture=new _i(e,t):this._cacheTexture.width===e&&this._cacheTexture.height===t||this._cacheTexture.setSize(e,t),this._cacheTexture}_destroyCacheTexture(){null!==this._cacheTexture&&(this._cacheTexture.destroy(),this._cacheTexture=null),this._cacheDirty=!0}_getCacheSprite(){if(null===this._cacheSprite){if(null===Si._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=Si._spriteFactory()}return this._cacheSprite}}class Bi extends Si{_children=[];get children(){return this._children}get width(){return Math.abs(this.scale.x)*this.getBounds().width}set width(e){this.scale.x=e/this.getBounds().width}get height(){return Math.abs(this.scale.y)*this.getBounds().height}set height(e){this.scale.y=e/this.getBounds().height}get left(){return this.x-this.width*this.origin.x}get top(){return this.y-this.height*this.origin.y}get right(){return this.x+this.width-this.origin.x}get bottom(){return this.y+this.height-this.origin.y}addChild(...e){for(const t of e)this.addChildAt(t,this._children.length);return this}addChildAt(e,t){if(t<0||t>this._children.length)throw new Error(`The index ${t} is out of bounds ${this._children.length}`);return e===this||(e.parent&&e.parent.removeChild(e),e.parent=this,this._children.splice(t,0,e),this.invalidateCache(),e._invalidateSubtreeTransform(),this._invalidateBoundsCascade(),e._setStage(this._stage),this._stage?.interaction._notifyNodeAdded(e)),this}swapChildren(e,t){if(e!==t){const i=this.getChildIndex(e),n=this.getChildIndex(t);this._children[i]=t,this._children[n]=e,this.invalidateCache()}return this}getChildIndex(e){const t=this._children.indexOf(e);if(-1===t)throw new Error("Drawable is not a child of the container.");return t}setChildIndex(e,t){if(t<0||t>=this._children.length)throw new Error(`The index ${t} is out of bounds ${this._children.length}`);return g(this._children,this.getChildIndex(e),1),this._children.splice(t,0,e),this.invalidateCache(),this}getChildAt(e){if(e<0||e>=this._children.length)throw new Error(`getChildAt: Index (${e}) does not exist.`);return this._children[e]}removeChild(e){const t=this._children.indexOf(e);return-1!==t&&this.removeChildAt(t),this}removeChildAt(e){const t=this._children[e];return g(this._children,e,1),t?.parent===this&&(this._invalidateBoundsCascade(),t.parent=null,t._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(t),this._stage?.focus._notifyNodeRemoved(t),t._setStage(null)),this.invalidateCache(),this}removeChildren(e=0,t=this._children.length){const i=t-e;if(i<0||i>t)throw new Error("Values are outside the acceptable range.");i>0&&this._invalidateBoundsCascade();for(let i=e;i<t;i++){const e=this._children[i];e?.parent===this&&(e.parent=null,e._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(e),this._stage?.focus._notifyNodeRemoved(e),e._setStage(null))}return g(this._children,e,i),this.invalidateCache(),this}_setStage(e){if(this._stage!==e){this._stage=e;for(const t of this._children)t._setStage(e)}}_collectContent(e){if(0!==this._children.length)for(let t=0;t<this._children.length;t++)this._children[t]._collect(e,t)}contains(e,t){const i=this._children;for(let n=0;n<i.length;n++)if(i[n].contains(e,t))return!0;return!1}_invalidateChildrenTransform(){for(const e of this._children)e._invalidateSubtreeTransform()}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const e of this._children)e.visible&&this._bounds.addRect(e.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}}class Ci{type;channel;target;_defaultPrevented=!1;constructor(e,t,i){this.type=e,this.channel=t,this.target=i}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}}var Ti,Mi;e.ChannelSize=void 0,(Ti=e.ChannelSize||(e.ChannelSize={}))[Ti.Container=768]="Container",Ti[Ti.Category=256]="Category",Ti[Ti.Gamepad=64]="Gamepad",e.ChannelOffset=void 0,(Mi=e.ChannelOffset||(e.ChannelOffset={}))[Mi.Keyboard=0]="Keyboard",Mi[Mi.Pointers=256]="Pointers",Mi[Mi.Gamepads=512]="Gamepads";var Pi;e.Keyboard=void 0,(Pi=e.Keyboard||(e.Keyboard={}))[Pi.Backspace=8]="Backspace",Pi[Pi.Tab=9]="Tab",Pi[Pi.Clear=12]="Clear",Pi[Pi.Enter=13]="Enter",Pi[Pi.Shift=16]="Shift",Pi[Pi.Control=17]="Control",Pi[Pi.Alt=18]="Alt",Pi[Pi.Pause=19]="Pause",Pi[Pi.CapsLock=20]="CapsLock",Pi[Pi.Escape=27]="Escape",Pi[Pi.Space=32]="Space",Pi[Pi.PageUp=33]="PageUp",Pi[Pi.PageDown=34]="PageDown",Pi[Pi.End=35]="End",Pi[Pi.Home=36]="Home",Pi[Pi.Left=37]="Left",Pi[Pi.Up=38]="Up",Pi[Pi.Right=39]="Right",Pi[Pi.Down=40]="Down",Pi[Pi.Insert=45]="Insert",Pi[Pi.Delete=46]="Delete",Pi[Pi.Help=47]="Help",Pi[Pi.Zero=48]="Zero",Pi[Pi.One=49]="One",Pi[Pi.Two=50]="Two",Pi[Pi.Three=51]="Three",Pi[Pi.Four=52]="Four",Pi[Pi.Five=53]="Five",Pi[Pi.Six=54]="Six",Pi[Pi.Seven=55]="Seven",Pi[Pi.Eight=56]="Eight",Pi[Pi.Nine=57]="Nine",Pi[Pi.A=65]="A",Pi[Pi.B=66]="B",Pi[Pi.C=67]="C",Pi[Pi.D=68]="D",Pi[Pi.E=69]="E",Pi[Pi.F=70]="F",Pi[Pi.G=71]="G",Pi[Pi.H=72]="H",Pi[Pi.I=73]="I",Pi[Pi.J=74]="J",Pi[Pi.K=75]="K",Pi[Pi.L=76]="L",Pi[Pi.M=77]="M",Pi[Pi.N=78]="N",Pi[Pi.O=79]="O",Pi[Pi.P=80]="P",Pi[Pi.Q=81]="Q",Pi[Pi.R=82]="R",Pi[Pi.S=83]="S",Pi[Pi.T=84]="T",Pi[Pi.U=85]="U",Pi[Pi.V=86]="V",Pi[Pi.W=87]="W",Pi[Pi.X=88]="X",Pi[Pi.Y=89]="Y",Pi[Pi.Z=90]="Z",Pi[Pi.NumPad0=96]="NumPad0",Pi[Pi.NumPad1=97]="NumPad1",Pi[Pi.NumPad2=98]="NumPad2",Pi[Pi.NumPad3=99]="NumPad3",Pi[Pi.NumPad4=100]="NumPad4",Pi[Pi.NumPad5=101]="NumPad5",Pi[Pi.NumPad6=102]="NumPad6",Pi[Pi.NumPad7=103]="NumPad7",Pi[Pi.NumPad8=104]="NumPad8",Pi[Pi.NumPad9=105]="NumPad9",Pi[Pi.NumPadMultiply=106]="NumPadMultiply",Pi[Pi.NumPadAdd=107]="NumPadAdd",Pi[Pi.NumPadEnter=108]="NumPadEnter",Pi[Pi.NumPadSubtract=109]="NumPadSubtract",Pi[Pi.NumPadDecimal=110]="NumPadDecimal",Pi[Pi.NumPadDivide=111]="NumPadDivide",Pi[Pi.F1=112]="F1",Pi[Pi.F2=113]="F2",Pi[Pi.F3=114]="F3",Pi[Pi.F4=115]="F4",Pi[Pi.F5=116]="F5",Pi[Pi.F6=117]="F6",Pi[Pi.F7=118]="F7",Pi[Pi.F8=119]="F8",Pi[Pi.F9=120]="F9",Pi[Pi.F10=121]="F10",Pi[Pi.F11=122]="F11",Pi[Pi.F12=123]="F12",Pi[Pi.NumLock=144]="NumLock",Pi[Pi.ScrollLock=145]="ScrollLock",Pi[Pi.Colon=186]="Colon",Pi[Pi.Equals=187]="Equals",Pi[Pi.Comma=188]="Comma",Pi[Pi.Dash=189]="Dash",Pi[Pi.Period=190]="Period",Pi[Pi.QuestionMark=191]="QuestionMark",Pi[Pi.Tilde=192]="Tilde",Pi[Pi.OpenBracket=219]="OpenBracket",Pi[Pi.BackwardSlash=220]="BackwardSlash",Pi[Pi.ClosedBracket=221]="ClosedBracket",Pi[Pi.Quotes=222]="Quotes";class Ai{_app;_focused=null;_shiftDown=!1;_scopeStack=[];_onKeyDownHandler;_onKeyUpHandler;constructor(e){this._app=e,this._onKeyDownHandler=this._handleKeyDown.bind(this),this._onKeyUpHandler=this._handleKeyUp.bind(this),e.input.onKeyDown.add(this._onKeyDownHandler),e.input.onKeyUp.add(this._onKeyUpHandler)}get focused(){return this._focused}focus(e){e!==this._focused&&e.focusable&&(this.blur(),this._focused=e,e._peekFocusSignal("focus")?.dispatch(e))}blur(e){const t=this._focused;null===t||void 0!==e&&e!==t||(this._focused=null,t._peekFocusSignal("blur")?.dispatch(t))}pushScope(e){this._scopeStack.push(e)}popScope(){this._scopeStack.pop()}focusNext(){this._step(1)}focusPrevious(){this._step(-1)}_notifyNodeRemoved(e){let t=this._focused;for(;null!==t;){if(t===e)return void this.blur();t=t.parent}}destroy(){this._app.input.onKeyDown.remove(this._onKeyDownHandler),this._app.input.onKeyUp.remove(this._onKeyUpHandler),this._scopeStack.length=0,this._focused=null}_handleKeyDown(t){t===e.Keyboard.Shift&&(this._shiftDown=!0);const i=this._focused;let n=!1;if(null!==i){const e=new Ci("keydown",t,i);i._peekKeySignal("keydown")?.dispatch(e),n=e.defaultPrevented}n||t!==e.Keyboard.Tab||(this._shiftDown?this.focusPrevious():this.focusNext())}_handleKeyUp(t){t===e.Keyboard.Shift&&(this._shiftDown=!1);const i=this._focused;null!==i&&i._peekKeySignal("keyup")?.dispatch(new Ci("keyup",t,i))}_step(e){const t=this._collectFocusables();if(0===t.length)return;const i=null===this._focused?-1:t.indexOf(this._focused),n=t.length;let r;r=-1===i?1===e?0:n-1:(i+e+n)%n;const s=t[r];void 0!==s&&this.focus(s)}_collectFocusables(){const e=this._scopeStack.at(-1)??this._app.scene.currentScene?.root??null;if(null===e)return[];const t=[];return this._collectInto(e,t),t.map((e,t)=>({node:e,index:t})).sort((e,t)=>e.node.tabIndex-t.node.tabIndex||e.index-t.index).map(e=>e.node)}_collectInto(e,t){if(e.visible&&(e.focusable&&t.push(e),e instanceof Bi))for(const i of e.children)this._collectInto(i,t)}}let Ei=null;class ki{_milliseconds;constructor(e=0,t=ki.milliseconds){this._milliseconds=e*t}get milliseconds(){return this._milliseconds}set milliseconds(e){this._milliseconds=e}get seconds(){return this._milliseconds/ki.seconds}set seconds(e){this._milliseconds=e*ki.seconds}get minutes(){return this._milliseconds/ki.minutes}set minutes(e){this._milliseconds=e*ki.minutes}get hours(){return this._milliseconds/ki.hours}set hours(e){this._milliseconds=e*ki.hours}set(e=0,t=ki.milliseconds){return this._milliseconds=e*t,this}setMilliseconds(e){return this.milliseconds=e,this}setSeconds(e){return this.seconds=e,this}setMinutes(e){return this.minutes=e,this}setHours(e){return this.hours=e,this}equals({milliseconds:e,seconds:t,minutes:i,hours:n}={}){return!(void 0!==e&&this.milliseconds!==e||void 0!==t&&this.seconds!==t||void 0!==i&&this.minutes!==i||void 0!==n&&this.hours!==n)}greaterThan(e){return this._milliseconds>e.milliseconds}lessThan(e){return this._milliseconds<e.milliseconds}clone(){return new ki(this._milliseconds)}copy(e){return this._milliseconds=e.milliseconds,this}add(e=0,t=ki.milliseconds){return this._milliseconds+=e*t,this}addTime(e){return this._milliseconds+=e.milliseconds,this}subtract(e=0,t=ki.milliseconds){return this._milliseconds-=e*t,this}subtractTime(e){return this._milliseconds-=e.milliseconds,this}destroy(){}static milliseconds=1;static seconds=1e3;static minutes=6e4;static hours=36e5;static now(){return new ki(performance.now())}static fromMilliseconds(e){return new ki(e,ki.milliseconds)}static fromSeconds(e){return new ki(e,ki.seconds)}static fromMinutes(e){return new ki(e,ki.minutes)}static fromHours(e){return new ki(e,ki.hours)}static zero=new ki(0);static oneMillisecond=new ki(1);static oneSecond=new ki(1,ki.seconds);static oneMinute=new ki(1,ki.minutes);static oneHour=new ki(1,ki.hours);static get temp(){return null===Ei&&(Ei=new ki),Ei}}class Ri{_startTime;_elapsedTime=new ki(0);_running=!1;constructor(e=ki.zero,t=!1){this._startTime=e.clone(),t&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const e=p();this._elapsedTime.add(e-this._startTime.milliseconds),this._startTime.milliseconds=e}return this._elapsedTime}get elapsedMilliseconds(){return this.elapsedTime.milliseconds}get elapsedSeconds(){return this.elapsedTime.seconds}get elapsedMinutes(){return this.elapsedTime.minutes}get elapsedHours(){return this.elapsedTime.hours}start(){return this._running||(this._running=!0,this._startTime.milliseconds=p()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(p()-this._startTime.milliseconds)),this}reset(){return this._running=!1,this._elapsedTime.setMilliseconds(0),this}restart(){return this.reset(),this.start(),this}destroy(){this._startTime.destroy(),this._elapsedTime.destroy()}}class Di extends Ri{_limit;constructor(e,t=!1){super(),this._limit=e.clone(),t&&this.restart()}get limit(){return this._limit}set limit(e){this._limit.copy(e)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/ki.seconds}get remainingMinutes(){return this.remainingMilliseconds/ki.minutes}get remainingHours(){return this.remainingMilliseconds/ki.hours}}class Fi{static defaultTriggerThreshold=300;channels;onStart=new x;onActive=new x;onStop=new x;onTrigger=new x;_triggerTimer;_detacher;_value=0;_unbound=!1;constructor(e,t={},i=null){this.channels=e,this._triggerTimer=new Di(ki.fromMilliseconds(t.threshold??Fi.defaultTriggerThreshold)),this._detacher=i}get value(){return this._value}get active(){return this._value>0}update(e){if(this._unbound)return;let t=0;for(const i of this.channels){const n=e[i];void 0!==n&&Math.abs(n)>Math.abs(t)&&(t=n)}this._value=t,0!==t?(this._triggerTimer.running||(this._triggerTimer.restart(),this.onStart.dispatch(t)),this.onActive.dispatch(t)):this._triggerTimer.running&&(this.onStop.dispatch(0),this._triggerTimer.expired||this.onTrigger.dispatch(0),this._triggerTimer.stop())}unbind(){this._unbound||(this._unbound=!0,this._detacher?.detach(this),this._triggerTimer.destroy(),this.onStart.destroy(),this.onActive.destroy(),this.onStop.destroy(),this.onTrigger.destroy())}}class Ii{onConnect=new x;onDisconnect=new x;onButtonDown=new x;onButtonUp=new x;onAxisChange=new x;onPadReassigned=new x;_slot;_channels;_bindings=new Set;_detacher={detach:e=>{this._bindings.delete(e)}};_channelOffset;_mapping=null;_info=null;_browserGamepad=null;constructor(t,i){this._slot=t,this._channels=i,this._channelOffset=e.ChannelOffset.Gamepads+t*e.ChannelSize.Gamepad}get slot(){return this._slot}get connected(){return null!==this._browserGamepad}get mapping(){return this._mapping}get mappingFamily(){return this._mapping?.family??null}get info(){return this._info}get browserGamepad(){return this._browserGamepad}get internalIndex(){return this._browserGamepad?.index??null}get canVibrate(){return null!=this._browserGamepad?.vibrationActuator}hasChannel(e){return this._mapping?.hasChannel(e)??!1}async vibrate(e){const t=this._browserGamepad?.vibrationActuator;t?.playEffect&&await t.playEffect("dual-rumble",{duration:e.duration,weakMagnitude:e.weakMagnitude??1,strongMagnitude:e.strongMagnitude??1,startDelay:e.startDelay??0})}stopVibration(){this._browserGamepad?.vibrationActuator?.reset?.()}onStart(e,t,i){const n=this._createBinding(e,i);return n.onStart.add(t),n}onActive(e,t,i){const n=this._createBinding(e,i);return n.onActive.add(t),n}onStop(e,t,i){const n=this._createBinding(e,i);return n.onStop.add(t),n}onTrigger(e,t,i){const n=this._createBinding(e,i);return n.onTrigger.add(t),n}_bind(e,t){this._browserGamepad=e,this._mapping=t.mapping,this._info={name:t.name,label:t.descriptor.label,vendorId:t.descriptor.vendorId,productId:t.descriptor.productId,productKey:t.descriptor.productKey},this.onConnect.dispatch()}_refreshBrowserGamepad(e){this._browserGamepad=e}_unbind(){null!==this._browserGamepad&&(this._clearMappedChannels(),this._browserGamepad=null,this._mapping=null,this._info=null,this.onDisconnect.dispatch())}_silentUnbind(){null!==this._browserGamepad&&(this._clearMappedChannels(),this._browserGamepad=null,this._mapping=null,this._info=null)}_dispatchDisconnect(){this.onDisconnect.dispatch()}_rebindFrom(e){const t=e._browserGamepad,i=e._mapping,n=e._info;this._clearMappedChannels(),e._clearMappedChannels(),e._browserGamepad=null,e._mapping=null,e._info=null,this._browserGamepad=t,this._mapping=i,this._info=n}update(){if(null===this._browserGamepad||null===this._mapping)return void this._updateBindings();const e=this._channels,{buttons:t,axes:i}=this._browserGamepad;for(const i of this._mapping.buttons){const n=t[i.index];if(void 0===n)continue;const r=this._resolveOffset(i.channel),s=e[r],o=i.transformValue(n.value)||0;s!==o&&(e[r]=o,0===s&&0!==o?this.onButtonDown.dispatch(i,o):0!==s&&0===o&&this.onButtonUp.dispatch(i,o))}for(const t of this._mapping.axes){const n=i[t.index];if(void 0===n)continue;const r=this._resolveOffset(t.channel),s=e[r],o=t.transformValue(n)||0;s!==o&&(e[r]=o,this.onAxisChange.dispatch(t,o))}this._updateBindings()}destroy(){for(const e of[...this._bindings])e.unbind();this._bindings.clear(),this._unbind(),this.onConnect.destroy(),this.onDisconnect.destroy(),this.onButtonDown.destroy(),this.onButtonUp.destroy(),this.onAxisChange.destroy(),this.onPadReassigned.destroy()}resolveChannelOffset(e){return this._resolveOffset(e)}static resolveChannelOffset(t,i){return e.ChannelOffset.Gamepads+t*e.ChannelSize.Gamepad+(i^e.ChannelOffset.Gamepads)}_resolveOffset(t){return this._channelOffset+(t^e.ChannelOffset.Gamepads)}_clearMappedChannels(){if(null!==this._mapping){for(const e of this._mapping.buttons)this._channels[this._resolveOffset(e.channel)]=0;for(const e of this._mapping.axes)this._channels[this._resolveOffset(e.channel)]=0}}_createBinding(e,t={}){const i=(Array.isArray(e)?e:[e]).map(e=>this._resolveExternalChannel(e)),n=new Fi(i,t,this._detacher);return this._bindings.add(n),n}_resolveExternalChannel(t){return t>=e.ChannelOffset.Gamepads&&t<e.ChannelOffset.Gamepads+e.ChannelSize.Category?this._resolveOffset(t):t}_updateBindings(){for(const e of this._bindings)e.update(this._channels)}}class Li{index;channel;invert;threshold;constructor(e,t,i={}){this.index=e,this.channel=t,this.invert=i.invert??!1,this.threshold=Y(i.threshold??.2,0,1)}transformValue(e){let t=Y(e,0,1);return this.invert&&(t=1-t),t>this.threshold?t:0}}const Ui=t=>e.ChannelOffset.Gamepads+t;var Gi;!function(e){e.South=Ui(0),e.East=Ui(1),e.West=Ui(2),e.North=Ui(3),e.LeftShoulder=Ui(4),e.RightShoulder=Ui(5),e.LeftTrigger=Ui(6),e.RightTrigger=Ui(7),e.Select=Ui(8),e.Start=Ui(9),e.LeftStick=Ui(10),e.RightStick=Ui(11),e.DPadUp=Ui(12),e.DPadDown=Ui(13),e.DPadLeft=Ui(14),e.DPadRight=Ui(15),e.Guide=Ui(16),e.Share=Ui(17),e.Capture=Ui(18),e.Touchpad=Ui(19),e.Paddle1=Ui(20),e.Paddle2=Ui(21),e.Paddle3=Ui(22),e.Paddle4=Ui(23)}(Li||(Li={})),e.GamepadMappingFamily=void 0,(Gi=e.GamepadMappingFamily||(e.GamepadMappingFamily={})).GenericDualAnalog="genericDualAnalog",Gi.Xbox="xbox",Gi.PlayStation="playStation",Gi.SwitchPro="switchPro",Gi.JoyConLeft="joyConLeft",Gi.JoyConRight="joyConRight",Gi.GameCube="gameCube",Gi.SteamController="steamController",Gi.SteamDeck="steamDeck",Gi.ArcadeStick="arcadeStick";class Ni{buttons;axes;constructor(e,t){this.buttons=e,this.axes=t}hasChannel(e){for(const t of this.buttons)if(t.channel===e)return!0;for(const t of this.axes)if(t.channel===e)return!0;return!1}destroy(){this.buttons.length=0,this.axes.length=0}}class Oi extends Ni{family=e.GamepadMappingFamily.ArcadeStick;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(6,Li.LeftTrigger),new Li(7,Li.RightTrigger),new Li(8,Li.Select),new Li(9,Li.Start),new Li(12,Li.DPadUp),new Li(13,Li.DPadDown),new Li(14,Li.DPadLeft),new Li(15,Li.DPadRight),new Li(16,Li.Guide)],[])}}class Vi{index;channel;invert;normalize;threshold;bipolar;constructor(e,t,i={}){this.index=e,this.channel=t,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=Y(i.threshold??.2,0,1),this.bipolar=i.bipolar??!1}transformValue(e){let t=Y(e,-1,1);return this.invert&&(t*=-1),this.normalize&&(t=(t+1)/2),this.bipolar?Math.abs(t)>this.threshold?t:0:t>this.threshold?t:0}}const zi=t=>e.ChannelOffset.Gamepads+t;!function(e){e.LeftStickLeft=zi(32),e.LeftStickRight=zi(33),e.LeftStickUp=zi(34),e.LeftStickDown=zi(35),e.RightStickLeft=zi(36),e.RightStickRight=zi(37),e.RightStickUp=zi(38),e.RightStickDown=zi(39),e.LeftStickX=zi(40),e.LeftStickY=zi(41),e.RightStickX=zi(42),e.RightStickY=zi(43),e.TouchpadX=zi(44),e.TouchpadY=zi(45),e.Touchpad2X=zi(46),e.Touchpad2Y=zi(47),e.AuxiliaryAxis0Negative=zi(48),e.AuxiliaryAxis0Positive=zi(49),e.AuxiliaryAxis1Negative=zi(50),e.AuxiliaryAxis1Positive=zi(51),e.AuxiliaryAxis2Negative=zi(52),e.AuxiliaryAxis2Positive=zi(53),e.AuxiliaryAxis3Negative=zi(54),e.AuxiliaryAxis3Positive=zi(55)}(Vi||(Vi={}));class qi extends Ni{family=e.GamepadMappingFamily.GenericDualAnalog;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(6,Li.LeftTrigger),new Li(7,Li.RightTrigger),new Li(8,Li.Select),new Li(9,Li.Start),new Li(10,Li.LeftStick),new Li(11,Li.RightStick),new Li(12,Li.DPadUp),new Li(13,Li.DPadDown),new Li(14,Li.DPadLeft),new Li(15,Li.DPadRight),new Li(16,Li.Guide),new Li(17,Li.Share),new Li(18,Li.Capture),new Li(19,Li.Touchpad),new Li(20,Li.Paddle1)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(2,Vi.RightStickLeft,{invert:!0}),new Vi(2,Vi.RightStickRight),new Vi(3,Vi.RightStickUp,{invert:!0}),new Vi(3,Vi.RightStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0}),new Vi(2,Vi.RightStickX,{bipolar:!0}),new Vi(3,Vi.RightStickY,{bipolar:!0}),new Vi(4,Vi.AuxiliaryAxis0Negative,{invert:!0}),new Vi(4,Vi.AuxiliaryAxis0Positive),new Vi(5,Vi.AuxiliaryAxis1Negative,{invert:!0}),new Vi(5,Vi.AuxiliaryAxis1Positive),new Vi(6,Vi.AuxiliaryAxis2Negative,{invert:!0}),new Vi(6,Vi.AuxiliaryAxis2Positive),new Vi(7,Vi.AuxiliaryAxis3Negative,{invert:!0}),new Vi(7,Vi.AuxiliaryAxis3Positive)])}}class Wi extends qi{family=e.GamepadMappingFamily.GameCube}class Yi extends Ni{family=e.GamepadMappingFamily.JoyConLeft;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(8,Li.Select),new Li(10,Li.LeftStick),new Li(16,Li.Capture)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0})])}}class $i extends Ni{family=e.GamepadMappingFamily.JoyConRight;constructor(){super([new Li(0,Li.South),new Li(1,Li.East),new Li(2,Li.West),new Li(3,Li.North),new Li(4,Li.LeftShoulder),new Li(5,Li.RightShoulder),new Li(9,Li.Start),new Li(10,Li.LeftStick),new Li(16,Li.Guide)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0})])}}class Xi extends qi{family=e.GamepadMappingFamily.PlayStation}class Hi extends qi{family=e.GamepadMappingFamily.SteamController}class ji extends Ni{family=e.GamepadMappingFamily.SteamDeck;constructor(){super([new Li(2,Li.Capture),new Li(3,Li.South),new Li(4,Li.East),new Li(5,Li.West),new Li(6,Li.North),new Li(7,Li.LeftShoulder),new Li(8,Li.RightShoulder),new Li(11,Li.Select),new Li(12,Li.Start),new Li(13,Li.Guide),new Li(14,Li.LeftStick),new Li(15,Li.RightStick),new Li(16,Li.DPadUp),new Li(17,Li.DPadDown),new Li(18,Li.DPadLeft),new Li(19,Li.DPadRight),new Li(20,Li.Paddle2),new Li(21,Li.Paddle1),new Li(22,Li.Paddle4),new Li(23,Li.Paddle3)],[new Vi(0,Vi.LeftStickLeft,{invert:!0}),new Vi(0,Vi.LeftStickRight),new Vi(1,Vi.LeftStickUp,{invert:!0}),new Vi(1,Vi.LeftStickDown),new Vi(2,Vi.RightStickLeft,{invert:!0}),new Vi(2,Vi.RightStickRight),new Vi(3,Vi.RightStickUp,{invert:!0}),new Vi(3,Vi.RightStickDown),new Vi(0,Vi.LeftStickX,{bipolar:!0}),new Vi(1,Vi.LeftStickY,{bipolar:!0}),new Vi(2,Vi.RightStickX,{bipolar:!0}),new Vi(3,Vi.RightStickY,{bipolar:!0}),new Vi(8,Vi.AuxiliaryAxis0Positive,{normalize:!0}),new Vi(9,Vi.AuxiliaryAxis1Positive,{normalize:!0})])}}class Ki extends qi{family=e.GamepadMappingFamily.SwitchPro}class Qi extends qi{family=e.GamepadMappingFamily.Xbox}const Zi=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Ji=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,en=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,tn=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,nn=(e,t,i)=>({...void 0!==i&&{ids:i},name:e,resolve:()=>({name:e,mapping:t()})}),rn=e=>e.trim().toLowerCase(),sn=e=>{const t=e.replace(Ji,"").replace(Zi,"").replace(tn,"").replace(en,"").replaceAll(/\s+/g," ").trim();return t.length>0?t:null},on=(e,t)=>{if(!t)return!0;for(const i of(e=>e?(Array.isArray(e)?e:[e]).map(rn):[])(t))if(i.includes(":")){if(e.productKey===i)return!0}else if(e.vendorId===i)return!0;return!1},an=e=>{const t=e.id.trim()||`Gamepad ${e.index}`,i=(e=>{const t=Ji.exec(e)||Zi.exec(e)||tn.exec(e)||en.exec(e);if(!t)return null;const[,i,n]=t;return void 0===i||void 0===n?null:`${i.toLowerCase()}:${n.toLowerCase()}`})(t),n=i?.slice(0,4)??null,r=i?.slice(5)??null;return{id:e.id,index:e.index,label:t,vendorId:n,productId:r,productKey:i,name:sn(t)}},hn=(e,t)=>on(t,e.ids)?((e,t)=>{const i=e.resolve(t);return null==i?null:"mapping"in i?{descriptor:t,name:i.name??e.name??t.name??t.label,mapping:i.mapping}:{descriptor:t,name:e.name??t.name??t.label,mapping:i}})(e,t):null,ln=[...[nn("Xbox 360 Controller",()=>new Qi,"045e:028e"),nn("Xbox One Controller",()=>new Qi,["045e:02d1","045e:02dd"]),nn("Xbox Wireless Controller",()=>new Qi,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),nn("Xbox One Elite Controller",()=>new Qi,"045e:02e3"),nn("Xbox Elite Wireless Controller Series 2",()=>new Qi,["045e:0b00","045e:0b05","045e:0b22"]),nn("Xbox Series Controller",()=>new Qi,["045e:0b12","045e:0b13"]),nn("PlayStation 3 Controller",()=>new Xi,"054c:0268"),nn("DualShock 4 Controller",()=>new Xi,["054c:05c4","054c:09cc","054c:0ba0"]),nn("DualSense Controller",()=>new Xi,"054c:0ce6"),nn("DualSense Edge Controller",()=>new Xi,"054c:0df2"),nn("GameCube Controller Adapter",()=>new Wi,"057e:0337"),nn("Joy-Con (L)",()=>new Yi,"057e:2006"),nn("Joy-Con (R)",()=>new $i,"057e:2007"),nn("Joy-Con Charging Grip",()=>new Ki,"057e:200e"),nn("Switch Pro Controller",()=>new Ki,"057e:2009"),nn("Joy-Con 2 (L)",()=>new Yi,"057e:2066"),nn("Joy-Con 2 (R)",()=>new $i,"057e:2067"),nn("Switch 2 Pro Controller",()=>new Ki,"057e:2069"),nn("Switch 2 GameCube Controller",()=>new Wi,"057e:2073"),nn("Steam Controller",()=>new Hi,["28de:1102","28de:1142"]),nn("Steam Virtual Gamepad",()=>new qi,"28de:11ff"),nn("Steam Deck",()=>new ji,"28de:1205"),nn("F310 Gamepad",()=>new qi,"046d:c216"),nn("F710 Gamepad",()=>new qi,["046d:c219","046d:c21f"]),nn("8BitDo P30 Controller",()=>new qi,["2dc8:5107","2dc8:5108"]),nn("8BitDo SF30 Pro Controller",()=>new Ki,["2dc8:3000","2dc8:6100","2dc8:6101"]),nn("8BitDo SN30 Controller",()=>new Ki,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),nn("8BitDo NES30 Controller",()=>new qi,"2dc8:ab12"),nn("PowerA Switch Controller",()=>new Ki,"20d6:a713"),nn("PowerA OPS Pro Wireless Controller",()=>new qi,"20d6:4033"),nn("PowerA OPS Wireless Controller",()=>new qi,"20d6:4026"),nn("Nacon Revolution 3 Controller",()=>new Xi,"146b:0611"),nn("Nacon Revolution Unlimited Pro Controller",()=>new Xi,"146b:0d08"),nn("Nacon Revolution Infinity Controller",()=>new Xi,"146b:0d10"),nn("Nacon Revolution 5 Pro Controller",()=>new Xi,["3285:0d17","3285:0d19"]),nn("Razer Raiju Controller",()=>new Xi,"1532:1000"),nn("Razer Raiju Mobile Controller",()=>new Xi,["1532:0705","1532:0707"]),nn("Razer Raiju Tournament Edition Controller",()=>new Xi,["1532:1007","1532:100a"]),nn("Razer Raiju Ultimate Controller",()=>new Xi,["1532:1004","1532:1009"]),nn("Razer Raion Controller",()=>new Oi,"1532:1100")],...[nn("Microsoft Controller",()=>new Qi,"045e"),nn("Sony Controller",()=>new Xi,"054c"),nn("Valve Controller",()=>new ji,"28de")],nn("Generic Gamepad",()=>new qi)];class un{onPinch;onRotate;onLongPress;touchPointers=new Map;longPressEntries=new Map;prevDistance=-1;prevAngle=0;centerVec=new it;constructor(e,t,i,n){this.onPinch=t,this.onRotate=i,this.onLongPress=n}onPointerDown(e){"touch"===e.type&&(this.touchPointers.set(e.id,e),this._resetTwoTouchBaseline());const t=setTimeout(()=>{this.longPressEntries.delete(e.id),this.onLongPress.dispatch(e)},500);this.longPressEntries.set(e.id,{pointerId:e.id,pointer:e,timerId:t,startX:e.x,startY:e.y})}onPointerMove(e,t){const i=this.longPressEntries.get(e.id);if(i){const n=e.x-i.startX,r=e.y-i.startY;Math.sqrt(n*n+r*r)>t&&(clearTimeout(i.timerId),this.longPressEntries.delete(e.id))}"touch"===e.type&&(this.touchPointers.size<2||this._processTwoTouchGestures())}onPointerUp(e){this._cancelLongPress(e.id)}onPointerLeave(e){this._cancelLongPress(e.id),"touch"===e.type&&(this.touchPointers.delete(e.id),this._resetTwoTouchBaseline())}onPointerCancel(e){this._cancelLongPress(e.id),"touch"===e.type&&(this.touchPointers.delete(e.id),this._resetTwoTouchBaseline())}destroy(){for(const e of this.longPressEntries.values())clearTimeout(e.timerId);this.longPressEntries.clear(),this.touchPointers.clear(),this.centerVec.destroy()}_cancelLongPress(e){const t=this.longPressEntries.get(e);t&&(clearTimeout(t.timerId),this.longPressEntries.delete(e))}_resetTwoTouchBaseline(){this.prevDistance=-1,this.prevAngle=0}_processTwoTouchGestures(){const e=this.touchPointers.values(),t=e.next().value,i=e.next().value,n=i.x-t.x,r=i.y-t.y,s=Math.sqrt(n*n+r*r),o=Math.atan2(r,n),a=(t.x+i.x)/2,h=(t.y+i.y)/2;if(this.centerVec.set(a,h),this.prevDistance>0){const e=s/this.prevDistance;Math.abs(e-1)>1e-4&&this.onPinch.dispatch(e,this.centerVec);const t=o-this.prevAngle;Math.abs(t)>1e-4&&this.onRotate.dispatch(t,this.centerVec)}this.prevDistance=s,this.prevAngle=o}}const cn=t=>e.ChannelOffset.Pointers+t,dn=(e,t)=>cn(16*e+t);var _n,fn;e.PointerStateFlag=void 0,(_n=e.PointerStateFlag||(e.PointerStateFlag={}))[_n.None=0]="None",_n[_n.Over=1]="Over",_n[_n.Leave=2]="Leave",_n[_n.Down=4]="Down",_n[_n.Move=8]="Move",_n[_n.Up=16]="Up",_n[_n.Cancel=32]="Cancel",e.PointerState=void 0,(fn=e.PointerState||(e.PointerState={}))[fn.Unknown=0]="Unknown",fn[fn.InsideCanvas=1]="InsideCanvas",fn[fn.OutsideCanvas=2]="OutsideCanvas",fn[fn.Pressed=3]="Pressed",fn[fn.Moving=4]="Moving",fn[fn.Released=5]="Released",fn[fn.Cancelled=6]="Cancelled";class pn{id;type;position;startPos=new it(-1,-1);size;tilt;stateFlags=new Mt;_app;_canvas;_channels;_slotIndex;_channelBase;_buttons;_pressure;_rotation;_isPrimary;_currentState=e.PointerState.Unknown;constructor(t,i,n,r,s){const{pointerId:o,pointerType:a,clientX:h,clientY:u,width:c,height:d,tiltX:_,tiltY:f,buttons:p,pressure:m,twist:g,isPrimary:y}=t;this._app=i,this._canvas=n,this._channels=r,this._slotIndex=s,this._channelBase=e.ChannelOffset.Pointers+16*s;const w=this._computeDesignGeometry(h,u,c,d);this.id=o,this.type=a,this.position=new it(w.x,w.y),this.size=new l(w.width,w.height),this.tilt=new it(_,f),this._buttons=p,this._pressure=m,this._rotation=g,this._isPrimary=y,this.stateFlags.push(e.PointerStateFlag.Over),this._writeChannels(!0)}get x(){return this.position.x}get y(){return this.position.y}get width(){return this.size.width}get height(){return this.size.height}get buttons(){return this._buttons}get pressure(){return this._pressure}get rotation(){return this._rotation}get twist(){return this._rotation}get tiltX(){return this.tilt.x}get tiltY(){return this.tilt.y}get isPrimary(){return this._isPrimary}get slotIndex(){return this._slotIndex}get currentState(){return this._currentState}handleEnter(t){this.handleEvent(t),this._currentState=e.PointerState.InsideCanvas,this._writeChannels(!0)}handleLeave(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Leave),this._currentState=e.PointerState.OutsideCanvas,this._writeChannels(!1)}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(e.PointerStateFlag.Down),this._currentState=e.PointerState.Pressed,this._writeChannels(!0)}handleMove(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Move),this._currentState=e.PointerState.Moving,this._writeChannels(!0)}handleRelease(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Up),this._currentState=e.PointerState.Released,this._writeChannels(!0)}handleCancel(t){this.handleEvent(t),this.stateFlags.push(e.PointerStateFlag.Cancel),this._currentState=e.PointerState.Cancelled,this._writeChannels(!1)}destroy(){this._clearChannels(),this.position.destroy(),this.startPos.destroy(),this.size.destroy(),this.tilt.destroy(),this._app=null,this._canvas=null,this._channels=null}handleEvent(e){const{clientX:t,clientY:i,width:n,height:r,tiltX:s,tiltY:o,buttons:a,pressure:h,twist:l,isPrimary:u}=e,c=this._computeDesignGeometry(t,i,n,r);return this.position.set(c.x,c.y),this.size.set(c.width,c.height),this.tilt.set(s,o),this._buttons=a,this._pressure=h,this._rotation=l,this._isPrimary=u,this}_computeDesignGeometry(e,t,i,n){const r=this._app,s=this._canvas;if(!r||!s)return{x:0,y:0,width:0,height:0};const o=s.getBoundingClientRect(),a=o.width>0?(e-o.left)/o.width:0,h=o.height>0?(t-o.top)/o.height:0,l=a*s.width,u=h*s.height,c=o.width>0?i/o.width*s.width:0,d=o.height>0?n/o.height*s.height:0,_=r._backingStoreToDesign(l,u),f=r._backingStoreToDesign(l+c,u+d);return{x:_.x,y:_.y,width:Math.abs(f.x-_.x),height:Math.abs(f.y-_.y)}}_writeChannels(e){const t=this._channels,i=this._canvas;if(!t||!i)return;const n=this._channelBase,r=this._app,s=(r?r.width:i.width)||1,o=(r?r.height:i.height)||1;if(!e){for(let e=0;e<16;e++)t[n+e]=0;return}const a=Math.min(1,Math.max(0,this.position.x/s)),h=Math.min(1,Math.max(0,this.position.y/o));t[n+0]=1,t[n+1]=a,t[n+2]=h,t[n+3]=this._pressure,t[n+4]=Math.min(1,this.size.width/s),t[n+5]=Math.min(1,this.size.height/o),t[n+6]=this._rotation/359,t[n+7]=(this.tilt.x+90)/180,t[n+8]=(this.tilt.y+90)/180,t[n+9]=1&this._buttons?1:0,t[n+10]=2&this._buttons?1:0,t[n+11]=4&this._buttons?1:0,t[n+12]="mouse"===this.type?1:0,t[n+13]="touch"===this.type?1:0,t[n+14]="pen"===this.type?1:0,t[n+15]=this._isPrimary?1:0}_clearChannels(){const e=this._channels;if(!e)return;const t=this._channelBase;for(let i=0;i<16;i++)e[t+i]=0}}!function(e){e.Active=cn(0),e.X=cn(1),e.Y=cn(2),e.Pressure=cn(3),e.Width=cn(4),e.Height=cn(5),e.Twist=cn(6),e.TiltX=cn(7),e.TiltY=cn(8),e.Left=cn(9),e.Right=cn(10),e.Middle=cn(11),e.IsMouse=cn(12),e.IsTouch=cn(13),e.IsPen=cn(14),e.IsPrimary=cn(15),e.Slot0Active=dn(0,0),e.Slot0X=dn(0,1),e.Slot0Y=dn(0,2),e.Slot1Active=dn(1,0),e.Slot1X=dn(1,1),e.Slot1Y=dn(1,2),e.Slot2Active=dn(2,0),e.Slot2X=dn(2,1),e.Slot2Y=dn(2,2),e.Slot3Active=dn(3,0),e.Slot3X=dn(3,1),e.Slot3Y=dn(3,2),e.Slot4Active=dn(4,0),e.Slot4X=dn(4,1),e.Slot4Y=dn(4,2),e.Slot5Active=dn(5,0),e.Slot5X=dn(5,1),e.Slot5Y=dn(5,2),e.Slot6Active=dn(6,0),e.Slot6X=dn(6,1),e.Slot6Y=dn(6,2),e.Slot7Active=dn(7,0),e.Slot7X=dn(7,1),e.Slot7Y=dn(7,2),e.Slot8Active=dn(8,0),e.Slot8X=dn(8,1),e.Slot8Y=dn(8,2),e.Slot9Active=dn(9,0),e.Slot9X=dn(9,1),e.Slot9Y=dn(9,2),e.Slot10Active=dn(10,0),e.Slot10X=dn(10,1),e.Slot10Y=dn(10,2),e.Slot11Active=dn(11,0),e.Slot11X=dn(11,1),e.Slot11Y=dn(11,2),e.Slot12Active=dn(12,0),e.Slot12X=dn(12,1),e.Slot12Y=dn(12,2),e.Slot13Active=dn(13,0),e.Slot13X=dn(13,1),e.Slot13Y=dn(13,2),e.Slot14Active=dn(14,0),e.Slot14X=dn(14,1),e.Slot14Y=dn(14,2),e.Slot15Active=dn(15,0),e.Slot15X=dn(15,1),e.Slot15Y=dn(15,2)}(pn||(pn={}));var mn,gn;!function(e){e[e.None=0]="None",e[e.KeyDown=1]="KeyDown",e[e.KeyUp=2]="KeyUp",e[e.MouseWheel=4]="MouseWheel",e[e.PointerUpdate=8]="PointerUpdate"}(mn||(mn={}));class yn{order=100;_app;canvas;channels=new Float32Array(e.ChannelSize.Container);pointers=new Map;_gamepads;gamepadsByBrowserIndex=new Map;bindings=new Set;capturedKeyChannels=new Map;bindingDetacher={detach:t=>{this.bindings.delete(t);for(const i of t.channels)if(i<e.ChannelSize.Category){const e=this.capturedKeyChannels.get(i);void 0!==e&&(e<=1?this.capturedKeyChannels.delete(i):this.capturedKeyChannels.set(i,e-1))}}};wheelOffset=new it;flags=new Mt;channelsPressed=[];channelsReleased=[];gamepadDefinitions;slotStrategy;pointerSlots=new Map;freeSlots=Array.from({length:16},(e,t)=>t);gestureRecognizer;canvasFocusedValue;pointerDistanceThreshold;keyDownHandler=this.handleKeyDown.bind(this);keyUpHandler=this.handleKeyUp.bind(this);canvasFocusHandler=this.handleCanvasFocus.bind(this);canvasBlurHandler=this.handleCanvasBlur.bind(this);windowBlurHandler=this.handleWindowBlur.bind(this);mouseWheelHandler=this.handleMouseWheel.bind(this);pointerOverHandler=this.handlePointerOver.bind(this);pointerLeaveHandler=this.handlePointerLeave.bind(this);pointerDownHandler=this.handlePointerDown.bind(this);pointerMoveHandler=this.handlePointerMove.bind(this);pointerUpHandler=this.handlePointerUp.bind(this);pointerCancelHandler=this.handlePointerCancel.bind(this);onCanvasFocusChange=new x;onPointerEnter=new x;onPointerLeave=new x;onPointerDown=new x;onPointerMove=new x;onPointerUp=new x;onPointerTap=new x;onPointerSwipe=new x;onPointerCancel=new x;onMouseWheel=new x;onKeyDown=new x;onKeyUp=new x;onGamepadConnected=new x;onGamepadDisconnected=new x;onAnyGamepadReassigned=new x;onAnyGamepadButtonDown=new x;onAnyGamepadButtonUp=new x;onAnyGamepadAxisChange=new x;onPinch=new x;onRotate=new x;onLongPress=new x;constructor(e){const t=e.options.input??{},i=t.gamepadDefinitions??[],n=t.pointerDistanceThreshold??10,r=t.gamepadSlotStrategy??"sticky";this._app=e,this.canvas=e.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=n,this.gamepadDefinitions=[...i,...ln],this.slotStrategy=r,this.canvas.style.touchAction="none",this.gestureRecognizer=new un(n,this.onPinch,this.onRotate,this.onLongPress);const s=new Ii(0,this.channels),o=new Ii(1,this.channels),a=new Ii(2,this.channels),h=new Ii(3,this.channels);this._gamepads=[s,o,a,h];for(const e of this._gamepads)this.wireGamepadEvents(e);this.addEventListeners()}getPrimaryPointerPosition(){for(const t of this.pointers.values())if(t.isPrimary&&t.currentState!==e.PointerState.Cancelled)return{x:t.x,y:t.y};for(const t of this.pointers.values())if(t.currentState!==e.PointerState.Cancelled)return{x:t.x,y:t.y};return null}get pointersInCanvas(){for(const t of this.pointers.values())if(t.currentState!==e.PointerState.OutsideCanvas&&t.currentState!==e.PointerState.Cancelled)return!0;return!1}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this._gamepads}get gamepadSlotStrategy(){return this.slotStrategy}getGamepad(e){return this._gamepads[e]}get connectedGamepads(){const e=[];for(const t of this._gamepads)t.connected&&e.push(t);return e}get connectedGamepadCount(){let e=0;for(const t of this._gamepads)t.connected&&e++;return e}get firstConnectedGamepad(){for(const e of this._gamepads)if(e.connected)return e;return null}get hasGamepad(){for(const e of this._gamepads)if(e.connected)return!0;return!1}onStart(e,t,i){const n=this.createBinding(e,i);return n.onStart.add(t),n}onActive(e,t,i){const n=this.createBinding(e,i);return n.onActive.add(t),n}onStop(e,t,i){const n=this.createBinding(e,i);return n.onStop.add(t),n}onTrigger(e,t,i){const n=this.createBinding(e,i);return n.onTrigger.add(t),n}update(e){this.updateGamepads();for(const e of this.bindings)e.update(this.channels);this.flags.value!==mn.None&&this.updateEvents()}destroy(){this.removeEventListeners(),this.gestureRecognizer.destroy();for(const e of this.pointers.values())e.destroy();this.pointers.clear();for(const e of this._gamepads)e.destroy();for(const e of[...this.bindings])e.unbind();this.bindings.clear(),this.capturedKeyChannels.clear(),this.gamepadsByBrowserIndex.clear(),this.channelsPressed.length=0,this.channelsReleased.length=0,this.pointerSlots.clear(),this.freeSlots.length=0,this.wheelOffset.destroy(),this.flags.destroy(),this.onPointerEnter.destroy(),this.onPointerLeave.destroy(),this.onPointerDown.destroy(),this.onPointerMove.destroy(),this.onPointerUp.destroy(),this.onPointerTap.destroy(),this.onPointerSwipe.destroy(),this.onPointerCancel.destroy(),this.onMouseWheel.destroy(),this.onKeyDown.destroy(),this.onKeyUp.destroy(),this.onGamepadConnected.destroy(),this.onGamepadDisconnected.destroy(),this.onAnyGamepadReassigned.destroy(),this.onAnyGamepadButtonDown.destroy(),this.onAnyGamepadButtonUp.destroy(),this.onAnyGamepadAxisChange.destroy(),this.onPinch.destroy(),this.onRotate.destroy(),this.onLongPress.destroy(),this.onCanvasFocusChange.destroy()}createBinding(t,i={}){const n=Array.isArray(t)?t:[t],r=i.gamepadSlot??0,s=n.map(e=>this.resolveExternalChannel(e,r)),o=new Fi(s,i,this.bindingDetacher);this.bindings.add(o);for(const t of s)t<e.ChannelSize.Category&&this.capturedKeyChannels.set(t,(this.capturedKeyChannels.get(t)??0)+1);return o}resolveExternalChannel(t,i){return t>=e.ChannelOffset.Gamepads&&t<e.ChannelOffset.Gamepads+e.ChannelSize.Category?e.ChannelOffset.Gamepads+i*e.ChannelSize.Gamepad+(t^e.ChannelOffset.Gamepads):t}wireGamepadEvents(e){e.onButtonDown.add((t,i)=>{this.onAnyGamepadButtonDown.dispatch(e,t,i)}),e.onButtonUp.add((t,i)=>{this.onAnyGamepadButtonUp.dispatch(e,t,i)}),e.onAxisChange.add((t,i)=>{this.onAnyGamepadAxisChange.dispatch(e,t,i)})}_assignSlot(e){if(this.pointerSlots.has(e))return this.pointerSlots.get(e);if(0===this.freeSlots.length)return null;const t=this.freeSlots.shift();return this.pointerSlots.set(e,t),t}_releaseSlot(e){const t=this.pointerSlots.get(e);void 0!==t&&(this.pointerSlots.delete(e),this.freeSlots.unshift(t))}handleKeyDown(t){if(!this.canvasFocusedValue)return;const i=e.ChannelOffset.Keyboard+t.keyCode;this.channels[i]=1,this.channelsPressed.push(i),this.flags.push(mn.KeyDown),this.capturedKeyChannels.has(i)&&_(t)}handleKeyUp(t){if(!this.canvasFocusedValue)return;const i=e.ChannelOffset.Keyboard+t.keyCode;this.channels[i]=0,this.channelsReleased.push(i),this.flags.push(mn.KeyUp),this.capturedKeyChannels.has(i)&&_(t)}handlePointerOver(e){const t=this._assignSlot(e.pointerId);null!==t&&(this.pointers.set(e.pointerId,new pn(e,this._app,this.canvas,this.channels,t)),this.flags.push(mn.PointerUpdate))}handlePointerLeave(e){const t=this.pointers.get(e.pointerId);t&&(t.handleLeave(e),this.gestureRecognizer.onPointerLeave(t),this._releaseSlot(e.pointerId),this.flags.push(mn.PointerUpdate))}handlePointerDown(e){this.canvas.focus(),this.canvasFocusedValue=!0;const t=this.pointers.get(e.pointerId);t&&(t.handlePress(e),this.gestureRecognizer.onPointerDown(t),this.flags.push(mn.PointerUpdate),_(e))}handlePointerMove(e){const t=this.pointers.get(e.pointerId);t&&(t.handleMove(e),this.gestureRecognizer.onPointerMove(t,this.pointerDistanceThreshold),this.flags.push(mn.PointerUpdate))}handlePointerUp(e){const t=this.pointers.get(e.pointerId);t&&(t.handleRelease(e),this.gestureRecognizer.onPointerUp(t),this.flags.push(mn.PointerUpdate),_(e))}handlePointerCancel(e){const t=this.pointers.get(e.pointerId);t&&(t.handleCancel(e),this.gestureRecognizer.onPointerCancel(t),this._releaseSlot(e.pointerId),this.flags.push(mn.PointerUpdate))}handleMouseWheel(e){this.canvasFocusedValue&&(this.wheelOffset.set(e.deltaX,e.deltaY),this.flags.push(mn.MouseWheel),_(e))}handleCanvasFocus(){this.canvasFocusedValue||(this.canvasFocusedValue=!0,this.onCanvasFocusChange.dispatch(!0))}handleCanvasBlur(){this.canvasFocusedValue&&(this.canvasFocusedValue=!1,this.releaseAllKeyboardChannels(),this.onCanvasFocusChange.dispatch(!1))}handleWindowBlur(){this.canvasFocusedValue&&(this.canvasFocusedValue=!1,this.releaseAllKeyboardChannels(),this.onCanvasFocusChange.dispatch(!1))}releaseAllKeyboardChannels(){for(let t=0;t<e.ChannelSize.Category;t++){const i=e.ChannelOffset.Keyboard+t;0!==this.channels[i]&&(this.channels[i]=0,this.channelsReleased.push(i),this.flags.push(mn.KeyUp))}}addEventListeners(){const e=window,t={capture:!0,passive:!1},i={capture:!0,passive:!0};e.addEventListener("keydown",this.keyDownHandler,!0),e.addEventListener("keyup",this.keyUpHandler,!0),e.addEventListener("blur",this.windowBlurHandler,!0),this.canvas.addEventListener("focus",this.canvasFocusHandler,!0),this.canvas.addEventListener("blur",this.canvasBlurHandler,!0),this.canvas.addEventListener("wheel",this.mouseWheelHandler,t),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,t),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",_,t),this.canvas.addEventListener("selectstart",_,t)}removeEventListeners(){const e={capture:!0,passive:!1},t={capture:!0,passive:!0};window.removeEventListener("keydown",this.keyDownHandler,!0),window.removeEventListener("keyup",this.keyUpHandler,!0),window.removeEventListener("blur",this.windowBlurHandler,!0),this.canvas.removeEventListener("focus",this.canvasFocusHandler,!0),this.canvas.removeEventListener("blur",this.canvasBlurHandler,!0),this.canvas.removeEventListener("wheel",this.mouseWheelHandler,e),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,t),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,t),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,t),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,e),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,t),this.canvas.removeEventListener("contextmenu",_,e),this.canvas.removeEventListener("selectstart",_,e)}updateGamepads(){const e=window.navigator.getGamepads(),t=new Set;for(const i of e){if(!i)continue;const e=i.index;if(e<0)continue;t.add(e);const n=this.gamepadsByBrowserIndex.get(e);if(void 0===n){const t=this.assignSlotForNewPad(i);if(null===t)continue;this.gamepadsByBrowserIndex.set(e,t),this.onGamepadConnected.dispatch(t)}else n._refreshBrowserGamepad(i)}for(const e of[...this.gamepadsByBrowserIndex.keys()]){if(t.has(e))continue;const i=this.gamepadsByBrowserIndex.get(e);this.gamepadsByBrowserIndex.delete(e),void 0!==i&&this.handleGamepadDisconnect(i)}for(const e of this._gamepads)e.update();return this}assignSlotForNewPad(e){const t=((e,t=ln)=>{const i="connected"in e?an(e):e;for(const e of t){const t=hn(e,i);if(t)return t}return{descriptor:i,name:i.name??i.label,mapping:new qi}})(e,this.gamepadDefinitions);for(const i of this._gamepads)if(!i.connected)return i._bind(e,t),i;return null}handleGamepadDisconnect(e){if("compact"!==this.slotStrategy)return e._unbind(),void this.onGamepadDisconnected.dispatch(e);let t=-1;for(let e=3;e>=0;e--){const i=this._gamepads[e];if(void 0!==i&&i.connected){t=e;break}}e._silentUnbind();for(let e=0;e<4;e++){const t=this._gamepads[e];if(void 0!==t&&!t.connected)for(let i=e+1;i<4;i++){const e=this._gamepads[i];if(void 0===e||!e.connected)continue;const n=e.browserGamepad?.index,r=e.slot;t._rebindFrom(e),void 0!==n&&this.gamepadsByBrowserIndex.set(n,t),t.onPadReassigned.dispatch(r),this.onAnyGamepadReassigned.dispatch(t,r);break}}if(t>=0){const e=this._gamepads[t];void 0!==e&&(e._dispatchDisconnect(),this.onGamepadDisconnected.dispatch(e))}}updateEvents(){if(this.flags.pop(mn.KeyDown)){for(const e of this.channelsPressed)this.onKeyDown.dispatch(e);this.channelsPressed.length=0}if(this.flags.pop(mn.KeyUp)){for(const e of this.channelsReleased)this.onKeyUp.dispatch(e);this.channelsReleased.length=0}return this.flags.pop(mn.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(mn.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of this.pointers.values()){const{stateFlags:i}=t;if(i.value!==e.PointerStateFlag.None){if(i.pop(e.PointerStateFlag.Over)&&this.onPointerEnter.dispatch(t),i.pop(e.PointerStateFlag.Down)&&this.onPointerDown.dispatch(t),i.pop(e.PointerStateFlag.Move)&&this.onPointerMove.dispatch(t),i.pop(e.PointerStateFlag.Up)){const{x:e,y:i}=t.startPos;this.onPointerUp.dispatch(t),e>=0&&i>=0&&(j(e,i,t.x,t.y)<this.pointerDistanceThreshold?this.onPointerTap.dispatch(t):this.onPointerSwipe.dispatch(t)),t.startPos.set(-1,-1)}i.pop(e.PointerStateFlag.Cancel)&&this.onPointerCancel.dispatch(t),i.pop(e.PointerStateFlag.Leave)&&(this.onPointerLeave.dispatch(t),this.pointers.delete(t.id))}}}}class wn{_bounds;_maxItems;_maxDepth;_depth;_items;_children;constructor(e,t=8,i=5,n=0){this._bounds=e,this._maxItems=t,this._maxDepth=i,this._depth=n,this._items=[],this._children=null}insert(e){if(null===this._children&&this._items.length<this._maxItems)this._items.push(e);else{if(null===this._children&&this._depth<this._maxDepth&&this._subdivide(),null!==this._children)for(const t of this._children)if(t._bounds.containsRect(e.bounds))return void t.insert(e);this._items.push(e)}}queryPoint(e,t,i=[]){if(!this._bounds.contains(e,t))return i;for(const n of this._items)n.bounds.contains(e,t)&&i.push(n);if(null!==this._children)for(const n of this._children)n.queryPoint(e,t,i);return i}queryRect(e,t=[]){if(e.right<this._bounds.left||e.left>this._bounds.right||e.bottom<this._bounds.top||e.top>this._bounds.bottom)return t;for(const i of this._items)i.bounds.right<e.left||i.bounds.left>e.right||i.bounds.bottom<e.top||i.bounds.top>e.bottom||t.push(i);if(null!==this._children)for(const i of this._children)i.queryRect(e,t);return t}remove(e){const t=this._items.indexOf(e);if(-1!==t)return this._items.splice(t,1),!0;if(null!==this._children)for(const t of this._children)if(t.remove(e))return!0;return!1}clear(){if(this._items.length=0,null!==this._children){for(const e of this._children)e.clear();this._children=null}}_walkBounds(e){if(e(this._bounds),null!==this._children)for(const t of this._children)t._walkBounds(e)}destroy(){if(this._items.length=0,this._bounds.destroy(),null!==this._children){for(const e of this._children)e.destroy();this._children=null}}_subdivide(){const{x:e,y:t,width:i,height:n}=this._bounds,r=i/2,s=n/2,o=this._depth+1,a=this._maxItems,h=this._maxDepth;this._children=[new wn(new et(e,t,r,s),a,h,o),new wn(new et(e+r,t,r,s),a,h,o),new wn(new et(e,t+s,r,s),a,h,o),new wn(new et(e+r,t+s,r,s),a,h,o)]}}class xn{type;target;currentTarget;pointer;worldX;worldY;_stopped=!1;constructor(e,t,i,n,r){this.type=e,this.target=t,this.currentTarget=t,this.pointer=i,this.worldX=n,this.worldY=r}get propagationStopped(){return this._stopped}stopPropagation(){this._stopped=!0}}!function(e){e[e.None=0]="None",e[e.Down=1]="Down",e[e.Move=2]="Move",e[e.Up=4]="Up",e[e.Tap=8]="Tap",e[e.Cancel=16]="Cancel",e[e.Leave=32]="Leave"}(gn||(gn={}));class vn{order=200;_app;_quadtree=null;_interactiveNodes=new Set;_staleNodes=new Set;_quadtreeItems=new Map;_quadtreeOrderCounter=0;_quadtreeQueryBuffer=[];_stage;_uiInteraction={_notifyNodeAdded:()=>{},_notifyNodeRemoved:()=>{},_notifyInteractiveChanged:()=>{},_notifyBoundsInvalidated:()=>{}};_uiStage;_lastHit=new Map;_pending=new Map;_capturedPointers=new Map;_drags=new Map;_captureStack=[];_dirty=!1;_onPointerDownHandler;_onPointerMoveHandler;_onPointerUpHandler;_onPointerTapHandler;_onPointerCancelHandler;_onPointerLeaveHandler;constructor(e){this._app=e,this._stage={interaction:this,focus:e.focus,app:e},this._uiStage={interaction:this._uiInteraction,focus:e.focus,app:e},this._onPointerDownHandler=this._handlePointerDown.bind(this),this._onPointerMoveHandler=this._handlePointerMove.bind(this),this._onPointerUpHandler=this._handlePointerUp.bind(this),this._onPointerTapHandler=this._handlePointerTap.bind(this),this._onPointerCancelHandler=this._handlePointerCancel.bind(this),this._onPointerLeaveHandler=this._handlePointerLeave.bind(this),e.input.onPointerDown.add(this._onPointerDownHandler),e.input.onPointerMove.add(this._onPointerMoveHandler),e.input.onPointerUp.add(this._onPointerUpHandler),e.input.onPointerTap.add(this._onPointerTapHandler),e.input.onPointerCancel.add(this._onPointerCancelHandler),e.input.onPointerLeave.add(this._onPointerLeaveHandler)}getHoveredNode(e){if(void 0!==e)return this._lastHit.get(e)??null;const t=this._lastHit.values().next();return t.done?null:t.value}getCapturedNodes(){return[...this._capturedPointers.values()]}pushInputCapture(e){this._captureStack.push(e)}popInputCapture(){this._captureStack.pop()}_getDebugQuadtree(){return this._quadtree}destroy(){this._app.input.onPointerDown.remove(this._onPointerDownHandler),this._app.input.onPointerMove.remove(this._onPointerMoveHandler),this._app.input.onPointerUp.remove(this._onPointerUpHandler),this._app.input.onPointerTap.remove(this._onPointerTapHandler),this._app.input.onPointerCancel.remove(this._onPointerCancelHandler),this._app.input.onPointerLeave.remove(this._onPointerLeaveHandler),this._lastHit.clear(),this._pending.clear(),this._capturedPointers.clear(),this._drags.clear(),this._captureStack.length=0,this._interactiveNodes.clear(),this._staleNodes.clear(),this._quadtreeItems.clear(),this._dirty=!1,null!==this._quadtree&&(this._quadtree.destroy(),this._quadtree=null)}update(e){if(this._dirty){this._dirty=!1,this._flushStaleEntries();for(const e of this._pending.values())this._processQueue(e);this._pending.clear(),this._updateCursor()}}attachRoot(e){e._setStage(this._stage),this._notifyNodeAdded(e)}detachRoot(e){this._app.focus.blur(),this._captureStack.length=0,this._notifyNodeRemoved(e),e._setStage(null)}attachUIRoot(e){e._setStage(this._uiStage)}detachUIRoot(e){e._setStage(null)}_notifyNodeAdded(e){for(const t of this._iterateSubtree(e))t.interactive&&this._registerNode(t)}_notifyNodeRemoved(e){for(const t of this._iterateSubtree(e))this._interactiveNodes.has(t)&&this._unregisterNode(t)}_notifyInteractiveChanged(e,t){t?this._registerNode(e):this._unregisterNode(e)}_notifyBoundsInvalidated(e){this._interactiveNodes.has(e)&&this._staleNodes.add(e)}_handlePointerDown(e){this._enqueue(e,gn.Down)}_handlePointerMove(e){this._enqueue(e,gn.Move)}_handlePointerUp(e){this._enqueue(e,gn.Up)}_handlePointerTap(e){this._enqueue(e,gn.Tap)}_handlePointerCancel(e){this._enqueue(e,gn.Cancel)}_handlePointerLeave(e){this._enqueue(e,gn.Leave)}_enqueue(e,t){let i=this._pending.get(e.id);i?i.pointer=e:(i={pointer:e,events:0},this._pending.set(e.id,i)),i.events|=t,this._dirty=!0}_processQueue(e){const{pointer:t,events:i}=e,{id:n}=t,r=this._capturedPointers.get(n)??null;let s,o,a;if(null!==r){const e=this._pointerCoords(t,this._isUINode(r));s=r,o=e.x,a=e.y}else{const e=this._resolveHit(t);s=e.node,o=e.x,a=e.y}const h=this._drags.get(n)??null,l=this._lastHit.get(n)??null,u=0!==(i&(gn.Cancel|gn.Leave));if(null!==r||s===l||u||(null!==l&&this._dispatchBubble(new xn("pointerout",l,t,o,a)),null!==s&&this._dispatchBubble(new xn("pointerover",s,t,o,a)),this._setLastHit(n,s)),0!==(i&gn.Down)&&null!==s&&(this._dispatchBubble(new xn("pointerdown",s,t,o,a)),s.draggable&&!this._drags.has(n))){const e=s.position.x-o,i=s.position.y-a;this._drags.set(n,{pointerId:n,node:s,offsetX:e,offsetY:i}),this._capturedPointers.set(n,s);try{this._app.canvas.setPointerCapture(n)}catch{}this._dispatchDirect(new xn("dragstart",s,t,o,a),s._peekInteractionSignal("dragstart"))}0!==(i&gn.Move)&&(null!==h&&(h.node.position.x=o+h.offsetX,h.node.position.y=a+h.offsetY),null!==s&&this._dispatchBubble(new xn("pointermove",s,t,o,a)),null!==h&&this._dispatchDirect(new xn("drag",h.node,t,o,a),h.node._peekInteractionSignal("drag"))),0!==(i&gn.Up)&&(null!==s&&this._dispatchBubble(new xn("pointerup",s,t,o,a)),null!==h&&(this._dispatchDirect(new xn("dragend",h.node,t,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(n))),0!==(i&gn.Tap)&&null!==s&&this._dispatchBubble(new xn("pointertap",s,t,o,a)),u&&(null!==h?(this._dispatchDirect(new xn("dragend",h.node,t,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(n)):null!==l&&this._dispatchBubble(new xn("pointerout",l,t,o,a)),this._lastHit.delete(n))}_endDrag(e){this._drags.delete(e),this._capturedPointers.delete(e);try{this._app.canvas.releasePointerCapture(e)}catch{}}_resolveHit(e){const t=this._captureStack.at(-1);if(void 0!==t){const i=this._pointerCoords(e,this._isUINode(t));return{node:this._hitTestNode(t,i.x,i.y),x:i.x,y:i.y}}const i=this._app.scene.currentScene?._peekUI()??null;if(null!==i){const t=this._app.rendering.screenView.screenToWorld(e.x,e.y),n=this._hitTestNode(i,t.x,t.y);if(null!==n)return{node:n,x:t.x,y:t.y}}const n=this._app.rendering.view.screenToWorld(e.x,e.y);return{node:this._hitTest(n.x,n.y),x:n.x,y:n.y}}_pointerCoords(e,t){return(t?this._app.rendering.screenView:this._app.rendering.view).screenToWorld(e.x,e.y)}_isUINode(e){const t=this._app.scene.currentScene?._peekUI()??null;if(null===t)return!1;let i=e;for(;null!==i;){if(i===t)return!0;i=i.parent}return!1}_hitTest(e,t){if(null!==this._quadtree)return this._hitTestIndexed(e,t);const i=this._app.scene.currentScene?.root;return i?this._hitTestNode(i,e,t):null}_hitTestIndexed(e,t){const i=this._quadtreeQueryBuffer;i.length=0,this._quadtree.queryPoint(e,t,i);let n=-1,r=null;for(const s of i){const i=s.payload;i.order>n&&i.node.contains(e,t)&&(n=i.order,r=i.node)}return r}_hitTestNode(e,t,i){if(!e.visible)return null;if(e instanceof Bi){const n=e.children;for(let e=n.length-1;e>=0;e--){const r=n[e];if(void 0===r)continue;const s=this._hitTestNode(r,t,i);if(s)return s}}return e.interactive&&e.contains(t,i)?e:null}_registerNode(e){this._interactiveNodes.has(e)||(this._interactiveNodes.add(e),null===this._quadtree&&(this._quadtree=this._createQuadtree()),this._insertNode(e))}_unregisterNode(e){if(!this._interactiveNodes.has(e))return;this._interactiveNodes.delete(e),this._staleNodes.delete(e);const t=this._quadtreeItems.get(e);void 0!==t&&null!==this._quadtree&&this._quadtree.remove(t),this._quadtreeItems.delete(e),0===this._interactiveNodes.size&&null!==this._quadtree&&(this._quadtree.destroy(),this._quadtree=null,this._quadtreeOrderCounter=0)}_insertNode(e){if(null===this._quadtree)return;const t=e.getBounds(),i={bounds:new et(t.x,t.y,t.width,t.height),payload:{node:e,order:this._quadtreeOrderCounter++}};this._quadtree.insert(i),this._quadtreeItems.set(e,i)}_flushStaleEntries(){if(null!==this._quadtree&&0!==this._staleNodes.size){for(const e of this._staleNodes){const t=this._quadtreeItems.get(e);void 0!==t&&(this._quadtree.remove(t),t.bounds.destroy()),this._quadtreeItems.delete(e);const i=e.getBounds(),n={bounds:new et(i.x,i.y,i.width,i.height),payload:{node:e,order:t?.payload.order??this._quadtreeOrderCounter++}};this._quadtree.insert(n),this._quadtreeItems.set(e,n)}this._staleNodes.clear()}}_createQuadtree(){const e=this._app.width||800,t=this._app.height||600,i=new et(0,0,e,t),n=this._app.scene.currentScene?.root;if(n){const e=n.getBounds(),t=Math.min(i.left,e.left),r=Math.min(i.top,e.top),s=Math.max(i.right,e.right),o=Math.max(i.bottom,e.bottom);i.set(t,r,s-t,o-r)}return new wn(i)}*_iterateSubtree(e){const t=[e];for(;t.length>0;){const e=t.pop();if(yield e,e instanceof Bi)for(let i=e.children.length-1;i>=0;i--){const n=e.children[i];void 0!==n&&t.push(n)}}}_dispatchBubble(e){let t=e.target;for(;null!==t&&!e.propagationStopped;){e.currentTarget=t;const i=this._signalFor(e.type,t);if(i?.dispatch(e),e.propagationStopped)break;const n=t.parent;t=null!==n&&n.interactive?n:null}}_dispatchDirect(e,t){e.currentTarget=e.target,t?.dispatch(e)}_signalFor(e,t){return t._peekInteractionSignal(e)}_setLastHit(e,t){null!==t?this._lastHit.set(e,t):this._lastHit.delete(e)}_updateCursor(){let e=null;for(const t of this._lastHit.values()){let i=t;for(;null!==i;){if(null!==i.cursor){e=i.cursor;break}i=i.parent}if(null!==e)break}this._app.canvas.style.cursor=e??""}}const bn=(e,t)=>(e<<t|e>>>32-t)>>>0,Sn=1/2**32;class Bn{_state=new Uint32Array(4);_seed=0;_value=0;constructor(e=Date.now()){this.setSeed(e)}get seed(){return this._seed}get value(){return this._value}setSeed(e){return this._seed=e,this.reset(),this}reset(){let e=0|this._seed;for(let t=0;t<4;t++){e=e+2654435769|0;let i=e^e>>>16;i=Math.imul(i,569420461),i^=i>>>15,i=Math.imul(i,1935289751),i^=i>>>15,this._state[t]=i>>>0}return this._value=0,this}next(e=0,t=1){const i=this._state;let n=i[0],r=i[1],s=i[2],o=i[3];const a=Math.imul(bn(Math.imul(r,5),7),9)>>>0,h=r<<9;return s^=n,o^=r,r^=s,n^=o,s^=h,o=bn(o,11),i[0]=n,i[1]=r,i[2]=s,i[3]=o,this._value=a*Sn*(t-e)+e,this._value}destroy(){}}const Cn=new Set(["none","position","geometry"]);function Tn(e){return"string"==typeof e&&Cn.has(e)}const Mn=1e-6;function Pn(e,t,i,n){const r=e.x,s=e.y;if(!(i>0&&n>0))return An(r,s);const o=t.worldToScreen(r,s,i,n);if(!Number.isFinite(o.x)||!Number.isFinite(o.y))return An(r,s);const a=t.worldToScreen(r+1,s,i,n),h=t.worldToScreen(r,s+1,i,n),l=a.x-o.x,u=a.y-o.y,c=h.x-o.x,d=h.y-o.y,_=e.a*l+e.c*c,f=e.a*u+e.c*d,p=e.b*l+e.d*c,m=e.b*u+e.d*d,g=Math.abs(f)<Mn&&Math.abs(p)<Mn,y=Math.round(o.x),w=Math.round(o.y);let x=r,v=s;const b=l*d-c*u;if(Math.abs(b)>Mn){const e=y-o.x,t=w-o.y;x=r+(d*e-c*t)/b,v=s+(l*t-u*e)/b}return{originX:o.x,originY:o.y,snappedOriginX:y,snappedOriginY:w,worldX:x,worldY:v,scaleX:_,scaleY:m,axisAligned:g}}function An(e,t){return{originX:e,originY:t,snappedOriginX:e,snappedOriginY:t,worldX:e,worldY:t,scaleX:0,scaleY:0,axisAligned:!1}}function En(e,t){return!Number.isFinite(e)||Math.abs(t)<Mn?e:Math.round(e*t)/t}function kn(e,t,i){const{scaleX:n,scaleY:r}=t;i.length=e.length;for(let t=0;t<e.length;t++){const s=e[t];let o=i[t];void 0===o&&(o=i[t]={x0:0,y0:0,x1:0,y1:0,u0:0,v0:0,u1:0,v1:0}),o.x0=En(s.x0,n),o.x1=En(s.x1,n),o.y0=En(s.y0,r),o.y1=En(s.y1,r),o.u0=s.u0,o.v0=s.v0,o.u1=s.u1,o.v1=s.v1}return i}function Rn(e,t,i,n,r){const s=e.getGlobalTransform();if("none"===e.pixelSnapMode)return s;return function(e,t,i){return e.copy(t),e.x=i.worldX,e.y=i.worldY,e}(r,s,Pn(s,t,i,n))}function Dn(e,t,i){const n=En(e.left,t.scaleX),r=En(e.top,t.scaleY),s=En(e.right,t.scaleX),o=En(e.bottom,t.scaleY);return i.set(n,r,s-n,o-r)}class Fn extends Si{_tint=Tt.white.clone();_blendMode=e.BlendModes.Normal;_pixelSnapMode="none";_materialKey=null;_materialKeyBackend=null;get tint(){return this._tint}set tint(e){this.setTint(e)}get blendMode(){return this._blendMode}set blendMode(e){this.setBlendMode(e)}get pixelSnapMode(){return this._pixelSnapMode}set pixelSnapMode(e){if(e!==this._pixelSnapMode){if(!Tn(e))throw new Error(`Drawable.pixelSnapMode must be 'none', 'position', or 'geometry' (got ${String(e)}).`);this._pixelSnapMode=e,this.invalidateCache()}}setTint(e){return e&&(this._tint.copy(e),this.invalidateCache()),this}setBlendMode(e){return this._blendMode!==e&&(this._blendMode=e,this.invalidateCache()),this}_collectContent(e){e.emitDraw(this)}_isDrawableForRenderPlan(){return!0}_renderPlanGetBlendMode(){return this._blendMode}_getOrComputeMaterialKey(e){const t=this._materialKey;if(null!==t)return null!==ei(this)?ti(t,this,e):this._materialKeyBackend===e?t:(this._materialKeyBackend=e,ti(t,this,e));const i=ti({rendererId:0,blendMode:this._blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},this,e);return this._materialKey=i,this._materialKeyBackend=e,i}invalidateCache(){return super.invalidateCache(),this._materialKeyBackend=null,this}destroy(){super.destroy(),this._tint.destroy()}}class In extends Fn{_vertices;_indices;_uvs;_colors;_material;_geometry;get vertices(){return this._vertices}get indices(){return this._indices}get uvs(){return this._uvs}get colors(){return this._colors}get material(){return this._material}get geometry(){return this._geometry}_texture;constructor(e){super();const{texture:t=null,material:i=null}=e;let n,r,s,o,a;if(void 0!==e.geometry){if(void 0!==e.vertices)throw new Error("Mesh accepts either `vertices` or `geometry`, not both.");a=e.geometry;const t=On(a);n=t.vertices,s=t.uvs,o=t.colors,r=t.indices}else{if(void 0===e.vertices)throw new Error("Mesh requires either `vertices` or `geometry`.");a=null,n=e.vertices,r=e.indices??null,s=e.uvs??null,o=e.colors??null}if(0===n.length||n.length%2!=0)throw new Error(`Mesh vertices must be a non-empty flat array of (x,y) pairs (got length ${n.length}).`);const h=n.length/2;if(h<3)throw new Error(`Mesh requires at least 3 vertices (got ${h}).`);if(null!==s&&s.length!==n.length)throw new Error(`Mesh uvs length ${s.length} must equal vertices length ${n.length}.`);if(null!==o&&o.length!==h)throw new Error(`Mesh colors length ${o.length} must equal vertex count ${h}.`);if(null!==r){if(0===r.length||r.length%3!=0)throw new Error(`Mesh indices must be a non-empty multiple of 3 (got length ${r.length}).`);for(let e=0;e<r.length;e++)if(r[e]>=h)throw new Error(`Mesh index ${r[e]} at position ${e} is out of range for vertex count ${h}.`)}else if(h%3!=0)throw new Error(`Non-indexed Mesh requires a vertex count that is a multiple of 3 (got ${h}).`);this._vertices=n,this._indices=r,this._uvs=s,this._colors=o,this._material=i,this._geometry=a,this._texture=t,this.recomputeLocalBounds()}get vertexCount(){return this.vertices.length/2}get indexCount(){return this.indices?.length??this.vertexCount}get texture(){return this._texture}set texture(e){this._texture=e,this.invalidateCache()}recomputeLocalBounds(){let e=1/0,t=1/0,i=-1/0,n=-1/0;for(let r=0;r<this.vertices.length;r+=2){const s=this.vertices[r],o=this.vertices[r+1];s<e&&(e=s),s>i&&(i=s),o<t&&(t=o),o>n&&(n=o)}return this.getLocalBounds().set(e,t,i-e,n-t),this._invalidateBoundsCascade(),this}}const Ln=new Set(["a_position","position"]),Un=new Set(["a_texcoord","texcoord","a_uv","uv"]),Gn=new Set(["a_color","color"]),Nn=(e,t)=>e.find(e=>t.has(e.name));function On(e){if("triangle-list"!==e.topology)throw new Error(`Mesh only supports triangle-list geometry (got "${e.topology}").`);const t=Nn(e.attributes,Ln);if(void 0===t)throw new Error("Mesh geometry requires a position attribute named `a_position` or `position`.");if("f32"!==t.type||t.size<2)throw new Error("Mesh geometry position attribute must be a float vector with at least 2 components.");const i=Nn(e.attributes,Un);if(void 0!==i&&("f32"!==i.type||i.size<2))throw new Error("Mesh geometry texcoord attribute must be a float vector with at least 2 components.");const n=Nn(e.attributes,Gn),r=e.vertexCount,{stride:s}=e,o=e.vertexData,a=o instanceof Float32Array?new DataView(o.buffer,o.byteOffset,o.byteLength):new DataView(o),h=new Float32Array(2*r),l=void 0!==i?new Float32Array(2*r):null,u=void 0!==n?new Uint32Array(r):null;for(let e=0;e<r;e++){const r=e*s;h[2*e]=a.getFloat32(r+t.offset,!0),h[2*e+1]=a.getFloat32(r+t.offset+4,!0),null!==l&&void 0!==i&&(l[2*e]=a.getFloat32(r+i.offset,!0),l[2*e+1]=a.getFloat32(r+i.offset+4,!0)),null!==u&&void 0!==n&&(u[e]=Vn(a,r+n.offset,n))}const c=function(e,t){if(null===e)return null;if(e instanceof Uint16Array)return e;if(t>65535)throw new Error(`Mesh geometry with ${t} vertices exceeds the 16-bit index limit.`);return Uint16Array.from(e)}(e.indices,r);return{vertices:h,uvs:l,colors:u,indices:c}}function Vn(e,t,i){if("u32"===i.type&&1===i.size)return e.getUint32(t,!0)>>>0;if("u8"===i.type&&4===i.size){return(e.getUint8(t)|e.getUint8(t+1)<<8|e.getUint8(t+2)<<16|e.getUint8(t+3)<<24)>>>0}if("f32"===i.type&&4===i.size){return(Math.round(255*zn(e.getFloat32(t,!0)))|Math.round(255*zn(e.getFloat32(t+4,!0)))<<8|Math.round(255*zn(e.getFloat32(t+8,!0)))<<16|Math.round(255*zn(e.getFloat32(t+12,!0)))<<24)>>>0}throw new Error("Mesh geometry color attribute must be u8x4, u32x1, or f32x4.")}function zn(e){return e<0?0:e>1?1:e}function qn(e){return"number"==typeof e&&Number.isFinite(e)}class Wn{texture;x;y;width;height;u0;v0;u1;v1;extrusion;constructor(e,t){if(!e)throw new Error("TextureRegion requires a non-null Texture.");const i=e.width,n=e.height;!function(e,t,i){const{x:n,y:r,width:s,height:o}=e;if(!(qn(n)&&qn(r)&&qn(s)&&qn(o)))throw new Error(`TextureRegion coordinates and dimensions must be finite numbers (got x=${n}, y=${r}, width=${s}, height=${o}).`);if(s<=0||o<=0)throw new Error(`TextureRegion dimensions must be positive (got width=${s}, height=${o}).`);if(t<=0||i<=0)throw new Error(`Texture must have positive dimensions (got ${t}x${i}).`);if(n<0||r<0)throw new Error(`TextureRegion origin must be non-negative (got x=${n}, y=${r}).`);if(n>=t||r>=i)throw new Error(`TextureRegion origin (${n}, ${r}) is outside texture bounds (${t}x${i}).`);if(n+s>t)throw new Error(`TextureRegion right edge (${n+s}) exceeds texture width (${t}).`);if(r+o>i)throw new Error(`TextureRegion bottom edge (${r+o}) exceeds texture height (${i}).`)}(t,i,n);const r=function(e){return void 0===e?Object.freeze({left:0,top:0,right:0,bottom:0}):"number"==typeof e?Object.freeze({left:e,top:e,right:e,bottom:e}):Object.freeze({left:e.left,top:e.top,right:e.right,bottom:e.bottom})}(t.extrusion);!function(e,t,i,n,r,s,o){const{left:a,top:h,right:l,bottom:u}=e;if(!(qn(a)&&qn(h)&&qn(l)&&qn(u)))throw new Error(`TextureRegion extrusion values must be finite numbers (got left=${a}, top=${h}, right=${l}, bottom=${u}).`);if(a<0||h<0||l<0||u<0)throw new Error(`TextureRegion extrusion values must be non-negative (got left=${a}, top=${h}, right=${l}, bottom=${u}).`);if(a>t||h>i||l>s-(t+n)||u>o-(i+r))throw new Error(`TextureRegion extrusion exceeds available source texture bounds: left=${a} (>${t}), top=${h} (>${i}), right=${l} (>${s-(t+n)}), bottom=${u} (>${o-(i+r)}).`)}(r,t.x,t.y,t.width,t.height,i,n),this.texture=e,this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this.u0=t.x/i,this.v0=t.y/n,this.u1=(t.x+t.width)/i,this.v1=(t.y+t.height)/n,this.extrusion=r}}function Yn(e,t,i){if(0===e)return{destinationLength:0,sourceLength:t,segments:[]};const n=[];let r=0,s=0;for(;r<e;){const o=e-r,a=Math.min(t,o),h=a/t,l=i&&s%2==1,u={destinationStart:r,destinationLength:a,sourceStart:l?1:0,sourceEnd:l?1-h:h,mirrored:l};n.push(u),r+=a,s++}return{destinationLength:e,sourceLength:t,segments:n}}function $n(e,t,i){if(0===e)return{destinationLength:0,sourceLength:t,segments:[]};const n=e/t,r=Math.max(1,Math.round(n)),s=e/r,o=[];for(let e=0;e<r;e++){const t=i&&e%2==1,n={destinationStart:e*s,destinationLength:s,sourceStart:t?1:0,sourceEnd:t?0:1,mirrored:t};o.push(n)}return{destinationLength:e,sourceLength:t,segments:o}}function Xn(e,t,i,n="round"){switch(function(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`RepeatPlanner: sourceLength and destinationLength must be finite numbers (got ${e}, ${t}).`);if(e<=0)throw new Error(`RepeatPlanner: sourceLength must be positive (got ${e}).`);if(t<0)throw new Error(`RepeatPlanner: destinationLength must be non-negative (got ${t}).`)}(e,t),i){case"stretch":return function(e,t){return 0===e?{destinationLength:0,sourceLength:t,segments:[]}:{destinationLength:e,sourceLength:t,segments:[{destinationStart:0,destinationLength:e,sourceStart:0,sourceEnd:1,mirrored:!1}]}}(t,e);case"repeat":return"round"===n?$n(t,e,!1):Yn(t,e,!1);case"mirror-repeat":return"round"===n?$n(t,e,!0):Yn(t,e,!0);default:throw new Error("RepeatPlanner: unknown RepeatMode.")}}const Hn=.5;function jn(e){return"number"==typeof e&&Number.isFinite(e)}function Kn(e,t,i){const{left:n,top:r,right:s,bottom:o}=e;if(!(jn(n)&&jn(r)&&jn(s)&&jn(o)))throw new Error(`NineSliceSprite: slice values must be finite numbers (got left=${n}, top=${r}, right=${s}, bottom=${o}).`);if(n<0||r<0||s<0||o<0)throw new Error(`NineSliceSprite: slice values must be non-negative (got left=${n}, top=${r}, right=${s}, bottom=${o}).`);if(n+s>t)throw new Error(`NineSliceSprite: slices.left (${n}) + slices.right (${s}) exceeds region width (${t}).`);if(r+o>i)throw new Error(`NineSliceSprite: slices.top (${r}) + slices.bottom (${o}) exceeds region height (${i}).`)}function Qn(e){const{left:t,top:i,right:n,bottom:r}=e;if(!(jn(t)&&jn(i)&&jn(n)&&jn(r)))throw new Error(`NineSliceSprite: border values must be finite numbers (got left=${t}, top=${i}, right=${n}, bottom=${r}).`);if(t<0||i<0||n<0||r<0)throw new Error(`NineSliceSprite: border values must be non-negative (got left=${t}, top=${i}, right=${n}, bottom=${r}).`)}function Zn(e,t){return"number"==typeof e?Object.freeze({left:e,top:e,right:e,bottom:e}):Object.freeze({left:e.left??t?.left??0,top:e.top??t?.top??0,right:e.right??t?.right??0,bottom:e.bottom??t?.bottom??0})}const Jn=new Set(["stretch","repeat","mirror-repeat"]),er=new Set(["clip","round"]);function tr(e,t){if("string"!=typeof e||!Jn.has(e))throw new Error(`NineSliceSprite: ${t} must be "stretch", "repeat", or "mirror-repeat".`)}function ir(e,t){if("string"!=typeof e||!er.has(e))throw new Error(`NineSliceSprite: ${t} must be "clip" or "round".`)}function nr(e){if(!e)return rr;const t={};return void 0!==e.edges&&(tr(e.edges,"modes.edges"),t.edges=e.edges),void 0!==e.center&&(tr(e.center,"modes.center"),t.center=e.center),void 0!==e.top&&(tr(e.top,"modes.top"),t.top=e.top),void 0!==e.right&&(tr(e.right,"modes.right"),t.right=e.right),void 0!==e.bottom&&(tr(e.bottom,"modes.bottom"),t.bottom=e.bottom),void 0!==e.left&&(tr(e.left,"modes.left"),t.left=e.left),void 0!==e.edgeFit&&(ir(e.edgeFit,"modes.edgeFit"),t.edgeFit=e.edgeFit),void 0!==e.centerFit&&(ir(e.centerFit,"modes.centerFit"),t.centerFit=e.centerFit),Object.freeze(t)}const rr=Object.freeze({});function sr(e,t){return e.left===t.left&&e.top===t.top&&e.right===t.right&&e.bottom===t.bottom}function or(e,t){return e?.[t]??e?.edges??"stretch"}function ar(e,t,i){return!jn(e)||e<t?t:e>i?i:e}function hr(e,t,i,n,r,s){const o=function(e,t){const i=e.texture.width,n=e.texture.height,r=e.x,s=e.y,o=e.width,a=e.height,h=e.extrusion,l=h.left>0||h.right>0?0:Hn/i,u=h.top>0||h.bottom>0?0:Hn/n,c=Hn/i,d=Hn/n,_=(r+t.left)/i,f=(r+o-t.right)/i,p=(s+t.top)/n,m=(s+a-t.bottom)/n,g=e.u0+l,y=e.u1-l,w=e.v0+u,x=e.v1-u,v=ar(_-c,g,y),b=ar(f+c,g,y),S=ar(p-d,w,x),B=ar(m+d,w,x);return{col0:{u0:g,u1:v},col1:{u0:v,u1:b},col2:{u0:b,u1:y},row0:{u0:w,u1:S},row1:{u0:S,u1:B},row2:{u0:B,u1:x}}}(e,t),a=function(e,t,i){let n=e.left,r=e.right,s=e.top,o=e.bottom;if(n+r>t&&n+r>0){const e=t/(n+r);n*=e,r*=e}if(s+o>i&&s+o>0){const e=i/(s+o);s*=e,o*=e}return{bl:n,br:r,bt:s,bb:o}}(i,n,r),h=a.bl,l=a.br,u=a.bt,c=a.bb,d=Math.max(0,n-h-l),_=Math.max(0,r-u-c),f=h,p=h+d,m=n,g=u,y=u+_,w=r,x=Math.max(0,e.width-t.left-t.right),v=Math.max(0,e.height-t.top-t.bottom),b=x*(t.top>0?u/t.top:1),S=x*(t.bottom>0?c/t.bottom:1),B=v*(t.left>0?h/t.left:1),C=v*(t.right>0?l/t.right:1),T=b,M=B,P=or(s,"top"),A=or(s,"bottom"),E=or(s,"left"),k=or(s,"right"),R=function(e){return e?.center??"stretch"}(s),D=function(e){return e?.edgeFit??"round"}(s),F=function(e){return e?.centerFit??"round"}(s),I=[],{col0:L,col1:U,col2:G,row0:N,row1:O,row2:V}=o;h>0&&u>0&&I.push({x0:0,y0:0,x1:f,y1:g,u0:L.u0,v0:N.u0,u1:L.u1,v1:N.u1}),l>0&&u>0&&I.push({x0:p,y0:0,x1:m,y1:g,u0:G.u0,v0:N.u0,u1:G.u1,v1:N.u1}),h>0&&c>0&&I.push({x0:0,y0:y,x1:f,y1:w,u0:L.u0,v0:V.u0,u1:L.u1,v1:V.u1}),l>0&&c>0&&I.push({x0:p,y0:y,x1:m,y1:w,u0:G.u0,v0:V.u0,u1:G.u1,v1:V.u1});const z=U.u0,q=U.u1,W=O.u0,Y=O.u1;if(d>0&&u>0&&x>0&&b>0){const e=Xn(b,d,P,D);for(const t of e.segments){const e=f+t.destinationStart,i=f+t.destinationStart+t.destinationLength,n=z+t.sourceStart*(q-z),r=z+t.sourceEnd*(q-z);I.push({x0:e,y0:0,x1:i,y1:g,u0:n,v0:N.u0,u1:r,v1:N.u1})}}if(d>0&&c>0&&x>0&&S>0){const e=Xn(S,d,A,D);for(const t of e.segments){const e=f+t.destinationStart,i=f+t.destinationStart+t.destinationLength,n=z+t.sourceStart*(q-z),r=z+t.sourceEnd*(q-z);I.push({x0:e,y0:y,x1:i,y1:w,u0:n,v0:V.u0,u1:r,v1:V.u1})}}if(h>0&&_>0&&v>0&&B>0){const e=Xn(B,_,E,D);for(const t of e.segments){const e=g+t.destinationStart,i=g+t.destinationStart+t.destinationLength,n=W+t.sourceStart*(Y-W),r=W+t.sourceEnd*(Y-W);I.push({x0:0,y0:e,x1:f,y1:i,u0:L.u0,v0:n,u1:L.u1,v1:r})}}if(l>0&&_>0&&v>0&&C>0){const e=Xn(C,_,k,D);for(const t of e.segments){const e=g+t.destinationStart,i=g+t.destinationStart+t.destinationLength,n=W+t.sourceStart*(Y-W),r=W+t.sourceEnd*(Y-W);I.push({x0:p,y0:e,x1:m,y1:i,u0:G.u0,v0:n,u1:G.u1,v1:r})}}if(d>0&&_>0&&x>0&&v>0&&T>0&&M>0){const e=Xn(T,d,R,F),t=Xn(M,_,R,F);for(const i of t.segments){const t=g+i.destinationStart,n=g+i.destinationStart+i.destinationLength,r=W+i.sourceStart*(Y-W),s=W+i.sourceEnd*(Y-W);for(const i of e.segments){const e=f+i.destinationStart,o=f+i.destinationStart+i.destinationLength,a=z+i.sourceStart*(q-z),h=z+i.sourceEnd*(q-z);I.push({x0:e,y0:t,x1:o,y1:n,u0:a,v0:r,u1:h,v1:s})}}}return I}function lr(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`NineSliceSprite: width and height must be finite numbers (got ${e}, ${t}).`);if(e<0)throw new Error(`NineSliceSprite: width must be non-negative (got ${e}).`);if(t<0)throw new Error(`NineSliceSprite: height must be non-negative (got ${t}).`)}class ur extends Fn{_region;_slices;_border;_width;_height;_modes;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(e,t){super(),this._region=e instanceof Wn?e:new Wn(e,{x:0,y:0,width:e.width,height:e.height});const i=this._region,n=Zn(t.slices);Kn(n,i.width,i.height),this._slices=n;const r=void 0!==t.border?Zn(t.border):Zn(t.slices);Qn(r),this._border=r;const s=t.width??i.width,o=t.height??i.height;lr(s,o),this._width=s,this._height=o,this._modes=nr(t.modes)}get region(){return this._region}get texture(){return this._region.texture}get slices(){return this._slices}get border(){return this._border}get modes(){return this._modes}get width(){return this._width}set width(e){this.setSize(e,this._height)}get height(){return this._height}set height(e){this.setSize(this._width,e)}setSize(e,t){return lr(e,t),this._width===e&&this._height===t||(this._width=e,this._height=t,this._geometryDirty=!0,this.invalidateCache()),this}setSlices(e){const t=this._region,i=Zn(e);return Kn(i,t.width,t.height),sr(i,this._slices)||(this._slices=i,this._geometryDirty=!0,this.invalidateCache()),this}setBorder(e){const t=Zn(e);return Qn(t),sr(t,this._border)||(this._border=t,this._geometryDirty=!0,this.invalidateCache()),this}setModes(e){const t=nr(e);return i=t,n=this._modes,i.edges===n.edges&&i.center===n.center&&i.top===n.top&&i.right===n.right&&i.bottom===n.bottom&&i.left===n.left&&i.edgeFit===n.edgeFit&&i.centerFit===n.centerFit||(this._modes=t,this._geometryDirty=!0,this.invalidateCache()),this;var i,n}getLocalBounds(){const e=super.getLocalBounds();return e.set(0,0,this._width,this._height),e}get quads(){return this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(e,t,i){const n=this.quads;if(0===n.length)return n;const r=Pn(this.getGlobalTransform(),e,t,i);return r.axisAligned?kn(n,r,this._renderQuads):n}_rebuildGeometry(){this._quads=hr(this._region,this._slices,this._border,this._width,this._height,this._modes),this._geometryDirty=!1}}const cr=new Set(["stretch","repeat","mirror-repeat"]),dr=new Set(["clip","round"]);function _r(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`RepeatingSprite: width and height must be finite numbers (got ${e}, ${t}).`);if(e<0)throw new Error(`RepeatingSprite: width must be non-negative (got ${e}).`);if(t<0)throw new Error(`RepeatingSprite: height must be non-negative (got ${t}).`)}function fr(e,t){if("string"!=typeof e||!cr.has(e))throw new Error(`RepeatingSprite: ${t} must be "stretch", "repeat", or "mirror-repeat" (got ${String(e)}).`)}function pr(e,t){if("string"!=typeof e||!dr.has(e))throw new Error(`RepeatingSprite: ${t} must be "clip" or "round" (got ${String(e)}).`)}function mr(e,t){if(!Number.isFinite(e))throw new Error(`RepeatingSprite: ${t} must be a finite number (got ${e}).`)}function gr(e,t,i,n){return"stretch"===i||e<=0||t<=0?1:"round"===n?Math.max(1,Math.round(t/e)):t/e}function yr(e,t,i,n,r){if(0===t||e<=0)return[];if("stretch"===i)return[...Xn(e,t,i,n).segments];const s=(r%e+e)%e;if(0===s)return[...Xn(e,t,i,n).segments];const o=Xn(e,t+s,i,n),a=[];for(const e of o.segments){const i=e.destinationStart-s,n=i+e.destinationLength;if(n<=0||i>=t)continue;const r=Math.max(0,i),o=Math.min(t,n),h=o-r;if(h<=0)continue;const l=(r-i)/e.destinationLength,u=(o-i)/e.destinationLength,c=e.sourceEnd-e.sourceStart;a.push({destinationStart:r,destinationLength:h,sourceStart:e.sourceStart+l*c,sourceEnd:e.sourceStart+u*c,mirrored:e.mirrored})}return a}class wr extends Fn{_source;_region;_width;_height;_modeX;_modeY;_fitX;_fitY;_offsetX;_offsetY;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(e,t){super(),this._source=e,this._region=e instanceof Wn?e:new Wn(e,{x:0,y:0,width:e.width,height:e.height});const i=this._region,n=t??{},r=n.modeX??"repeat",s=n.modeY??"repeat";fr(r,"modeX"),fr(s,"modeY"),this._modeX=r,this._modeY=s;const o=n.fitX??"round",a=n.fitY??"round";pr(o,"fitX"),pr(a,"fitY"),this._fitX=o,this._fitY=a;const h=n.offsetX??0,l=n.offsetY??0;mr(h,"offsetX"),mr(l,"offsetY"),this._offsetX=h,this._offsetY=l;const u=n.width??i.width,c=n.height??i.height;_r(u,c),this._width=u,this._height=c}get source(){return this._source}get region(){return this._region}get texture(){return this._region.texture}get width(){return this._width}set width(e){this.setSize(e,this._height)}get height(){return this._height}set height(e){this.setSize(this._width,e)}get modeX(){return this._modeX}set modeX(e){fr(e,"modeX"),this._modeX!==e&&(this._modeX=e,this._geometryDirty=!0,this.invalidateCache())}get modeY(){return this._modeY}set modeY(e){fr(e,"modeY"),this._modeY!==e&&(this._modeY=e,this._geometryDirty=!0,this.invalidateCache())}get fitX(){return this._fitX}set fitX(e){pr(e,"fitX"),this._fitX!==e&&(this._fitX=e,this._geometryDirty=!0,this.invalidateCache())}get fitY(){return this._fitY}set fitY(e){pr(e,"fitY"),this._fitY!==e&&(this._fitY=e,this._geometryDirty=!0,this.invalidateCache())}get offsetX(){return this._offsetX}set offsetX(e){this.setOffset(e,this._offsetY)}get offsetY(){return this._offsetY}set offsetY(e){this.setOffset(this._offsetX,e)}setSize(e,t){return _r(e,t),this._width===e&&this._height===t||(this._width=e,this._height=t,this._geometryDirty=!0,this.invalidateCache()),this}setOffset(e,t){return mr(e,"offsetX"),mr(t,"offsetY"),this._offsetX===e&&this._offsetY===t||(this._offsetX=e,this._offsetY=t,"geometry"===this.resolvedStrategy&&(this._geometryDirty=!0),this.invalidateCache()),this}getLocalBounds(){const e=super.getLocalBounds();return e.set(0,0,this._width,this._height),e}get resolvedStrategy(){return this._source instanceof Wn?"geometry":"shader"}get quads(){return"geometry"===this.resolvedStrategy&&this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(e,t,i){const n=this.quads;if("geometry"!==this.pixelSnapMode||0===n.length)return n;const r=Pn(this.getGlobalTransform(),e,t,i);return r.axisAligned?kn(n,r,this._renderQuads):n}getRenderBounds(e,t,i,n){const r=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return r;const s=Pn(this.getGlobalTransform(),e,t,i);return s.axisAligned?Dn(r,s,n):r}_rebuildGeometry(){this._quads=function(e,t,i,n,r,s,o,a,h){if(0===t||0===i||e.width<=0||e.height<=0)return[];const l=e.texture.width,u=e.texture.height,c=e.extrusion,d=c.left>0||c.right>0?0:.5/l,_=c.top>0||c.bottom>0?0:.5/u,f=e.u0+d,p=e.u1-d,m=e.v0+_,g=e.v1-_,y=e.width,w=e.height,x=p-f,v=g-m,b=yr(y,t,n,s,a),S=yr(w,i,r,o,h),B=[];for(const e of S){const t=e.destinationStart,i=e.destinationStart+e.destinationLength,n=m+e.sourceStart*v,r=m+e.sourceEnd*v;for(const e of b){const s=e.destinationStart,o=e.destinationStart+e.destinationLength,a=f+e.sourceStart*x,h=f+e.sourceEnd*x;B.push({x0:s,y0:t,x1:o,y1:i,u0:a,v0:n,u1:h,v1:r})}}return B}(this._region,this._width,this._height,this._modeX,this._modeY,this._fitX,this._fitY,this._offsetX,this._offsetY),this._geometryDirty=!1}}var xr;e.SpriteFlags=void 0,(xr=e.SpriteFlags||(e.SpriteFlags={}))[xr.None=0]="None",xr[xr.Translation=1]="Translation",xr[xr.Rotation=2]="Rotation",xr[xr.Scaling=4]="Scaling",xr[xr.Origin=8]="Origin",xr[xr.Transform=15]="Transform",xr[xr.TransformInverse=16]="TransformInverse",xr[xr.BoundingBox=32]="BoundingBox",xr[xr.TextureCoords=64]="TextureCoords",xr[xr.VertexTint=128]="VertexTint",xr[xr.Vertices=1024]="Vertices",xr[xr.Normals=2048]="Normals";class vr extends Fn{_texture=null;_textureFrame=new et;_material=null;_vertices=new Float32Array(8);_texCoords=new Uint32Array(4);_normals=[new it,new it,new it,new it];constructor(t){super(),this.flags.push(e.SpriteFlags.Vertices|e.SpriteFlags.Normals),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(e){this.setTexture(e)}get textureFrame(){return this._textureFrame}set textureFrame(e){this.setTextureFrame(e)}get material(){return this._material}set material(e){if(null!==e&&"sprite"!==e.target)throw new Error(`Sprite requires a SpriteMaterial (got a ${e.target} material).`);this._material=e,this.invalidateCache()}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(e){this.scale.x=e/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(e){this.scale.y=e/this._textureFrame.height}get vertices(){if(this.flags.has(e.SpriteFlags.Vertices)){const{left:t,top:i,right:n,bottom:r}=this.getLocalBounds(),{a:s,b:o,x:a,c:h,d:l,y:u}=this.getGlobalTransform();this._vertices[0]=t*s+i*o+a,this._vertices[1]=t*h+i*l+u,this._vertices[2]=n*s+i*o+a,this._vertices[3]=n*h+i*l+u,this._vertices[4]=n*s+r*o+a,this._vertices[5]=n*h+r*l+u,this._vertices[6]=t*s+r*o+a,this._vertices[7]=t*h+r*l+u,this.flags.remove(e.SpriteFlags.Vertices)}return this._vertices}getRenderBounds(e,t,i,n){const r=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return r;const s=Pn(this.getGlobalTransform(),e,t,i);return s.axisAligned?Dn(r,s,n):r}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(e.SpriteFlags.TextureCoords)){const{width:e,height:t}=this._texture,{left:i,top:n,right:r,bottom:s}=this._textureFrame,o=i/e*65535&65535,a=(n/t*65535&65535)<<16,h=r/e*65535&65535,l=(s/t*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o)}return this._texCoords}setTexture(e){return this._texture!==e&&(this._texture=e,null!==e&&this.resetTextureFrame(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,i=!0){const n=this.width,r=this.height;return this._textureFrame.copy(t),this.flags.push(e.SpriteFlags.TextureCoords),this.getLocalBounds().set(0,0,t.width,t.height),this._invalidateBoundsCascade(),i?(this.width=t.width,this.height=t.height):(this.width=n,this.height=r),0===this.anchor.x&&0===this.anchor.y||this._updateOrigin(),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(et.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){if(this.flags.has(e.SpriteFlags.Normals)){const t=this.vertices,i=t[0],n=t[1],r=t[2],s=t[3],o=t[4],a=t[5],h=t[6],l=t[7];this._normals[0].set(r-i,s-n).rperp().normalize(),this._normals[1].set(o-r,a-s).rperp().normalize(),this._normals[2].set(h-o,l-a).rperp().normalize(),this._normals[3].set(i-h,n-l).rperp().normalize(),this.flags.remove(e.SpriteFlags.Normals)}return this._normals}project(e,t=new me){const i=this.vertices,n=i[0],r=i[1],s=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=e.dot(n,r),d=e.dot(s,o),_=e.dot(a,h),f=e.dot(l,u);return t.set(Math.min(c,d,_,f),Math.max(c,d,_,f))}contains(e,t){if(this.isAlignedBox)return this.getBounds().contains(e,t);const i=this.vertices,n=i[0],r=i[1],s=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=(s-n)*(t-r)-(o-r)*(e-n),d=(a-s)*(t-o)-(h-o)*(e-s),_=(l-a)*(t-h)-(u-h)*(e-a),f=(n-l)*(t-u)-(r-u)*(e-l);return c>=0&&d>=0&&_>=0&&f>=0||c<=0&&d<=0&&_<=0&&f<=0}_invalidateSubtreeTransform(){super._invalidateSubtreeTransform(),this.flags.push(e.SpriteFlags.Vertices|e.SpriteFlags.Normals)}_invalidateBoundsCascade(){super._invalidateBoundsCascade(),this.flags.push(e.SpriteFlags.Vertices|e.SpriteFlags.Normals)}destroy(){super.destroy();for(const e of this._normals)e.destroy();this._textureFrame.destroy(),this._texture=null,this._material=null}}Si.setInternalSpriteFactory(()=>new vr(null));class br extends Fn{_text;constructor(e){super(),this._text=e}get text(){return this._text}get textBounds(){return{width:0,height:0}}syncDirty(){}update(e){this.syncDirty()}}class Sr{fontData;textures;constructor(e,t){t.length,e.pages.length,t.length,e.pages.length,this.fontData=e,this.textures=t}}function Br(e,t,i,n){if(0===e.length)return[];const{fontSize:r,lineHeight:s,leading:o,align:a}=t,h=r*s+o,l=i.letterSpacing??0,u=i.maxWidth,c=i.breakWords??!1,d=function(e,t){if("pre"===t)return e;if("normal"===t)return e.replaceAll("\n"," ").replaceAll(/[ \t]+/g," ");return e.split("\n").map(e=>e.replaceAll(/[ \t]+/g," ")).join("\n")}(e,i.whiteSpace??"pre-line"),_=d.split("\n"),f=[];for(const e of _)void 0===u?f.push(e):f.push(...Tr(e,r,n,u,l,c));const p=[];let m=0;for(let e=0;e<f.length;e++){const t=f[e],i=e*h;let s=0,o=0,a=!1;const u=[];let c=null;for(const e of t){null!==c&&void 0!==n.getKerning&&(s+=n.getKerning(c,e,r));const t=n.getGlyph(e,r);u.push({info:t,x:s,y:i,char:e}),s+=t.advance+l," "===e?a=!1:a||(a=!0,o++),c=e}const d=s-(u.length>0?l:0);d>m&&(m=d),p.push({placements:u,width:d,wordCount:o})}const g=[],y=p.length-1;for(let e=0;e<p.length;e++){const t=p[e];let i=0;if("right"===a)i=m-t.width;else if("center"===a)i=(m-t.width)/2;else if("justify"===a&&e!==y&&t.wordCount>1){const e=t.wordCount-1,n=(m-t.width)/e;let r=-1,s=!0;for(const e of t.placements)s&&" "!==e.char?(r++,s=!1):s||" "!==e.char||(s=!0),g.push({x:e.x+i+r*n+(e.info.xBearing??0),y:e.y+(e.info.yBearing??0),width:e.info.width,height:e.info.height,page:e.info.page,uvLeft:e.info.uvLeft,uvTop:e.info.uvTop,uvRight:e.info.uvRight,uvBottom:e.info.uvBottom});continue}for(const{info:e,x:n,y:r}of t.placements)g.push({x:n+i+(e.xBearing??0),y:r+(e.yBearing??0),width:e.width,height:e.height,page:e.page,uvLeft:e.uvLeft,uvTop:e.uvTop,uvRight:e.uvRight,uvBottom:e.uvBottom})}return g}function Cr(e){const t=new Map;for(const i of e){if(i.width<=0||i.height<=0)continue;let e=t.get(i.page);void 0===e&&t.set(i.page,e=[]),e.push(i)}const i=[];for(const[e,n]of t){const t=n.length,r=new Float32Array(8*t),s=new Float32Array(8*t),o=new Uint16Array(6*t);for(let e=0;e<t;e++){const t=n[e],i=8*e,a=4*e,h=6*e;r[i+0]=t.x,r[i+1]=t.y,r[i+2]=t.x+t.width,r[i+3]=t.y,r[i+4]=t.x+t.width,r[i+5]=t.y+t.height,r[i+6]=t.x,r[i+7]=t.y+t.height,s[i+0]=t.uvLeft,s[i+1]=t.uvTop,s[i+2]=t.uvRight,s[i+3]=t.uvTop,s[i+4]=t.uvRight,s[i+5]=t.uvBottom,s[i+6]=t.uvLeft,s[i+7]=t.uvBottom,o[h+0]=a,o[h+1]=a+1,o[h+2]=a+2,o[h+3]=a,o[h+4]=a+2,o[h+5]=a+3}i.push({pageIndex:e,vertices:r,uvs:s,indices:o,quadCount:t})}return i}function Tr(e,t,i,n,r,s){if(0===e.length)return[""];const o=e.split(" "),a=[];let h="",l=0;const u=i.getGlyph(" ",t).advance+r;for(const e of o){let o=0;for(const n of e)o+=i.getGlyph(n,t).advance+r;if(o=Math.max(0,o-r),s&&o>n){h.length>0&&(a.push(h),h="",l=0);let s="",o=0;for(const h of e){const e=i.getGlyph(h,t).advance+r;s.length>0&&o+e>n?(a.push(s),s=h,o=e):(s+=h,o+=e)}s.length>0&&(h=s,l=o)}else if(0===h.length)h=e,l=o;else{const t=l+u+o;t<=n?(h+=` ${e}`,l=t):(a.push(h),h=e,l=o)}}return a.push(h),a}class Mr{_dirty=!1;_pendingHint="tint";onChange=new x;_fontFamily;_fontWeight;_fontStyle;_fontSize;_fillColor;_outlineColor;_outlineWidth;_align;_lineHeight;_leading;_shadowColor;_shadowOffsetX;_shadowOffsetY;_shadowAlpha;_shadowBlur;_gradientColors;_gradientAxis;constructor(e={}){const t="undefined"!=typeof FontFace&&e.font instanceof FontFace?e.font:null;this._fontFamily=t?t.family:e.fontFamily??"Arial",this._fontWeight=e.fontWeight??"normal",this._fontStyle=e.fontStyle??"normal",this._fontSize=e.fontSize??20,this._fillColor=e.fillColor?e.fillColor.clone():Tt.white.clone(),this._outlineColor=e.outlineColor?e.outlineColor.clone():Tt.black.clone(),this._outlineWidth=e.outlineWidth??0,this._align=e.align??"left",this._lineHeight=e.lineHeight??1.2,this._leading=e.leading??0,this._shadowColor=e.shadowColor?e.shadowColor.clone():Tt.black.clone(),this._shadowOffsetX=e.shadowOffsetX??0,this._shadowOffsetY=e.shadowOffsetY??0,this._shadowAlpha=e.shadowAlpha??0,this._shadowBlur=e.shadowBlur??0,this._gradientColors=e.gradientColors?[e.gradientColors[0].clone(),e.gradientColors[1].clone()]:null,this._gradientAxis=e.gradientAxis??"vertical",this._dirty=!0,this._pendingHint="font"}consumeDirty(){if(!this._dirty)return null;const e=this._pendingHint;return this._dirty=!1,this._pendingHint="tint",e}_markDirty(e){var t,i;this._pendingHint=(t=this._pendingHint,i=e,"font"===t||"font"===i?"font":"layout"===t||"layout"===i?"layout":"tint"),this._dirty||(this._dirty=!0,this.onChange.dispatch())}get fontFamily(){return this._fontFamily}set fontFamily(e){const t="undefined"!=typeof FontFace&&e instanceof FontFace?e.family:e;this._fontFamily!==t&&(this._fontFamily=t,this._markDirty("font"))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this._markDirty("font"))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this._markDirty("font"))}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(this._fontSize=e,this._markDirty("layout"))}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this._markDirty("layout"))}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this._markDirty("layout"))}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this._markDirty("layout"))}get fillColor(){return this._fillColor}set fillColor(e){this._fillColor=e.clone(),this._markDirty("tint")}get outlineColor(){return this._outlineColor}set outlineColor(e){this._outlineColor=e.clone(),this._markDirty("tint")}get outlineWidth(){return this._outlineWidth}set outlineWidth(e){this._outlineWidth!==e&&(this._outlineWidth=e,this._markDirty("tint"))}get shadowColor(){return this._shadowColor}set shadowColor(e){this._shadowColor=e.clone(),this._markDirty("tint")}get shadowOffsetX(){return this._shadowOffsetX}set shadowOffsetX(e){this._shadowOffsetX!==e&&(this._shadowOffsetX=e,this._markDirty("tint"))}get shadowOffsetY(){return this._shadowOffsetY}set shadowOffsetY(e){this._shadowOffsetY!==e&&(this._shadowOffsetY=e,this._markDirty("tint"))}get shadowAlpha(){return this._shadowAlpha}set shadowAlpha(e){this._shadowAlpha!==e&&(this._shadowAlpha=e,this._markDirty("tint"))}get shadowBlur(){return this._shadowBlur}set shadowBlur(e){this._shadowBlur!==e&&(this._shadowBlur=e,this._markDirty("tint"))}get gradientColors(){return this._gradientColors}set gradientColors(e){this._gradientColors=e?[e[0].clone(),e[1].clone()]:null,this._markDirty("tint")}get gradientAxis(){return this._gradientAxis}set gradientAxis(e){this._gradientAxis!==e&&(this._gradientAxis=e,this._markDirty("tint"))}get font(){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}copy(e){return e!==this&&(this._fontFamily=e._fontFamily,this._fontWeight=e._fontWeight,this._fontStyle=e._fontStyle,this._fontSize=e._fontSize,this._fillColor=e._fillColor.clone(),this._outlineColor=e._outlineColor.clone(),this._outlineWidth=e._outlineWidth,this._align=e._align,this._lineHeight=e._lineHeight,this._leading=e._leading,this._shadowColor=e._shadowColor.clone(),this._shadowOffsetX=e._shadowOffsetX,this._shadowOffsetY=e._shadowOffsetY,this._shadowAlpha=e._shadowAlpha,this._shadowBlur=e._shadowBlur,this._gradientColors=e._gradientColors?[e._gradientColors[0].clone(),e._gradientColors[1].clone()]:null,this._gradientAxis=e._gradientAxis,this._markDirty("font")),this}clone(){const e=new Mr;return e._fontFamily=this._fontFamily,e._fontWeight=this._fontWeight,e._fontStyle=this._fontStyle,e._fontSize=this._fontSize,e._fillColor=this._fillColor.clone(),e._outlineColor=this._outlineColor.clone(),e._outlineWidth=this._outlineWidth,e._align=this._align,e._lineHeight=this._lineHeight,e._leading=this._leading,e._shadowColor=this._shadowColor.clone(),e._shadowOffsetX=this._shadowOffsetX,e._shadowOffsetY=this._shadowOffsetY,e._shadowAlpha=this._shadowAlpha,e._shadowBlur=this._shadowBlur,e._gradientColors=this._gradientColors?[this._gradientColors[0].clone(),this._gradientColors[1].clone()]:null,e._gradientAxis=this._gradientAxis,e._dirty=!0,e._pendingHint="font",e}}class Pr{_fontData;_textures;_scale;_fallbackAdvance;_fontId;constructor(e,t,i){this._fontData=e,this._textures=t,this._scale=i,this._fallbackAdvance=e.lineHeight*i*.5,this._fontId=e.pages[0]??"unknown"}getGlyph(e,t){const i=e.codePointAt(0)??0,n=this._fontData.chars.get(i),r=this._scale,s=this._fontData.lineHeight,o=this._fontData.base;if(void 0===n)return{x:0,y:0,width:0,height:0,advance:this._fallbackAdvance,ascent:0,page:0,uvLeft:0,uvTop:0,uvRight:0,uvBottom:0};n.page,this._textures.length,n.page,this._fontId,this._textures.length;const a=this._textures[n.page]?.width??1,h=this._textures[n.page]?.height??1;return{x:n.x,y:n.y,width:n.width*r,height:n.height*r,advance:n.xAdvance*r,ascent:0,page:n.page,uvLeft:n.x/a,uvTop:n.y/h,uvRight:(n.x+n.width)/a,uvBottom:(n.y+n.height)/h,xBearing:n.xOffset*r,yBearing:(n.yOffset-o)*r+s*r}}getKerning(e,t,i){const n=e.codePointAt(0),r=t.codePointAt(0);return void 0===n||void 0===r?0:(this._fontData.kernings.get(`${n},${r}`)??0)*this._scale}}class Ar extends br{_font;_fontScale;_msdf;_style;_layout;_pageQuads=[];_textBounds={width:0,height:0};_adapter;constructor(e,t,i={}){super(e),this._font=t,this._fontScale=i.scale??1,this._msdf=i.msdf??!1,this._style=new Mr(i),this._layout=i.layout??{},this._adapter=new Pr(t.fontData,t.textures,this._fontScale),this._rebuild()}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuild())}get style(){return this._style}set style(e){this._style=e instanceof Mr?e:new Mr(e),this._rebuild()}get layout(){return this._layout}set layout(e){this._layout=e,this._rebuild()}get fontScale(){return this._fontScale}set fontScale(e){this._fontScale!==e&&(this._fontScale=e,this._adapter=new Pr(this._font.fontData,this._font.textures,e),this._rebuild())}get msdf(){return this._msdf}get font(){return this._font}get pageQuads(){return this._pageQuads}get textBounds(){return this._textBounds}get textures(){return this._font.textures}setFont(e){this._font=e,this._adapter=new Pr(e.fontData,e.textures,this._fontScale),this._rebuild()}destroy(){this._pageQuads=[],super.destroy()}_rebuild(){if(this._pageQuads=[],this._textBounds={width:0,height:0},0===this._text.length)return;const e={fontSize:this._font.fontData.lineHeight*this._fontScale,lineHeight:this._style.lineHeight,leading:this._style.leading,align:this._style.align},t=Br(this._text,e,this._layout,this._adapter);let i=0,n=0;for(const e of t){const t=e.x+e.width,r=e.y+e.height;t>i&&(i=t),r>n&&(n=r)}this._textBounds={width:i,height:n},this.getLocalBounds().set(0,0,i,n),this._invalidateBoundsCascade(),this._pageQuads=Cr(t)}}const Er={r8:1,r32f:1,rgba8:4,rgba32f:4},kr={r8:1,r32f:4,rgba8:1,rgba32f:4};class Rr extends pi{static defaultSamplerOptions={scaleMode:e.ScaleModes.Nearest,wrapMode:e.WrapModes.ClampToEdge,premultiplyAlpha:!1,generateMipMap:!1,flipY:!1};format;buffer;_dirty=null;constructor(e){super(null,{...Rr.defaultSamplerOptions,...e.samplerOptions});const{width:t,height:i,format:n,data:r}=e;if(!Number.isInteger(t)||t<=0)throw new Error(`DataTexture width must be a positive integer (got ${t}).`);if(!Number.isInteger(i)||i<=0)throw new Error(`DataTexture height must be a positive integer (got ${i}).`);const s=t*i*Er[n]*kr[n];let o;if(void 0===r)o=Dr(n)?new Float32Array(s/4):new Uint8Array(s);else if(r instanceof ArrayBuffer){if(r.byteLength!==s)throw new Error(`DataTexture data byteLength ${r.byteLength} does not match ${t}x${i} ${n} (${s} bytes expected).`);o=Dr(n)?new Float32Array(r):new Uint8Array(r)}else if(r instanceof Uint8Array){if(Dr(n))throw new Error(`DataTexture format '${n}' requires a Float32Array, got Uint8Array.`);if(r.byteLength!==s)throw new Error(`DataTexture Uint8Array length ${r.length} does not match ${t}x${i} ${n} (${s} expected).`);o=r}else{if(!Dr(n))throw new Error(`DataTexture format '${n}' requires a Uint8Array, got Float32Array.`);if(r.byteLength!==s)throw new Error(`DataTexture Float32Array byteLength ${r.byteLength} does not match ${t}x${i} ${n} (${s} expected).`);o=r}this.format=n,this.buffer=o,this.setSize(t,i),this._dirty={full:!0,x:0,y:0,width:t,height:i}}updateSource(){return this.commit()}commit(){return this._dirty={full:!0,x:0,y:0,width:this.width,height:this.height},this.setSize(this.width,this.height),this._bumpVersion(),this}commitRect(e,t,i,n){if(!(Number.isInteger(e)&&Number.isInteger(t)&&Number.isInteger(i)&&Number.isInteger(n)))throw new Error(`DataTexture commitRect requires integer coordinates (got ${e}, ${t}, ${i}, ${n}).`);if(i<=0||n<=0)throw new Error(`DataTexture commitRect requires positive width and height (got ${i}, ${n}).`);if(e<0||t<0||e+i>this.width||t+n>this.height)throw new Error(`DataTexture commitRect (${e}, ${t}, ${i}, ${n}) is out of bounds for ${this.width}x${this.height}.`);if(null===this._dirty)this._dirty={full:!1,x:e,y:t,width:i,height:n};else if(this._dirty.full);else{const r=Math.min(this._dirty.x,e),s=Math.min(this._dirty.y,t),o=Math.max(this._dirty.x+this._dirty.width,e+i),a=Math.max(this._dirty.y+this._dirty.height,t+n);this._dirty={full:!1,x:r,y:s,width:o-r,height:a-s}}return this._bumpVersion(),this}_consumeDirtyRegion(){const e=this._dirty;return this._dirty=null,e}}function Dr(e){return"r32f"===e||"rgba32f"===e}const Fr=1e20;class Ir{_buffer;_radius;_cutoff;_font;_fontSize;_fontAscent=0;_fontDescent=0;_metricsReady=!1;_canvasW=0;_canvasH=0;_canvas;_ctx;_gridOuter=new Float64Array(0);_gridInner=new Float64Array(0);_f=new Float64Array(0);_d=new Float64Array(0);_z=new Float64Array(0);_v=new Int16Array(0);_out=new Uint8ClampedArray(0);constructor(e){this._buffer=e.buffer??8,this._radius=e.radius??this._buffer,this._cutoff=e.cutoff??.5,this._fontSize=e.fontSize;const t=e.fontStyle&&"normal"!==e.fontStyle?`${e.fontStyle} `:"",i=e.fontWeight??"normal";if(this._font=`${t}${i} ${e.fontSize}px ${e.fontFamily}`,"undefined"!=typeof OffscreenCanvas){const e=new OffscreenCanvas(1,1);this._canvas=e,this._ctx=e.getContext("2d",{willReadFrequently:!0})}else{const e=document.createElement("canvas");this._canvas=e,this._ctx=e.getContext("2d",{willReadFrequently:!0})}}_ensureFontMetrics(){if(this._metricsReady)return;const e=this._ctx;e.font=this._font,e.textBaseline="alphabetic";const t=e.measureText("HgjpqyÉÅ");this._fontAscent=Math.max(1,Math.ceil(t.fontBoundingBoxAscent??t.actualBoundingBoxAscent??.8*this._fontSize)),this._fontDescent=Math.max(1,Math.ceil(t.fontBoundingBoxDescent??t.actualBoundingBoxDescent??.2*this._fontSize)),this._metricsReady=!0}draw(e){this._ensureFontMetrics();const t=this._ctx,i=this._buffer;t.font=this._font,t.textBaseline="alphabetic";const n=t.measureText(e),r=n.width,s=Math.max(0,Math.ceil(n.actualBoundingBoxLeft??0)),o=Math.max(0,Math.ceil(n.actualBoundingBoxRight??r)),a=Math.max(1,s+o),h=this._fontAscent+this._fontDescent,l=a+2*i,u=h+2*i;this._canvasW===l&&this._canvasH===u||(this._canvas.width=l,this._canvas.height=u,this._canvasW=l,this._canvasH=u),t.clearRect(0,0,l,u),t.font=this._font,t.textBaseline="alphabetic",t.fillStyle="#ffffff",t.fillText(e,i+s,i+this._fontAscent);const c=t.getImageData(0,0,l,u).data,d=l*u;if(d>this._gridOuter.length){const e=Math.max(l,u);this._gridOuter=new Float64Array(d),this._gridInner=new Float64Array(d),this._f=new Float64Array(e),this._d=new Float64Array(e),this._z=new Float64Array(e+1),this._v=new Int16Array(e)}d>this._out.length&&(this._out=new Uint8ClampedArray(d));for(let e=0;e<d;e++){const t=c[4*e+3]/255;1===t?(this._gridOuter[e]=0,this._gridInner[e]=Fr):0===t?(this._gridOuter[e]=Fr,this._gridInner[e]=0):(this._gridOuter[e]=Math.max(0,.5-t)**2,this._gridInner[e]=Math.max(0,t-.5)**2)}Lr(this._gridOuter,l,u,this._f,this._d,this._v,this._z),Lr(this._gridInner,l,u,this._f,this._d,this._v,this._z);for(let e=0;e<d;e++){const t=this._gridOuter[e]-this._gridInner[e];this._out[e]=Math.max(0,Math.min(255,Math.round(255-255*(t/this._radius+this._cutoff))))}return{data:this._out.slice(0,d),width:l,height:u,glyphWidth:a,glyphHeight:h,glyphTop:i,glyphLeft:i,glyphAdvance:r}}}function Lr(e,t,i,n,r,s,o){for(let a=0;a<t;a++){for(let r=0;r<i;r++)n[r]=e[r*t+a];Ur(n,r,s,o,i);for(let n=0;n<i;n++)e[n*t+a]=r[n]}for(let a=0;a<i;a++){for(let i=0;i<t;i++)n[i]=e[a*t+i];Ur(n,r,s,o,t);for(let i=0;i<t;i++)e[a*t+i]=Math.sqrt(r[i])}}function Ur(e,t,i,n,r){let s=0;i[0]=0,n[0]=-Fr,n[1]=Fr;for(let t=1;t<r;t++){let r;do{const o=i[s];if(r=(e[t]+t*t-e[o]-o*o)/(2*(t-o)),r>n[s])break;s--}while(s>=0);s++,i[s]=t,n[s]=r,n[s+1]=Fr}s=0;for(let o=0;o<r;o++){for(;n[s+1]<o;)s++;const r=i[s];t[o]=(o-r)*(o-r)+e[r]}}class Gr{_shelves=[];_width;_height;constructor(e,t){this._width=e,this._height=t}insert(e,t){for(const i of this._shelves)if(i.height>=t&&i.cursorX+e<=this._width){const t=i.cursorX;return i.cursorX+=e,{x:t,y:i.y}}const i=this._shelves[this._shelves.length-1],n=void 0===i?0:i.y+i.height;return n+t>this._height?null:(this._shelves.push({y:n,height:t,cursorX:e}),{x:0,y:n})}reset(){this._shelves.length=0}}class Nr{texture;index;mode;_packer;_width;_height;_sdfBuffer=null;_sdfTexture=null;_ctx=null;_colorGlyphs;constructor(e,t,i,n){if(this.index=e,this.mode=n,this._width=t,this._height=i,this._colorGlyphs="color"===n,this._packer=new Gr(t,i),"sdf"===n)this._sdfBuffer=new Uint8Array(t*i),this._sdfTexture=new Rr({width:t,height:i,format:"r8",data:this._sdfBuffer}),this._sdfTexture.setSize(t,i),this.texture=this._sdfTexture;else{const{canvas:e,ctx:n}=function(e,t){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(e,t),n=i.getContext("2d");if(!n)throw new Error("GlyphAtlas: could not obtain OffscreenCanvas 2D context.");return{canvas:i,ctx:n}}const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");if(!n)throw new Error("GlyphAtlas: could not obtain canvas 2D context.");return{canvas:i,ctx:n}}(t,i);this._ctx=n,this.texture=new pi(e),this.texture.setSize(t,i)}}insert(e,t){return this._packer.insert(e,t)}writeSdf(e,t,i,n,r){const s=this._sdfBuffer,o=this._width;for(let a=0;a<r;a++){const r=a*n,h=(i+a)*o+t;s.set(e.subarray(r,r+n),h)}this._sdfTexture.commitRect(t,i,n,r)}measureGlyph(e,t){if(null!==this._ctx)return this._ctx.font=t,this._ctx.textBaseline="alphabetic",this._ctx.measureText(e);const i=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")).getContext("2d");return i.font=t,i.textBaseline="alphabetic",i.measureText(e)}rasterize(e,t,i,n,r,s){const o=this._ctx;o.font=s,o.textBaseline="alphabetic",this._colorGlyphs||(o.fillStyle="#ffffff"),o.fillText(e,t+2+r,i+2+n)}uploadDirtyRegion(){null!==this._sdfTexture?this._sdfTexture.commit():this.texture.updateSource()}reset(){this._packer.reset(),null!==this._sdfBuffer&&null!==this._sdfTexture?(this._sdfBuffer.fill(0),this._sdfTexture.commit()):null!==this._ctx&&(this._ctx.clearRect(0,0,this._width,this._height),this.texture.updateSource())}}class Or{_pages=[];_cache=new Map;_kerningCache=new Map;_pageSize;_family;_fontStyle;_fontWeight;_mode;_sdfRadius;onPageAdded=new x;_sdfInstances=new Map;constructor(e,t,i,n=1024,r="sdf",s=8){this._family=e,this._fontStyle=t,this._fontWeight=i,this._pageSize=n,this._mode=r,this._sdfRadius=s,this._addPage()}get pages(){return this._pages}get mode(){return this._mode}getGlyph(e,t){const i=`${e}:${t}`,n=this._cache.get(i);return void 0!==n?n:"sdf"===this._mode?this._rasterizeSdf(e,t,i):this._rasterizeCanvas(e,t,i)}getKerning(e,t,i){const n=`${e}${t}:${i}`,r=this._kerningCache.get(n);if(void 0!==r)return r;const s=this._cssFont(i),o=this._pages[0],a=o.measureGlyph(e+t,s).width-o.measureGlyph(e,s).width-o.measureGlyph(t,s).width;return this._kerningCache.set(n,a),a}clear(){this._cache.clear(),this._kerningCache.clear(),this._sdfInstances.clear();for(const e of this._pages)e.reset();this._pages=[],this._addPage()}_addPage(){const e=this._pages.length,t=new Nr(e,this._pageSize,this._pageSize,this._mode);return this._pages.push(t),e>0&&this.onPageAdded.dispatch(e),t}_cssFont(e){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${e}px ${this._family}`}_getSdf(e){let t=this._sdfInstances.get(e);return void 0===t&&(t=new Ir({fontSize:e,fontFamily:this._family,fontWeight:this._fontWeight,fontStyle:this._fontStyle,buffer:this._sdfRadius,radius:this._sdfRadius,cutoff:.5}),this._sdfInstances.set(e,t)),t}_rasterizeSdf(e,t,i){const n=this._getSdf(t).draw(e),{page:r,slot:s}=this._allocateSlot(n.width,n.height);r.writeSdf(n.data,s.x,s.y,n.width,n.height);const o=this._pageSize,a={x:s.x,y:s.y,width:n.width,height:n.height,advance:n.glyphAdvance,ascent:n.glyphTop+n.glyphHeight,page:r.index,uvLeft:s.x/o,uvTop:s.y/o,uvRight:(s.x+n.width)/o,uvBottom:(s.y+n.height)/o,xBearing:-n.glyphLeft,yBearing:-n.glyphTop};return this._cache.set(i,a),a}_rasterizeCanvas(e,t,i){const n=this._cssFont(t),r=this._pages[0].measureGlyph(e,n),s=Math.ceil(r.fontBoundingBoxAscent??r.actualBoundingBoxAscent??.8*t),o=Math.ceil(r.fontBoundingBoxDescent??r.actualBoundingBoxDescent??.2*t),a=r.width,h=r.actualBoundingBoxLeft??0,l=r.actualBoundingBoxRight??0,u=Math.max(1,Math.ceil(h+l)||Math.ceil(a)),c=Math.max(1,s+o),d=u+4,_=c+4,{page:f,slot:p}=this._allocateSlot(d,_);f.rasterize(e,p.x,p.y,s,h,n),f.uploadDirtyRegion();const m=this._pageSize,g={x:p.x,y:p.y,width:u,height:c,advance:a,ascent:s,page:f.index,uvLeft:p.x/m,uvTop:p.y/m,uvRight:(p.x+d)/m,uvBottom:(p.y+_)/m};return this._cache.set(i,g),g}_allocateSlot(e,t){for(const i of this._pages){const n=i.insert(e,t);if(null!==n)return{page:i,slot:n}}const i=this._addPage(),n=i.insert(e,t);if(null===n)throw new Error(`GlyphAtlas: glyph (${e}×${t}px) exceeds page size (${this._pageSize}px).`);return{page:i,slot:n}}}class Vr{_atlases=new Map;_pageSize;constructor(e=1024){this._pageSize=e}getAtlas(e,t,i,n="sdf",r=8){const s=`${e}:${t}:${i}:${n}:${r}`;let o=this._atlases.get(s);return void 0===o&&(o=new Or(e,t,i,this._pageSize,n,r),this._atlases.set(s,o)),o}clearAll(){for(const e of this._atlases.values())e.clear()}}let zr=null;function qr(){return null===zr&&(zr=new Vr),zr}class Wr extends br{_style;_layout;_colorGlyphs;_sdfRadius;_atlas=null;_destroyed=!1;_faceLoadVersion=0;_pageQuads=[];_textBounds={width:0,height:0};constructor(e,t={}){super(e),this._style=new Mr(t),this._layout=t,this._colorGlyphs=t.colorGlyphs??!1,this._sdfRadius=t.sdfRadius??8;const i=this._extractFace(t);null!==i&&this._loadFace(i),this._rebuild("font")}get style(){return this._style}set style(e){if(this._style=e instanceof Mr?e:new Mr(e),!(e instanceof Mr)){const t=this._extractFace(e);null!==t&&this._loadFace(t)}this._rebuild("font")}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuild("layout"))}get layout(){return this._layout}set layout(e){this._layout=e,this._rebuild("layout")}get colorGlyphs(){return this._colorGlyphs}get sdfRadius(){return this._sdfRadius}get atlasMode(){return this._colorGlyphs?"color":"sdf"}get pageQuads(){return this._pageQuads}get textBounds(){return this._textBounds}get atlas(){return this._atlas}syncDirty(){const e=this._style.consumeDirty();null!==e&&"tint"!==e&&this._rebuild(e)}destroy(){this._destroyed=!0,this._faceLoadVersion++,this._pageQuads=[],this._atlas=null,super.destroy()}_extractFace(e){return"undefined"==typeof FontFace?null:e.font instanceof FontFace?e.font:null}async _loadFace(e){if("undefined"==typeof document||!document.fonts)return;const t=++this._faceLoadVersion;document.fonts.has(e)||document.fonts.add(e);try{await e.load()}catch{return}if(this._destroyed||t!==this._faceLoadVersion)return;qr().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius).clear(),this._rebuild("font")}_rebuild(e){if(this._pageQuads=[],this._textBounds={width:0,height:0},0===this._text.length)return void this._style.consumeDirty();const t=qr().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius);this._atlas=t;const i=Br(this._text,this._style,this._layout,t);if(0===i.length)return void this._style.consumeDirty();let n=0,r=0;for(const e of i){const t=e.x+e.width,i=e.y+e.height;t>n&&(n=t),i>r&&(r=i)}this._textBounds={width:n,height:r},this.getLocalBounds().set(0,0,n,r),this._invalidateBoundsCascade(),this._pageQuads=Cr(i),this._style.consumeDirty()}}class Yr{attributes=new Map;uniforms=new Map;_vertexSource;_fragmentSource;_program=null;constructor(e,t){this._vertexSource=e,this._fragmentSource=t}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(e){return this._program=e,e.initialize(this),this}disconnect(){return this._program=null,this.attributes.clear(),this.uniforms.clear(),this}bind(){return this._program?.bind(this),this}unbind(){return this._program?.unbind(this),this}sync(){return this._program?.sync(this),this}getAttribute(e){const t=this.attributes.get(e);if(!t)throw new Error(`Attribute "${e}" is not available.`);return t}getUniform(e){const t=this.uniforms.get(e);if(!t)throw new Error(`Uniform "${e}" is not available.`);return t}destroy(){this._program?.destroy(this),this._program=null,this.attributes.clear(),this.uniforms.clear()}}var $r;e.RenderBackendType=void 0,($r=e.RenderBackendType||(e.RenderBackendType={}))[$r.WebGl2=0]="WebGl2",$r[$r.WebGpu=1]="WebGpu";class Xr{backendType=e.RenderBackendType.WebGl2;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==e.RenderBackendType.WebGl2)throw new Error(`${this.constructor.name} requires a WebGL2 backend, but received backendType ${String(t.backendType)}.`);this._backend=t,this.onConnect(t)}}disconnect(){null!==this._backend&&(this.flush(),this.onDisconnect(),this._backend=null)}getBackend(){if(null===this._backend)throw new Error(`${this.constructor.name} is not connected to a backend.`);return this._backend}getBackendOrNull(){return this._backend}}class Hr{_type;_usage;_runtime=null;_data=m;_version=0;_accountant=null;_accountedBytes=0;constructor(e,t,i){this._type=e,this._usage=i,t&&this.upload(t)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(e,t){return this._runtime=e,this._accountant=t??null,this._data.byteLength>0&&(e.upload(this,0),this._bookUpload()),this}disconnect(){return this._runtime=null,this}upload(e,t=0){this._data=e,this._version++,this._runtime?.upload(this,t),this._bookUpload()}bind(){this._runtime?.bind(this)}destroy(){this._runtime?.destroy(this),this._runtime=null,this._accountedBytes>0&&(this._accountant?.free(this._accountedBytes),this._accountedBytes=0)}_bookUpload(){const e=this._accountant;if(null===e||null===this._runtime)return;const t=this._data.byteLength;e.recordBufferUpload(t),t>this._accountedBytes&&(this._accountedBytes=e.reallocate(this._accountedBytes,t))}}const jr={[e.ShaderPrimitives.Float]:1,[e.ShaderPrimitives.FloatVec2]:2,[e.ShaderPrimitives.FloatVec3]:3,[e.ShaderPrimitives.FloatVec4]:4,[e.ShaderPrimitives.Int]:1,[e.ShaderPrimitives.IntVec2]:2,[e.ShaderPrimitives.IntVec3]:3,[e.ShaderPrimitives.IntVec4]:4,[e.ShaderPrimitives.UnsignedInt]:1,[e.ShaderPrimitives.UnsignedIntVec2]:2,[e.ShaderPrimitives.UnsignedIntVec3]:3,[e.ShaderPrimitives.UnsignedIntVec4]:4,[e.ShaderPrimitives.Bool]:1,[e.ShaderPrimitives.BoolVec2]:2,[e.ShaderPrimitives.BoolVec3]:3,[e.ShaderPrimitives.BoolVec4]:4,[e.ShaderPrimitives.FloatMat2]:4,[e.ShaderPrimitives.FloatMat3]:9,[e.ShaderPrimitives.FloatMat4]:16,[e.ShaderPrimitives.Sampler2D]:1},Kr={[e.ShaderPrimitives.Float]:Float32Array,[e.ShaderPrimitives.FloatVec2]:Float32Array,[e.ShaderPrimitives.FloatVec3]:Float32Array,[e.ShaderPrimitives.FloatVec4]:Float32Array,[e.ShaderPrimitives.Int]:Int32Array,[e.ShaderPrimitives.IntVec2]:Int32Array,[e.ShaderPrimitives.IntVec3]:Int32Array,[e.ShaderPrimitives.IntVec4]:Int32Array,[e.ShaderPrimitives.UnsignedInt]:Int32Array,[e.ShaderPrimitives.UnsignedIntVec2]:Int32Array,[e.ShaderPrimitives.UnsignedIntVec3]:Int32Array,[e.ShaderPrimitives.UnsignedIntVec4]:Int32Array,[e.ShaderPrimitives.Bool]:Uint8Array,[e.ShaderPrimitives.BoolVec2]:Uint8Array,[e.ShaderPrimitives.BoolVec3]:Uint8Array,[e.ShaderPrimitives.BoolVec4]:Uint8Array,[e.ShaderPrimitives.FloatMat2]:Float32Array,[e.ShaderPrimitives.FloatMat3]:Float32Array,[e.ShaderPrimitives.FloatMat4]:Float32Array,[e.ShaderPrimitives.Sampler2D]:Uint8Array};e.ShaderPrimitives.Float,e.ShaderPrimitives.FloatVec2,e.ShaderPrimitives.FloatVec3,e.ShaderPrimitives.FloatVec4,e.ShaderPrimitives.Int,e.ShaderPrimitives.IntVec2,e.ShaderPrimitives.IntVec3,e.ShaderPrimitives.IntVec4,e.ShaderPrimitives.UnsignedInt,e.ShaderPrimitives.UnsignedIntVec2,e.ShaderPrimitives.UnsignedIntVec3,e.ShaderPrimitives.UnsignedIntVec4,e.ShaderPrimitives.Bool,e.ShaderPrimitives.BoolVec2,e.ShaderPrimitives.BoolVec3,e.ShaderPrimitives.BoolVec4,e.ShaderPrimitives.FloatMat2,e.ShaderPrimitives.FloatMat3,e.ShaderPrimitives.FloatMat4,e.ShaderPrimitives.Sampler2D;class Qr{index;name;type;size;location=-1;constructor(e,t,i){this.index=e,this.name=t,this.type=i,this.size=jr[i]}destroy(){}}class Zr{index;type;size;name;_value;_dirty=!0;constructor(e,t,i,n,r){this.name=n.replace(/\[.*?]/,""),this.index=e,this.type=t,this.size=i,this._value=r}get propName(){return this.name.substring(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(e){return this._value.set(e),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class Jr{index;name;binding;dataSize;_context;_program;_blockData;_uniformBuffer;_uniforms=new Map;constructor(e,t,i){this._context=e,this._program=t,this.index=i,this.name=e.getActiveUniformBlockName(t,i)||"",this.binding=e.getActiveUniformBlockParameter(t,i,e.UNIFORM_BLOCK_BINDING),this.dataSize=e.getActiveUniformBlockParameter(t,i,e.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=e.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),e.bindBuffer(e.UNIFORM_BUFFER,this._uniformBuffer),e.bufferData(e.UNIFORM_BUFFER,this._blockData,e.DYNAMIC_DRAW),e.bindBufferBase(e.UNIFORM_BUFFER,this.binding,this._uniformBuffer),e.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(e){if(!this._uniforms.has(e))throw new Error(`Uniform "${e}" is not available.`);return this._uniforms.get(e)}upload(){const e=this._context;e.bindBuffer(e.UNIFORM_BUFFER,this._uniformBuffer),e.bufferSubData(e.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const e of this._uniforms.values())e.destroy();this._uniforms.clear()}_extractUniforms(){const e=this._context,t=this._program,i=this._blockData,n=e.getActiveUniformBlockParameter(t,this.index,e.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),r=e.getActiveUniforms(t,n,e.UNIFORM_OFFSET),s=n.length;for(let o=0;o<s;o++){const s=n[o],{type:a,size:h,name:l}=e.getActiveUniform(t,s),u=Kr[a],c=jr[a];if(void 0===u||void 0===c)throw new Error(`Unsupported uniform type ${a} for uniform "${l}".`);const d=new u(i,r[o],c*h),_=new Zr(s,a,h,l,d);this._uniforms.set(_.propName,_)}}}const es={[e.ShaderPrimitives.Float]:(e,t,i)=>{e.uniform1f(t,i[0])},[e.ShaderPrimitives.FloatVec2]:(e,t,i)=>{e.uniform2fv(t,i)},[e.ShaderPrimitives.FloatVec3]:(e,t,i)=>{e.uniform3fv(t,i)},[e.ShaderPrimitives.FloatVec4]:(e,t,i)=>{e.uniform4fv(t,i)},[e.ShaderPrimitives.Int]:(e,t,i)=>{e.uniform1i(t,i[0])},[e.ShaderPrimitives.IntVec2]:(e,t,i)=>{e.uniform2iv(t,i)},[e.ShaderPrimitives.IntVec3]:(e,t,i)=>{e.uniform3iv(t,i)},[e.ShaderPrimitives.IntVec4]:(e,t,i)=>{e.uniform4iv(t,i)},[e.ShaderPrimitives.Bool]:(e,t,i)=>{e.uniform1i(t,i[0])},[e.ShaderPrimitives.BoolVec2]:(e,t,i)=>{e.uniform2iv(t,i)},[e.ShaderPrimitives.BoolVec3]:(e,t,i)=>{e.uniform3iv(t,i)},[e.ShaderPrimitives.BoolVec4]:(e,t,i)=>{e.uniform4iv(t,i)},[e.ShaderPrimitives.FloatMat2]:(e,t,i)=>{e.uniformMatrix2fv(t,!1,i)},[e.ShaderPrimitives.FloatMat3]:(e,t,i)=>{e.uniformMatrix3fv(t,!1,i)},[e.ShaderPrimitives.FloatMat4]:(e,t,i)=>{e.uniformMatrix4fv(t,!1,i)},[e.ShaderPrimitives.Sampler2D]:(e,t,i)=>{e.uniform1i(t,i[0])}};function ts(e){let t=null,i=null,n=null,r=null;const s=[],o=[],a=e.getExtension("KHR_parallel_shader_compile"),h=a?.COMPLETION_STATUS_KHR??37297;function l(s){t||(i=is(e,e.VERTEX_SHADER,s.vertexSource),n=is(e,e.FRAGMENT_SHADER,s.fragmentSource),t=function(e,t,i){const n=e.createProgram();if(!n)throw new Error("Could not create shader program.");return e.attachShader(n,t),e.attachShader(n,i),e.linkProgram(n),n}(e,i,n),r=s)}function u(){if(null!==r&&null!==t&&null!==i&&null!==n){if(null!==a&&e.getProgramParameter(t,h),!e.getShaderParameter(i,e.COMPILE_STATUS)){const t=e.getShaderInfoLog(i);throw new Error(`Vertex shader compilation failed: ${t??"<no log>"}`)}if(!e.getShaderParameter(n,e.COMPILE_STATUS)){const t=e.getShaderInfoLog(n);throw new Error(`Fragment shader compilation failed: ${t??"<no log>"}`)}if(!e.getProgramParameter(t,e.LINK_STATUS)){const i=e.getProgramInfoLog(t);throw new Error(`Shader program linking failed: ${i??"<no log>"}`)}!function(e,t,i){const n=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<n;r++){const n=e.getActiveAttrib(t,r);if(!n)continue;const s=new Qr(r,n.name,n.type);s.location=e.getAttribLocation(t,n.name),i.attributes.set(n.name,s)}}(e,t,r),function(e,t,i,n){const r=e.getProgramParameter(t,e.ACTIVE_UNIFORMS),s=new Uint8Array(r).map((e,t)=>t),o=e.getActiveUniforms(t,s,e.UNIFORM_BLOCK_INDEX),a=s.filter(e=>-1===o[e]);for(const r of a){const s=e.getActiveUniform(t,r);if(!s)continue;const o=Kr[s.type],a=jr[s.type],h=es[s.type];if(void 0===o||void 0===a||void 0===h)throw new Error(`Unsupported uniform type ${s.type} for uniform "${s.name}".`);const l=new o(a*s.size),u=new Zr(r,s.type,s.size,s.name,l),c=e.getUniformLocation(t,u.name);i.uniforms.set(u.name,u),c&&n.push({location:c,uploadFn:h,uniform:u})}}(e,t,r,s),function(e,t,i){const n=e.getProgramParameter(t,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<n;r++){const n=new Jr(e,t,r);i.push(n)}}(e,t,o),r=null}}function c(){for(const t of s)t.uniform.dirty&&(t.uploadFn(e,t.location,t.uniform.value),t.uniform.markClean());for(const e of o)e.upload()}return{initialize:l,bind:i=>{l(i),u(),e.useProgram(t),c()},unbind:()=>{e.useProgram(null)},sync:()=>{u(),e.useProgram(t),c()},destroy:a=>{e.deleteShader(i),e.deleteShader(n),e.deleteProgram(t);for(const e of o)e.destroy();i=null,n=null,t=null,r=null,s.length=0,o.length=0,a.disconnect()}}}function is(e,t,i){const n=e.createShader(t);if(!n)throw new Error("Could not create shader.");return e.shaderSource(n,i),e.compileShader(n),n}class ns{_attributes=[];_indexBuffer=null;_drawMode;_runtime=null;_version=0;constructor(t=e.RenderingPrimitives.Triangles){this._drawMode=t}get attributes(){return this._attributes}get indexBuffer(){return this._indexBuffer}get drawMode(){return this._drawMode}get version(){return this._version}connect(e){return this._runtime=e,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(t,i,n=e.ShaderPrimitives.Float,r=!1,s=0,o=0,a=!1,h=0){const{location:l,size:u}=i;return this._attributes.push({buffer:t,location:l,size:u,type:n,normalized:r,stride:s,start:o,integer:a,divisor:h}),this._version++,this}addIndex(e){return this._indexBuffer=e,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(e,t,i=this._drawMode){return this._runtime?.draw(this,e,t,i),this}drawInstanced(e,t,i,n=this._drawMode){return this._runtime?.drawInstanced?.(this,e,t,i,n),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}const rs=20;class ss extends Xr{_defaultShader=new Yr("#version 300 es\nprecision lowp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 6) in uint a_nodeIndex;\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms;\n\nout vec2 v_texcoord;\nout vec4 v_color;\nout vec4 v_tint;\n\nvoid main(void) {\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0); // a,b,c,d\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0); // tx,ty,0,0\n mat3 transform = mat3(\n m0.x, m0.z, 0.0,\n m0.y, m0.w, 0.0,\n m1.x, m1.y, 1.0\n );\n\n gl_Position = vec4((u_projection * transform * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n v_color = a_color;\n v_tint = texelFetch(u_transforms, ivec2(2, row), 0);\n}\n","#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\nin vec4 v_tint;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 base = texture(u_texture, v_texcoord) * v_color * v_tint;\n fragColor = vec4(base.rgb * base.a, base.a);\n}\n");_customShaders=new Map;_compatibilityCache=new Map;_textureUnitScratch=new Int32Array([0]);_transformUnitScratch=new Int32Array([8]);_slotScratches=Array.from({length:Math.max(9,9)},(e,t)=>new Int32Array([t]));_vertexCapacity=64;_indexCapacity=192;_nodeIndexCapacity=64;_vertexData=new ArrayBuffer(1280);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_indexData=new Uint16Array(192);_nodeIndexData=new Uint32Array(64);_pendingDraws=[];_pendingCount=0;_staticGeometryCache=new Map;_connection=null;_currentBlendMode=null;render(t){const i=this._connection;if(!i)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(0===t.vertexCount)return;const n=this.getBackend(),r=t.material,s=null===r?this._defaultShader:this._getOrCreateCustomShader(r,i.gl),o=null!==r&&t.blendMode===e.BlendModes.Normal?r.blendMode:t.blendMode,a=t.texture??pi.white,h=n.activeDrawCommand,l=null===r||this._isInstancingCompatible(s);let u=this._pendingDraws[this._pendingCount];void 0===u?(u={mesh:t,command:h,material:r,shader:s,blendMode:o,texture:a,supportsInstancing:l},this._pendingDraws.push(u)):(u.mesh=t,u.command=h,u.material=r,u.shader=s,u.blendMode=o,u.texture=a,u.supportsInstancing=l),this._pendingCount++}drawInstancedBatch(t,i,n){const r=this._connection;if(!r)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(n<=0||0===t.vertexCount)return;const s=t.geometry;if(null===s)throw new Error("drawInstancedBatch requires a mesh constructed from a geometry.");if(null!==t.material)throw new Error("RenderBatch custom materials are not supported yet (v1 renders with the default mesh material).");const o=this.getBackend(),a=this._defaultShader,h=t.blendMode,l=t.texture??pi.white,u=this._getOrCreateStaticGeometryEntry(s,t,r),c=this._getOrCreateStaticGeometryVao(u,a,r.gl,r.dynamicNodeIndexBuffer);this._setBlendMode(h,o),this._ensureNodeIndexCapacity(n);const d=i+n-1>>>0;for(let e=0;e<n;e++)this._nodeIndexData[e]=i+e>>>0;this._bindInstancedShaderState(a,l,null,o,d),o.bindVertexArrayObject(c),r.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,n)),c.drawInstanced(u.indexCount,0,n,e.RenderingPrimitives.Triangles),o.stats.batches++,o.stats.drawCalls++}flush(){const e=this.getBackendOrNull(),t=this._connection,i=this._pendingCount;if(null!==e&&null!==t&&0!==i){for(let n=0;n<i;n++){const r=this._pendingDraws[n];if(this._canBatchStatic(r)){let r=n+1;for(;r<i&&this._isSameBatch(this._pendingDraws[r-1],this._pendingDraws[r]);)r++;if(r-n>=2){this._drawStaticBatch(n,r,e,t),n=r-1;continue}}this._drawSingle(n,e,t)}this._pendingCount=0}else this._pendingCount=0}destroy(){this.disconnect(),this._defaultShader.destroy();for(const e of this._customShaders.values())e.destroy();this._customShaders.clear(),this._compatibilityCache.clear()}onConnect(t){const i=t.context;this._defaultShader.connect(ts(i)),this._defaultShader.sync();for(const e of this._customShaders.values())e.connect(ts(i)),e.sync();const n=new Map,r=new Hr(e.BufferTypes.ElementArrayBuffer,this._indexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),s=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),o=new Hr(e.BufferTypes.ArrayBuffer,this._nodeIndexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),a=i.createVertexArray();if(null===a)throw new Error("Could not create vertex array object.");const h=(new ns).addIndex(r).addAttribute(s,this._defaultShader.getAttribute("a_position"),i.FLOAT,!1,rs,0).addAttribute(s,this._defaultShader.getAttribute("a_texcoord"),i.FLOAT,!1,rs,8).addAttribute(s,this._defaultShader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,rs,16).addAttribute(o,this._defaultShader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(i,a));this._connection={gl:i,buffers:n,dynamicVao:h,dynamicVertexBuffer:s,dynamicIndexBuffer:r,dynamicNodeIndexBuffer:o}}onDisconnect(){const e=this._connection;if(e){this._defaultShader.disconnect();for(const e of this._customShaders.values())e.disconnect();for(const e of this._staticGeometryCache.values()){for(const t of e.vaos.values())t.destroy();e.vaos.clear(),e.indexBuffer.destroy(),e.vertexBuffer.destroy()}this._staticGeometryCache.clear(),e.dynamicNodeIndexBuffer.destroy(),e.dynamicIndexBuffer.destroy(),e.dynamicVertexBuffer.destroy(),e.dynamicVao.destroy(),this._connection=null,this._currentBlendMode=null,this._pendingDraws.length=0,this._pendingCount=0}}_drawSingle(e,t,i){const n=this._pendingDraws[e];this._canBatchStatic(n)?this._drawStaticBatch(e,e+1,t,i):n.supportsInstancing&&null===n.material?this._drawDynamicInstancedSingle(n,t,i):this._drawLegacyImmediate(n,t,i)}_drawDynamicInstancedSingle(t,i,n){const r=t.command?.nodeIndex??0;null===t.command&&i._writeTransformCommand(this._createSyntheticCommand(t.mesh,r)),this._setBlendMode(t.blendMode,i),this._bindInstancedShaderState(t.shader,t.texture,t.material,i,r),this._ensureVertexCapacity(t.mesh.vertexCount),this._ensureIndexCapacity(t.mesh.indexCount),this._ensureNodeIndexCapacity(1),this._packVertices(t.mesh,0),this._packIndices(t.mesh,0),this._nodeIndexData[0]=r>>>0,i.bindVertexArrayObject(n.dynamicVao),n.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*t.mesh.vertexCount)),n.dynamicIndexBuffer.upload(this._indexData.subarray(0,t.mesh.indexCount)),n.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,1)),n.dynamicVao.drawInstanced(t.mesh.indexCount,0,1,e.RenderingPrimitives.Triangles),i.stats.batches++,i.stats.drawCalls++}_drawStaticBatch(t,i,n,r){const s=this._pendingDraws[t],o=s.mesh.geometry,a=i-t,h=this._getOrCreateStaticGeometryEntry(o,s.mesh,r),l=this._getOrCreateStaticGeometryVao(h,s.shader,r.gl,r.dynamicNodeIndexBuffer);this._setBlendMode(s.blendMode,n);let u=0;this._ensureNodeIndexCapacity(a);for(let e=0;e<a;e++){const i=this._pendingDraws[t+e].command.nodeIndex>>>0;this._nodeIndexData[e]=i,i>u&&(u=i)}this._bindInstancedShaderState(s.shader,s.texture,s.material,n,u),n.bindVertexArrayObject(l),r.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,a)),l.drawInstanced(h.indexCount,0,a,e.RenderingPrimitives.Triangles),n.stats.batches++,n.stats.drawCalls++}_drawLegacyImmediate(t,i,n){const r=t.mesh,s=t.shader;this._setBlendMode(t.blendMode,i),s.uniforms.has("u_projection")&&s.getUniform("u_projection").setValue(i.view.getTransform().toArray(!1)),s.uniforms.has("u_translation")&&s.getUniform("u_translation").setValue(r.getGlobalTransform().toArray(!1)),s.uniforms.has("u_tint")&&s.getUniform("u_tint").setValue(r.tint.toArray(!1)),s.uniforms.has("u_texture")&&(s.getUniform("u_texture").setValue(this._textureUnitScratch),i.bindTexture(t.texture,0)),null!==t.material&&this._bindCustomUniforms(s,t.material,i),this._ensureVertexCapacity(r.vertexCount),this._ensureIndexCapacity(r.indexCount),this._packVertices(r,0),this._packIndices(r,0),s.sync(),i.bindVertexArrayObject(n.dynamicVao),n.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*r.vertexCount)),n.dynamicIndexBuffer.upload(this._indexData.subarray(0,r.indexCount)),n.dynamicVao.draw(r.indexCount,0,e.RenderingPrimitives.Triangles),i.stats.batches++,i.stats.drawCalls++}_bindInstancedShaderState(e,t,i,n,r){e.uniforms.has("u_projection")&&e.getUniform("u_projection").setValue(n.view.getTransform().toArray(!1)),e.uniforms.has("u_transforms")&&(n.bindTransformBufferTexture(8,r+1),e.getUniform("u_transforms").setValue(this._transformUnitScratch)),e.uniforms.has("u_texture")&&(e.getUniform("u_texture").setValue(this._textureUnitScratch),n.bindTexture(t,0)),null!==i&&this._bindCustomUniforms(e,i,n),e.sync()}_canBatchStatic(e){if(!e.supportsInstancing)return!1;if(void 0===e.command?.groupIndex)return!1;const t=e.mesh.geometry;return"static"===t?.usage}_isSameBatch(e,t){return!(!this._canBatchStatic(e)||!this._canBatchStatic(t))&&(e.command.groupIndex===t.command.groupIndex&&e.mesh.geometry===t.mesh.geometry&&e.shader===t.shader&&e.material===t.material&&e.blendMode===t.blendMode&&e.texture===t.texture&&e.command.material.pipelineKey===t.command.material.pipelineKey&&e.command.material.bindKey===t.command.material.bindKey)}_isInstancingCompatible(e){const t=this._compatibilityCache.get(e);if(void 0!==t)return t;const i=e.attributes.has("a_nodeIndex")&&e.uniforms.has("u_transforms")&&!e.uniforms.has("u_translation")&&!e.uniforms.has("u_tint");return this._compatibilityCache.set(e,i),i}_getOrCreateStaticGeometryEntry(t,i,n){const r=this._staticGeometryCache.get(t);if(void 0!==r)return r;const s=i.vertexCount,o=i.indexCount,a=new ArrayBuffer(s*rs),h=new Float32Array(a),l=new Uint32Array(a);this._packVertices(i,0,h,l);const u=new Uint16Array(o);this._packIndices(i,0,u);const c=this.getBackend().accountant,d=new Hr(e.BufferTypes.ArrayBuffer,h,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(n.gl,n.buffers),c),_=new Hr(e.BufferTypes.ElementArrayBuffer,u,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(n.gl,n.buffers),c);d.upload(h),_.upload(u);const f=()=>{const e=this._staticGeometryCache.get(t);if(void 0!==e){for(const t of e.vaos.values())t.destroy();e.vaos.clear(),e.indexBuffer.destroy(),e.vertexBuffer.destroy(),this._staticGeometryCache.delete(t)}};t._onDispose(f);const p={geometry:t,vertexBuffer:d,indexBuffer:_,vaos:new Map,disposeListener:f,indexCount:o};return this._staticGeometryCache.set(t,p),p}_getOrCreateStaticGeometryVao(e,t,i,n){const r=e.vaos.get(t);if(void 0!==r)return r;const s=i.createVertexArray();if(null===s)throw new Error("Could not create vertex array object.");const o=t.getAttribute("a_nodeIndex"),a=(new ns).addIndex(e.indexBuffer).addAttribute(e.vertexBuffer,t.getAttribute("a_position"),i.FLOAT,!1,rs,0).addAttribute(e.vertexBuffer,t.getAttribute("a_texcoord"),i.FLOAT,!1,rs,8).addAttribute(e.vertexBuffer,t.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,rs,16).addAttribute(n,o,i.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(i,s));return e.vaos.set(t,a),a}_setBlendMode(e,t){this._currentBlendMode!==e&&(this._currentBlendMode=e,t.setBlendMode(e))}_packVertices(e,t,i=this._float32View,n=this._uint32View){const r=e.vertices,s=e.uvs,o=e.colors,a=e.vertexCount;for(let e=0;e<a;e++){const a=5*(t+e),h=2*e;i[a]=r[h],i[a+1]=r[h+1],null!==s?(i[a+2]=s[h],i[a+3]=s[h+1]):(i[a+2]=0,i[a+3]=0),n[a+4]=null!==o?o[e]:4294967295}}_packIndices(e,t,i=this._indexData){const n=e.indexCount;if(null===e.indices)for(let e=0;e<n;e++)i[t+e]=e;else i.set(e.indices,t)}_ensureVertexCapacity(e){if(!(e<=this._vertexCapacity)){for(;this._vertexCapacity<e;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*rs),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(e){if(!(e<=this._indexCapacity)){for(;this._indexCapacity<e;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeIndexCapacity(e){if(!(e<=this._nodeIndexCapacity)){for(;this._nodeIndexCapacity<e;)this._nodeIndexCapacity*=2;this._nodeIndexData=new Uint32Array(this._nodeIndexCapacity)}}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:(n,r)=>{const s=t.get(n),o=n.data;e.bindBuffer(n.type,i),s&&s.dataByteLength>=o.byteLength?(e.bufferSubData(n.type,r,o),s.dataByteLength=o.byteLength):(e.bufferData(n.type,o,n.usage),t.set(n,{handle:i,dataByteLength:o.byteLength}))},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),i.integer?e.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location),e.vertexAttribDivisor(i.location,i.divisor);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{t.indexBuffer?e.drawElementsInstanced(s,i,e.UNSIGNED_SHORT,n,r):e.drawArraysInstanced(s,n,i,r)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}_getOrCreateCustomShader(e,t){const i=this._customShaders.get(e);if(void 0!==i)return i;const n=e.shader.glsl;if(null===n)throw new Error("Mesh material shader has no `glsl` source; cannot render through the WebGL2 backend.");const r=new Yr(n.vertex,n.fragment);return r.connect(ts(t)),r.sync(),this._customShaders.set(e,r),e._onDispose(()=>{const t=this._customShaders.get(e);void 0!==t&&(t.destroy(),this._customShaders.delete(e))}),r}_bindCustomUniforms(e,t,i){let n=1;const r=t.uniforms;for(const t in r){if(!e.uniforms.has(t))continue;const s=r[t],o=e.getUniform(t);if(s instanceof pi||s instanceof _i){if(n>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(s,n),o.setValue(this._slotScratches[n]),n++}else o.setValue(this._marshalUniformValue(s))}const s=t.textures;for(const t in s)if(e.uniforms.has(t)){if(n>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(s[t],n),e.getUniform(t).setValue(this._slotScratches[n]),n++}}_marshalUniformValue(e){return e instanceof Float32Array||e instanceof Int32Array?e:"number"==typeof e?new Float32Array([e]):new Float32Array(e)}_createSyntheticCommand(e,t){return{kind:Yt.Draw,drawable:e,nodeIndex:t,seq:0,zIndex:e.zIndex,material:{rendererId:0,blendMode:e.blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},minX:0,minY:0,maxX:0,maxY:0,groupIndex:0}}}const os=32,as=os/Uint32Array.BYTES_PER_ELEMENT;class hs extends Xr{_shader;_batchSize;_instanceData;_instanceFloat32;_instanceUint32;_transformUnitScratch=new Int32Array([1]);_quadIndex=0;_maxNodeIndex=0;_currentBlendMode=null;_currentTexture=null;_currentView=null;_currentViewId=-1;_instanceBuffer=null;_vao=null;_connection=null;constructor(e){super(),this._batchSize=e,this._shader=new Yr("#version 300 es\nprecision lowp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). One entry per nine-slice quad.\n// gl_VertexID 0..3 selects which corner of the quad this invocation computes.\nlayout(location = 0) in vec4 a_quadBounds; // x0, y0, x1, y1 (local space)\nlayout(location = 1) in vec4 a_uvBounds; // u0, v0, u1, v1 (normalised, flipY pre-applied)\nlayout(location = 2) in vec4 a_color; // RGBA tint\nlayout(location = 3) in uint a_nodeIndex; // row into the shared transform buffer\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms; // shared per-frame transform buffer (3 texels/row)\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n // gl_VertexID 0..3 -> corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n float localX = (cornerX == 0) ? a_quadBounds.x : a_quadBounds.z;\n float localY = (cornerY == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0); // a, b, c, d\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0); // tx, ty, 0, 0\n\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n gl_Position = vec4((u_projection * vec3(worldX, worldY, 1.0)).xy, 0.0, 1.0);\n\n float u = (cornerX == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cornerY == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}","#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 sampleColor = texture(u_texture, v_texcoord);\n fragColor = sampleColor * v_color;\n}"),this._instanceData=new ArrayBuffer(e*os),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(e){const t=this.getBackend();let i=e.quads;if("geometry"===e.pixelSnapMode){const n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}if(0===i.length)return;const n=e.texture,r=e.blendMode,s=e.tint.toRgba(),o=t.activeDrawCommand,a=null!==o?o.nodeIndex:t._pushTransform(e),h=null!==this._currentTexture&&n!==this._currentTexture,l=r!==this._currentBlendMode;this._quadIndex>0&&(l||h||this._quadIndex+i.length>this._batchSize)&&this.flush(),null!==this._currentBlendMode&&this._currentBlendMode===r||(this._currentBlendMode=r,t.setBlendMode(r)),this._currentTexture!==n&&(this._currentTexture=n,t.bindTexture(n,0));let u=0;for(;u<i.length;){const e=Math.min(u+this._batchSize,i.length);this._writeQuadChunk(i,u,e,n,s,a),u=e,u<i.length&&(this.flush(),this._currentBlendMode=r,t.setBlendMode(r),this._currentTexture=n,t.bindTexture(n,0))}}_writeQuadChunk(e,t,i,n,r,s){const o=this._instanceFloat32,a=this._instanceUint32,h=n.flipY;for(let n=t;n<i;n++){const t=e[n],i=this._quadIndex*as;o[i+0]=t.x0,o[i+1]=t.y0,o[i+2]=t.x1,o[i+3]=t.y1;const l=65535*t.u0&65535,u=65535*t.u1&65535,c=65535*t.v0&65535,d=65535*t.v1&65535,_=h?d:c,f=h?c:d;a[i+4]=l|_<<16,a[i+5]=u|f<<16,a[i+6]=r,a[i+7]=s>>>0,this._quadIndex++,s>this._maxNodeIndex&&(this._maxNodeIndex=s)}}flush(){const t=this.getBackendOrNull(),i=this._instanceBuffer,n=this._vao;if(0===this._quadIndex||null===t||null===i||null===n)return this._quadIndex=0,void(this._maxNodeIndex=0);const r=t.view;this._currentView===r&&this._currentViewId===r.updateId||(this._currentView=r,this._currentViewId=r.updateId,this._shader.getUniform("u_projection").setValue(r.getTransform().toArray(!1))),null!==this._currentTexture&&this._shader.getUniform("u_texture").setValue(new Int32Array([0])),t.bindTransformBufferTexture(1,this._maxNodeIndex+1),this._shader.getUniform("u_transforms").setValue(this._transformUnitScratch),this._shader.sync(),t.bindVertexArrayObject(n),i.upload(this._instanceFloat32.subarray(0,this._quadIndex*as)),n.drawInstanced(4,0,this._quadIndex,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._quadIndex=0,this._maxNodeIndex=0}onConnect(t){const i=t.context;this._shader.connect(ts(i)),this._connection=this._createConnection(i),this._instanceBuffer=new Hr(e.BufferTypes.ArrayBuffer,this._instanceData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_quadBounds"),i.FLOAT,!1,os,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),i.UNSIGNED_SHORT,!0,os,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,os,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,os,28,!0,1).connect(this._createVaoRuntime(this._connection))}onDisconnect(){this._shader.disconnect(),this._instanceBuffer?.destroy(),this._instanceBuffer=null,this._vao?.destroy(),this._vao=null,this._connection=null,this._currentBlendMode=null,this._currentTexture=null,this._currentView=null,this._currentViewId=-1,this._quadIndex=0,this._maxNodeIndex=0}destroy(){this.disconnect(),this._shader.destroy()}_createConnection(e){const t=e.createVertexArray();if(null===t)throw new Error("WebGl2NineSliceSpriteRenderer: could not create vertex array object.");return{gl:e,buffers:new Map,vaoHandle:t}}_createBufferRuntime(e){const t=e.gl.createBuffer();if(null===t)throw new Error("WebGl2NineSliceSpriteRenderer: could not create render buffer.");return{bind:i=>{e.gl.bindBuffer(i.type,t)},upload:(i,n)=>{const r=e.gl,s=i.data,o=e.buffers.get(i);r.bindBuffer(i.type,t),o&&o.dataByteLength>=s.byteLength?(r.bufferSubData(i.type,n,s),o.dataByteLength=s.byteLength):(r.bufferData(i.type,s,i.usage),e.buffers.set(i,{handle:t,dataByteLength:s.byteLength}))},destroy:i=>{e.gl.deleteBuffer(t),e.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(e){let t=-1;return{bind:i=>{const n=e.gl;if(n.bindVertexArray(e.vaoHandle),t!==i.version){let e=null;for(const t of i.attributes)e!==t.buffer&&(t.buffer.bind(),e=t.buffer),t.integer?n.vertexAttribIPointer(t.location,t.size,t.type,t.stride,t.start):n.vertexAttribPointer(t.location,t.size,t.type,t.normalized,t.stride,t.start),n.enableVertexAttribArray(t.location),n.vertexAttribDivisor(t.location,t.divisor);t=i.version}},unbind:()=>{e.gl.bindVertexArray(null)},draw:(t,i,n,r)=>{e.gl.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{e.gl.drawArraysInstanced(s,n,i,r)},destroy:t=>{e.gl.deleteVertexArray(e.vaoHandle),t.disconnect()}}}}const ls="#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_texture;\n\nin vec2 v_texcoord;\nin vec4 v_color;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n fragColor = texture(u_texture, v_texcoord) * v_color;\n}",us=40,cs=us/Uint32Array.BYTES_PER_ELEMENT,ds=32,_s=ds/Uint32Array.BYTES_PER_ELEMENT;function fs(t){return"repeat"===t?e.WrapModes.Repeat:"mirror-repeat"===t?e.WrapModes.MirroredRepeat:e.WrapModes.ClampToEdge}class ps extends Xr{_shaderPathShader;_geoPathShader;_batchSize;_shaderData;_shaderF32;_shaderU32;_shaderBuf=null;_shaderVao=null;_shaderQuadCount=0;_geoData;_geoF32;_geoU32;_geoBuf=null;_geoVao=null;_geoQuadCount=0;_samplers=new Map;_maxNodeIndex=0;_currentTexture=null;_currentBlendMode=null;_currentModeX=null;_currentModeY=null;_currentPath=null;_connection=null;_transformUnitScratch=new Int32Array([1]);_snapBounds=new et;_currentView=null;_currentViewId=-1;constructor(e){super(),this._batchSize=e,this._shaderPathShader=new Yr("#version 300 es\nprecision mediump float;\nprecision highp int;\n\nlayout(location = 0) in vec4 a_quadBounds; // x0,y0,x1,y1 (local space)\nlayout(location = 1) in vec4 a_uvParams; // tilingX, tilingY, offsetU, offsetV\nlayout(location = 2) in vec4 a_color; // RGBA tint (normalised)\nlayout(location = 3) in uint a_nodeIndex; // transform row\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms;\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n int vid = gl_VertexID;\n int cx = vid & 1;\n int cy = (vid >> 1) & 1;\n\n float lx = (cx == 0) ? a_quadBounds.x : a_quadBounds.z;\n float ly = (cy == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n float destW = a_quadBounds.z - a_quadBounds.x;\n float destH = a_quadBounds.w - a_quadBounds.y;\n\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0);\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0);\n\n float wx = m0.x * lx + m0.y * ly + m1.x;\n float wy = m0.z * lx + m0.w * ly + m1.y;\n gl_Position = vec4((u_projection * vec3(wx, wy, 1.0)).xy, 0.0, 1.0);\n\n float u = (destW > 0.0)\n ? ((lx - a_quadBounds.x) / destW) * a_uvParams.x + a_uvParams.z\n : a_uvParams.z;\n float v = (destH > 0.0)\n ? ((ly - a_quadBounds.y) / destH) * a_uvParams.y + a_uvParams.w\n : a_uvParams.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}",ls),this._geoPathShader=new Yr("#version 300 es\nprecision lowp float;\nprecision highp int;\n\nlayout(location = 0) in vec4 a_quadBounds; // x0,y0,x1,y1 (local space)\nlayout(location = 1) in vec4 a_uvBounds; // u0,v0,u1,v1 (normalised, flipY pre-applied)\nlayout(location = 2) in vec4 a_color; // RGBA tint\nlayout(location = 3) in uint a_nodeIndex; // transform row\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms;\n\nout vec2 v_texcoord;\nout vec4 v_color;\n\nvoid main(void) {\n int vid = gl_VertexID;\n int cx = vid & 1;\n int cy = (vid >> 1) & 1;\n\n float lx = (cx == 0) ? a_quadBounds.x : a_quadBounds.z;\n float ly = (cy == 0) ? a_quadBounds.y : a_quadBounds.w;\n\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0);\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0);\n\n float wx = m0.x * lx + m0.y * ly + m1.x;\n float wy = m0.z * lx + m0.w * ly + m1.y;\n gl_Position = vec4((u_projection * vec3(wx, wy, 1.0)).xy, 0.0, 1.0);\n\n float u = (cx == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cy == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n}",ls),this._shaderData=new ArrayBuffer(e*us),this._shaderF32=new Float32Array(this._shaderData),this._shaderU32=new Uint32Array(this._shaderData),this._geoData=new ArrayBuffer(e*ds),this._geoF32=new Float32Array(this._geoData),this._geoU32=new Uint32Array(this._geoData)}render(e){const t=e.resolvedStrategy,i=e.texture,n=e.blendMode,r=e.modeX,s=e.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const e=this._currentPath!==t,o=this._currentTexture!==i,a=this._currentBlendMode!==n,h="shader"===t&&(this._currentModeX!==r||this._currentModeY!==s);(e||o||a||h)&&this.flush()}const o=this.getBackend();this._currentTexture!==i&&(this._currentTexture=i,o.bindTexture(i,0)),this._currentBlendMode!==n&&(this._currentBlendMode=n,o.setBlendMode(n)),this._currentPath=t;const a=o.activeDrawCommand,h=null!==a?a.nodeIndex:o._pushTransform(e);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===t?(this._currentModeX=r,this._currentModeY=s,this._writeShaderInstance(e,h)):this._writeGeoQuads(e,h)}_writeShaderInstance(e,t){const i=e.texture,n=e.region.width,r=e.region.height;let s=e.width,o=e.height;const a=i instanceof pi&&i.flipY;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),i=t._getSnapPixelSize(),n=e.getRenderBounds(t.view,i.width,i.height,this._snapBounds);s=n.width,o=n.height}const h=gr(n,s,e.modeX,e.fitX),l=gr(r,o,e.modeY,e.fitY),u=e.offsetX/(n>0?n:1),c=e.offsetY/(r>0?r:1),d=a?-l:l,_=a?l+c:c;this._shaderQuadCount>=this._batchSize&&this.flush();const f=this._shaderQuadCount*cs,p=this._shaderF32,m=this._shaderU32;p[f+0]=0,p[f+1]=0,p[f+2]=s,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,m[f+8]=e.tint.toRgba(),m[f+9]=t>>>0,this._shaderQuadCount++}_writeGeoQuads(e,t){let i=e.quads;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}const n=e.texture instanceof pi&&e.texture.flipY,r=e.tint.toRgba();let s=0;for(;s<i.length;){const o=i.length-s,a=Math.min(o,this._batchSize-this._geoQuadCount);if(a<=0){this.flush();const i=this.getBackend();i.bindTexture(e.texture,0),i.setBlendMode(e.blendMode),this._currentTexture=e.texture,this._currentBlendMode=e.blendMode,this._currentPath="geometry",t>this._maxNodeIndex&&(this._maxNodeIndex=t);continue}const h=this._geoF32,l=this._geoU32;for(let e=0;e<a;e++){const o=i[s+e],a=(this._geoQuadCount+e)*_s;h[a+0]=o.x0,h[a+1]=o.y0,h[a+2]=o.x1,h[a+3]=o.y1;const u=65535*o.u0&65535,c=65535*o.u1&65535,d=65535*o.v0&65535,_=65535*o.v1&65535,f=n?_:d,p=n?d:_;l[a+4]=u|f<<16,l[a+5]=c|p<<16,l[a+6]=r,l[a+7]=t>>>0}this._geoQuadCount+=a,s+=a}}flush(){const e=this.getBackendOrNull();if(null===e)return void this._resetBatchState();const t=e.view;if(this._currentView!==t||this._currentViewId!==t.updateId){this._currentView=t,this._currentViewId=t.updateId;const e=t.getTransform().toArray(!1);this._shaderPathShader.getUniform("u_projection").setValue(e),this._geoPathShader.getUniform("u_projection").setValue(e)}this._shaderQuadCount>0&&this._flushShaderBatch(e),this._geoQuadCount>0&&this._flushGeoBatch(e),this._resetBatchState()}_flushShaderBatch(t){const i=this._connection,n=this._shaderBuf,r=this._shaderVao;if(!i||!n||!r||0===this._shaderQuadCount)return;const s=i.gl,o=this._currentTexture,a=o instanceof pi?o.scaleMode:e.ScaleModes.Linear,h=fs(this._currentModeX??"repeat"),l=fs(this._currentModeY??"repeat"),u=this._getOrCreateSampler(s,h,l,a);s.bindSampler(0,u),t.bindTransformBufferTexture(1,this._maxNodeIndex+1),this._shaderPathShader.getUniform("u_texture").setValue(new Int32Array([0])),this._shaderPathShader.getUniform("u_transforms").setValue(this._transformUnitScratch),this._shaderPathShader.sync(),t.bindVertexArrayObject(r),n.upload(this._shaderF32.subarray(0,this._shaderQuadCount*cs)),r.drawInstanced(4,0,this._shaderQuadCount,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,s.bindSampler(0,null),this._shaderQuadCount=0}_flushGeoBatch(t){const i=this._connection,n=this._geoBuf,r=this._geoVao;i&&n&&r&&0!==this._geoQuadCount&&(t.bindTransformBufferTexture(1,this._maxNodeIndex+1),this._geoPathShader.getUniform("u_texture").setValue(new Int32Array([0])),this._geoPathShader.getUniform("u_transforms").setValue(this._transformUnitScratch),this._geoPathShader.sync(),t.bindVertexArrayObject(r),n.upload(this._geoF32.subarray(0,this._geoQuadCount*_s)),r.drawInstanced(4,0,this._geoQuadCount,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._geoQuadCount=0)}_resetBatchState(){this._shaderQuadCount=0,this._geoQuadCount=0,this._maxNodeIndex=0,this._currentTexture=null,this._currentBlendMode=null,this._currentModeX=null,this._currentModeY=null,this._currentPath=null}_getOrCreateSampler(e,t,i,n){const r=`${t}:${i}:${n}`,s=this._samplers.get(r);if(void 0!==s)return s;const o=e.createSampler();if(null===o)throw new Error("WebGl2RepeatingSpriteRenderer: could not create sampler.");return e.samplerParameteri(o,e.TEXTURE_WRAP_S,t),e.samplerParameteri(o,e.TEXTURE_WRAP_T,i),e.samplerParameteri(o,e.TEXTURE_MAG_FILTER,n),e.samplerParameteri(o,e.TEXTURE_MIN_FILTER,n),this._samplers.set(r,o),o}onConnect(t){const i=t.context;this._shaderPathShader.connect(ts(i)),this._geoPathShader.connect(ts(i)),this._shaderPathShader.sync(),this._geoPathShader.sync();const n=this._createConnection(i);this._connection=n,this._shaderBuf=new Hr(e.BufferTypes.ArrayBuffer,this._shaderData,e.BufferUsage.DynamicDraw).connect(this._createBufRuntime(n,"shader"),t.accountant),this._shaderVao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_quadBounds"),i.FLOAT,!1,us,0,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_uvParams"),i.FLOAT,!1,us,16,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,us,32,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,us,36,!0,1).connect(this._createVaoRuntime(n,"shader")),this._geoBuf=new Hr(e.BufferTypes.ArrayBuffer,this._geoData,e.BufferUsage.DynamicDraw).connect(this._createBufRuntime(n,"geo"),t.accountant),this._geoVao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_quadBounds"),i.FLOAT,!1,ds,0,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_uvBounds"),i.UNSIGNED_SHORT,!0,ds,16,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,ds,24,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,ds,28,!0,1).connect(this._createVaoRuntime(n,"geo"))}onDisconnect(){const e=this._connection?.gl;if(void 0!==e)for(const t of this._samplers.values())e.deleteSampler(t);this._samplers.clear(),this._shaderPathShader.disconnect(),this._geoPathShader.disconnect(),this._shaderBuf?.destroy(),this._shaderBuf=null,this._shaderVao?.destroy(),this._shaderVao=null,this._geoBuf?.destroy(),this._geoBuf=null,this._geoVao?.destroy(),this._geoVao=null,this._connection=null,this._currentView=null,this._currentViewId=-1,this._resetBatchState()}destroy(){this.disconnect(),this._shaderPathShader.destroy(),this._geoPathShader.destroy()}_createConnection(e){const t=e.createVertexArray(),i=e.createVertexArray();if(null===t||null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create vertex array object.");return{gl:e,buffers:new Map,shaderVaoHandle:t,geoVaoHandle:i}}_createBufRuntime(e,t){const i=e.gl.createBuffer();if(null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create render buffer.");return{bind:t=>{e.gl.bindBuffer(t.type,i)},upload:(t,n)=>{const r=e.gl,s=t.data,o=e.buffers.get(t);r.bindBuffer(t.type,i),o&&o.dataByteLength>=s.byteLength?(r.bufferSubData(t.type,n,s),o.dataByteLength=s.byteLength):(r.bufferData(t.type,s,t.usage),e.buffers.set(t,{handle:i,dataByteLength:s.byteLength}))},destroy:t=>{e.gl.deleteBuffer(i),e.buffers.delete(t),t.disconnect()}}}_createVaoRuntime(e,t){const i="shader"===t?e.shaderVaoHandle:e.geoVaoHandle;let n=-1;return{bind:t=>{const r=e.gl;if(r.bindVertexArray(i),n!==t.version){let e=null;for(const i of t.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),i.integer?r.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):r.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),r.enableVertexAttribArray(i.location),r.vertexAttribDivisor(i.location,i.divisor);n=t.version}},unbind:()=>{e.gl.bindVertexArray(null)},draw:(t,i,n,r)=>{e.gl.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{e.gl.drawArraysInstanced(s,n,i,r)},destroy:t=>{e.gl.deleteVertexArray(i),t.disconnect()}}}}const ms=36,gs=ms/Uint32Array.BYTES_PER_ELEMENT;class ys extends Xr{_shader;_batchSize;_instanceData;_instanceFloat32;_instanceUint32;_activeTextures=new Array(8).fill(null);_textureSlots=new Map;_slotCount=0;_customShaders=new Map;_slotScratches=Array.from({length:8},(e,t)=>new Int32Array([t]));_transformUnitScratch=new Int32Array([8]);_currentMaterial=null;_currentBaseTexture=null;_snapBounds=new et;_activeBounds=null;_instanceCount=0;_maxNodeIndex=0;_currentBlendMode=null;_currentView=null;_currentViewId=-1;_instanceBuffer=null;_vao=null;_connection=null;constructor(e){super(),this._batchSize=e,this._shader=new Yr("#version 300 es\nprecision lowp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). Each Sprite contributes one entry\n// to the per-instance buffer; gl_VertexID 0..3 selects which corner of the\n// quad this invocation is computing.\nlayout(location = 0) in vec4 a_localBounds; // left, top, right, bottom (local space)\nlayout(location = 3) in vec4 a_uvBounds; // uMin, vMin, uMax, vMax (normalised, already flipY-swapped)\nlayout(location = 4) in vec4 a_color; // RGBA tint\nlayout(location = 5) in uint a_textureSlot;\nlayout(location = 6) in uint a_nodeIndex; // row into the shared transform buffer\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms; // shared per-frame transform buffer (3 texels/row)\n\nout vec2 v_texcoord;\nout vec4 v_color;\nflat out uint v_textureSlot;\n\nvoid main(void) {\n // gl_VertexID 0..3 → corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n // Local-space corner: pick from the bounds rectangle.\n float localX = (cornerX == 0) ? a_localBounds.x : a_localBounds.z;\n float localY = (cornerY == 0) ? a_localBounds.y : a_localBounds.w;\n\n // Fetch the world transform for this instance from the shared buffer,\n // keyed by a_nodeIndex. Row layout: texel 0 = (a, b, c, d),\n // texel 1 = (tx, ty, 0, 0). (texel 2 carries tint, unused here — the\n // sprite keeps its own per-instance a_color.)\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0); // a, b, c, d\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0); // tx, ty, 0, 0\n\n // world = M * (localX, localY, 1)\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n gl_Position = vec4((u_projection * vec3(worldX, worldY, 1.0)).xy, 0.0, 1.0);\n\n // UV: pick from the bounds rectangle. The CPU pre-swaps Y bounds when\n // the texture is flipY, so the shader doesn't have to know.\n float u = (cornerX == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cornerY == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n v_textureSlot = a_textureSlot;\n}\n","#version 300 es\nprecision lowp float;\nprecision lowp int;\n\n// Multi-texture sprite batching: up to 8 textures bound per draw call,\n// each fragment selects its source via a flat-interpolated slot index.\n//\n// GLSL ES 3.0 forbids non-constant array-of-sampler indexing unless the\n// expression is dynamically uniform — which a per-vertex slot is not\n// once different triangles in the same batch carry different slots. The\n// if/else chain below dispatches statically and dodges that constraint.\n\nuniform sampler2D u_texture0;\nuniform sampler2D u_texture1;\nuniform sampler2D u_texture2;\nuniform sampler2D u_texture3;\nuniform sampler2D u_texture4;\nuniform sampler2D u_texture5;\nuniform sampler2D u_texture6;\nuniform sampler2D u_texture7;\n\nin vec2 v_texcoord;\nin vec4 v_color;\nflat in uint v_textureSlot;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 sampleColor;\n\n if (v_textureSlot == 0u) {\n sampleColor = texture(u_texture0, v_texcoord);\n } else if (v_textureSlot == 1u) {\n sampleColor = texture(u_texture1, v_texcoord);\n } else if (v_textureSlot == 2u) {\n sampleColor = texture(u_texture2, v_texcoord);\n } else if (v_textureSlot == 3u) {\n sampleColor = texture(u_texture3, v_texcoord);\n } else if (v_textureSlot == 4u) {\n sampleColor = texture(u_texture4, v_texcoord);\n } else if (v_textureSlot == 5u) {\n sampleColor = texture(u_texture5, v_texcoord);\n } else if (v_textureSlot == 6u) {\n sampleColor = texture(u_texture6, v_texcoord);\n } else {\n sampleColor = texture(u_texture7, v_texcoord);\n }\n\n fragColor = sampleColor * v_color;\n}\n"),this._instanceData=new ArrayBuffer(e*ms),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(e){const t=e.texture;if(null===t)return this;const i=this.getBackend(),n=e.material,r=i.activeDrawCommand,s=null!==r?r.nodeIndex:i._pushTransform(e);return this._activeBounds=this._resolveBounds(e,i),null===n?this._renderDefault(e,t,i,s):this._renderCustom(e,t,n,i,s),this}_resolveBounds(e,t){if("geometry"!==e.pixelSnapMode)return e.getLocalBounds();const i=t._getSnapPixelSize();return e.getRenderBounds(t.view,i.width,i.height,this._snapBounds)}flush(){const t=this.getBackendOrNull(),i=this._instanceBuffer,n=this._vao,r=this._connection;if(0===this._instanceCount||null===t||null===i||null===n||null===r)return this._maxNodeIndex=0,void this._resetSlots();const s=this._currentMaterial,o=null===s?this._shader:this._getOrCreateCustomShader(s,r.gl);if(null===s){const e=t.view;this._currentView===e&&this._currentViewId===e.updateId||(this._currentView=e,this._currentViewId=e.updateId,this._shader.getUniform("u_projection").setValue(e.getTransform().toArray(!1)))}else{o.uniforms.has("u_projection")&&o.getUniform("u_projection").setValue(t.view.getTransform().toArray(!1));const e=this._currentBaseTexture;null!==e&&o.uniforms.has("u_texture")&&(t.bindTexture(e,0),o.getUniform("u_texture").setValue(this._slotScratches[0])),this._bindCustomUniforms(o,s,t)}t.bindTransformBufferTexture(8,this._maxNodeIndex+1),o.uniforms.has("u_transforms")&&o.getUniform("u_transforms").setValue(this._transformUnitScratch),o.sync(),t.bindVertexArrayObject(n),i.upload(this._instanceFloat32.subarray(0,this._instanceCount*gs)),n.drawInstanced(4,0,this._instanceCount,e.RenderingPrimitives.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots()}onConnect(t){const i=t.context;this._shader.connect(ts(i)),this._connection=this._createConnection(i),this._instanceBuffer=new Hr(e.BufferTypes.ArrayBuffer,this._instanceData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new ns(e.RenderingPrimitives.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_localBounds"),i.FLOAT,!1,ms,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),i.UNSIGNED_SHORT,!0,ms,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,ms,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_textureSlot"),i.UNSIGNED_INT,!1,ms,28,!0,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),i.UNSIGNED_INT,!1,ms,32,!0,1).connect(this._createVaoRuntime(this._connection));const n=new Int32Array(1);for(let e=0;e<8;e++)n[0]=e,this._shader.getUniform(`u_texture${e}`).setValue(n)}onDisconnect(){this._shader.disconnect();for(const e of this._customShaders.values())e.destroy();this._customShaders.clear(),this._currentMaterial=null,this._currentBaseTexture=null,this._instanceBuffer?.destroy(),this._instanceBuffer=null,this._vao?.destroy(),this._vao=null,this._connection=null,this._currentBlendMode=null,this._currentView=null,this._currentViewId=-1,this._instanceCount=0,this._maxNodeIndex=0}destroy(){this.disconnect(),this._shader.destroy()}_renderDefault(e,t,i,n){const r=e.blendMode,s=this._instanceCount>=this._batchSize,o=r!==this._currentBlendMode,a=!this._textureSlots.has(t)&&this._slotCount>=8,h=null!==this._currentMaterial&&this._instanceCount>0;(s||o||a||h)&&(this.flush(),o&&(this._currentBlendMode=r,i.setBlendMode(r))),this._currentMaterial=null;let l=this._textureSlots.get(t);void 0===l&&(l=this._slotCount++,this._textureSlots.set(t,l),this._activeTextures[l]=t,i.bindTexture(t,l)),this._packInstance(e,t,l,n),this._instanceCount++}_renderCustom(t,i,n,r,s){const o=t.blendMode===e.BlendModes.Normal?n.blendMode:t.blendMode,a=this._instanceCount>=this._batchSize,h=o!==this._currentBlendMode,l=n!==this._currentMaterial,u=i!==this._currentBaseTexture;this._instanceCount>0&&(a||h||l||u)&&this.flush(),h&&(this._currentBlendMode=o,r.setBlendMode(o)),this._currentMaterial=n,this._currentBaseTexture=i,this._packInstance(t,i,0,s),this._instanceCount++}_packInstance(e,t,i,n){const r=this._instanceCount*gs,s=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??e.getLocalBounds();s[r+0]=a.left,s[r+1]=a.top,s[r+2]=a.right,s[r+3]=a.bottom;const h=e.textureFrame,l=t.width,u=t.height,c=h.left/l*65535&65535,d=h.right/l*65535&65535,_=h.top/u*65535&65535,f=h.bottom/u*65535&65535,p=t.flipY?f:_,m=t.flipY?_:f;o[r+4]=c|p<<16,o[r+5]=d|m<<16,o[r+6]=e.tint.toRgba(),o[r+7]=i;const g=n>>>0;o[r+8]=g,g>this._maxNodeIndex&&(this._maxNodeIndex=g)}_getOrCreateCustomShader(e,t){const i=this._customShaders.get(e);if(void 0!==i)return i;const n=e.shader.glsl;if(null===n)throw new Error("SpriteMaterial shader has no `glsl` source; cannot render through the WebGL2 backend.");const r=new Yr("#version 300 es\nprecision highp float;\nprecision highp int;\n\n// Per-instance attributes (divisor = 1). Each Sprite contributes one entry\n// to the per-instance buffer; gl_VertexID 0..3 selects which corner of the\n// quad this invocation is computing.\nlayout(location = 0) in vec4 a_localBounds; // left, top, right, bottom (local space)\nlayout(location = 3) in vec4 a_uvBounds; // uMin, vMin, uMax, vMax (normalised, already flipY-swapped)\nlayout(location = 4) in vec4 a_color; // RGBA tint\nlayout(location = 5) in uint a_textureSlot;\nlayout(location = 6) in uint a_nodeIndex; // row into the shared transform buffer\n\nuniform mat3 u_projection;\nuniform sampler2D u_transforms; // shared per-frame transform buffer (3 texels/row)\n\nout vec2 v_texcoord;\nout vec4 v_color;\nflat out uint v_textureSlot;\n\nvoid main(void) {\n // gl_VertexID 0..3 → corner: 0=TL, 1=TR, 2=BL, 3=BR (TRIANGLE_STRIP order)\n int vid = gl_VertexID;\n int cornerX = vid & 1;\n int cornerY = (vid >> 1) & 1;\n\n float localX = (cornerX == 0) ? a_localBounds.x : a_localBounds.z;\n float localY = (cornerY == 0) ? a_localBounds.y : a_localBounds.w;\n\n // Fetch the per-instance world transform from the shared buffer (row =\n // a_nodeIndex): texel 0 = (a, b, c, d), texel 1 = (tx, ty, 0, 0).\n int row = int(a_nodeIndex);\n vec4 m0 = texelFetch(u_transforms, ivec2(0, row), 0);\n vec4 m1 = texelFetch(u_transforms, ivec2(1, row), 0);\n\n float worldX = (m0.x * localX) + (m0.y * localY) + m1.x;\n float worldY = (m0.z * localX) + (m0.w * localY) + m1.y;\n\n gl_Position = vec4((u_projection * vec3(worldX, worldY, 1.0)).xy, 0.0, 1.0);\n\n float u = (cornerX == 0) ? a_uvBounds.x : a_uvBounds.z;\n float v = (cornerY == 0) ? a_uvBounds.y : a_uvBounds.w;\n v_texcoord = vec2(u, v);\n\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\n v_textureSlot = a_textureSlot;\n}\n",n.fragment);return r.connect(ts(t)),r.sync(),this._customShaders.set(e,r),e._onDispose(()=>{const t=this._customShaders.get(e);void 0!==t&&(t.destroy(),this._customShaders.delete(e))}),r}_bindCustomUniforms(e,t,i){let n=1;const r=t.uniforms;for(const t in r){if(!e.uniforms.has(t))continue;const s=r[t],o=e.getUniform(t);if(s instanceof pi||s instanceof _i){if(n>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(s,n),o.setValue(this._slotScratches[n]),n++}else o.setValue(this._marshalUniformValue(s))}const s=t.textures;for(const t in s)if(e.uniforms.has(t)){if(n>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(s[t],n),e.getUniform(t).setValue(this._slotScratches[n]),n++}}_marshalUniformValue(e){return e instanceof Float32Array||e instanceof Int32Array?e:"number"==typeof e?new Float32Array([e]):new Float32Array(e)}_resetSlots(){if(this._slotCount>0){for(let e=0;e<this._slotCount;e++)this._activeTextures[e]=null;this._textureSlots.clear(),this._slotCount=0}}_createConnection(e){const t=e.createVertexArray();if(null===t)throw new Error("WebGl2SpriteRenderer: could not create vertex array object.");return{gl:e,buffers:new Map,vaoHandle:t}}_createBufferRuntime(e){const t=e.gl.createBuffer();if(null===t)throw new Error("WebGl2SpriteRenderer: could not create render buffer.");return{bind:i=>{e.gl.bindBuffer(i.type,t)},upload:(i,n)=>{const r=e.gl,s=i.data,o=e.buffers.get(i);r.bindBuffer(i.type,t),o&&o.dataByteLength>=s.byteLength?(r.bufferSubData(i.type,n,s),o.dataByteLength=s.byteLength):(r.bufferData(i.type,s,i.usage),e.buffers.set(i,{handle:t,dataByteLength:s.byteLength}))},destroy:i=>{e.gl.deleteBuffer(t),e.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(e){let t=-1;return{bind:i=>{const n=e.gl;if(n.bindVertexArray(e.vaoHandle),t!==i.version){let e=null;for(const t of i.attributes)e!==t.buffer&&(t.buffer.bind(),e=t.buffer),t.integer?n.vertexAttribIPointer(t.location,t.size,t.type,t.stride,t.start):n.vertexAttribPointer(t.location,t.size,t.type,t.normalized,t.stride,t.start),n.enableVertexAttribArray(t.location),n.vertexAttribDivisor(t.location,t.divisor);t=i.version}},unbind:()=>{e.gl.bindVertexArray(null)},draw:(t,i,n,r)=>{e.gl.drawArrays(r,n,i)},drawInstanced:(t,i,n,r,s)=>{e.gl.drawArraysInstanced(s,n,i,r)},destroy:t=>{e.gl.deleteVertexArray(e.vaoHandle),t.disconnect()}}}}var ws="#version 300 es\nprecision highp float;\n\n// a_position arrives already in WORLD space: the renderer applies each node's\n// world transform on the CPU while building the vertex buffer. This deliberately\n// avoids a vertex-stage texelFetch of the per-node data texture — on ANGLE/D3D11\n// a vertex texture fetch of the RGBA32F data texture returns garbage (RGB read as\n// 0) whenever an RGBA8 atlas is also bound, which collapsed all text glyphs to a\n// point and made colour/MSDF bitmap text invisible. The fragment still reads the\n// per-node style from the data texture (a fragment texture fetch is unaffected).\nlayout(location = 0) in vec2 a_position; // world-space quad corner\nlayout(location = 1) in vec2 a_texcoord;\nlayout(location = 2) in float a_nodeIndex; // row into the per-node data texture (style lookup)\nlayout(location = 3) in vec2 a_gradUV; // normalised gradient UV (CPU-computed)\n\nuniform mat3 u_projection;\n\nflat out int v_nodeIndex;\n out vec2 v_texcoord;\n out vec2 v_gradUV;\n\nvoid main(void) {\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n v_nodeIndex = int(a_nodeIndex);\n v_gradUV = a_gradUV;\n}\n";const xs=28;class vs extends Xr{_consumesSharedTransform=!1;_sdfShader=new Yr(ws,"#version 300 es\nprecision mediump float;\n\nuniform sampler2D u_texture; // R8 SDF atlas\nuniform sampler2D u_nodeData; // RGBA32F per-node data (see WebGl2TextRenderer)\nuniform float u_pageSize; // atlas page size in px (for shadow UV conversion)\n\nflat in int v_nodeIndex;\n in vec2 v_texcoord;\n in vec2 v_gradUV;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n int ni = v_nodeIndex;\n\n // texel 2: fillColor\n // texel 3: outlineColor\n // texel 4: (outlineMin, shadowAlpha, softness, gradientEnabled)\n // outlineMin = 0.5 → disabled; outlineMin < 0.5 → enabled\n // texel 5: shadowColor\n // texel 6: (shadowOffsetX_px, shadowOffsetY_px, gradientVertical, unused)\n // texel 7: gradientTop\n // texel 8: gradientBottom\n vec4 tFill = texelFetch(u_nodeData, ivec2(2, ni), 0);\n vec4 tOutline = texelFetch(u_nodeData, ivec2(3, ni), 0);\n vec4 tParams = texelFetch(u_nodeData, ivec2(4, ni), 0);\n vec4 tShadow = texelFetch(u_nodeData, ivec2(5, ni), 0);\n vec4 tShadow2 = texelFetch(u_nodeData, ivec2(6, ni), 0);\n vec4 tGradTop = texelFetch(u_nodeData, ivec2(7, ni), 0);\n vec4 tGradBot = texelFetch(u_nodeData, ivec2(8, ni), 0);\n\n float outlineMin = tParams.x;\n float shadowAlpha = tParams.y;\n float soft = max(tParams.z, 0.001);\n float gradEnabled = tParams.w;\n vec2 shadowOffset = tShadow2.xy / u_pageSize;\n float gradVertical = tShadow2.z;\n\n float sd = texture(u_texture, v_texcoord).r;\n float fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n float outline = outlineMin < 0.5\n ? smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill)\n : 0.0;\n\n float shadowSd = texture(u_texture, v_texcoord - shadowOffset).r;\n float shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n vec4 fillColor;\n if (gradEnabled > 0.5) {\n float t = gradVertical > 0.5 ? v_gradUV.y : v_gradUV.x;\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n fragColor = fillColor * fill\n + tOutline * outline\n + tShadow * shadow;\n}\n");_msdfShader=new Yr(ws,"#version 300 es\nprecision mediump float;\n\nuniform sampler2D u_texture; // RGB MSDF atlas\nuniform sampler2D u_nodeData; // RGBA32F per-node data (see WebGl2TextRenderer)\nuniform float u_pageSize; // atlas page size in px (for shadow UV conversion)\n\nflat in int v_nodeIndex;\n in vec2 v_texcoord;\n in vec2 v_gradUV;\n\nlayout(location = 0) out vec4 fragColor;\n\nfloat median(float r, float g, float b) {\n return max(min(r, g), min(max(r, g), b));\n}\n\nvoid main(void) {\n int ni = v_nodeIndex;\n\n // Same node data layout as text-sdf.frag\n vec4 tFill = texelFetch(u_nodeData, ivec2(2, ni), 0);\n vec4 tOutline = texelFetch(u_nodeData, ivec2(3, ni), 0);\n vec4 tParams = texelFetch(u_nodeData, ivec2(4, ni), 0); // (outlineMin, shadowAlpha, softness, gradientEnabled)\n vec4 tShadow = texelFetch(u_nodeData, ivec2(5, ni), 0);\n vec4 tShadow2 = texelFetch(u_nodeData, ivec2(6, ni), 0); // (shadowOffX_px, shadowOffY_px, gradientVertical, 0)\n vec4 tGradTop = texelFetch(u_nodeData, ivec2(7, ni), 0);\n vec4 tGradBot = texelFetch(u_nodeData, ivec2(8, ni), 0);\n\n float outlineMin = tParams.x;\n float shadowAlpha = tParams.y;\n float soft = max(tParams.z, 0.001);\n float gradEnabled = tParams.w;\n vec2 shadowOffset = tShadow2.xy / u_pageSize;\n float gradVertical = tShadow2.z;\n\n vec3 msd = texture(u_texture, v_texcoord).rgb;\n float sd = median(msd.r, msd.g, msd.b);\n float fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n float outline = outlineMin < 0.5\n ? smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill)\n : 0.0;\n\n vec3 shadowMsd = texture(u_texture, v_texcoord - shadowOffset).rgb;\n float shadowSd = median(shadowMsd.r, shadowMsd.g, shadowMsd.b);\n float shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n vec4 fillColor;\n if (gradEnabled > 0.5) {\n float t = gradVertical > 0.5 ? v_gradUV.y : v_gradUV.x;\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n fragColor = fillColor * fill\n + tOutline * outline\n + tShadow * shadow;\n}\n");_colorShader=new Yr(ws,"#version 300 es\nprecision mediump float;\n\nuniform sampler2D u_texture; // RGBA colour-font / emoji atlas\nuniform sampler2D u_nodeData; // RGBA32F per-node data\n\nflat in int v_nodeIndex;\n in vec2 v_texcoord;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n // texel 2: fillColor (tint multiplier; (1,1,1,1) = no tint)\n vec4 tint = texelFetch(u_nodeData, ivec2(2, v_nodeIndex), 0);\n vec4 texel = texture(u_texture, v_texcoord);\n fragColor = texel * tint;\n}\n");_textureUnitScratch=new Int32Array([0]);_nodeDataUnitScratch=new Int32Array([1]);_floatScratch=new Float32Array(1);_vertexCapacity=256;_indexCapacity=384;_vertexData=new ArrayBuffer(7168);_float32View=new Float32Array(this._vertexData);_indexData=new Uint16Array(384);_nodeDataArray=new Float32Array(1280);_nodeCapacity=32;_nodeCount=0;_pendingQuads=[];_nodeIndexMap=new Map;_textureKeyMap=new Map;_textureKeyCounter=0;_connection=null;render(e){if(!this._connection)throw new Error("WebGl2TextRenderer is not connected to a backend.");e instanceof Wr?this._collectText(e):this._collectBitmapText(e)}flush(){const e=this._connection;e&&0!==this._pendingQuads.length?(this._uploadNodeData(e),this._drawBatches(e),this._resetFrameState()):this._resetFrameState()}destroy(){this.disconnect(),this._sdfShader.destroy(),this._msdfShader.destroy(),this._colorShader.destroy()}onConnect(t){const i=t.context,n=new Map;this._sdfShader.connect(ts(i)),this._msdfShader.connect(ts(i)),this._colorShader.connect(ts(i)),this._sdfShader.sync(),this._msdfShader.sync(),this._colorShader.sync();const r=new Hr(e.BufferTypes.ElementArrayBuffer,this._indexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),s=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,n),t.accountant),o=i.createVertexArray();if(null===o)throw new Error("WebGl2TextRenderer: could not create VAO.");const a=(new ns).addIndex(r).addAttribute(s,this._sdfShader.getAttribute("a_position"),i.FLOAT,!1,xs,0).addAttribute(s,this._sdfShader.getAttribute("a_texcoord"),i.FLOAT,!1,xs,8).addAttribute(s,this._sdfShader.getAttribute("a_nodeIndex"),i.FLOAT,!1,xs,16);this._sdfShader.attributes.has("a_gradUV")&&a.addAttribute(s,this._sdfShader.getAttribute("a_gradUV"),i.FLOAT,!1,xs,20),a.connect(this._createVaoRuntime(i,o));const h=this._createNodeDataTexture(i,32);this._connection={gl:i,buffers:n,vertexBuffer:s,indexBuffer:r,vao:a,nodeDataTexture:h,nodeDataCapacity:32}}onDisconnect(){const e=this._connection;e&&(this._sdfShader.disconnect(),this._msdfShader.disconnect(),this._colorShader.disconnect(),e.indexBuffer.destroy(),e.vertexBuffer.destroy(),e.vao.destroy(),e.gl.deleteTexture(e.nodeDataTexture),this._connection=null)}_collectText(e){e.syncDirty();const{pageQuads:t,atlas:i}=e;if(0===t.length||null===i)return;const n=this._assignNodeIndex(e),r=e.colorGlyphs?"color":"sdf",s=i.pages;for(const e of t){const t=s[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:n,shaderType:r,atlasTexture:t.texture})}}_collectBitmapText(e){const{pageQuads:t,textures:i,msdf:n}=e;if(0===t.length)return;const r=this._assignNodeIndex(e),s=n?"msdf":"color";for(const e of t){const t=i[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:r,shaderType:s,atlasTexture:t})}}_assignNodeIndex(e){const t=this._nodeIndexMap.get(e);if(void 0!==t)return t;const i=this._nodeCount++;return this._nodeIndexMap.set(e,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,e),i}_packNodeData(e,t){const i=this._nodeDataArray,n=40*e,r=t.style,s=t.getGlobalTransform().toArray(!1);i[n+0]=s[0],i[n+1]=s[1],i[n+2]=s[2],i[n+3]=s[6],i[n+4]=s[3],i[n+5]=s[4],i[n+6]=s[5],i[n+7]=s[7];const o=r.fillColor;i[n+8]=o.r/255,i[n+9]=o.g/255,i[n+10]=o.b/255,i[n+11]=o.a;const a=r.outlineColor;i[n+12]=a.r/255,i[n+13]=a.g/255,i[n+14]=a.b/255,i[n+15]=a.a;const h=r.outlineWidth>0?Math.max(0,.5-r.outlineWidth):.5;i[n+16]=h,i[n+17]=r.shadowAlpha,i[n+18]=Math.max(.03,.1*r.shadowBlur),i[n+19]=null!==r.gradientColors?1:0;const l=r.shadowColor;i[n+20]=l.r/255,i[n+21]=l.g/255,i[n+22]=l.b/255,i[n+23]=l.a,i[n+24]=r.shadowOffsetX,i[n+25]=r.shadowOffsetY,i[n+26]="vertical"===r.gradientAxis?1:0,i[n+27]=0;const u=r.gradientColors;null!==u?(i[n+28]=u[0].r/255,i[n+29]=u[0].g/255,i[n+30]=u[0].b/255,i[n+31]=u[0].a,i[n+32]=u[1].r/255,i[n+33]=u[1].g/255,i[n+34]=u[1].b/255,i[n+35]=u[1].a):(i[n+28]=i[n+29]=i[n+30]=i[n+31]=0,i[n+32]=i[n+33]=i[n+34]=i[n+35]=0);const c=t.textBounds;i[n+36]=0,i[n+37]=0,i[n+38]=c.width,i[n+39]=c.height}_uploadNodeData(e){const t=e.gl,i=this._nodeCount;if(i>e.nodeDataCapacity){let n=e.nodeDataCapacity;for(;n<i;)n*=2;t.deleteTexture(e.nodeDataTexture),e.nodeDataTexture=this._createNodeDataTexture(t,n),e.nodeDataCapacity=n}this.getBackend().setActiveTextureUnit(1),t.bindTexture(t.TEXTURE_2D,e.nodeDataTexture),t.texSubImage2D(t.TEXTURE_2D,0,0,0,10,i,t.RGBA,t.FLOAT,this._nodeDataArray.subarray(0,40*i))}_drawBatches(t){const i=this.getBackend(),n=i.view;for(const e of this._pendingQuads)this._textureKeyMap.has(e.atlasTexture)||this._textureKeyMap.set(e.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((e,t)=>{const i=e.shaderType.localeCompare(t.shaderType);return 0!==i?i:(this._textureKeyMap.get(e.atlasTexture)??0)-(this._textureKeyMap.get(t.atlasTexture)??0)});const r=this._pendingQuads;let s=0;for(;s<r.length;){const o=r[s],a=this._textureKeyMap.get(o.atlasTexture);let h=s+1;for(;h<r.length;){const e=r[h];if(e.shaderType!==o.shaderType||this._textureKeyMap.get(e.atlasTexture)!==a)break;h++}const l=this._shaderFor(o.shaderType);let u=0,c=0;for(let e=s;e<h;e++)u+=4*r[e].quads.quadCount,c+=r[e].quads.indices.length;this._ensureVertexCapacity(u),this._ensureIndexCapacity(c);let d=0,_=0,f=0;for(let e=s;e<h;e++){const{quads:t,nodeIndex:i}=r[e],n=4*t.quadCount,{vertices:s,uvs:o,indices:a}=t,h=40*i,l=this._nodeDataArray[h+0],u=this._nodeDataArray[h+1],c=this._nodeDataArray[h+3],p=this._nodeDataArray[h+4],m=this._nodeDataArray[h+5],g=this._nodeDataArray[h+7],y=this._nodeDataArray[h+36],w=this._nodeDataArray[h+37],x=this._nodeDataArray[h+38],v=this._nodeDataArray[h+39],b=x>0&&v>0;for(let e=0;e<n;e++){const t=7*(d+e),n=2*e,r=s[n],a=s[n+1];this._float32View[t+0]=l*r+p*a+c,this._float32View[t+1]=u*r+m*a+g,this._float32View[t+2]=o[n],this._float32View[t+3]=o[n+1],this._float32View[t+4]=i,this._float32View[t+5]=b?Math.min(1,Math.max(0,(r-y)/x)):0,this._float32View[t+6]=b?Math.min(1,Math.max(0,(a-w)/v)):0}for(let e=0;e<a.length;e++)this._indexData[_+e]=a[e]+f;d+=n,_+=a.length,f+=n}t.vertexBuffer.upload(this._float32View.subarray(0,7*u)),t.indexBuffer.upload(this._indexData.subarray(0,c)),l.sync(),i.bindVertexArrayObject(t.vao),i.bindTexture(o.atlasTexture,0),l.uniforms.has("u_projection")&&l.getUniform("u_projection").setValue(n.getTransform().toArray(!1)),l.uniforms.has("u_texture")&&l.getUniform("u_texture").setValue(this._textureUnitScratch),l.uniforms.has("u_nodeData")&&l.getUniform("u_nodeData").setValue(this._nodeDataUnitScratch),l.uniforms.has("u_pageSize")&&(this._floatScratch[0]=o.atlasTexture.width,l.getUniform("u_pageSize").setValue(this._floatScratch)),t.vao.draw(c,0,e.RenderingPrimitives.Triangles),i.stats.batches++,i.stats.drawCalls++,s=h}}_shaderFor(e){return"sdf"===e?this._sdfShader:"msdf"===e?this._msdfShader:this._colorShader}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}_ensureVertexCapacity(e){if(!(e<=this._vertexCapacity)){for(;this._vertexCapacity<e;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*xs),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(e){if(!(e<=this._indexCapacity)){for(;this._indexCapacity<e;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(e){if(e<=this._nodeCapacity)return;for(;this._nodeCapacity<e;)this._nodeCapacity*=2;const t=new Float32Array(40*this._nodeCapacity);t.set(this._nodeDataArray),this._nodeDataArray=t}_createNodeDataTexture(e,t){const i=e.createTexture();if(null===i)throw new Error("WebGl2TextRenderer: could not create node data texture.");return e.bindTexture(e.TEXTURE_2D,i),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA32F,10,t,0,e.RGBA,e.FLOAT,null),e.bindTexture(e.TEXTURE_2D,null),i}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("WebGl2TextRenderer: could not create buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:(n,r)=>{const s=t.get(n),o=n.data;e.bindBuffer(n.type,i),s&&s.dataByteLength>=o.byteLength?(e.bufferSubData(n.type,r,o),s.dataByteLength=o.byteLength):(e.bufferData(n.type,o,n.usage),t.set(n,{handle:i,dataByteLength:o.byteLength}))},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}class bs{backendType=e.RenderBackendType.WebGpu;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==e.RenderBackendType.WebGpu)throw new Error(`${this.constructor.name} requires a WebGPU backend, but received backendType ${String(t.backendType)}.`);this._backend=t,this.onConnect(t)}}disconnect(){null!==this._backend&&(this.flush(),this.onDisconnect(),this._backend=null)}getBackend(){if(null===this._backend)throw new Error(`${this.constructor.name} is not connected to a backend.`);return this._backend}getBackendOrNull(){return this._backend}}function Ss(t){switch(t){case e.BlendModes.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case e.BlendModes.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case e.BlendModes.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case e.BlendModes.Screen:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}};default:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}}const Bs="depth24plus-stencil8",Cs=new Set(["a_position","position"]);class Ts{_matrix=new At;_matrixData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_positions=new Float32Array(64);_device=null;_shaderModule=null;_bindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_bindGroup=null;_vertexBuffer=null;_vertexBufferCapacity=0;_incrementPipelines=new Map;_decrementPipelines=new Map;_stencilTextures=new Map;connect(e){null===this._device&&(this._device=e,this._shaderModule=e.createShaderModule({code:"\nstruct Uniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> u: Uniforms;\n\n@vertex\nfn vertexMain(@location(0) position: vec2<f32>) -> @builtin(position) vec4<f32> {\n return u.matrix * vec4<f32>(position, 0.0, 1.0);\n}\n\n@fragment\nfn fragmentMain() -> @location(0) vec4<f32> {\n // Color writes are masked off (writeMask 0); only the stencil aspect is touched.\n return vec4<f32>(0.0);\n}\n"}),this._bindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._pipelineLayout=e.createPipelineLayout({bindGroupLayouts:[this._bindGroupLayout]}),this._uniformBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._bindGroup=e.createBindGroup({layout:this._bindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}))}disconnect(){if(null!==this._device){this._uniformBuffer?.destroy(),this._vertexBuffer?.destroy();for(const e of this._stencilTextures.values())e.texture.destroy();this._stencilTextures.clear(),this._incrementPipelines.clear(),this._decrementPipelines.clear(),this._uniformBuffer=null,this._vertexBuffer=null,this._bindGroup=null,this._pipelineLayout=null,this._bindGroupLayout=null,this._shaderModule=null,this._vertexBufferCapacity=0,this._device=null}}getAttachmentView(e,t,i){const n=this._device;if(null===n)throw new Error("WebGpuStencilClipper: not connected.");const r=Math.max(1,t),s=Math.max(1,i),o=this._stencilTextures.get(e);if(o?.width===r&&o.height===s)return o.view;o?.texture.destroy();const a=n.createTexture({size:{width:r,height:s},format:Bs,usage:GPUTextureUsage.RENDER_ATTACHMENT}),h={texture:a,view:a.createView(),width:r,height:s};return this._stencilTextures.set(e,h),h.view}releaseAttachment(e){const t=this._stencilTextures.get(e);void 0!==t&&(t.texture.destroy(),this._stencilTextures.delete(e))}draw(e,t,i,n,r,s){const o=this._device;if(null===o||null===this._bindGroup)throw new Error("WebGpuStencilClipper: not connected.");const a=this._extractPositions(n);0!==a&&(this._matrix.copy(r).combine(s.getTransform()),this._packMatrix(this._matrix),o.queue.writeBuffer(this._uniformBuffer,0,this._matrixData.buffer,this._matrixData.byteOffset,this._matrixData.byteLength),this._ensureVertexCapacity(a),o.queue.writeBuffer(this._vertexBuffer,0,this._positions.buffer,this._positions.byteOffset,2*a*Float32Array.BYTES_PER_ELEMENT),e.setPipeline(this._getPipeline(t,i,n.topology)),e.setBindGroup(0,this._bindGroup),e.setVertexBuffer(0,this._vertexBuffer),e.draw(a))}_getPipeline(e,t,i){const n=t?this._incrementPipelines:this._decrementPipelines,r=n.get(e);if(void 0!==r)return r;const s={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:t?"increment-clamp":"decrement-clamp"},o=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,writeMask:0}]},primitive:{topology:"triangle-strip"===i?"triangle-strip":"triangle-list"},depthStencil:{format:Bs,depthWriteEnabled:!1,depthCompare:"always",stencilFront:s,stencilBack:s,stencilReadMask:255,stencilWriteMask:255}});return n.set(e,o),o}_packMatrix(e){const t=this._matrixData;t[0]=e.a,t[1]=e.c,t[2]=0,t[3]=0,t[4]=e.b,t[5]=e.d,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=e.x,t[13]=e.y,t[14]=0,t[15]=e.z}_extractPositions(e){const t=this._resolvePositionAttribute(e.attributes);if("f32"!==t.type)throw new Error(`Stencil clipShape position attribute "${t.name}" must be of type f32 (got "${t.type}").`);const{stride:i,vertexData:n,indices:r}=e,s=n instanceof Float32Array?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),o=null!==r?r.length:e.vertexCount;this._ensurePositionCapacity(o);const a=this._positions;for(let e=0;e<o;e++){const n=(null!==r?r[e]:e)*i+t.offset;a[2*e]=s.getFloat32(n,!0),a[2*e+1]=s.getFloat32(n+4,!0)}return o}_resolvePositionAttribute(e){const t=e.find(e=>Cs.has(e.name));if(t)return t;const i=e.find(e=>e.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensurePositionCapacity(e){const t=2*e;this._positions.length<t&&(this._positions=new Float32Array(Math.max(t,2*this._positions.length)))}_ensureVertexCapacity(e){const t=2*e*Float32Array.BYTES_PER_ELEMENT;t>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(t,2*this._vertexBufferCapacity||512),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}}const Ms={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:"keep"};function Ps(){return{format:Bs,depthWriteEnabled:!1,depthCompare:"always",stencilFront:Ms,stencilBack:Ms,stencilReadMask:255,stencilWriteMask:0}}const As=20;function Es(e,t,i){return`${e}:${t}:${i?"s":"n"}`}const ks=256;class Rs extends bs{_combinedTransform=new At;_drawCalls=[];_pipelines=new Map;_instancedPipelines=new Map;_staticGeometryCache=new Map;_textureBindGroups=new WeakMap;_customShaders=new Map;_device=null;_shaderModule=null;_instancedShaderModule=null;_uniformBindGroupLayout=null;_instancedTransformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_instancedPipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_uniformBuffer=null;_uniformBindGroup=null;_instancedUniformBuffer=null;_instancedUniformBufferCapacity=0;_instancedUniformScratch=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_instancedNodeIndexBuffer=null;_instancedNodeIndexBufferCapacity=0;_instancedNodeIndexData=new Uint32Array(0);_instancedTransformBindGroup=null;_instancedTransformStorageBuffer=null;_uniformAlignment=256;_vertexBufferCapacity=0;_indexBufferCapacity=0;_uniformBufferCapacity=0;_vertexData=new ArrayBuffer(0);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_packedIndexData=new Uint16Array(0);_drawCallCount=0;render(t){const i=this._backend;if(null===i)throw new Error("WebGpuMeshRenderer is not connected to a backend.");const n=t.material;if(null!==n&&null===n.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const r=t.vertexCount;if(0===r)return;const s=null!==n&&t.blendMode===e.BlendModes.Normal?n.blendMode:t.blendMode;i.setBlendMode(s);const o=t.texture??pi.white,a=i.activeDrawCommand,h=i.shouldPremultiplyTextureSample(o),l=t.indexCount;let u=-1;if(null!==n){const e=this._getOrCreateCustomShaderResources(n);u=e.drawCount,e.drawCount++,e.totalVertices+=r,e.totalIndices+=l}const c={mesh:t,customShader:n,command:a,blendMode:s,texture:o,premultiplySample:h,vertexByteOffset:0,vertexCount:r,indexByteOffset:0,indexCount:l,customDrawIndex:u};this._drawCalls[this._drawCallCount++]=c}drawInstancedBatch(e,t,i){const n=this._backend,r=this._device;if(null===n||null===r||i<=0||0===e.vertexCount)return;if(null!==e.material)throw new Error("RenderBatch custom materials are not supported on the WebGPU backend yet (v1 renders with the default mesh material).");const s=e.geometry;if("static"!==s?.usage)throw new Error('drawInstancedBatch requires a mesh with usage="static" geometry.');const o=e.texture??pi.white,a=n.shouldPremultiplyTextureSample(o);this._ensureInstancedUniformCapacity(1);const h=this._uploadInstancedNodeIndexRange(t,i),l=n.getTransformStorageBuffer(h+1);this._writeInstancedUniformSlot(0,n,a);const u=this._getOrCreateStaticGeometryEntry(e),c=this._instancedNodeIndexBuffer;if(null===c)throw new Error("Instanced node-index buffer must be initialized before drawing.");const d=n.renderTargetFormat,_=n._passCoordinator.stencilActive,f=n._passCoordinator.acquirePass().pass;f.setPipeline(this._getInstancedPipeline({blendMode:e.blendMode,format:d,stencil:_})),f.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(l.buffer),[0]),f.setBindGroup(1,this._getTextureBindGroup(n,o)),f.setVertexBuffer(0,u.vertexBuffer),f.setVertexBuffer(1,c),f.setIndexBuffer(u.indexBuffer,"uint16"),f.drawIndexed(u.indexCount,i),n._passCoordinator.endPass(),n.stats.batches++,n.stats.drawCalls++}flush(){const e=this._backend,t=this._device;if(!e||!t)return;if(0===this._drawCallCount&&!e.clearRequested)return;const i=e.getScissorRect(),n=null!==i&&(i.width<=0||i.height<=0);if(0===this._drawCallCount||n)return e.clearRequested&&(e._passCoordinator.acquirePass(),e._passCoordinator.endPass()),void this._resetFrame();let r=0,s=0;const o=new Map,a=new Map;for(let e=0;e<this._drawCallCount;e++){const t=this._drawCalls[e];if(null===t.customShader)t.vertexByteOffset=r*As,t.indexByteOffset=s*Uint16Array.BYTES_PER_ELEMENT,r+=t.vertexCount,s+=t.indexCount;else{const e=o.get(t.customShader)??0,i=a.get(t.customShader)??0;t.vertexByteOffset=e*As,t.indexByteOffset=i*Uint16Array.BYTES_PER_ELEMENT,o.set(t.customShader,e+t.vertexCount),a.set(t.customShader,i+t.indexCount)}}this._ensureVertexCapacity(r),this._ensureIndexCapacity(s);const h=this._drawCallCount-this._totalCustomDraws();this._ensureUniformCapacity(h),this._ensureInstancedUniformCapacity(this._drawCallCount);const l=h*this._uniformAlignment,u=l>0?new ArrayBuffer(l):null,c=null!==u?new Float32Array(u):null;let d=0;for(let t=0;t<this._drawCallCount;t++){const i=this._drawCalls[t];if(null===i.customShader){if(this._writeMeshVertices(e,i.mesh,i.vertexByteOffset/As,!0),null!==i.mesh.indices)this._packedIndexData.set(i.mesh.indices,i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT);else{const e=i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT;for(let t=0;t<i.indexCount;t++)this._packedIndexData[e+t]=t}if(null!==c){const e=d*this._uniformAlignment/Float32Array.BYTES_PER_ELEMENT,t=i.mesh.tint;c[e+0]=t.r/255,c[e+1]=t.g/255,c[e+2]=t.b/255,c[e+3]=t.a,c[e+4]=i.premultiplySample?1:0,c[e+5]=0,c[e+6]=0,c[e+7]=0}d++}}for(const[i,n]of this._customShaders){if(0===n.drawCount)continue;this._ensureCustomCapacities(n);let r=0,s=0,o=0;for(let t=0;t<this._drawCallCount;t++){const a=this._drawCalls[t];if(a.customShader===i){if(this._writeMeshVerticesIntoBuffer(a.mesh,r,n.vertexFloatView,n.vertexUintView),null!==a.mesh.indices)n.indexData.set(a.mesh.indices,s);else for(let e=0;e<a.indexCount;e++)n.indexData[s+e]=e;this._writeCustomMeshUniform(i,n,o,a.mesh,e),r+=a.vertexCount,s+=a.indexCount,o++}}t.queue.writeBuffer(n.vertexBuffer,0,n.vertexData,0,n.totalVertices*As),t.queue.writeBuffer(n.indexBuffer,0,n.indexData.buffer,n.indexData.byteOffset,n.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4),this._uploadUserUniforms(i,n)}r>0&&(t.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,r*As),t.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,s*Uint16Array.BYTES_PER_ELEMENT+3&-4)),null!==u&&t.queue.writeBuffer(this._uniformBuffer,0,u,0,l);const _=e._passCoordinator.acquirePass().pass,f=e.renderTargetFormat,p=e._passCoordinator.stencilActive;let m=null,g=null,y=null,w=null,x=0,v=0;const b=new Map;for(let t=0;t<this._drawCallCount;t++){const i=this._drawCalls[t];if(null===i.customShader){const n=this._getStaticBatchLength(t);if(n>=2){("instanced"!==m||i.blendMode!==g||f!==y)&&(_.setPipeline(this._getInstancedPipeline({blendMode:i.blendMode,format:f,stencil:p})),m="instanced",g=i.blendMode,y=f,w=null);const r=this._uploadInstancedNodeIndices(t,n),s=e.getTransformStorageBuffer(r+1);this._writeInstancedUniformSlot(v,e,i.premultiplySample),_.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(s.buffer),[v*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(e,i.texture)));const o=this._getOrCreateStaticGeometryEntry(i.mesh),a=this._instancedNodeIndexBuffer;if(null===a)throw new Error("Instanced node-index buffer must be initialized before drawing.");_.setVertexBuffer(0,o.vertexBuffer),_.setVertexBuffer(1,a),_.setIndexBuffer(o.indexBuffer,"uint16"),_.drawIndexed(o.indexCount,n),e.stats.batches++,e.stats.drawCalls++,x+=n,v++,t+=n-1;continue}("default"!==m||i.blendMode!==g||f!==y)&&(_.setPipeline(this._getPipeline({blendMode:i.blendMode,format:f,stencil:p})),m="default",g=i.blendMode,y=f,w=null),_.setBindGroup(0,this._uniformBindGroup,[x*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(e,i.texture))),_.setVertexBuffer(0,this._vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(this._indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),x++}else{const t=this._customShaders.get(i.customShader),n=m!==i.customShader||i.blendMode!==g||f!==y;_.pushDebugGroup("MeshMaterial (custom)"),n&&(_.setPipeline(this._getOrCreateCustomPipeline(t,i.blendMode,f,p)),m=i.customShader,g=i.blendMode,y=f,w=null,_.setBindGroup(2,this._buildUserBindGroup(e,i.customShader,t)));const r=b.get(i.customShader)??0;_.setBindGroup(0,t.meshUniformBindGroup,[r*ks]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getOrCreateMeshTextureBindGroup(t,e,i.texture))),_.setVertexBuffer(0,t.vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(t.indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),_.popDebugGroup(),b.set(i.customShader,r+1)}e.stats.batches++,e.stats.drawCalls++}e._passCoordinator.endPass(),this._resetFrame()}destroy(){this.disconnect(),this._combinedTransform.destroy()}async prewarmPipelines(t){const i=this._device;if(!i||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof i.createRenderPipelineAsync)return;const n=[e.BlendModes.Normal,e.BlendModes.Additive,e.BlendModes.Subtract,e.BlendModes.Multiply,e.BlendModes.Screen,e.BlendModes.Darken,e.BlendModes.Lighten],r=[];for(const e of n)for(const n of t){const t=Es(e,n,!1);this._pipelines.has(t)||(r.push(i.createRenderPipelineAsync(this._buildPipelineDescriptor(e,n)).then(e=>{this._pipelines.set(t,e)})),this._instancedPipelines.has(t)||r.push(i.createRenderPipelineAsync(this._buildInstancedPipelineDescriptor(e,n)).then(e=>{this._instancedPipelines.set(t,e)})))}await Promise.all(r)}onConnect(e){this._device||(this._device=e.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n};\n\nstruct TintUniform {\n tint: vec4<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> uniforms: TintUniform;\n\n@group(1) @binding(0) var meshTexture: texture_2d<f32>;\n@group(1) @binding(1) var meshSampler: sampler;\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n output.position = vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = input.color;\n output.premultiplySample = u32(uniforms.flags.x);\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(meshTexture, meshSampler, input.texcoord);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n let modulated = resolvedSample * input.color * uniforms.tint;\n return vec4<f32>(modulated.rgb * modulated.a, modulated.a);\n}\n"}),this._instancedShaderModule=this._device.createShaderModule({code:"\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n @location(6) nodeIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) tint: vec4<f32>,\n @location(3) @interpolate(flat) premultiplySample: u32,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\nstruct TransformUniforms {\n projection: mat3x3<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> uniforms: TransformUniforms;\n@group(0) @binding(1) var<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0) var meshTexture: texture_2d<f32>;\n@group(1) @binding(1) var meshSampler: sampler;\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let slot = transforms[input.nodeIndex];\n let world = vec3<f32>(\n slot.m0.x * input.position.x + slot.m0.z * input.position.y + slot.m1.x,\n slot.m0.y * input.position.x + slot.m0.w * input.position.y + slot.m1.y,\n 1.0\n );\n\n var output: VertexOutput;\n output.position = vec4<f32>((uniforms.projection * world).xy, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = input.color;\n output.tint = slot.m2;\n output.premultiplySample = u32(uniforms.flags.x);\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(meshTexture, meshSampler, input.texcoord);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n let modulated = resolvedSample * input.color * input.tint;\n return vec4<f32>(modulated.rgb * modulated.a, modulated.a);\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._instancedTransformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._instancedPipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._instancedTransformBindGroupLayout,this._textureBindGroupLayout]}))}onDisconnect(){this.flush(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._instancedUniformBuffer?.destroy(),this._instancedNodeIndexBuffer?.destroy(),this._pipelines.clear(),this._instancedPipelines.clear(),this._textureBindGroups=new WeakMap;for(const e of this._staticGeometryCache.values())e.vertexBuffer.destroy(),e.indexBuffer.destroy();this._staticGeometryCache.clear(),this._vertexBuffer=null,this._indexBuffer=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._instancedUniformBuffer=null,this._instancedNodeIndexBuffer=null,this._instancedTransformBindGroup=null,this._instancedTransformStorageBuffer=null,this._pipelineLayout=null,this._instancedPipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._instancedTransformBindGroupLayout=null,this._shaderModule=null,this._instancedShaderModule=null;for(const e of this._customShaders.values())this._releaseCustomShaderResources(e);this._customShaders.clear(),this._device=null,this._backend=null,this._drawCallCount=0,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._uniformBufferCapacity=0,this._instancedUniformBufferCapacity=0,this._instancedNodeIndexBufferCapacity=0,this._instancedNodeIndexData=new Uint32Array(0)}_writeMeshVertices(e,t,i,n){const r=t.vertices,s=t.uvs,o=t.colors,a=t.vertexCount;if(n){const n=this._combinedTransform.copy(t.getGlobalTransform()).combine(e.view.getTransform()),h=n.a,l=n.b,u=n.c,c=n.d,d=n.x,_=n.y;for(let e=0;e<a;e++){const t=2*e,n=5*(i+e),a=r[t],f=r[t+1];this._float32View[n+0]=h*a+l*f+d,this._float32View[n+1]=u*a+c*f+_,this._float32View[n+2]=null!==s?s[t]:0,this._float32View[n+3]=null!==s?s[t+1]:0,this._uint32View[n+4]=null!==o?o[e]:4294967295}}else for(let e=0;e<a;e++){const t=2*e,n=5*(i+e);this._float32View[n+0]=r[t],this._float32View[n+1]=r[t+1],this._float32View[n+2]=null!==s?s[t]:0,this._float32View[n+3]=null!==s?s[t+1]:0,this._uint32View[n+4]=null!==o?o[e]:4294967295}}_getPipeline(e){const t=Es(e.blendMode,e.format,e.stencil);let i=this._pipelines.get(t);return i||(i=this._device.createRenderPipeline(this._buildPipelineDescriptor(e.blendMode,e.format,e.stencil)),this._pipelines.set(t,i)),i}_buildPipelineDescriptor(e,t,i=!1){const n={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:As,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(n.depthStencil=Ps()),n}_getTextureBindGroup(e,t){const i=e.getTextureBinding(t),n=this._textureBindGroups.get(t);if(n?.view===i.view)return n.group;const r=this._device.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:i.view},{binding:1,resource:i.sampler}]});return this._textureBindGroups.set(t,{group:r,view:i.view}),r}_getStaticBatchLength(e){const t=this._drawCalls[e];if(!this._isStaticBatchCandidate(t))return 1;let i=1;for(let n=e+1;n<this._drawCallCount;n++){const e=this._drawCalls[n];if(!this._isSameStaticBatch(t,e))break;i++}return i}_isStaticBatchCandidate(e){const t=e.command;return null===e.customShader&&void 0!==t?.groupIndex&&"static"===e.mesh.geometry?.usage}_isSameStaticBatch(e,t){return!(!this._isStaticBatchCandidate(e)||!this._isStaticBatchCandidate(t))&&(e.command.groupIndex===t.command.groupIndex&&e.mesh.geometry===t.mesh.geometry&&e.texture===t.texture&&e.blendMode===t.blendMode&&e.command.material.pipelineKey===t.command.material.pipelineKey&&e.command.material.bindKey===t.command.material.bindKey)}_uploadInstancedNodeIndices(e,t){this._ensureInstancedNodeIndexCapacity(t);let i=0;for(let n=0;n<t;n++){const t=this._drawCalls[e+n].command.nodeIndex>>>0;this._instancedNodeIndexData[n]=t,t>i&&(i=t)}return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,t*Uint32Array.BYTES_PER_ELEMENT),i}_uploadInstancedNodeIndexRange(e,t){this._ensureInstancedNodeIndexCapacity(t);for(let i=0;i<t;i++)this._instancedNodeIndexData[i]=e+i>>>0;return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,t*Uint32Array.BYTES_PER_ELEMENT),e+t-1>>>0}_ensureInstancedNodeIndexCapacity(e){const t=e*Uint32Array.BYTES_PER_ELEMENT;this._instancedNodeIndexData.length<e&&(this._instancedNodeIndexData=new Uint32Array(Math.max(e,2*this._instancedNodeIndexData.length||1))),t>this._instancedNodeIndexBufferCapacity&&(this._instancedNodeIndexBuffer?.destroy(),this._instancedNodeIndexBufferCapacity=Math.max(t,2*this._instancedNodeIndexBufferCapacity||Uint32Array.BYTES_PER_ELEMENT),this._instancedNodeIndexBuffer=this._device.createBuffer({size:this._instancedNodeIndexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureInstancedUniformCapacity(e){if(0===e)return;const t=e*this._uniformAlignment;t>this._instancedUniformBufferCapacity&&(this._instancedUniformBuffer?.destroy(),this._instancedUniformBufferCapacity=Math.max(t,2*this._instancedUniformBufferCapacity||this._uniformAlignment),this._instancedUniformBuffer=this._device.createBuffer({size:this._instancedUniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._instancedTransformBindGroup=null,this._instancedTransformStorageBuffer=null)}_writeInstancedUniformSlot(e,t,i){const n=this._instancedUniformScratch,r=t.view.getTransform();n.fill(0),n[0]=r.a,n[1]=r.b,n[4]=r.c,n[5]=r.d,n[8]=r.x,n[9]=r.y,n[10]=1,n[12]=i?1:0,this._device.queue.writeBuffer(this._instancedUniformBuffer,e*this._uniformAlignment,n.buffer,n.byteOffset,64)}_getOrCreateInstancedTransformBindGroup(e){return null!==this._instancedTransformBindGroup&&this._instancedTransformStorageBuffer===e||(this._instancedTransformStorageBuffer=e,this._instancedTransformBindGroup=this._device.createBindGroup({layout:this._instancedTransformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._instancedUniformBuffer,size:64}},{binding:1,resource:{buffer:e}}]})),this._instancedTransformBindGroup}_getInstancedPipeline(e){const t=Es(e.blendMode,e.format,e.stencil);let i=this._instancedPipelines.get(t);return i||(i=this._device.createRenderPipeline(this._buildInstancedPipelineDescriptor(e.blendMode,e.format,e.stencil)),this._instancedPipelines.set(t,i)),i}_buildInstancedPipelineDescriptor(e,t,i=!1){const n={layout:this._instancedPipelineLayout,vertex:{module:this._instancedShaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:As,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]},{arrayStride:Uint32Array.BYTES_PER_ELEMENT,stepMode:"instance",attributes:[{shaderLocation:6,offset:0,format:"uint32"}]}]},fragment:{module:this._instancedShaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(n.depthStencil=Ps()),n}_getOrCreateStaticGeometryEntry(e){const t=e.geometry;if("static"!==t?.usage)throw new Error('Static mesh batching requires Geometry with usage="static".');const i=this._staticGeometryCache.get(t);if(void 0!==i)return i;const n=new ArrayBuffer(e.vertexCount*As),r=new Float32Array(n),s=new Uint32Array(n);this._writeMeshVerticesIntoBuffer(e,0,r,s);const o=new Uint16Array(e.indexCount+(1&e.indexCount));if(null!==e.indices)o.set(e.indices,0);else for(let t=0;t<e.indexCount;t++)o[t]=t;const a=e.indexCount*Uint16Array.BYTES_PER_ELEMENT+3&-4,h=this._device.createBuffer({size:n.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),l=this._device.createBuffer({size:a,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});this._device.queue.writeBuffer(h,0,n,0,n.byteLength),this._device.queue.writeBuffer(l,0,o.buffer,o.byteOffset,a);const u=()=>{const e=this._staticGeometryCache.get(t);void 0!==e&&(e.vertexBuffer.destroy(),e.indexBuffer.destroy(),this._staticGeometryCache.delete(t))};t._onDispose(u);const c={geometry:t,vertexBuffer:h,indexBuffer:l,indexCount:e.indexCount,disposeListener:u};return this._staticGeometryCache.set(t,c),c}_ensureVertexCapacity(e){const t=e*As;if(t>this._vertexData.byteLength){const e=Math.max(t,0===this._vertexData.byteLength?As:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(e),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}t>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(t,0===this._vertexBufferCapacity?As:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(e){const t=e*Uint16Array.BYTES_PER_ELEMENT+3&-4;this._packedIndexData.length*Uint16Array.BYTES_PER_ELEMENT<t&&(this._packedIndexData=new Uint16Array(Math.max(t/Uint16Array.BYTES_PER_ELEMENT,0===this._packedIndexData.length?2:2*this._packedIndexData.length))),t>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(t,0===this._indexBufferCapacity?4:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_ensureUniformCapacity(e){if(0===e)return;const t=e*this._uniformAlignment;t>this._uniformBufferCapacity&&(this._uniformBuffer?.destroy(),this._uniformBufferCapacity=Math.max(t,0===this._uniformBufferCapacity?this._uniformAlignment:2*this._uniformBufferCapacity),this._uniformBuffer=this._device.createBuffer({size:this._uniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer,size:32}}]}))}_totalCustomDraws(){let e=0;for(const t of this._customShaders.values())e+=t.drawCount;return e}_resetFrame(){this._drawCallCount=0;for(const e of this._customShaders.values())e.drawCount=0,e.totalVertices=0,e.totalIndices=0}_getOrCreateCustomShaderResources(e){let t=this._customShaders.get(e);if(void 0!==t)return t;if(null===this._device)throw new Error("WebGpuMeshRenderer is not connected to a backend.");if(null===e.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const i=this._device,n=i.createShaderModule({code:e.shader.wgsl}),r=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}}]}),s=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),o=this._buildUserBindGroupLayout(i,e),a=i.createPipelineLayout({bindGroupLayouts:[r,s,o]}),h=i.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),l=new ArrayBuffer(1280);return t={shaderModule:n,meshUniformLayout:r,meshTextureLayout:s,userLayout:o,pipelineLayout:a,pipelines:new Map,vertexBuffer:null,indexBuffer:null,vertexBufferCapacity:0,indexBufferCapacity:0,vertexData:l,vertexFloatView:new Float32Array(l),vertexUintView:new Uint32Array(l),indexData:new Uint16Array(192),meshUniformBuffer:null,meshUniformBufferCapacity:0,meshUniformBindGroup:null,userUniformBuffer:null,userUniformBufferCapacity:0,meshTextureBindGroups:new WeakMap,sampler:h,drawCount:0,totalVertices:0,totalIndices:0},this._customShaders.set(e,t),e._onDispose(()=>{const t=this._customShaders.get(e);void 0!==t&&(this._releaseCustomShaderResources(t),this._customShaders.delete(e))}),t}_ensureCustomCapacities(e){const t=this._device,i=e.totalVertices*As;if(i>e.vertexData.byteLength){const t=Math.max(i,2*e.vertexData.byteLength);e.vertexData=new ArrayBuffer(t),e.vertexFloatView=new Float32Array(e.vertexData),e.vertexUintView=new Uint32Array(e.vertexData)}i>e.vertexBufferCapacity&&(e.vertexBuffer?.destroy(),e.vertexBufferCapacity=Math.max(i,2*e.vertexBufferCapacity||As),e.vertexBuffer=t.createBuffer({size:e.vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}));const n=e.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4;e.indexData.length*Uint16Array.BYTES_PER_ELEMENT<n&&(e.indexData=new Uint16Array(Math.max(n/Uint16Array.BYTES_PER_ELEMENT,2*e.indexData.length))),n>e.indexBufferCapacity&&(e.indexBuffer?.destroy(),e.indexBufferCapacity=Math.max(n,2*e.indexBufferCapacity||4),e.indexBuffer=t.createBuffer({size:e.indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}));const r=e.drawCount*ks;r>e.meshUniformBufferCapacity&&(e.meshUniformBuffer?.destroy(),e.meshUniformBufferCapacity=Math.max(r,2*e.meshUniformBufferCapacity||ks),e.meshUniformBuffer=t.createBuffer({size:e.meshUniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.meshUniformBindGroup=t.createBindGroup({layout:e.meshUniformLayout,entries:[{binding:0,resource:{buffer:e.meshUniformBuffer,size:112}}]}))}_writeMeshVerticesIntoBuffer(e,t,i,n){const r=e.vertices,s=e.uvs,o=e.colors,a=e.vertexCount;for(let e=0;e<a;e++){const a=2*e,h=5*(t+e);i[h+0]=r[a],i[h+1]=r[a+1],i[h+2]=null!==s?s[a]:0,i[h+3]=null!==s?s[a+1]:0,n[h+4]=null!==o?o[e]:4294967295}}_writeCustomMeshUniform(e,t,i,n,r){const s=256/Float32Array.BYTES_PER_ELEMENT,o=new Float32Array(s),a=r.view.getTransform(),h=n.getGlobalTransform();let l=0;o[l+0]=a.a,o[l+1]=a.b,o[l+2]=0,o[l+3]=0,o[l+4]=a.c,o[l+5]=a.d,o[l+6]=0,o[l+7]=0,o[l+8]=a.x,o[l+9]=a.y,o[l+10]=1,o[l+11]=0,l+=12,o[l+0]=h.a,o[l+1]=h.b,o[l+2]=0,o[l+3]=0,o[l+4]=h.c,o[l+5]=h.d,o[l+6]=0,o[l+7]=0,o[l+8]=h.x,o[l+9]=h.y,o[l+10]=1,o[l+11]=0,l+=12;const u=n.tint;o[l+0]=u.r/255,o[l+1]=u.g/255,o[l+2]=u.b/255,o[l+3]=u.a,this._device.queue.writeBuffer(t.meshUniformBuffer,256*i,o)}_getOrCreateCustomPipeline(e,t,i,n){const r=`${t}:${i}:${n?"s":"n"}`;let s=e.pipelines.get(r);if(void 0===s){const o={layout:e.pipelineLayout,vertex:{module:e.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:As,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]}]},fragment:{module:e.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:Ss(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};n&&(o.depthStencil=Ps()),s=this._device.createRenderPipeline(o),e.pipelines.set(r,s)}return s}_getOrCreateMeshTextureBindGroup(e,t,i){const n=t.getTextureBinding(i),r=e.meshTextureBindGroups.get(i);if(r?.view===n.view)return r.group;const s=this._device.createBindGroup({layout:e.meshTextureLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]});return e.meshTextureBindGroups.set(i,{group:s,view:n.view}),s}_buildUserBindGroupLayout(e,t){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const n=Fs(t);if(n.length>7)throw new Error("Mesh material requested more than 7 user texture bindings.");let r=1;for(let e=0;e<n.length;e++)i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),r++,i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),r++;return e.createBindGroupLayout({entries:i})}_uploadUserUniforms(e,t){const i=this._device,n=function(e){const t=[];for(const i of Object.values(e.uniforms))Ds(i)||t.push(i);return t}(e),r=16*Math.max(n.length,1);(null===t.userUniformBuffer||t.userUniformBufferCapacity<r)&&(t.userUniformBuffer?.destroy(),t.userUniformBufferCapacity=r,t.userUniformBuffer=i.createBuffer({size:r,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const s=new Float32Array(r/4);let o=0;for(const e of n){const t=4*o;if("number"==typeof e)s[t]=e;else if(e instanceof Float32Array)s.set(e,t);else if(e instanceof Int32Array)for(let i=0;i<e.length;i++)s[t+i]=e[i];else{const i=e;for(let e=0;e<i.length;e++)s[t+e]=i[e]}o++}i.queue.writeBuffer(t.userUniformBuffer,0,s)}_buildUserBindGroup(e,t,i){const n=this._device,r=[];r.push({binding:0,resource:{buffer:i.userUniformBuffer}});let s=1;for(const i of Fs(t)){const t=e.getTextureBinding(i);r.push({binding:s,resource:t.view}),s++,r.push({binding:s,resource:t.sampler}),s++}return n.createBindGroup({layout:i.userLayout,entries:r})}_releaseCustomShaderResources(e){e.vertexBuffer?.destroy(),e.indexBuffer?.destroy(),e.meshUniformBuffer?.destroy(),e.userUniformBuffer?.destroy(),e.pipelines.clear(),e.meshTextureBindGroups=new WeakMap,e.vertexBuffer=null,e.indexBuffer=null,e.meshUniformBuffer=null,e.userUniformBuffer=null,e.meshUniformBindGroup=null,e.vertexBufferCapacity=0,e.indexBufferCapacity=0,e.meshUniformBufferCapacity=0,e.userUniformBufferCapacity=0}}function Ds(e){return!("object"!=typeof e||null===e||!("width"in e)||!("height"in e)||e instanceof Float32Array||e instanceof Int32Array||Array.isArray(e))}function Fs(e){const t=[];for(const i of Object.values(e.uniforms))Ds(i)&&t.push(i);for(const i of Object.values(e.textures))t.push(i);return t}const Is=32/Uint32Array.BYTES_PER_ELEMENT,Ls=new Uint16Array([0,1,2,0,2,3]);class Us extends bs{_projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_transformBindGroup=null;_transformStorageBuffer=null;_indexBuffer=null;_instanceBuffer=null;_instanceCapacity=0;_instanceData=new ArrayBuffer(0);_instanceFloat32=new Float32Array(this._instanceData);_instanceUint32=new Uint32Array(this._instanceData);_pipelines=new Map;_quadIndex=0;_maxNodeIndex=0;_currentBlendMode=null;_currentTexture=null;onConnect(e){this._device||(this._device=e.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1)\nvar<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0)\nvar nineSliceTexture: texture_2d<f32>;\n@group(1) @binding(1)\nvar nineSliceSampler: sampler;\n\nstruct VertexInput {\n @location(0) quadBounds: vec4<f32>, // x0, y0, x1, y1\n @location(1) uvBounds: vec4<f32>, // u0, v0, u1, v1 (normalised, flipY pre-applied)\n @location(2) color: vec4<f32>, // RGBA tint\n @location(3) nodeIndex: u32, // transform buffer row\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput, @builtin(vertex_index) vid: u32) -> VertexOutput {\n var output: VertexOutput;\n\n // vid 0..3 → TL, TR, BR, BL (matches static index buffer [0,1,2,0,2,3])\n let cornerX = ((vid + 1u) >> 1u) & 1u;\n let cornerY = vid >> 1u;\n\n let localX = select(input.quadBounds.x, input.quadBounds.z, cornerX == 1u);\n let localY = select(input.quadBounds.y, input.quadBounds.w, cornerY == 1u);\n\n let slot = transforms[input.nodeIndex];\n let worldX = slot.m0.x * localX + slot.m0.y * localY + slot.m1.x;\n let worldY = slot.m0.z * localX + slot.m0.w * localY + slot.m1.y;\n\n output.position = projection.matrix * vec4<f32>(worldX, worldY, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cornerX == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cornerY == 1u);\n output.texcoord = vec2<f32>(u, v);\n\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(nineSliceTexture, nineSliceSampler, input.texcoord);\n return sample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=this._device.createBuffer({size:Ls.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Ls.buffer,Ls.byteOffset,Ls.byteLength))}onDisconnect(){this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._instanceBuffer=null,this._indexBuffer=null,this._transformBindGroup=null,this._transformStorageBuffer=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._backend=null,this._instanceCapacity=0,this._instanceData=new ArrayBuffer(0),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData),this._quadIndex=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentTexture=null}render(e){const t=this._backend;if(null===t)return;let i=e.quads;if("geometry"===e.pixelSnapMode){const n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}if(0===i.length)return;const n=e.texture;if(0===n.width||0===n.height)return;if(n instanceof pi&&null===n.source)return;const r=e.blendMode,s=t.activeDrawCommand,o=null!==s?s.nodeIndex:t._pushTransform(e),a=null!==this._currentBlendMode&&r!==this._currentBlendMode,h=null!==this._currentTexture&&n!==this._currentTexture,l=this._quadIndex+i.length>this._instanceCapacity&&this._instanceCapacity>0;(a||h||l)&&this._quadIndex>0&&this.flush(),this._currentBlendMode=r,this._currentTexture=n,t.setBlendMode(r),this._ensureInstanceCapacity(this._quadIndex+i.length);const u=this._instanceFloat32,c=this._instanceUint32,d=n instanceof pi&&n.flipY;for(const t of i){const i=this._quadIndex*Is;u[i+0]=t.x0,u[i+1]=t.y0,u[i+2]=t.x1,u[i+3]=t.y1;const n=65535*t.u0&65535,r=65535*t.u1&65535,s=65535*t.v0&65535,a=65535*t.v1&65535,h=d?a:s,l=d?s:a;c[i+4]=n|h<<16,c[i+5]=r|l<<16,c[i+6]=e.tint.toRgba(),c[i+7]=o>>>0,this._quadIndex++,o>this._maxNodeIndex&&(this._maxNodeIndex=o)}}flush(){const e=this._backend,t=this._device,i=this._uniformBuffer;if(!e||!t||!i)return;if(0===this._quadIndex&&!e.clearRequested)return;const n=e.view.getTransform();this._projectionData.set([n.a,n.c,0,0,n.b,n.d,0,0,0,0,1,0,n.x,n.y,0,n.z]),t.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const r=e.getScissorRect(),s=null!==r&&(r.width<=0||r.height<=0),o=e._passCoordinator.acquirePass().pass;if(this._quadIndex>0&&!s&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode&&null!==this._currentTexture){t.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,32*this._quadIndex);const n=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,i,n.buffer),s=this._createTextureBindGroup(t,e,this._currentTexture),a=e._passCoordinator.stencilActive,h=this._getPipeline(this._currentBlendMode,e.renderTargetFormat,a);o.setPipeline(h),o.setBindGroup(0,r),o.setBindGroup(1,s),o.setVertexBuffer(0,this._instanceBuffer),o.setIndexBuffer(this._indexBuffer,"uint16"),o.drawIndexed(6,this._quadIndex,0,0,0),e.stats.batches++,e.stats.drawCalls++}e._passCoordinator.endPass(),this._quadIndex=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentTexture=null}destroy(){this.disconnect()}_getOrCreateTransformBindGroup(e,t,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=e.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_createTextureBindGroup(e,t,i){const n=t.getTextureBinding(i);return e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]})}_getPipeline(e,t,i){const n=`${e}:${t}:${i?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;if(!this._device||!this._shaderModule||!this._pipelineLayout)throw new Error("WebGpuNineSliceSpriteRenderer: renderer must be connected first.");const s={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:32,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm16x4"},{shaderLocation:2,offset:24,format:"unorm8x4"},{shaderLocation:3,offset:28,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};i&&(s.depthStencil=Ps());const o=this._device.createRenderPipeline(s);return this._pipelines.set(n,o),o}_ensureInstanceCapacity(e){if(!this._device||e<=this._instanceCapacity)return;let t=Math.max(this._instanceCapacity,32);for(;t<e;)t*=2;const i=this._instanceData,n=Math.min(32*this._quadIndex,i.byteLength),r=new ArrayBuffer(32*t);n>0&&new Uint8Array(r).set(new Uint8Array(i,0,n));const s=this._device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=t,this._instanceData=r,this._instanceFloat32=new Float32Array(r),this._instanceUint32=new Uint32Array(r),this._instanceBuffer=s}}const Gs=new Uint16Array([0,1,2,0,2,3]);function Ns(e){return"repeat"===e?"repeat":"mirror-repeat"===e?"mirror-repeat":"clamp-to-edge"}class Os extends bs{_projData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_device=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_shaderModule=null;_uniformBuffer=null;_indexBuffer=null;_transformBindGroup=null;_transformStorageBuf=null;_pipelines=new Map;_samplers=new Map;_shaderInstBuf=null;_shaderInstCapacity=0;_shaderInstData=new ArrayBuffer(0);_shaderInstF32=new Float32Array(this._shaderInstData);_shaderInstU32=new Uint32Array(this._shaderInstData);_shaderQuadCount=0;_geoInstBuf=null;_geoInstCapacity=0;_geoInstData=new ArrayBuffer(0);_geoInstF32=new Float32Array(this._geoInstData);_geoInstU32=new Uint32Array(this._geoInstData);_geoQuadCount=0;_maxNodeIndex=0;_currentTexture=null;_currentBlendMode=null;_currentModeX=null;_currentModeY=null;_currentPath=null;_snapBounds=new et;onConnect(e){if(this._device)return;const t=e.device;this._device=t,this._shaderModule=t.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1) var<storage, read> transforms: array<TransformSlot>;\n@group(1) @binding(0) var spriteTexture: texture_2d<f32>;\n@group(1) @binding(1) var spriteSampler: sampler;\n\nstruct VOut {\n @builtin(position) pos: vec4<f32>,\n @location(0) uv: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\nstruct ShaderVIn {\n @location(0) quadBounds: vec4<f32>, // x0,y0,x1,y1\n @location(1) uvParams: vec4<f32>, // tilingX, tilingY, offsetU, offsetV\n @location(2) color: vec4<f32>, // RGBA tint\n @location(3) nodeIndex: u32,\n};\n\n@vertex\nfn shaderVert(input: ShaderVIn, @builtin(vertex_index) vid: u32) -> VOut {\n var out: VOut;\n let cx = ((vid + 1u) >> 1u) & 1u;\n let cy = vid >> 1u;\n let lx = select(input.quadBounds.x, input.quadBounds.z, cx == 1u);\n let ly = select(input.quadBounds.y, input.quadBounds.w, cy == 1u);\n\n let destW = input.quadBounds.z - input.quadBounds.x;\n let destH = input.quadBounds.w - input.quadBounds.y;\n\n let slot = transforms[input.nodeIndex];\n let wx = slot.m0.x * lx + slot.m0.y * ly + slot.m1.x;\n let wy = slot.m0.z * lx + slot.m0.w * ly + slot.m1.y;\n out.pos = projection.matrix * vec4<f32>(wx, wy, 0.0, 1.0);\n\n let u = select(input.uvParams.z, ((lx - input.quadBounds.x) / destW) * input.uvParams.x + input.uvParams.z, destW > 0.0);\n let v = select(input.uvParams.w, ((ly - input.quadBounds.y) / destH) * input.uvParams.y + input.uvParams.w, destH > 0.0);\n out.uv = vec2<f32>(u, v);\n out.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n return out;\n}\n\n@fragment\nfn shaderFrag(input: VOut) -> @location(0) vec4<f32> {\n return textureSample(spriteTexture, spriteSampler, input.uv) * input.color;\n}\n\nstruct GeoVIn {\n @location(0) quadBounds: vec4<f32>, // x0,y0,x1,y1\n @location(1) uvBounds: vec4<f32>, // u0,v0,u1,v1 (normalised, flipY pre-applied)\n @location(2) color: vec4<f32>, // RGBA tint\n @location(3) nodeIndex: u32,\n};\n\n@vertex\nfn geoVert(input: GeoVIn, @builtin(vertex_index) vid: u32) -> VOut {\n var out: VOut;\n let cx = ((vid + 1u) >> 1u) & 1u;\n let cy = vid >> 1u;\n let lx = select(input.quadBounds.x, input.quadBounds.z, cx == 1u);\n let ly = select(input.quadBounds.y, input.quadBounds.w, cy == 1u);\n\n let slot = transforms[input.nodeIndex];\n let wx = slot.m0.x * lx + slot.m0.y * ly + slot.m1.x;\n let wy = slot.m0.z * lx + slot.m0.w * ly + slot.m1.y;\n out.pos = projection.matrix * vec4<f32>(wx, wy, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cx == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cy == 1u);\n out.uv = vec2<f32>(u, v);\n out.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n return out;\n}\n\n@fragment\nfn geoFrag(input: VOut) -> @location(0) vec4<f32> {\n return textureSample(spriteTexture, spriteSampler, input.uv) * input.color;\n}\n"}),this._uniformBindGroupLayout=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._uniformBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=t.createBuffer({size:Gs.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this._indexBuffer,0,Gs.buffer,Gs.byteOffset,Gs.byteLength)}onDisconnect(){this._shaderInstBuf?.destroy(),this._geoInstBuf?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._samplers.clear(),this._shaderInstBuf=null,this._geoInstBuf=null,this._indexBuffer=null,this._uniformBuffer=null,this._transformBindGroup=null,this._transformStorageBuf=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._backend=null,this._shaderInstCapacity=0,this._shaderInstData=new ArrayBuffer(0),this._shaderInstF32=new Float32Array(this._shaderInstData),this._shaderInstU32=new Uint32Array(this._shaderInstData),this._geoInstCapacity=0,this._geoInstData=new ArrayBuffer(0),this._geoInstF32=new Float32Array(this._geoInstData),this._geoInstU32=new Uint32Array(this._geoInstData),this._shaderQuadCount=0,this._geoQuadCount=0,this._maxNodeIndex=0,this._currentTexture=null,this._currentBlendMode=null,this._currentModeX=null,this._currentModeY=null,this._currentPath=null}render(e){const t=this._backend;if(!t)return;const i=e.texture;if(i instanceof pi&&null===i.source)return;if(0===i.width||0===i.height)return;const n=e.resolvedStrategy,r=e.blendMode,s=e.modeX,o=e.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const e=this._currentPath!==n,t=this._currentTexture!==i,a=this._currentBlendMode!==r,h="shader"===n&&(this._currentModeX!==s||this._currentModeY!==o);(e||t||a||h)&&this.flush()}this._currentTexture=i,this._currentBlendMode=r,this._currentPath=n,t.setBlendMode(r);const a=t.activeDrawCommand,h=null!==a?a.nodeIndex:t._pushTransform(e);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===n?(this._currentModeX=s,this._currentModeY=o,this._writeShaderInstance(e,h)):this._writeGeoQuads(e,h)}_writeShaderInstance(e,t){const i=e.texture,n=e.region.width,r=e.region.height;let s=e.width,o=e.height;const a=i instanceof pi&&i.flipY;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),i=t._getSnapPixelSize(),n=e.getRenderBounds(t.view,i.width,i.height,this._snapBounds);s=n.width,o=n.height}const h=gr(n,s,e.modeX,e.fitX),l=gr(r,o,e.modeY,e.fitY),u=e.offsetX/(n>0?n:1),c=e.offsetY/(r>0?r:1),d=a?-l:l,_=a?l+c:c;this._ensureShaderCapacity(this._shaderQuadCount+1);const f=10*this._shaderQuadCount,p=this._shaderInstF32,m=this._shaderInstU32;p[f+0]=0,p[f+1]=0,p[f+2]=s,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,m[f+8]=e.tint.toRgba(),m[f+9]=t>>>0,this._shaderQuadCount++}_writeGeoQuads(e,t){let i=e.quads;if("geometry"===e.pixelSnapMode){const t=this.getBackend(),n=t._getSnapPixelSize();i=e.getRenderQuads(t.view,n.width,n.height)}if(0===i.length)return;const n=e.texture instanceof pi&&e.texture.flipY,r=e.tint.toRgba();this._ensureGeoCapacity(this._geoQuadCount+i.length);const s=this._geoInstF32,o=this._geoInstU32;for(let e=0;e<i.length;e++){const a=i[e],h=8*(this._geoQuadCount+e);s[h+0]=a.x0,s[h+1]=a.y0,s[h+2]=a.x1,s[h+3]=a.y1;const l=65535*a.u0&65535,u=65535*a.u1&65535,c=65535*a.v0&65535,d=65535*a.v1&65535,_=n?d:c,f=n?c:d;o[h+4]=l|_<<16,o[h+5]=u|f<<16,o[h+6]=r,o[h+7]=t>>>0}this._geoQuadCount+=i.length}flush(){const e=this._backend,t=this._device,i=this._uniformBuffer;if(!e||!t||!i)return;if(0===this._shaderQuadCount&&0===this._geoQuadCount&&!e.clearRequested)return;const n=e.view.getTransform();this._projData.set([n.a,n.c,0,0,n.b,n.d,0,0,0,0,1,0,n.x,n.y,0,n.z]),t.queue.writeBuffer(i,0,this._projData.buffer,this._projData.byteOffset,this._projData.byteLength);const r=e.getScissorRect(),s=null!==r&&(r.width<=0||r.height<=0),o=e._passCoordinator.acquirePass().pass,a=e._passCoordinator.stencilActive;this._shaderQuadCount>0&&!s&&this._drawShaderBatch(t,e,o,a),this._geoQuadCount>0&&!s&&this._drawGeoBatch(t,e,o,a),e._passCoordinator.endPass(),this._shaderQuadCount=0,this._geoQuadCount=0,this._maxNodeIndex=0,this._currentTexture=null,this._currentBlendMode=null,this._currentModeX=null,this._currentModeY=null,this._currentPath=null}_drawShaderBatch(e,t,i,n){if(!this._shaderInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;e.queue.writeBuffer(this._shaderInstBuf,0,this._shaderInstData,0,40*this._shaderQuadCount);const r=t.getTransformStorageBuffer(this._maxNodeIndex+1),s=this._getOrCreateTransformBindGroup(e,this._uniformBuffer,r.buffer),o=this._currentModeX??"repeat",a=this._currentModeY??"repeat",h=this._getOrCreateSampler(e,o,a),l=t.getTextureBinding(this._currentTexture).view,u=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:l},{binding:1,resource:h}]}),c=this._getPipeline("shader",this._currentBlendMode,t.renderTargetFormat,n);i.setPipeline(c),i.setBindGroup(0,s),i.setBindGroup(1,u),i.setVertexBuffer(0,this._shaderInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._shaderQuadCount,0,0,0),t.stats.batches++,t.stats.drawCalls++}_drawGeoBatch(e,t,i,n){if(!this._geoInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;e.queue.writeBuffer(this._geoInstBuf,0,this._geoInstData,0,32*this._geoQuadCount);const r=t.getTransformStorageBuffer(this._maxNodeIndex+1),s=this._getOrCreateTransformBindGroup(e,this._uniformBuffer,r.buffer),o=t.getTextureBinding(this._currentTexture),a=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:o.view},{binding:1,resource:o.sampler}]}),h=this._getPipeline("geo",this._currentBlendMode,t.renderTargetFormat,n);i.setPipeline(h),i.setBindGroup(0,s),i.setBindGroup(1,a),i.setVertexBuffer(0,this._geoInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._geoQuadCount,0,0,0),t.stats.batches++,t.stats.drawCalls++}destroy(){this.disconnect()}_getOrCreateSampler(e,t,i){const n=`${t}:${i}`,r=this._samplers.get(n);if(r)return r;const s=e.createSampler({addressModeU:Ns(t),addressModeV:Ns(i),magFilter:"linear",minFilter:"linear"});return this._samplers.set(n,s),s}_getOrCreateTransformBindGroup(e,t,i){return null!==this._transformBindGroup&&this._transformStorageBuf===i||(this._transformStorageBuf=i,this._transformBindGroup=e.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_getPipeline(e,t,i,n){const r=`${e}:${t}:${i}:${n?"s":"n"}`,s=this._pipelines.get(r);if(s)return s;if(!(this._device&&this._shaderModule&&this._uniformBindGroupLayout&&this._textureBindGroupLayout))throw new Error("WebGpuRepeatingSpriteRenderer: not connected.");const o="shader"===e,a=o?40:32,h=o?[{arrayStride:a,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"float32x4"},{shaderLocation:2,offset:32,format:"unorm8x4"},{shaderLocation:3,offset:36,format:"uint32"}]}]:[{arrayStride:a,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm16x4"},{shaderLocation:2,offset:24,format:"unorm8x4"},{shaderLocation:3,offset:28,format:"uint32"}]}],l={layout:this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),vertex:{module:this._shaderModule,entryPoint:o?"shaderVert":"geoVert",buffers:h},fragment:{module:this._shaderModule,entryPoint:o?"shaderFrag":"geoFrag",targets:[{format:i,blend:Ss(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};n&&(l.depthStencil=Ps());const u=this._device.createRenderPipeline(l);return this._pipelines.set(r,u),u}_ensureShaderCapacity(e){if(!this._device||e<=this._shaderInstCapacity)return;this._shaderInstCapacity=this._growCapacity(this._shaderInstCapacity,e);const t=this._shaderInstData,i=40*this._shaderQuadCount;this._shaderInstData=new ArrayBuffer(40*this._shaderInstCapacity),i>0&&new Uint8Array(this._shaderInstData).set(new Uint8Array(t,0,i)),this._shaderInstF32=new Float32Array(this._shaderInstData),this._shaderInstU32=new Uint32Array(this._shaderInstData),this._shaderInstBuf?.destroy(),this._shaderInstBuf=this._device.createBuffer({size:this._shaderInstData.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})}_ensureGeoCapacity(e){if(!this._device||e<=this._geoInstCapacity)return;this._geoInstCapacity=this._growCapacity(this._geoInstCapacity,e);const t=this._geoInstData,i=32*this._geoQuadCount;this._geoInstData=new ArrayBuffer(32*this._geoInstCapacity),i>0&&new Uint8Array(this._geoInstData).set(new Uint8Array(t,0,i)),this._geoInstF32=new Float32Array(this._geoInstData),this._geoInstU32=new Uint32Array(this._geoInstData),this._geoInstBuf?.destroy(),this._geoInstBuf=this._device.createBuffer({size:this._geoInstData.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST})}_growCapacity(e,t){let i=Math.max(e,32);for(;i<t;)i*=2;return i}}const Vs=36,zs=Vs/Uint32Array.BYTES_PER_ELEMENT,qs=new Uint16Array([0,1,2,0,2,3]);class Ws extends bs{_projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_transformBindGroup=null;_transformStorageBuffer=null;_indexBuffer=null;_instanceBuffer=null;_instanceCapacity=0;_instanceData=new ArrayBuffer(0);_instanceFloat32=new Float32Array(this._instanceData);_instanceUint32=new Uint32Array(this._instanceData);_pipelines=new Map;_activeTextures=new Array(8).fill(null);_textureSlots=new Map;_slotCount=0;_instanceCount=0;_maxNodeIndex=0;_currentBlendMode=null;_customMaterials=new Map;_customBaseTextureLayout=null;_currentMaterial=null;_currentBaseTexture=null;_snapBounds=new et;_activeBounds=null;onConnect(e){this._device||(this._device=e.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1)\nvar<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0)\nvar spriteTexture0: texture_2d<f32>;\n@group(1) @binding(1)\nvar spriteTexture1: texture_2d<f32>;\n@group(1) @binding(2)\nvar spriteTexture2: texture_2d<f32>;\n@group(1) @binding(3)\nvar spriteTexture3: texture_2d<f32>;\n@group(1) @binding(4)\nvar spriteTexture4: texture_2d<f32>;\n@group(1) @binding(5)\nvar spriteTexture5: texture_2d<f32>;\n@group(1) @binding(6)\nvar spriteTexture6: texture_2d<f32>;\n@group(1) @binding(7)\nvar spriteTexture7: texture_2d<f32>;\n\n@group(1) @binding(8)\nvar spriteSampler0: sampler;\n@group(1) @binding(9)\nvar spriteSampler1: sampler;\n@group(1) @binding(10)\nvar spriteSampler2: sampler;\n@group(1) @binding(11)\nvar spriteSampler3: sampler;\n@group(1) @binding(12)\nvar spriteSampler4: sampler;\n@group(1) @binding(13)\nvar spriteSampler5: sampler;\n@group(1) @binding(14)\nvar spriteSampler6: sampler;\n@group(1) @binding(15)\nvar spriteSampler7: sampler;\n\n// Per-instance vertex layout (36 bytes per sprite). The four corners\n// of the quad are derived from @builtin(vertex_index) 0..3 inside the\n// vertex shader — there is no per-vertex stream. The world transform is\n// fetched from the shared transform storage buffer keyed by nodeIndex\n// instead of being packed inline.\nstruct VertexInput {\n @location(0) localBounds: vec4<f32>, // left, top, right, bottom (local space)\n @location(3) uvBounds: vec4<f32>, // uMin, vMin, uMax, vMax (CPU pre-swaps for flipY)\n @location(4) color: vec4<f32>, // RGBA tint\n @location(5) packedSlotFlags: u32, // bits 0..7 = slot, bit 8 = premultiply\n @location(6) nodeIndex: u32, // row into the shared transform storage buffer\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n @location(3) @interpolate(flat) textureSlot: u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput, @builtin(vertex_index) vid: u32) -> VertexOutput {\n var output: VertexOutput;\n\n // vid 0..3 → corners in TL, TR, BR, BL order (matches the static index\n // buffer [0,1,2,0,2,3] used for indexed triangle-list drawing).\n let cornerX = ((vid + 1u) >> 1u) & 1u;\n let cornerY = vid >> 1u;\n\n let localX = select(input.localBounds.x, input.localBounds.z, cornerX == 1u);\n let localY = select(input.localBounds.y, input.localBounds.w, cornerY == 1u);\n\n // Fetch this instance's world transform from the shared storage buffer,\n // keyed by nodeIndex: m0 = (a, b, c, d), m1 = (tx, ty, 0, 0). (m2 carries the\n // node tint, unused here — the sprite keeps its own per-instance color.)\n let slot = transforms[input.nodeIndex];\n let worldX = slot.m0.x * localX + slot.m0.y * localY + slot.m1.x;\n let worldY = slot.m0.z * localX + slot.m0.w * localY + slot.m1.y;\n\n output.position = projection.matrix * vec4<f32>(worldX, worldY, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cornerX == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cornerY == 1u);\n output.texcoord = vec2<f32>(u, v);\n\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n output.textureSlot = input.packedSlotFlags & 0xFFu;\n output.premultiplySample = (input.packedSlotFlags >> 8u) & 1u;\n\n return output;\n}\n\nfn sampleTexture(slot: u32, uv: vec2<f32>, ddx: vec2<f32>, ddy: vec2<f32>) -> vec4<f32> {\n switch slot {\n case 0u: {\n return textureSampleGrad(spriteTexture0, spriteSampler0, uv, ddx, ddy);\n }\n case 1u: {\n return textureSampleGrad(spriteTexture1, spriteSampler1, uv, ddx, ddy);\n }\n case 2u: {\n return textureSampleGrad(spriteTexture2, spriteSampler2, uv, ddx, ddy);\n }\n case 3u: {\n return textureSampleGrad(spriteTexture3, spriteSampler3, uv, ddx, ddy);\n }\n case 4u: {\n return textureSampleGrad(spriteTexture4, spriteSampler4, uv, ddx, ddy);\n }\n case 5u: {\n return textureSampleGrad(spriteTexture5, spriteSampler5, uv, ddx, ddy);\n }\n case 6u: {\n return textureSampleGrad(spriteTexture6, spriteSampler6, uv, ddx, ddy);\n }\n default: {\n return textureSampleGrad(spriteTexture7, spriteSampler7, uv, ddx, ddy);\n }\n }\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n // Compute screen-space derivatives in uniform control flow before the\n // per-slot switch. WGSL requires textureSample (implicit LOD) to run in\n // uniform control flow, which multi-texture batching breaks because the\n // slot varies per fragment. textureSampleGrad takes explicit derivatives\n // and is valid regardless of control-flow uniformity, while preserving\n // mipmap-correct LOD when sprites use mipmapped textures.\n let ddx = dpdx(input.texcoord);\n let ddy = dpdy(input.texcoord);\n let sample = sampleTexture(input.textureSlot, input.texcoord, ddx, ddy);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n\n return resolvedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[...Array.from({length:8},(e,t)=>({binding:t,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(e,t)=>({binding:8+t,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}))]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._customBaseTextureLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=this._device.createBuffer({size:qs.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,qs.buffer,qs.byteOffset,qs.byteLength))}onDisconnect(){this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy();for(const e of this._customMaterials.values())this._releaseCustomResources(e);this._customMaterials.clear(),this._pipelines.clear(),this._instanceBuffer=null,this._indexBuffer=null,this._transformBindGroup=null,this._transformStorageBuffer=null,this._uniformBuffer=null,this._pipelineLayout=null,this._customBaseTextureLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._backend=null,this._instanceCapacity=0,this._instanceData=new ArrayBuffer(0),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData),this._instanceCount=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentMaterial=null,this._currentBaseTexture=null,this._resetSlots()}render(e){const t=this._backend,i=e.texture;if(null===t||!(i instanceof pi)&&!(i instanceof _i)||0===i.width||0===i.height||i instanceof pi&&null===i.source)return;const n=e.material,r=t.activeDrawCommand,s=null!==r?r.nodeIndex:t._pushTransform(e);this._activeBounds=this._resolveBounds(e,t),null===n?this._renderDefault(e,i,t,s):this._renderCustom(e,i,n,t,s)}_resolveBounds(e,t){if("geometry"!==e.pixelSnapMode)return e.getLocalBounds();const i=t._getSnapPixelSize();return e.getRenderBounds(t.view,i.width,i.height,this._snapBounds)}_renderDefault(e,t,i,n){const r=e.blendMode,s=null!==this._currentBlendMode&&r!==this._currentBlendMode,o=!this._textureSlots.has(t)&&this._slotCount>=8,a=null!==this._currentMaterial&&this._instanceCount>0;(s||o||a)&&this.flush(),this._currentBlendMode=r,this._currentMaterial=null,i.setBlendMode(r);let h=this._textureSlots.get(t);void 0===h&&(h=this._slotCount++,this._textureSlots.set(t,h),this._activeTextures[h]=t);const l=h|(i.shouldPremultiplyTextureSample(t)?1:0)<<8;this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(e,t,l,n),this._instanceCount++}_renderCustom(t,i,n,r,s){if(null===n.shader.wgsl)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const o=t.blendMode===e.BlendModes.Normal?n.blendMode:t.blendMode,a=null!==this._currentBlendMode&&o!==this._currentBlendMode,h=null!==this._currentMaterial&&n!==this._currentMaterial,l=null!==this._currentBaseTexture&&i!==this._currentBaseTexture,u=null===this._currentMaterial&&this._instanceCount>0;(a||h||l||u)&&this.flush(),this._currentBlendMode=o,this._currentMaterial=n,this._currentBaseTexture=i,r.setBlendMode(o),this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(t,i,0,s),this._instanceCount++}flush(){const e=this._backend,t=this._device,i=this._uniformBuffer;if(!e||!t||!i)return;if(0===this._instanceCount&&!e.clearRequested)return;const n=e.view.getTransform();this._projectionData.set([n.a,n.c,0,0,n.b,n.d,0,0,0,0,1,0,n.x,n.y,0,n.z]),t.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const r=e.getScissorRect(),s=null!==r&&(r.width<=0||r.height<=0),o=e._passCoordinator.acquirePass().pass;if(this._instanceCount>0&&!s&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode){t.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,this._instanceCount*Vs);const n=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,i,n.buffer),s=this._currentMaterial,a=e._passCoordinator.stencilActive;if(null===s){const i=this._getPipeline(this._currentBlendMode,e.renderTargetFormat,a),n=this._createTextureBindGroup(t,e);o.setPipeline(i),o.setBindGroup(0,r),o.setBindGroup(1,n),o.setVertexBuffer(0,this._instanceBuffer),o.setIndexBuffer(this._indexBuffer,"uint16"),o.drawIndexed(6,this._instanceCount,0,0,0)}else o.pushDebugGroup("SpriteMaterial (custom)"),this._drawCustomBatch(o,t,e,s,r,a),o.popDebugGroup();e.stats.batches++,e.stats.drawCalls++}e._passCoordinator.endPass(),this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots(),this._currentBlendMode=null,this._currentMaterial=null,this._currentBaseTexture=null}_getOrCreateTransformBindGroup(e,t,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=e.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}destroy(){this.disconnect()}async prewarmPipelines(t){const i=this._device;if(!i||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof i.createRenderPipelineAsync)return;const n=[e.BlendModes.Normal,e.BlendModes.Additive,e.BlendModes.Subtract,e.BlendModes.Multiply,e.BlendModes.Screen,e.BlendModes.Darken,e.BlendModes.Lighten],r=[];for(const e of n)for(const n of t){const t=`${e}:${n}`;if(this._pipelines.has(t))continue;const s=i.createRenderPipelineAsync(this._buildPipelineDescriptor(e,n)).then(e=>{this._pipelines.set(t,e)});r.push(s)}await Promise.all(r)}_packInstance(e,t,i,n){const r=this._instanceCount*zs,s=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??e.getLocalBounds();s[r+0]=a.left,s[r+1]=a.top,s[r+2]=a.right,s[r+3]=a.bottom;const h=e.textureFrame,l=t.width,u=t.height,c=h.left/l*65535&65535,d=h.right/l*65535&65535,_=h.top/u*65535&65535,f=h.bottom/u*65535&65535,p=t instanceof pi&&t.flipY,m=p?f:_,g=p?_:f;o[r+4]=c|m<<16,o[r+5]=d|g<<16,o[r+6]=e.tint.toRgba(),o[r+7]=i;const y=n>>>0;o[r+8]=y,y>this._maxNodeIndex&&(this._maxNodeIndex=y)}_ensureInstanceCapacity(e){if(!this._device||e<=this._instanceCapacity)return;let t=Math.max(this._instanceCapacity,32);for(;t<e;)t*=2;const i=this._instanceData,n=Math.min(this._instanceCount*Vs,i.byteLength),r=new ArrayBuffer(t*Vs);n>0&&new Uint8Array(r).set(new Uint8Array(i,0,n));const s=this._device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=t,this._instanceData=r,this._instanceFloat32=new Float32Array(r),this._instanceUint32=new Uint32Array(r),this._instanceBuffer=s}_resetSlots(){if(this._slotCount>0){for(let e=0;e<this._slotCount;e++)this._activeTextures[e]=null;this._textureSlots.clear(),this._slotCount=0}}_createTextureBindGroup(e,t){const i=this._activeTextures[0]??pi.empty,n=t.getTextureBinding(i),r=new Array(8);for(let e=0;e<8;e++){const s=this._activeTextures[e]??i;r[e]=s===i?n:t.getTextureBinding(s)}const s=[];for(let e=0;e<8;e++)s.push({binding:e,resource:r[e].view});for(let e=0;e<8;e++)s.push({binding:8+e,resource:r[e].sampler});return e.createBindGroup({layout:this._textureBindGroupLayout,entries:s})}_getPipeline(e,t,i){const n=`${e}:${t}:${i?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._backend))throw new Error("Renderer has to be connected first!");const s=this._device.createRenderPipeline(this._buildPipelineDescriptor(e,t,i));return this._pipelines.set(n,s),s}_buildPipelineDescriptor(e,t,i=!1){if(!this._shaderModule||!this._pipelineLayout)throw new Error("Renderer has to be connected first!");const n={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Vs,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:3,offset:16,format:"unorm16x4"},{shaderLocation:4,offset:24,format:"unorm8x4"},{shaderLocation:5,offset:28,format:"uint32"},{shaderLocation:6,offset:32,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return i&&(n.depthStencil=Ps()),n}_drawCustomBatch(e,t,i,n,r,s){const o=this._getOrCreateCustomResources(n,t),a=this._currentBaseTexture??pi.empty;this._uploadUserUniforms(n,o,t);const h=this._getOrCreateCustomPipeline(o,this._currentBlendMode,i.renderTargetFormat,s,t);e.setPipeline(h),e.setBindGroup(0,r),e.setBindGroup(1,this._getCustomBaseTextureBindGroup(o,i,a,t)),e.setBindGroup(2,this._buildUserBindGroup(n,o,i,t)),e.setVertexBuffer(0,this._instanceBuffer),e.setIndexBuffer(this._indexBuffer,"uint16"),e.drawIndexed(6,this._instanceCount,0,0,0)}_getOrCreateCustomResources(e,t){const i=this._customMaterials.get(e);if(void 0!==i)return i;const n=e.shader.wgsl;if(null===n)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const r=t.createShaderModule({code:`\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct TransformSlot {\n m0: vec4<f32>,\n m1: vec4<f32>,\n m2: vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> projection: ProjectionUniforms;\n@group(0) @binding(1) var<storage, read> transforms: array<TransformSlot>;\n\n@group(1) @binding(0) var u_texture: texture_2d<f32>;\n@group(1) @binding(1) var u_sampler: sampler;\n\nstruct VertexInput {\n @location(0) localBounds: vec4<f32>,\n @location(3) uvBounds: vec4<f32>,\n @location(4) color: vec4<f32>,\n @location(5) textureSlot: u32,\n @location(6) nodeIndex: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput, @builtin(vertex_index) vid: u32) -> VertexOutput {\n var output: VertexOutput;\n\n let cornerX = ((vid + 1u) >> 1u) & 1u;\n let cornerY = vid >> 1u;\n\n let localX = select(input.localBounds.x, input.localBounds.z, cornerX == 1u);\n let localY = select(input.localBounds.y, input.localBounds.w, cornerY == 1u);\n\n // Fetch this instance's world transform from the shared storage buffer,\n // keyed by nodeIndex: m0 = (a, b, c, d), m1 = (tx, ty, 0, 0). (m2 carries the\n // node tint, unused here — the sprite keeps its own per-instance color.)\n let slot = transforms[input.nodeIndex];\n let worldX = slot.m0.x * localX + slot.m0.y * localY + slot.m1.x;\n let worldY = slot.m0.z * localX + slot.m0.w * localY + slot.m1.y;\n\n output.position = projection.matrix * vec4<f32>(worldX, worldY, 0.0, 1.0);\n\n let u = select(input.uvBounds.x, input.uvBounds.z, cornerX == 1u);\n let v = select(input.uvBounds.y, input.uvBounds.w, cornerY == 1u);\n output.texcoord = vec2<f32>(u, v);\n\n output.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n${n}`}),s=this._buildUserBindGroupLayout(t,e),o={shaderModule:r,userLayout:s,pipelineLayout:t.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._customBaseTextureLayout,s]}),pipelines:new Map,userUniformBuffer:null,userUniformBufferCapacity:0,baseTextureBindGroups:new WeakMap};return this._customMaterials.set(e,o),e._onDispose(()=>{const t=this._customMaterials.get(e);void 0!==t&&(this._releaseCustomResources(t),this._customMaterials.delete(e))}),o}_getOrCreateCustomPipeline(e,t,i,n,r){const s=`${t}:${i}:${n?"s":"n"}`,o=e.pipelines.get(s);if(void 0!==o)return o;const a={layout:e.pipelineLayout,vertex:{module:e.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Vs,stepMode:"instance",attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:3,offset:16,format:"unorm16x4"},{shaderLocation:4,offset:24,format:"unorm8x4"},{shaderLocation:5,offset:28,format:"uint32"},{shaderLocation:6,offset:32,format:"uint32"}]}]},fragment:{module:e.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:Ss(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};n&&(a.depthStencil=Ps());const h=r.createRenderPipeline(a);return e.pipelines.set(s,h),h}_getCustomBaseTextureBindGroup(e,t,i,n){const r=t.getTextureBinding(i),s=e.baseTextureBindGroups.get(i);if(s?.view===r.view)return s.group;const o=n.createBindGroup({layout:this._customBaseTextureLayout,entries:[{binding:0,resource:r.view},{binding:1,resource:r.sampler}]});return e.baseTextureBindGroups.set(i,{group:o,view:r.view}),o}_buildUserBindGroupLayout(e,t){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const n=$s(t);if(n.length>7)throw new Error("SpriteMaterial requested more than 7 user texture bindings.");let r=1;for(let e=0;e<n.length;e++)i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),r++,i.push({binding:r,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),r++;return e.createBindGroupLayout({entries:i})}_uploadUserUniforms(e,t,i){const n=function(e){const t=[];for(const i of Object.values(e.uniforms))Ys(i)||t.push(i);return t}(e),r=16*Math.max(n.length,1);(null===t.userUniformBuffer||t.userUniformBufferCapacity<r)&&(t.userUniformBuffer?.destroy(),t.userUniformBufferCapacity=r,t.userUniformBuffer=i.createBuffer({size:r,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const s=new Float32Array(r/4);let o=0;for(const e of n){const t=4*o;if("number"==typeof e)s[t]=e;else if(e instanceof Float32Array)s.set(e,t);else if(e instanceof Int32Array)for(let i=0;i<e.length;i++)s[t+i]=e[i];else{const i=e;for(let e=0;e<i.length;e++)s[t+e]=i[e]}o++}i.queue.writeBuffer(t.userUniformBuffer,0,s)}_buildUserBindGroup(e,t,i,n){const r=[];r.push({binding:0,resource:{buffer:t.userUniformBuffer}});let s=1;for(const t of $s(e)){const e=i.getTextureBinding(t);r.push({binding:s,resource:e.view}),s++,r.push({binding:s,resource:e.sampler}),s++}return n.createBindGroup({layout:t.userLayout,entries:r})}_releaseCustomResources(e){e.userUniformBuffer?.destroy(),e.pipelines.clear(),e.userUniformBuffer=null,e.userUniformBufferCapacity=0,e.baseTextureBindGroups=new WeakMap}}function Ys(e){return!("object"!=typeof e||null===e||!("width"in e)||!("height"in e)||e instanceof Float32Array||e instanceof Int32Array||Array.isArray(e))}function $s(e){const t=[];for(const i of Object.values(e.uniforms))Ys(i)&&t.push(i);for(const i of Object.values(e.textures))t.push(i);return t}const Xs=20;class Hs extends bs{_consumesSharedTransform=!1;_device=null;_shaderModule=null;_frameBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_pipelines=new Map;_texBindGroups=new WeakMap;_projBuffer=null;_nodeBuffer=null;_vertexBuffer=null;_indexBuffer=null;_nodeBufferCapacity=0;_vertexBufferCapacity=0;_indexBufferCapacity=0;_frameBindGroup=null;_frameBindGroupDirty=!0;_vertexCapacity=256;_indexCapacity=384;_vertexData=new ArrayBuffer(5120);_float32View=new Float32Array(this._vertexData);_indexData=new Uint16Array(384);_projData=new Float32Array(12);_nodeDataArray=new Float32Array(1280);_nodeCapacity=32;_nodeCount=0;_pendingQuads=[];_nodeIndexMap=new Map;_textureKeyMap=new Map;_textureKeyCounter=0;render(e){if(!this._device)throw new Error("WebGpuTextRenderer is not connected to a backend.");e instanceof Wr?this._collectText(e):this._collectBitmapText(e)}flush(){if(0===this._pendingQuads.length)return void this._resetFrameState();const e=this.getBackend(),t=this._device;for(const e of this._pendingQuads)this._textureKeyMap.has(e.atlasTexture)||this._textureKeyMap.set(e.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((e,t)=>{const i=e.shaderType.localeCompare(t.shaderType);return 0!==i?i:(this._textureKeyMap.get(e.atlasTexture)??0)-(this._textureKeyMap.get(t.atlasTexture)??0)});const i=e.view.getTransform().toArray(!1);this._projData[0]=i[0],this._projData[1]=i[1],this._projData[2]=i[2],this._projData[3]=0,this._projData[4]=i[3],this._projData[5]=i[4],this._projData[6]=i[5],this._projData[7]=0,this._projData[8]=i[6],this._projData[9]=i[7],this._projData[10]=i[8],this._projData[11]=0,t.queue.writeBuffer(this._projBuffer,0,this._projData.buffer,0,48),this._uploadNodeBuffer(t);const n=this._pendingQuads,r=[];let s=0,o=0;for(const e of n)s+=4*e.quads.quadCount,o+=e.quads.indices.length;this._ensureVertexCapacity(s),this._ensureIndexCapacity(o);let a=0,h=0,l=0;for(;l<n.length;){const e=n[l],t=this._textureKeyMap.get(e.atlasTexture);let i=l+1;for(;i<n.length;){const r=n[i];if(r.shaderType!==e.shaderType||this._textureKeyMap.get(r.atlasTexture)!==t)break;i++}const s=h;let o=0;for(let e=l;e<i;e++){const{quads:t,nodeIndex:i}=n[e],r=4*t.quadCount,{vertices:s,uvs:l,indices:u}=t;for(let e=0;e<r;e++){const t=5*(a+e),n=2*e;this._float32View[t+0]=s[n],this._float32View[t+1]=s[n+1],this._float32View[t+2]=l[n],this._float32View[t+3]=l[n+1],this._float32View[t+4]=i}for(let e=0;e<u.length;e++)this._indexData[h+e]=u[e]+a;a+=r,h+=u.length,o+=u.length}r.push({shaderType:e.shaderType,atlasTexture:e.atlasTexture,firstIndex:s,indexCount:o}),l=i}this._ensureGpuVertexBuffer(t,a),this._ensureGpuIndexBuffer(t,h),t.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,a*Xs),t.queue.writeBuffer(this._indexBuffer,0,this._indexData.buffer,0,2*h);const u=e.renderTargetFormat,c=e._passCoordinator.stencilActive,d=this._getFrameBindGroup(t),_=e._passCoordinator.acquirePass().pass;_.setVertexBuffer(0,this._vertexBuffer),_.setIndexBuffer(this._indexBuffer,"uint16");let f=null,p=null;for(const i of r)i.shaderType!==f&&(_.setPipeline(this._getPipeline(i.shaderType,u,c)),_.setBindGroup(0,d),f=i.shaderType),i.atlasTexture!==p&&(_.setBindGroup(1,this._getTexBindGroup(t,e,i.atlasTexture)),p=i.atlasTexture),_.drawIndexed(i.indexCount,1,i.firstIndex,0,0),e.stats.batches++,e.stats.drawCalls++;e._passCoordinator.endPass(),this._resetFrameState()}destroy(){this.disconnect()}async prewarmPipelines(e){const t=this._device;if(!t||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof t.createRenderPipelineAsync)return;const i=["sdf","msdf","color"],n=[];for(const r of i)for(const i of e){const e=`${r}:${i}:n`;this._pipelines.has(e)||n.push(t.createRenderPipelineAsync(this._buildPipelineDescriptor(r,i)).then(t=>{this._pipelines.set(e,t)}))}await Promise.all(n)}onConnect(e){const t=e.device;this._device=t,this._shaderModule=t.createShaderModule({label:"WebGpuTextRenderer",code:"\nstruct FrameUniforms {\n projCol0 : vec4<f32>,\n projCol1 : vec4<f32>,\n projCol2 : vec4<f32>,\n};\n\n@group(0) @binding(0) var<uniform> frame : FrameUniforms;\n@group(0) @binding(1) var<storage, read> nodes : array<vec4<f32>>;\n\n@group(1) @binding(0) var atlasTexture : texture_2d<f32>;\n@group(1) @binding(1) var atlasSampler : sampler;\n\nstruct VertexInput {\n @location(0) position : vec2<f32>,\n @location(1) texcoord : vec2<f32>,\n @location(2) nodeIndex : f32,\n};\n\nstruct VertexOutput {\n @builtin(position) clipPos : vec4<f32>,\n @location(0) texcoord : vec2<f32>,\n @location(1) gradUV : vec2<f32>,\n @location(2) @interpolate(flat) nodeIdx : u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let ni = u32(input.nodeIndex);\n let base = ni * 10u;\n\n let t0 = nodes[base + 0u];\n let t1 = nodes[base + 1u];\n let t9 = nodes[base + 9u];\n\n let proj = mat3x3<f32>(\n frame.projCol0.xyz,\n frame.projCol1.xyz,\n frame.projCol2.xyz,\n );\n let xf = mat3x3<f32>(\n vec3<f32>(t0.x, t0.y, 0.0),\n vec3<f32>(t1.x, t1.y, 0.0),\n vec3<f32>(t0.w, t1.w, 1.0),\n );\n\n let worldPos = proj * xf * vec3<f32>(input.position, 1.0);\n\n let bSize = t9.zw;\n var gradUV = vec2<f32>(0.0);\n if (bSize.x > 0.0 && bSize.y > 0.0) {\n gradUV = clamp((input.position - t9.xy) / bSize, vec2<f32>(0.0), vec2<f32>(1.0));\n }\n\n var out: VertexOutput;\n out.clipPos = vec4<f32>(worldPos.xy, 0.0, 1.0);\n out.texcoord = input.texcoord;\n out.gradUV = gradUV;\n out.nodeIdx = ni;\n return out;\n}\n\n// ── SDF (R8 atlas) ────────────────────────────────────────────────────────────\n\n@fragment\nfn fragmentSdf(in: VertexOutput) -> @location(0) vec4<f32> {\n let ni = in.nodeIdx;\n let base = ni * 10u;\n\n let tFill = nodes[base + 2u];\n let tOutline = nodes[base + 3u];\n let tParams = nodes[base + 4u];\n let tShadow = nodes[base + 5u];\n let tShadow2 = nodes[base + 6u];\n let tGradTop = nodes[base + 7u];\n let tGradBot = nodes[base + 8u];\n\n let outlineMin = tParams.x;\n let shadowAlpha = tParams.y;\n let soft = max(tParams.z, 0.001);\n let gradEnabled = tParams.w;\n let pageSize = f32(textureDimensions(atlasTexture, 0).x);\n let shadowOffset = tShadow2.xy / pageSize;\n let gradVertical = tShadow2.z;\n\n let sd = textureSample(atlasTexture, atlasSampler, in.texcoord).r;\n let fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n let shadowSd = textureSample(atlasTexture, atlasSampler, in.texcoord - shadowOffset).r;\n\n let outline = select(0.0,\n smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill),\n outlineMin < 0.5);\n\n let shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n var fillColor : vec4<f32>;\n if (gradEnabled > 0.5) {\n let t = select(in.gradUV.x, in.gradUV.y, gradVertical > 0.5);\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n return fillColor * fill + tOutline * outline + tShadow * shadow;\n}\n\n// ── MSDF (RGB atlas) ──────────────────────────────────────────────────────────\n\nfn median3(r: f32, g: f32, b: f32) -> f32 {\n return max(min(r, g), min(max(r, g), b));\n}\n\n@fragment\nfn fragmentMsdf(in: VertexOutput) -> @location(0) vec4<f32> {\n let ni = in.nodeIdx;\n let base = ni * 10u;\n\n let tFill = nodes[base + 2u];\n let tOutline = nodes[base + 3u];\n let tParams = nodes[base + 4u];\n let tShadow = nodes[base + 5u];\n let tShadow2 = nodes[base + 6u];\n let tGradTop = nodes[base + 7u];\n let tGradBot = nodes[base + 8u];\n\n let outlineMin = tParams.x;\n let shadowAlpha = tParams.y;\n let soft = max(tParams.z, 0.001);\n let gradEnabled = tParams.w;\n let pageSize = f32(textureDimensions(atlasTexture, 0).x);\n let shadowOffset = tShadow2.xy / pageSize;\n let gradVertical = tShadow2.z;\n\n let msd = textureSample(atlasTexture, atlasSampler, in.texcoord).rgb;\n let sd = median3(msd.r, msd.g, msd.b);\n let fill = smoothstep(0.5 - soft, 0.5 + soft, sd);\n\n let shadowMsd = textureSample(atlasTexture, atlasSampler, in.texcoord - shadowOffset).rgb;\n let shadowSd = median3(shadowMsd.r, shadowMsd.g, shadowMsd.b);\n\n let outline = select(0.0,\n smoothstep(outlineMin - soft, outlineMin + soft, sd) * (1.0 - fill),\n outlineMin < 0.5);\n\n let shadow = smoothstep(0.5 - soft, 0.5 + soft, shadowSd)\n * shadowAlpha * (1.0 - fill) * (1.0 - outline);\n\n var fillColor : vec4<f32>;\n if (gradEnabled > 0.5) {\n let t = select(in.gradUV.x, in.gradUV.y, gradVertical > 0.5);\n fillColor = mix(tGradBot, tGradTop, t);\n } else {\n fillColor = tFill;\n }\n\n return fillColor * fill + tOutline * outline + tShadow * shadow;\n}\n\n// ── Color (RGBA atlas) ────────────────────────────────────────────────────────\n\n@fragment\nfn fragmentColor(in: VertexOutput) -> @location(0) vec4<f32> {\n let ni = in.nodeIdx;\n let base = ni * 10u;\n let tint = nodes[base + 2u];\n let sample = textureSample(atlasTexture, atlasSampler, in.texcoord);\n return sample * tint;\n}\n"}),this._frameBindGroupLayout=t.createBindGroupLayout({label:"WebGpuTextRenderer/frame",entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=t.createBindGroupLayout({label:"WebGpuTextRenderer/texture",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=t.createPipelineLayout({label:"WebGpuTextRenderer",bindGroupLayouts:[this._frameBindGroupLayout,this._textureBindGroupLayout]}),this._projBuffer=t.createBuffer({label:"WebGpuTextRenderer/proj",size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this._nodeBuffer=t.createBuffer({label:"WebGpuTextRenderer/nodes",size:5120,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=5120;this._vertexBuffer=t.createBuffer({label:"WebGpuTextRenderer/vertices",size:5120,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=5120;this._indexBuffer=t.createBuffer({label:"WebGpuTextRenderer/indices",size:768,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._indexBufferCapacity=768,this._frameBindGroupDirty=!0}onDisconnect(){this._projBuffer?.destroy(),this._nodeBuffer?.destroy(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._projBuffer=null,this._nodeBuffer=null,this._vertexBuffer=null,this._indexBuffer=null,this._nodeBufferCapacity=0,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._frameBindGroup=null,this._frameBindGroupDirty=!0,this._pipelines.clear(),this._texBindGroups=new WeakMap,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._frameBindGroupLayout=null,this._shaderModule=null,this._device=null,this._resetFrameState()}_collectText(e){e.syncDirty();const{pageQuads:t,atlas:i}=e;if(0===t.length||null===i)return;const n=this._assignNodeIndex(e),r=e.colorGlyphs?"color":"sdf",s=i.pages;for(const e of t){const t=s[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:n,shaderType:r,atlasTexture:t.texture})}}_collectBitmapText(e){const{pageQuads:t,textures:i,msdf:n}=e;if(0===t.length)return;const r=this._assignNodeIndex(e),s=n?"msdf":"color";for(const e of t){const t=i[e.pageIndex];void 0!==t&&this._pendingQuads.push({quads:e,nodeIndex:r,shaderType:s,atlasTexture:t})}}_assignNodeIndex(e){const t=this._nodeIndexMap.get(e);if(void 0!==t)return t;const i=this._nodeCount++;return this._nodeIndexMap.set(e,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,e),i}_packNodeData(e,t){const i=this._nodeDataArray,n=40*e,r=t.style,s=t.getGlobalTransform().toArray(!1);i[n+0]=s[0],i[n+1]=s[1],i[n+2]=s[2],i[n+3]=s[6],i[n+4]=s[3],i[n+5]=s[4],i[n+6]=s[5],i[n+7]=s[7];const o=r.fillColor;i[n+8]=o.r/255,i[n+9]=o.g/255,i[n+10]=o.b/255,i[n+11]=o.a;const a=r.outlineColor;i[n+12]=a.r/255,i[n+13]=a.g/255,i[n+14]=a.b/255,i[n+15]=a.a;const h=r.outlineWidth>0?Math.max(0,.5-r.outlineWidth):.5;i[n+16]=h,i[n+17]=r.shadowAlpha,i[n+18]=Math.max(.03,.1*r.shadowBlur),i[n+19]=null!==r.gradientColors?1:0;const l=r.shadowColor;i[n+20]=l.r/255,i[n+21]=l.g/255,i[n+22]=l.b/255,i[n+23]=l.a,i[n+24]=r.shadowOffsetX,i[n+25]=r.shadowOffsetY,i[n+26]="vertical"===r.gradientAxis?1:0,i[n+27]=0;const u=r.gradientColors;null!==u?(i[n+28]=u[0].r/255,i[n+29]=u[0].g/255,i[n+30]=u[0].b/255,i[n+31]=u[0].a,i[n+32]=u[1].r/255,i[n+33]=u[1].g/255,i[n+34]=u[1].b/255,i[n+35]=u[1].a):(i[n+28]=i[n+29]=i[n+30]=i[n+31]=0,i[n+32]=i[n+33]=i[n+34]=i[n+35]=0);const c=t.textBounds;i[n+36]=0,i[n+37]=0,i[n+38]=c.width,i[n+39]=c.height}_uploadNodeBuffer(e){const t=40*this._nodeCount*4;if(t>this._nodeBufferCapacity){let i=this._nodeBufferCapacity;for(;i<t;)i*=2;this._nodeBuffer?.destroy(),this._nodeBuffer=e.createBuffer({label:"WebGpuTextRenderer/nodes",size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=i,this._frameBindGroupDirty=!0}e.queue.writeBuffer(this._nodeBuffer,0,this._nodeDataArray.buffer,0,t)}_ensureGpuVertexBuffer(e,t){const i=t*Xs;if(i<=this._vertexBufferCapacity)return;let n=this._vertexBufferCapacity;for(;n<i;)n*=2;this._vertexBuffer?.destroy(),this._vertexBuffer=e.createBuffer({label:"WebGpuTextRenderer/vertices",size:n,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=n}_ensureGpuIndexBuffer(e,t){const i=2*t;if(i<=this._indexBufferCapacity)return;let n=this._indexBufferCapacity;for(;n<i;)n*=2;this._indexBuffer?.destroy(),this._indexBuffer=e.createBuffer({label:"WebGpuTextRenderer/indices",size:n,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._indexBufferCapacity=n}_getFrameBindGroup(e){return this._frameBindGroupDirty||null===this._frameBindGroup?(this._frameBindGroup=e.createBindGroup({layout:this._frameBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projBuffer}},{binding:1,resource:{buffer:this._nodeBuffer}}]}),this._frameBindGroupDirty=!1,this._frameBindGroup):this._frameBindGroup}_getTexBindGroup(e,t,i){const{view:n,sampler:r}=t.getTextureBinding(i),s=this._texBindGroups.get(i);if(s?.view===n)return s.group;const o=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:n},{binding:1,resource:r}]});return this._texBindGroups.set(i,{group:o,view:n}),o}_getPipeline(e,t,i){const n=`${e}:${t}:${i?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;const s=this._device.createRenderPipeline(this._buildPipelineDescriptor(e,t,i));return this._pipelines.set(n,s),s}_buildPipelineDescriptor(t,i,n=!1){let r;r="sdf"===t?"fragmentSdf":"msdf"===t?"fragmentMsdf":"fragmentColor";const s={label:`WebGpuTextRenderer/${t}`,layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Xs,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"float32"}]}]},fragment:{module:this._shaderModule,entryPoint:r,targets:[{format:i,blend:Ss(e.BlendModes.Normal),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return n&&(s.depthStencil=Ps()),s}_ensureVertexCapacity(e){if(!(e<=this._vertexCapacity)){for(;this._vertexCapacity<e;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*Xs),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(e){if(!(e<=this._indexCapacity)){for(;this._indexCapacity<e;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(e){if(e<=this._nodeCapacity)return;for(;this._nodeCapacity<e;)this._nodeCapacity*=2;const t=new Float32Array(40*this._nodeCapacity);t.set(this._nodeDataArray),this._nodeDataArray=t}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}}class js extends In{_rawTransform=null;_sourceGeometry=null;_sourceVersion=-1;constructor(){super({vertices:new Float32Array([0,0,1,0,0,1])})}getGlobalTransform(){return this._rawTransform??super.getGlobalTransform()}configure(e,t,i,n){this._flattenGeometry(e),this._geometry=null,this._material=i,this._rawTransform=t,this.setTint(n??Tt.white)}configureBatchSource(e,t){this._flattenGeometry(e),this._geometry=e,this._material=t,this._rawTransform=null,this.setTint(Tt.white)}_flattenGeometry(e){if(e===this._sourceGeometry&&e.version===this._sourceVersion)return;const t=On(e);this._vertices=t.vertices,this._uvs=t.uvs,this._colors=t.colors,this._indices=t.indices,this._sourceGeometry=e,this._sourceVersion=e.version}}const Ks=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0,rawFrameDeltaMs:0,gpuMemoryBytes:0,textureUploadBytes:0,bufferUploadBytes:0,downloadBytes:0,downloadCount:0}),Qs=e=>(e.frame++,e.submittedNodes=0,e.culledNodes=0,e.drawCalls=0,e.batches=0,e.renderPasses=0,e.renderTargetChanges=0,e.frameTimeMs=0,e.rawFrameDeltaMs=0,e.textureUploadBytes=0,e.bufferUploadBytes=0,e.downloadBytes=0,e.downloadCount=0,e);class Zs{order=500;_backend;_view;_screenView;_immediateMesh=null;_batchMesh=null;_trackedViews=new Set;_renderedViews=new Set;constructor(e){this._backend=e;const t=e.view?.width??0,i=e.view?.height??0,n=e.view?.center?.x??t/2,r=e.view?.center?.y??i/2;this._view=ci.from({center:{x:n,y:r},size:{width:t,height:i}}),this._screenView=new ci(n,r,t,i)}get view(){return this._view}set view(e){const t=this._view;this._view=e,t!==e&&t.destroy()}get screenView(){return this._screenView}trackView(e){this._trackedViews.add(e)}untrackView(e){this._trackedViews.delete(e)}update(e){const t=e.milliseconds;this._view.update(t);for(const e of this._trackedViews)e!==this._view&&e.update(t);for(const e of this._renderedViews)e===this._view||this._trackedViews.has(e)||e.update(t);this._renderedViews.clear()}destroy(){this._view.destroy(),this._screenView.destroy(),this._trackedViews.clear(),this._renderedViews.clear(),this._immediateMesh?.destroy(),this._immediateMesh=null,this._batchMesh?.destroy(),this._batchMesh=null}resize(e,t){this._view.resize(e,t),this._screenView.resize(e,t),this._screenView.setCenter(e/2,t/2)}render(e,t={}){const i=t.view??this._view;this._renderedViews.add(i),this._backend.setView(i),wi(e,this._backend)}capture(e,t){const i=new _i(t.width,t.height),n=new ci(t.width/2,t.height/2,t.width,t.height),r=this._backend._passCoordinator;if(r)return r.withChildPass({target:i,view:n,load:void 0!==t.clearColor?"clear":"load",clearColor:t.clearColor??null,stencil:xi.None},()=>{wi(e,this._backend)}),i;const s=this._backend.renderTarget,o=this._backend.view;this._backend.setRenderTarget(i),this._backend.setView(n),void 0!==t.clearColor&&this._backend.clear(t.clearColor);try{wi(e,this._backend)}finally{this._backend.setRenderTarget(s),this._backend.setView(o)}return i}clear(e){const t=this._backend._passCoordinator;t?t.withChildPass({target:t.activeTarget,view:t.activeView,load:"clear",clearColor:e,stencil:xi.None},()=>{}):this._backend.clear(e)}renderTo(e,t){const i=t.view??t.target.view;this._renderedViews.add(i);const n=this._backend._passCoordinator;if(n)return void n.withChildPass({target:t.target,view:i,load:void 0!==t.clear?"clear":"load",clearColor:t.clear??null,stencil:xi.None},()=>{wi(e,this._backend)});const r=this._backend.renderTarget,s=this._backend.view;this._backend.setRenderTarget(t.target),this._backend.setView(i),void 0!==t.clear&&this._backend.clear(t.clear);try{wi(e,this._backend)}finally{this._backend.setRenderTarget(r),this._backend.setView(s)}}drawGeometry(e,t,i={}){const n=i.material??null;if(null!==n&&"mesh"!==n.target)throw new Error(`drawGeometry material must target 'mesh' (got '${String(n.target)}').`);const r=i.view??this._view;this._renderedViews.add(r);const s=this._immediateMesh??=new js;this._backend.setView(r),s.configure(e,t,n,i.tint??null),this._backend.draw(s),this._backend.flush()}drawBatch(e,t={}){if(null!==e.material)throw new Error("drawBatch custom materials are not supported yet — v1 renders batches with the default mesh material.");if(0===e.count)return;const i=t.view??this._view;this._renderedViews.add(i);const n=this._batchMesh??=new js;this._backend.setView(i),n.configureBatchSource(e.geometry,e.material),this._backend.drawInstanced(n,e._instanceTransforms,e._instanceTints,e.count),this._backend.flush()}get stats(){return this._backend.stats}get backend(){return this._backend}}class Js{_stats;_liveBytes=0;constructor(e){this._stats=e,this._stats.gpuMemoryBytes=0}get liveBytes(){return this._liveBytes}allocate(e){e<=0||(this._liveBytes+=e,this._stats.gpuMemoryBytes=this._liveBytes)}free(e){e<=0||(this._liveBytes=Math.max(0,this._liveBytes-e),this._stats.gpuMemoryBytes=this._liveBytes)}reallocate(e,t){return this.free(e),this.allocate(t),t}recordTextureUpload(e){e<=0||(this._stats.textureUploadBytes+=e)}recordBufferUpload(e){e<=0||(this._stats.bufferUploadBytes+=e)}recordDownload(e){e<=0||(this._stats.downloadBytes+=e,this._stats.downloadCount++)}}const eo=(e,t,i,n=1)=>{const r=Math.max(1,Math.floor(e)),s=Math.max(1,Math.floor(t)),o=Math.max(1,Math.floor(n));let a=0,h=r,l=s;for(let e=0;e<o&&(a+=h*l*i,1!==h||1!==l);e++)h=Math.max(1,h>>1),l=Math.max(1,l>>1);return a},to=e=>{switch(e){case"r8":return 1;case"r32f":case"rgba8":return 4;case"rgba32f":return 16}};class io{_entries=new Map;_walk;_dispose;constructor(e={}){this._walk=e.walk??null,this._dispose=e.dispose??null}set(e,t){this._entries.set(e,t)}hasOwn(e){return this._entries.has(e)}has(e){return void 0!==this._find(e)}resolve(e){return this._find(e)}values(){return this._entries.values()}destroy(){if(null!==this._dispose){const e=new Set;for(const t of this._entries.values())e.has(t)||(e.add(t),this._dispose(t))}this._entries.clear()}_find(e){let t,i=e;for(;null!==i&&void 0===t;)t=this._entries.get(i),void 0===t&&(i=null!==this._walk?this._walk(i):null);return t}}const no=e=>{const t=Object.getPrototypeOf(e.prototype);return t?.constructor??null};class ro{_renderers=new io({walk:no,dispose:e=>{e.disconnect(),"destroy"in e&&"function"==typeof e.destroy&&e.destroy()}});_resolved=new Map;_backend=null;registerRenderer(e,t){if(this._renderers.hasOwn(e))throw new Error(`A renderer is already registered for ${e.name}.`);this._renderers.set(e,t),this._resolved.clear(),null!==this._backend&&t.connect(this._backend)}bindRenderer(e,t){if(0===e.length)throw new Error("A RendererBinding must declare at least one target.");const i=new Set;for(const t of e){if(i.has(t))throw new Error(`A RendererBinding declares the same target ${t.name} more than once.`);i.add(t)}for(const t of e)if(this._renderers.hasOwn(t))throw new Error(`A renderer is already registered for ${t.name}.`);for(const i of e)this._renderers.set(i,t);this._resolved.clear(),null!==this._backend&&t.connect(this._backend)}renderers(){return this._renderers.values()}resolve(e){const t=e.constructor,i=this._resolved.get(t);if(void 0!==i)return i;const n=this._renderers.resolve(t);if(!n)throw new Error(`No renderer registered for ${e.constructor.name}. If it comes from an ExoJS extension, import that package before creating the Application, or pass the extension via ApplicationOptions.extensions.`);return this._resolved.set(t,n),n}connect(e){this._backend=e;for(const t of this._renderers.values())t.connect(e)}disconnect(){for(const e of this._renderers.values())e.disconnect();this._backend=null}destroy(){this._renderers.destroy(),this._resolved.clear(),this._backend=null}}const so=new Float32Array(1),oo=new Uint32Array(so.buffer);class ao{_data=new Float32Array(192);_count=0;_version=0;_frameHash=2166136261;_lastCommittedHash=0;_lastCommittedCount=-1;_writeCount=0;_skippedWriteCount=0;_uploadCount=0;_uploadedRecordCount=0;_dirtyMin=0;_dirtyMax=-1;get count(){return this._count}get writeCount(){return this._writeCount}get skippedWriteCount(){return this._skippedWriteCount}get uploadCount(){return this._uploadCount}get uploadedRecordCount(){return this._uploadedRecordCount}get capacity(){return this._data.length/12}get data(){return this._data}get version(){return this._version}get frameHash(){return this._frameHash}begin(e=0){return e>0&&this._ensureCapacity(e),this._count=0,this._frameHash=2166136261,this._writeCount=0,this._skippedWriteCount=0,this._uploadCount=0,this._uploadedRecordCount=0,this._dirtyMin=0,this._dirtyMax=-1,this}push(e,t){const i=this._count;return this.write(i,e,t),i}rewindTo(e,t){return e>=0&&e<this._count&&(this._count=e,void 0!==t&&(this._frameHash=t>>>0)),this}consumeDirtyRange(e){if(this._dirtyMax<this._dirtyMin)return{firstRow:0,rowCount:0};const t=Math.max(0,this._dirtyMin),i=Math.min(this._dirtyMax,e-1),n=i>=t?i-t+1:0;return this._dirtyMin=0,this._dirtyMax=-1,{firstRow:t,rowCount:n}}write(e,t,i){if(!Number.isInteger(e)||e<0)throw new Error(`TransformBuffer slot must be a non-negative integer (got ${e}).`);this._ensureCapacity(e+1);const n=12*e,r=this._data;r[n+0]=t.a,r[n+1]=t.b,r[n+2]=t.c,r[n+3]=t.d,r[n+4]=t.x,r[n+5]=t.y,r[n+6]=0,r[n+7]=0,r[n+8]=i.r/255,r[n+9]=i.g/255,r[n+10]=i.b/255,r[n+11]=i.a,e>=this._count&&(this._count=e+1),this._dirtyMax<this._dirtyMin?(this._dirtyMin=e,this._dirtyMax=e):(e<this._dirtyMin&&(this._dirtyMin=e),e>this._dirtyMax&&(this._dirtyMax=e)),this._frameHash=this._mix(this._frameHash,e);for(let e=0;e<12;e++)this._frameHash=this._mix(this._frameHash,this._hashFloat(r[n+e]));return this._writeCount++,this}recordSkippedWrite(){return this._skippedWriteCount++,this}recordUpload(e){return this._uploadCount++,this._uploadedRecordCount+=e,this}commitSnapshot(e=0){const t=Math.max(this._count,e),i=this._mix(this._frameHash,t),n=i!==this._lastCommittedHash||t!==this._lastCommittedCount;return n&&(this._version++,this._lastCommittedHash=i,this._lastCommittedCount=t),{count:t,hash:i,changed:n,version:this._version}}_ensureCapacity(e){const t=this.capacity;if(e<=t)return;let i=Math.max(t,16);for(;i<e;)i*=2;const n=new Float32Array(12*i);n.set(this._data),this._data=n}_hashFloat(e){return so[0]=e,oo[0]>>>0}_mix(e,t){return Math.imul((e^t)>>>0,16777619)>>>0}}const ho=new Uint16Array([0,1,2,0,2,3]);class lo{_shader=new Yr("#version 300 es\nprecision mediump float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\n\nuniform mat3 u_projection;\n\nout vec2 v_texcoord;\n\nvoid main(void) {\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n}\n","#version 300 es\nprecision highp float;\n\n// Backdrop-aware blend compositor (advanced blend modes).\n//\n// Samples the premultiplied source (the drawable rendered to a texture) and the\n// captured premultiplied backdrop (the target contents behind it), computes the\n// W3C blend B(Cb, Cs) for the requested mode, and outputs the blended source\n// premultiplied by its own alpha. The caller draws this with normal\n// (premultiplied source-over) blending, so the GPU composites it over the\n// untouched backdrop already in the target — transparent source regions\n// (alpha 0) leave the backdrop showing through instead of going black.\n//\n// Mode values match the BlendModes enum (src/rendering/types.ts).\n\nuniform sampler2D u_source;\nuniform sampler2D u_backdrop;\nuniform int u_mode;\n// 1.0 when the target is opaque (the on-screen root canvas), whose captured\n// alpha is unreliable — an opaque framebuffer reports backdrop alpha 0, which\n// would make the blend ignore the backdrop. Forces backdrop coverage to full.\nuniform float u_opaqueBackdrop;\n\nin vec2 v_texcoord;\n\nlayout(location = 0) out vec4 fragColor;\n\nconst int MODE_MULTIPLY = 3;\nconst int MODE_SCREEN = 4;\nconst int MODE_DARKEN = 5;\nconst int MODE_LIGHTEN = 6;\nconst int MODE_OVERLAY = 7;\nconst int MODE_COLOR_DODGE = 8;\nconst int MODE_COLOR_BURN = 9;\nconst int MODE_HARD_LIGHT = 10;\nconst int MODE_SOFT_LIGHT = 11;\nconst int MODE_DIFFERENCE = 12;\nconst int MODE_EXCLUSION = 13;\nconst int MODE_HUE = 14;\nconst int MODE_SATURATION = 15;\nconst int MODE_COLOR = 16;\n\nvec3 unpremultiply(vec4 color) {\n return color.a > 0.0 ? color.rgb / color.a : vec3(0.0);\n}\n\n// W3C separable blend B(Cb, Cs) for one channel (straight color in [0, 1]).\nfloat blendChannel(int mode, float cb, float cs) {\n if (mode == MODE_MULTIPLY) {\n return cb * cs;\n }\n if (mode == MODE_SCREEN) {\n return cb + cs - cb * cs;\n }\n if (mode == MODE_DARKEN) {\n return min(cb, cs);\n }\n if (mode == MODE_LIGHTEN) {\n return max(cb, cs);\n }\n if (mode == MODE_OVERLAY) {\n return cb <= 0.5 ? (2.0 * cb * cs) : (1.0 - 2.0 * (1.0 - cb) * (1.0 - cs));\n }\n if (mode == MODE_HARD_LIGHT) {\n return cs <= 0.5 ? (2.0 * cb * cs) : (1.0 - 2.0 * (1.0 - cb) * (1.0 - cs));\n }\n if (mode == MODE_COLOR_DODGE) {\n if (cb <= 0.0) {\n return 0.0;\n }\n return cs >= 1.0 ? 1.0 : min(1.0, cb / (1.0 - cs));\n }\n if (mode == MODE_COLOR_BURN) {\n if (cb >= 1.0) {\n return 1.0;\n }\n return cs <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - cb) / cs);\n }\n if (mode == MODE_SOFT_LIGHT) {\n if (cs <= 0.5) {\n return cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb);\n }\n float d = cb <= 0.25 ? (((16.0 * cb - 12.0) * cb + 4.0) * cb) : sqrt(cb);\n return cb + (2.0 * cs - 1.0) * (d - cb);\n }\n if (mode == MODE_DIFFERENCE) {\n return abs(cb - cs);\n }\n if (mode == MODE_EXCLUSION) {\n return cb + cs - 2.0 * cb * cs;\n }\n return min(cb, cs); // default: Darken\n}\n\nvec3 blendSeparable(int mode, vec3 cb, vec3 cs) {\n return vec3(blendChannel(mode, cb.r, cs.r), blendChannel(mode, cb.g, cs.g), blendChannel(mode, cb.b, cs.b));\n}\n\n// Non-separable helpers (W3C): operate on the whole color.\nfloat lum(vec3 c) {\n return dot(c, vec3(0.3, 0.59, 0.11));\n}\n\nvec3 clipColor(vec3 c) {\n float l = lum(c);\n float n = min(min(c.r, c.g), c.b);\n float x = max(max(c.r, c.g), c.b);\n\n if (n < 0.0) {\n c = l + ((c - l) * l) / (l - n);\n }\n if (x > 1.0) {\n c = l + ((c - l) * (1.0 - l)) / (x - l);\n }\n\n return c;\n}\n\nvec3 setLum(vec3 c, float l) {\n return clipColor(c + (l - lum(c)));\n}\n\nfloat sat(vec3 c) {\n return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b);\n}\n\n// Map the channels so min → 0, max → s, mid → proportional (W3C SetSat result).\nvec3 setSat(vec3 c, float s) {\n float mn = min(min(c.r, c.g), c.b);\n float mx = max(max(c.r, c.g), c.b);\n\n return mx > mn ? (c - mn) * (s / (mx - mn)) : vec3(0.0);\n}\n\nvec3 blendNonSeparable(int mode, vec3 cb, vec3 cs) {\n if (mode == MODE_HUE) {\n return setLum(setSat(cs, sat(cb)), lum(cb));\n }\n if (mode == MODE_SATURATION) {\n return setLum(setSat(cb, sat(cs)), lum(cb));\n }\n if (mode == MODE_COLOR) {\n return setLum(cs, lum(cb));\n }\n return setLum(cb, lum(cs)); // default: Luminosity\n}\n\nvec3 blendAdvanced(int mode, vec3 cb, vec3 cs) {\n return mode >= MODE_HUE ? blendNonSeparable(mode, cb, cs) : blendSeparable(mode, cb, cs);\n}\n\nvoid main(void) {\n vec4 src = texture(u_source, v_texcoord);\n // The backdrop is captured from the framebuffer (bottom-left origin), so its\n // V axis is flipped relative to the source/quad UVs.\n vec4 dst = texture(u_backdrop, vec2(v_texcoord.x, 1.0 - v_texcoord.y));\n\n float alphaSource = src.a;\n float alphaBackdrop = max(dst.a, u_opaqueBackdrop);\n vec3 colorSource = unpremultiply(src);\n vec3 colorBackdrop = unpremultiply(dst);\n\n vec3 blended = blendAdvanced(u_mode, colorBackdrop, colorSource);\n // Cs' = (1 - αb)·Cs + αb·B(Cb, Cs)\n vec3 mixedSource = mix(colorSource, blended, alphaBackdrop);\n\n // Premultiplied blended source; GPU source-over composites it over backdrop.\n fragColor = vec4(mixedSource * alphaSource, alphaSource);\n}\n");_vertexData=new ArrayBuffer(64);_float32View=new Float32Array(this._vertexData);_sourceSamplerSlot=new Int32Array([0]);_backdropSamplerSlot=new Int32Array([1]);_modeValue=new Int32Array([0]);_opaqueValue=new Float32Array([0]);_connection=null;connect(t){if(null!==this._connection)return;const i=t.context,n=i.createVertexArray();if(null===n)throw new Error("WebGl2BackdropBlendCompositor: could not create vertex array object.");this._shader.connect(ts(i));const r=new Map,s=new Hr(e.BufferTypes.ElementArrayBuffer,ho,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(i,r)),o=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,r));this._shader.sync();const a=(new ns).addIndex(s).addAttribute(o,this._shader.getAttribute("a_position"),i.FLOAT,!1,16,0).addAttribute(o,this._shader.getAttribute("a_texcoord"),i.FLOAT,!1,16,8).connect(this._createVaoRuntime(i,n));this._connection={gl:i,vaoHandle:n,vao:a,indexBuffer:s,vertexBuffer:o,bufferHandles:r}}disconnect(){const e=this._connection;null!==e&&(e.indexBuffer.destroy(),e.vertexBuffer.destroy(),e.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(e,t,i,n,r,s,o){if(null===this._connection)throw new Error("WebGl2BackdropBlendCompositor: not connected.");if(r<=0||s<=0)return;const a=e.context,h=e.renderTarget,l=h.root&&h.width>0?a.drawingBufferWidth/h.width:1,u=h.root&&h.height>0?a.drawingBufferHeight/h.height:1,c=Math.max(0,Math.floor(i*l)),d=Math.max(0,Math.floor(a.drawingBufferHeight-(n+s)*u)),_=e.acquireRenderTexture(r,s),f=Math.min(_.width,Math.max(0,Math.round(r*l))),p=Math.min(_.height,Math.max(0,Math.round(s*u))),m=h.root&&!a.getContextAttributes()?.alpha;try{a.bindFramebuffer(a.READ_FRAMEBUFFER,e._renderTargetFramebuffer(h)),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,e._renderTargetFramebuffer(_)),a.blitFramebuffer(c,d,c+f,d+p,0,0,f,p,a.COLOR_BUFFER_BIT,a.NEAREST),a.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,null),e._rebindActiveTarget(),this._drawBlend(e,t,_,i,n,r,s,o,m)}finally{e.releaseRenderTexture(_)}}_drawBlend(t,i,n,r,s,o,a,h,l){const u=this._connection;if(null===u)throw new Error("WebGl2BackdropBlendCompositor: not connected.");this._writeQuadVertices(r,s,r+o,s+a),t.bindShader(this._shader);const c=t.view.getTransform().toArray(!1);this._modeValue[0]=h,this._opaqueValue[0]=l?1:0,this._shader.getUniform("u_projection").setValue(c),this._shader.getUniform("u_source").setValue(this._sourceSamplerSlot),this._shader.getUniform("u_backdrop").setValue(this._backdropSamplerSlot),this._shader.getUniform("u_mode").setValue(this._modeValue),this._shader.getUniform("u_opaqueBackdrop").setValue(this._opaqueValue),this._shader.sync(),t.bindTexture(i,0),t.bindTexture(n,1),t.setBlendMode(e.BlendModes.Normal),t.bindVertexArrayObject(u.vao),u.vertexBuffer.upload(this._float32View),u.vao.draw(6,0),t.stats.batches++,t.stats.drawCalls++,t.bindTexture(null,1)}_writeQuadVertices(e,t,i,n){const r=this._float32View;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("WebGl2BackdropBlendCompositor: could not create render buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:n=>{const r=n.data;e.bindBuffer(n.type,i),e.bufferData(n.type,r,n.usage),t.set(n,i)},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}const uo=new Uint16Array([0,1,2,0,2,3]);class co{_shader=new Yr("#version 300 es\nprecision lowp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\n\nuniform mat3 u_projection;\n\nout vec2 v_texcoord;\n\nvoid main(void) {\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n}\n","#version 300 es\nprecision lowp float;\n\nuniform sampler2D u_content;\nuniform sampler2D u_mask;\n\nin vec2 v_texcoord;\n\nlayout(location = 0) out vec4 fragColor;\n\nvoid main(void) {\n vec4 contentColor = texture(u_content, v_texcoord);\n float maskAlpha = texture(u_mask, v_texcoord).a;\n\n fragColor = vec4(contentColor.rgb * maskAlpha, contentColor.a * maskAlpha);\n}\n");_vertexData=new ArrayBuffer(64);_float32View=new Float32Array(this._vertexData);_contentSamplerSlot=new Int32Array([0]);_maskSamplerSlot=new Int32Array([1]);_connection=null;connect(t){if(null!==this._connection)return;const i=t.context,n=i.createVertexArray();if(null===n)throw new Error("WebGl2MaskCompositor: could not create vertex array object.");this._shader.connect(ts(i));const r=new Map,s=new Hr(e.BufferTypes.ElementArrayBuffer,uo,e.BufferUsage.StaticDraw).connect(this._createBufferRuntime(i,r),t.accountant),o=new Hr(e.BufferTypes.ArrayBuffer,this._vertexData,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i,r),t.accountant);this._shader.sync();const a=(new ns).addIndex(s).addAttribute(o,this._shader.getAttribute("a_position"),i.FLOAT,!1,16,0).addAttribute(o,this._shader.getAttribute("a_texcoord"),i.FLOAT,!1,16,8).connect(this._createVaoRuntime(i,n));this._connection={gl:i,vaoHandle:n,vao:a,indexBuffer:s,vertexBuffer:o,bufferHandles:r}}disconnect(){const e=this._connection;null!==e&&(e.indexBuffer.destroy(),e.vertexBuffer.destroy(),e.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(e,t,i,n,r,s,o,a){const h=this._connection;if(null===h)throw new Error("WebGl2MaskCompositor: not connected.");this._writeQuadVertices(n,r,n+s,r+o),e.bindShader(this._shader);const l=e.view.getTransform().toArray(!1);this._shader.getUniform("u_projection").setValue(l),this._shader.getUniform("u_content").setValue(this._contentSamplerSlot),this._shader.getUniform("u_mask").setValue(this._maskSamplerSlot),this._shader.sync(),e.bindTexture(t,0),e.bindTexture(i,1),e.setBlendMode(a),e.bindVertexArrayObject(h.vao),h.vertexBuffer.upload(this._float32View),h.vao.draw(6,0),e.stats.batches++,e.stats.drawCalls++,e.bindTexture(null,1)}_writeQuadVertices(e,t,i,n){const r=this._float32View;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_createBufferRuntime(e,t){const i=e.createBuffer();if(null===i)throw new Error("WebGl2MaskCompositor: could not create render buffer.");return{bind:t=>{e.bindBuffer(t.type,i)},upload:n=>{const r=n.data;e.bindBuffer(n.type,i),e.bufferData(n.type,r,n.usage),t.set(n,i)},destroy:n=>{e.deleteBuffer(i),t.delete(n),n.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{t.indexBuffer?e.drawElements(r,i,e.UNSIGNED_SHORT,n):e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}class _o{_backend;_stencilEnabled=!1;constructor(e){this._backend=e}get activeTarget(){return this._backend.renderTarget}get activeView(){return this._backend.view}hasActivePass=!0;beginPass(e){this._backend.setRenderTarget(e.target),this._backend.setView(e.view),this._stencilEnabled=e.stencil===xi.Enabled,"clear"===e.load&&this._backend.clear(e.clearColor??void 0)}endPass(){this._backend.flush()}withChildPass(e,t){const i=this._backend.renderTarget,n=this._backend.view,r=this._stencilEnabled;this.beginPass(e);try{t()}finally{this._backend.setRenderTarget(i),this._backend.setView(n),this._stencilEnabled=r}}pushScissorRect(e){this._backend.pushScissorRect(e)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(e,t){this._backend.pushStencilClip(e,t)}popStencilClip(){this._backend.popStencilClip()}resolveLoad(e,t){return t?"clear":"load"}}const fo=new Set(["a_position","position"]);class po{_shader=new Yr("#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\n\nuniform mat3 u_matrix;\n\nvoid main(void) {\n gl_Position = vec4((u_matrix * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n}\n","#version 300 es\nprecision lowp float;\n\nlayout(location = 0) out vec4 fragColor;\n\n// Color writes are masked off while the stencil silhouette is drawn, so this\n// output is discarded; it exists only to make the program link.\nvoid main(void) {\n fragColor = vec4(0.0);\n}\n");_matrix=new At;_positions=new Float32Array(64);_connection=null;connect(t){if(null!==this._connection)return;const i=t.context,n=i.createVertexArray();if(null===n)throw new Error("WebGl2StencilClipper: could not create vertex array object.");this._shader.connect(ts(i)),this._shader.sync();const r=new Hr(e.BufferTypes.ArrayBuffer,this._positions,e.BufferUsage.DynamicDraw).connect(this._createBufferRuntime(i),t.accountant),s=new ns(e.RenderingPrimitives.Triangles).addAttribute(r,this._shader.getAttribute("a_position"),i.FLOAT,!1,8,0).connect(this._createVaoRuntime(i,n));this._connection={gl:i,vao:s,vertexBuffer:r}}disconnect(){const e=this._connection;null!==e&&(e.vertexBuffer.destroy(),e.vao.destroy(),this._shader.disconnect(),this._connection=null)}draw(t,i,n){const r=this._connection;if(null===r)throw new Error("WebGl2StencilClipper: not connected.");const s=this._extractPositions(i);if(0===s)return;this._matrix.copy(n).combine(t.view.getTransform()),t.bindShader(this._shader),this._shader.getUniform("u_matrix").setValue(this._matrix.toArray(!1)),this._shader.sync(),t.bindVertexArrayObject(r.vao),r.vertexBuffer.upload(this._positions.subarray(0,2*s));const o="triangle-strip"===i.topology?e.RenderingPrimitives.TriangleStrip:e.RenderingPrimitives.Triangles;r.vao.draw(s,0,o),t.stats.drawCalls++}_extractPositions(e){const t=this._resolvePositionAttribute(e.attributes);if("f32"!==t.type)throw new Error(`Stencil clipShape position attribute "${t.name}" must be of type f32 (got "${t.type}").`);const{stride:i,vertexData:n,indices:r}=e,s=n instanceof Float32Array?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),o=null!==r?r.length:e.vertexCount;this._ensureCapacity(o);const a=this._positions;for(let e=0;e<o;e++){const n=(null!==r?r[e]:e)*i+t.offset;a[2*e]=s.getFloat32(n,!0),a[2*e+1]=s.getFloat32(n+4,!0)}return o}_resolvePositionAttribute(e){const t=e.find(e=>fo.has(e.name));if(t)return t;const i=e.find(e=>e.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensureCapacity(e){const t=2*e;this._positions.length<t&&(this._positions=new Float32Array(Math.max(t,2*this._positions.length)))}_createBufferRuntime(e){const t=e.createBuffer();if(null===t)throw new Error("WebGl2StencilClipper: could not create render buffer.");return{bind:i=>{e.bindBuffer(i.type,t)},upload:i=>{e.bindBuffer(i.type,t),e.bufferData(i.type,i.data,i.usage)},destroy:i=>{e.deleteBuffer(t),i.disconnect()}}}_createVaoRuntime(e,t){let i=-1;return{bind:n=>{if(e.bindVertexArray(t),i!==n.version){let t=null;for(const i of n.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),e.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),e.enableVertexAttribArray(i.location);i=n.version}},unbind:()=>{e.bindVertexArray(null)},draw:(t,i,n,r)=>{e.drawArrays(r,n,i)},destroy:i=>{e.deleteVertexArray(t),i.disconnect()}}}}class mo{backendType=e.RenderBackendType.WebGl2;rendererRegistry=new ro;onContextLost=new x;onContextRestored=new x;_context;_rootRenderTarget;_onContextLostHandler;_onContextRestoredHandler;_textureStates=new Map;_renderTargetStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_clipBoundsStack=[];_clipPixelStack=[];_clipPointA=new it;_clipPointB=new it;_maskCompositor=new co;_maskCompositorConnected=!1;_backdropBlendCompositor=new lo;_backdropBlendCompositorConnected=!1;_stencilClipper=new po;_stencilStates=new Map;_stencilClipperConnected=!1;_passCoordinatorInstance=null;_canvas;_contextLost;_renderTarget;_snapTransform=new At;_renderer=null;_shader=null;_blendMode=null;_texture=null;_textureUnit=0;_vao=null;_clearColor=new Tt;_boundFramebuffer=null;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0,rawFrameDeltaMs:0,gpuMemoryBytes:0,textureUploadBytes:0,bufferUploadBytes:0,downloadBytes:0,downloadCount:0};_accountant=new Js(this._stats);_transformBuffer=new ao;_transformTexture=null;_transformTextureHash=0;_transformTextureCount=-1;_activeDrawCommand=null;_drawPlanDepth=0;_planBaseStack=[];_planHashStack=[];constructor(t){const i=t.options.canvas??{},n=t.options.rendering??{},r=i.width??800,s=i.height??600,o=t.options.clearColor,a=n.webglAttributes;n.debug,this._canvas=t.canvas;const h=this._createContext(a);if(!h)throw new Error("This browser or hardware does not support WebGL.");this._context=h,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),o&&this.clearColor.copy(o),this._rootRenderTarget=new di(r,s,!0),this._renderTarget=this._rootRenderTarget,this._onContextLostHandler=this._onContextLost.bind(this),this._onContextRestoredHandler=this._onContextRestored.bind(this),this._setupContext(),this._addEvents(),this.rendererRegistry.connect(this),this._bindRenderTarget(this._renderTarget),this.setBlendMode(e.BlendModes.Normal),this.resize(r,s)}get context(){return this._context}get renderTarget(){return this._renderTarget}get view(){return this._renderTarget.view}get clearColor(){return this._clearColor}get stats(){return this._stats}get accountant(){return this._accountant}get activeDrawCommand(){return this._activeDrawCommand}get _passCoordinator(){return this._passCoordinatorInstance??=new _o(this)}async initialize(){return this}resetStats(){return Qs(this._stats),this._transformBuffer.begin(),this}get transformBufferCount(){return this._transformBuffer.count}_beginDrawPlan(e){this._planBaseStack.push(this._transformBuffer.count),this._planHashStack.push(this._transformBuffer.frameHash),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(e,t,i){const n=t+i;for(let i=t;i<n;i++){const t=e[i];if(t.kind!==Yt.Draw)continue;const n=t.command;ii(n,this)?this._writeTransformCommand(n):this._transformBuffer.recordSkippedWrite()}}_prepareDrawCommand(e){this._activeDrawCommand=e}_writeTransformCommand(e){const t=e.drawable;this._transformBuffer.write(e.nodeIndex,this._resolveSnapTransform(t),t.tint)}_resolveSnapTransform(e){const t=this._renderTarget,i=t.root?this._canvas.width:t.width,n=t.root?this._canvas.height:t.height;return Rn(e,t.view,i,n,this._snapTransform)}_getSnapPixelSize(){const e=this._renderTarget;return{width:e.root?this._canvas.width:e.width,height:e.root?this._canvas.height:e.height}}_pushTransform(e){return this._transformBuffer.push(this._resolveSnapTransform(e),e.tint)}_endDrawPlan(){this._activeDrawCommand=null;const e=this._planBaseStack.pop()??0,t=this._planHashStack.pop()??0;this._drawPlanDepth>0&&this._drawPlanDepth--,this._drawPlanDepth>0&&(this._flushActiveRenderer(),this._transformBuffer.rewindTo(e,t)),0===this._drawPlanDepth&&this._assertBalancedStencil()}_assertBalancedStencil(){let e=0;for(const t of this._stencilStates.values())e+=t.stack.length;if(0===e)return;for(const e of this._stencilStates.values())e.depth=0,e.stack.length=0;const t=this._context;throw t.stencilFunc(t.ALWAYS,0,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.disable(t.STENCIL_TEST),new Error(`Unbalanced stencil clip stack at end of frame (${e} unpopped clip(s)).`)}draw(e){const t=this.rendererRegistry.resolve(e);return this._setActiveRenderer(t),t.render(e),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(e,t,i,n){if(n<=0||0===e.vertexCount)return this;if(t.length<n||i.length<n)throw new Error(`drawInstanced requires ${n} transforms and tints (got ${t.length}/${i.length}).`);const r=this.rendererRegistry.resolve(e);if(!(r instanceof ss))throw new Error("drawInstanced requires a mesh handled by the WebGL2 mesh renderer.");this._setActiveRenderer(r);const s=this._transformBuffer.push(t[0],i[0]);for(let e=1;e<n;e++)this._transformBuffer.push(t[e],i[e]);return r.drawInstancedBatch(e,s,n),this._activeDrawCommand=null,this._stats.submittedNodes+=n,this}execute(e){return this._flushActiveRenderer(),this._stats.renderPasses++,e.execute(this),this}setRenderTarget(e){const t=e||this._rootRenderTarget,i=this._renderTarget!==t;return i&&(this._flushActiveRenderer(),this._renderTarget=t,this._stats.renderTargetChanges++),this._bindRenderTarget(t),i&&this._applyStencilState(t),this}pushScissorRect(e){this._flushActiveRenderer(),this._clipBoundsStack.push(e.clone());const t=this._toClipPixels(e),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,n=i?this._intersectClips(i,t):t;return this._clipPixelStack.push(n),this._applyClipState(),this}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const e=this._clipBoundsStack.pop();return e&&e.destroy(),this._clipPixelStack.pop(),this._applyClipState(),this}pushStencilClip(e,t){const i=this._renderTarget,n=this._getStencilState(i);if(n.depth>=255)throw new Error("Stencil clip nesting exceeds the 255-level limit.");this._flushActiveRenderer(),this._setActiveRenderer(null),this._stencilClipperConnected||(this._stencilClipper.connect(this),this._stencilClipperConnected=!0);const r=this._context,s=n.depth;return 0===s&&(this._ensureTargetStencil(),r.enable(r.STENCIL_TEST),r.disable(r.SCISSOR_TEST),r.clearStencil(0),r.clear(r.STENCIL_BUFFER_BIT),this._applyClipState()),r.colorMask(!1,!1,!1,!1),r.stencilFunc(r.EQUAL,s,255),r.stencilOp(r.KEEP,r.KEEP,r.INCR),this._stencilClipper.draw(this,e,t),r.colorMask(!0,!0,!0,!0),n.depth=s+1,n.stack.push({shape:e,transform:(new At).copy(t)}),r.stencilFunc(r.EQUAL,n.depth,255),r.stencilOp(r.KEEP,r.KEEP,r.KEEP),this}popStencilClip(){const e=this._renderTarget,t=this._getStencilState(e),i=t.stack.pop();if(void 0===i)return this;this._flushActiveRenderer(),this._setActiveRenderer(null);const n=this._context,r=t.depth;return n.colorMask(!1,!1,!1,!1),n.stencilFunc(n.EQUAL,r,255),n.stencilOp(n.KEEP,n.KEEP,n.DECR),this._stencilClipper.draw(this,i.shape,i.transform),n.colorMask(!0,!0,!0,!0),t.depth=r-1,this._applyStencilState(e),this}composeWithAlphaMask(e,t,i,n,r,s,o){return r<=0||s<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._maskCompositorConnected||(this._maskCompositor.connect(this),this._maskCompositorConnected=!0),this._maskCompositor.compose(this,e,t,i,n,r,s,o)),this}composeWithBackdropBlend(e,t,i,n,r,s){return n<=0||r<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._backdropBlendCompositorConnected||(this._backdropBlendCompositor.connect(this),this._backdropBlendCompositorConnected=!0),this._backdropBlendCompositor.compose(this,e,t,i,n,r,s)),this}_renderTargetFramebuffer(e){return this._prepareRenderTarget(e).framebuffer}_rebindActiveTarget(){this._bindRenderTarget(this._renderTarget)}acquireRenderTexture(e,t){for(let i=0;i<this._temporaryRenderTextures.length;i++){const n=this._temporaryRenderTextures[i];if(n.width===e&&n.height===t)return this._temporaryRenderTextures.splice(i,1),n}return new _i(e,t)}releaseRenderTexture(e){return this._temporaryRenderTextures.includes(e)||(e.setView(null),this._temporaryRenderTextures.push(e)),this}setView(e){return this._renderTarget.view!==e&&this._flushActiveRenderer(),this._renderTarget.setView(e),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(e){return this._vao!==e&&(e?e.bind():this._vao?.unbind(),this._vao=e),this}bindShader(e){return this._shader!==e&&(this._shader&&(this._shader.unbind(),this._shader=null),e&&e.bind(),this._shader=e),this}bindTexture(e,t){if(void 0!==t&&this._setTextureUnit(t),null===e)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(e);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=e,this}setActiveTextureUnit(e){return this._setTextureUnit(e),this}bindTransformBufferTexture(e,t){const i=Math.max(1,t),n=this._transformTexture;n?.height===this._transformBuffer.capacity&&n.buffer===this._transformBuffer.data||(n?.destroy(),this._transformTexture=new Rr({width:3,height:this._transformBuffer.capacity,format:"rgba32f",data:this._transformBuffer.data}),this._transformTextureHash=0,this._transformTextureCount=-1);const r=this._transformBuffer.commitSnapshot(i),s=this._transformTexture;if(null===s)throw new Error("Transform texture must be initialized before binding.");if(r.changed||r.count!==this._transformTextureCount||r.hash!==this._transformTextureHash){const{firstRow:e,rowCount:t}=this._transformBuffer.consumeDirtyRange(r.count);t>0&&(s.commitRect(0,e,3,t),this._transformBuffer.recordUpload(t)),this._transformTextureCount=r.count,this._transformTextureHash=r.hash}return this.bindTexture(s,e)}setBlendMode(t){if(t!==this._blendMode){const i=this._context;switch(this._blendMode=t,t){case e.BlendModes.Additive:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ONE);break;case e.BlendModes.Subtract:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ZERO,i.ONE_MINUS_SRC_COLOR);break;case e.BlendModes.Multiply:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA);break;case e.BlendModes.Screen:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_COLOR);break;default:i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(e){if(this._textureUnit!==e){const t=this._context;this._textureUnit=e,t.activeTexture(t.TEXTURE0+e)}}setClearColor(e){if(!this._clearColor.equals(e)){const t=this._context;this._clearColor.copy(e),t.clearColor(e.r/255,e.g/255,e.b/255,e.a)}return this}clear(e){const t=this._context;return e&&this.setClearColor(e),this._bindRenderTarget(this._renderTarget),t.clear(t.COLOR_BUFFER_BIT),this}resize(e,t){return this._rootRenderTarget.resize(e,t),this._bindRenderTarget(this._renderTarget),this}flush(){return this._flushActiveRenderer(),this}destroy(){this._removeEvents(),this.onContextLost.destroy(),this.onContextRestored.destroy(),this.setRenderTarget(null),this._setActiveRenderer(null),this.bindVertexArrayObject(null),this.bindShader(null),this.bindTexture(null),this.rendererRegistry.destroy(),this._clearColor.destroy(),this._destroyManagedResources(),this._destroyTemporaryRenderTextures();for(const e of this._clipBoundsStack)e.destroy();this._clipBoundsStack.length=0,this._clipPixelStack.length=0,this._clipPointA.destroy(),this._clipPointB.destroy(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._backdropBlendCompositorConnected&&(this._backdropBlendCompositor.disconnect(),this._backdropBlendCompositorConnected=!1),this._stencilClipperConnected&&(this._stencilClipper.disconnect(),this._stencilClipperConnected=!1),this._stencilStates.clear(),this._drawPlanDepth=0,this._rootRenderTarget.destroy(),null!==this._transformTexture&&(this._transformTexture.destroy(),this._transformTexture=null),this._vao=null,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._boundFramebuffer=null,this._activeDrawCommand=null,this._transformTextureCount=-1,this._transformTextureHash=0}_createContext(e){try{return this._canvas.getContext("webgl2",{...e,stencil:!0})}catch(e){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const e=this._context,{r:t,g:i,b:n,a:r}=this._clearColor;e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.CULL_FACE),e.enable(e.BLEND),e.blendEquation(e.FUNC_ADD),e.clearColor(t/255,i/255,n/255,r)}_addEvents(){this._canvas.addEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.addEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_removeEvents(){this._canvas.removeEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_onContextLost(){this._contextLost=!0,this.onContextLost.dispatch(),this._restoreContext()}_onContextRestored(){this._contextLost=!1,this.onContextRestored.dispatch()}_createFramebuffer(){const e=this._context.createFramebuffer();if(null===e)throw new Error("Could not create framebuffer.");return e}_createTextureHandle(){const e=this._context.createTexture();if(null===e)throw new Error("Could not create texture.");return e}_bookTextureStorage(e,t,i){const n=eo(t.width,t.height,i,this._textureMipLevelCount(t));e.accountedBytes=this._accountant.reallocate(e.accountedBytes,n)}_textureMipLevelCount(e){if(!e.generateMipMap)return 1;const t=Math.max(e.width,e.height);return t<=1?1:Math.floor(Math.log2(t))+1}_destroyManagedResources(){for(const e of[...this._renderTargetStates.keys()])this._evictRenderTarget(e,!1);for(const e of[...this._textureStates.keys()])this._evictTexture(e,!1)}_destroyTemporaryRenderTextures(){for(const e of this._temporaryRenderTextures)e.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(e){let t=this._renderTargetStates.get(e);return t||(this._subscribeToDestroy(e,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(e,!0)}),t={framebuffer:e.root?null:this._createFramebuffer(),version:-1,attachedTexture:null,stencilRenderbuffer:null,stencilWidth:0,stencilHeight:0},this._renderTargetStates.set(e,t)),t}_getTextureState(e){let t=this._textureStates.get(e);return t||(this._subscribeToDestroy(e,this._textureDestroyHandlers,()=>{this._evictTexture(e,!0)}),t={handle:this._createTextureHandle(),version:-1,width:0,height:0,accountedBytes:0},this._textureStates.set(e,t)),t}_subscribeToDestroy(e,t,i){t.has(e)||(e.addDestroyListener(i),t.set(e,i))}_unsubscribeFromDestroy(e,t){const i=t.get(e);i&&(e.removeDestroyListener(i),t.delete(e))}_evictRenderTarget(e,t){const i=this._renderTargetStates.get(e);this._unsubscribeFromDestroy(e,this._renderTargetDestroyHandlers),e instanceof _i&&this._evictTexture(e,!1),i&&(this._boundFramebuffer===i.framebuffer&&(this._context.bindFramebuffer(this._context.FRAMEBUFFER,null),this._boundFramebuffer=null),null!==i.framebuffer&&this._context.deleteFramebuffer(i.framebuffer),null!==i.stencilRenderbuffer&&(this._context.deleteRenderbuffer(i.stencilRenderbuffer),i.stencilRenderbuffer=null),this._renderTargetStates.delete(e)),this._stencilStates.delete(e),this._renderTarget===e&&(this._renderTarget=this._rootRenderTarget,t&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(e,t){const i=this._textureStates.get(e);this._unsubscribeFromDestroy(e,this._textureDestroyHandlers),i&&(this._texture===e&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this._context.deleteTexture(i.handle),this._accountant.free(i.accountedBytes),i.accountedBytes=0,this._textureStates.delete(e)),this._texture===e&&(this._texture=null),t&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(e){const t=this._prepareRenderTarget(e);if(this._boundFramebuffer!==t.framebuffer||t.version!==e.version){const i=this._context,n=e.getViewport(),r=e.root&&e.width>0?this._canvas.width/e.width:1,s=e.root&&e.height>0?this._canvas.height/e.height:1,o=Math.floor(n.x*r),a=Math.max(0,Math.round(n.width*r)),h=Math.max(0,Math.round(n.height*s)),l=(e.root?this._canvas.height:e.height)-(Math.floor(n.y*s)+h);i.bindFramebuffer(i.FRAMEBUFFER,t.framebuffer),i.viewport(o,l,a,h),this._boundFramebuffer=t.framebuffer,t.version=e.version}this._clipPixelStack.length>0&&this._applyClipState()}_setActiveRenderer(e){this._renderer!==e&&(this._flushActiveRenderer(),this._renderer=e)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(e){const t=this._getRenderTargetState(e);if(e instanceof _i&&t.framebuffer){const i=this._boundFramebuffer,n=this._textureUnit;this._setTextureUnit(15);const r=this._syncTexture(e);if(this._setTextureUnit(n),t.attachedTexture!==r.handle){const e=this._context;e.bindFramebuffer(e.FRAMEBUFFER,t.framebuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r.handle,0),e.bindFramebuffer(e.FRAMEBUFFER,i),t.attachedTexture=r.handle}this._stencilStates.has(e)||(e.needsStencil=!1),(e.needsStencil||null!==t.stencilRenderbuffer)&&this._syncStencilAttachment(e,t)}return t}_ensureTargetStencil(){const e=this._renderTarget;e.root||(e.needsStencil=!0,this._syncStencilAttachment(e,this._getRenderTargetState(e)))}_syncStencilAttachment(e,t){if(null===t.framebuffer)return;const i=this._context,n=Math.max(1,e.width),r=Math.max(1,e.height);if(null!==t.stencilRenderbuffer&&t.stencilWidth===n&&t.stencilHeight===r)return;null===t.stencilRenderbuffer&&(t.stencilRenderbuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,t.stencilRenderbuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH24_STENCIL8,n,r),i.bindRenderbuffer(i.RENDERBUFFER,null);const s=this._boundFramebuffer;i.bindFramebuffer(i.FRAMEBUFFER,t.framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,t.stencilRenderbuffer),i.bindFramebuffer(i.FRAMEBUFFER,s),t.stencilWidth=n,t.stencilHeight=r}_getStencilState(e){let t=this._stencilStates.get(e);return void 0===t&&(t={depth:0,stack:[]},this._stencilStates.set(e,t)),t}_applyStencilState(e){const t=this._context,i=this._getStencilState(e).depth;if(0===i)return t.stencilFunc(t.ALWAYS,0,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),void t.disable(t.STENCIL_TEST);t.enable(t.STENCIL_TEST),t.stencilFunc(t.EQUAL,i,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}_syncTexture(e){const t=this._context,i=this._getTextureState(e),n=e instanceof _i?e.textureVersion:e.version;if(t.bindTexture(t.TEXTURE_2D,i.handle),i.version!==n){if(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,e.scaleMode),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,e.scaleMode),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,e.wrapMode),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,e.wrapMode),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),e instanceof Rr){const n=e.format,r=function(e){const t=WebGL2RenderingContext;switch(e){case"r8":return{internalFormat:t.R8,format:t.RED,type:t.UNSIGNED_BYTE,channels:1};case"r32f":return{internalFormat:t.R32F,format:t.RED,type:t.FLOAT,channels:1};case"rgba8":return{internalFormat:t.RGBA8,format:t.RGBA,type:t.UNSIGNED_BYTE,channels:4};case"rgba32f":return{internalFormat:t.RGBA32F,format:t.RGBA,type:t.FLOAT,channels:4}}}(n),s=e._consumeDirtyRegion(),o=-1===i.version||i.width!==e.width||i.height!==e.height;t.pixelStorei(t.UNPACK_ALIGNMENT,1);const a=to(n);if(o||null===s||s.full)t.texImage2D(t.TEXTURE_2D,0,r.internalFormat,e.width,e.height,0,r.format,r.type,e.buffer),this._bookTextureStorage(i,e,a),this._accountant.recordTextureUpload(e.width*e.height*a);else{const i=r.channels,n=e.width*i,o=s.width*i,h=e.buffer instanceof Float32Array?new Float32Array(s.width*s.height*i):new Uint8Array(s.width*s.height*i);for(let t=0;t<s.height;t++){const r=(s.y+t)*n+s.x*i,a=t*o;h.set(e.buffer.subarray(r,r+o),a)}t.texSubImage2D(t.TEXTURE_2D,0,s.x,s.y,s.width,s.height,r.format,r.type,h),this._accountant.recordTextureUpload(s.width*s.height*a)}t.pixelStorei(t.UNPACK_ALIGNMENT,4)}else e instanceof _i?-1===i.version||i.width!==e.width||i.height!==e.height||null===e.source?(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,e.source),this._bookTextureStorage(i,e,go),this._accountant.recordTextureUpload(e.width*e.height*go)):(t.texSubImage2D(t.TEXTURE_2D,0,0,0,e.width,e.height,t.RGBA,t.UNSIGNED_BYTE,e.source),this._accountant.recordTextureUpload(e.width*e.height*go)):e.source&&(-1===i.version||i.width!==e.width||i.height!==e.height?(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e.source),this._bookTextureStorage(i,e,go)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,e.source),this._accountant.recordTextureUpload(e.width*e.height*go));e.generateMipMap&&(e instanceof _i||null!==e.source)&&t.generateMipmap(t.TEXTURE_2D),i.version=n,i.width=e.width,i.height=e.height}return i}_toClipPixels(e){const t=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(e.left,e.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(e.right,e.bottom)),n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),s=Math.min(t.y,i.y),o=Math.max(t.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(n))),u=Math.max(0,Math.min(a,Math.ceil(r))),c=Math.max(0,Math.min(h,Math.floor(s))),d=Math.max(0,Math.min(h,Math.ceil(o))),_=Math.max(0,u-l),f=Math.max(0,d-c);return{x:l,y:Math.max(0,h-d),width:_,height:f}}_intersectClips(e,t){const i=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.width,t.x+t.width),s=Math.min(e.y+e.height,t.y+t.height);return{x:i,y:n,width:Math.max(0,r-i),height:Math.max(0,s-n)}}_applyClipState(){const e=this._context;if(0===this._clipPixelStack.length)return void e.disable(e.SCISSOR_TEST);const t=this._clipPixelStack[this._clipPixelStack.length-1],i=this._renderTarget.root&&this._renderTarget.width>0?this._canvas.width/this._renderTarget.width:1,n=this._renderTarget.root&&this._renderTarget.height>0?this._canvas.height/this._renderTarget.height:1,r=Math.floor(t.x*i),s=Math.floor(t.y*n),o=Math.max(0,Math.round(t.width*i)),a=Math.max(0,Math.round(t.height*n));e.enable(e.SCISSOR_TEST),e.scissor(r,s,o,a)}}const go=4;class yo{_projectionData=new Float32Array(16);_vertexData=new Float32Array(16);_indexData=new Uint16Array([0,1,2,0,2,3]);_blendData=new ArrayBuffer(16);_blendModeView=new Uint32Array(this._blendData,0,1);_blendOpaqueView=new Float32Array(this._blendData,4,1);_projectionMatrix=new At;_pipelines=new Map;_device=null;_shaderModule=null;_projectionBindGroupLayout=null;_textureBindGroupLayout=null;_blendBindGroupLayout=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_projectionBuffer=null;_blendBuffer=null;_projectionBindGroup=null;_blendBindGroup=null;_backdropSampler=null;_backdropTexture=null;_backdropView=null;_backdropWidth=0;_backdropHeight=0;_backdropFormat=null;connect(e){null===this._device&&(this._device=e,this._shaderModule=e.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\nstruct BlendUniforms {\n mode: u32,\n opaqueBackdrop: f32,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(1) @binding(1)\nvar sourceSampler: sampler;\n@group(1) @binding(2)\nvar backdropTexture: texture_2d<f32>;\n@group(1) @binding(3)\nvar backdropSampler: sampler;\n\n@group(2) @binding(0)\nvar<uniform> blend: BlendUniforms;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n\n return output;\n}\n\nfn unpremultiply(color: vec4<f32>) -> vec3<f32> {\n if (color.a > 0.0) {\n return color.rgb / color.a;\n }\n\n return vec3<f32>(0.0);\n}\n\n// W3C separable blend B(Cb, Cs) for one channel (straight color in [0, 1]).\n// Mode values match the BlendModes enum (src/rendering/types.ts).\nfn blendChannel(mode: u32, cb: f32, cs: f32) -> f32 {\n switch mode {\n case 3u { return cb * cs; } // Multiply\n case 4u { return cb + cs - cb * cs; } // Screen\n case 5u { return min(cb, cs); } // Darken\n case 6u { return max(cb, cs); } // Lighten\n case 7u { return select(1.0 - 2.0 * (1.0 - cb) * (1.0 - cs), 2.0 * cb * cs, cb <= 0.5); } // Overlay\n case 8u { // ColorDodge\n if (cb <= 0.0) { return 0.0; }\n return select(min(1.0, cb / (1.0 - cs)), 1.0, cs >= 1.0);\n }\n case 9u { // ColorBurn\n if (cb >= 1.0) { return 1.0; }\n return select(1.0 - min(1.0, (1.0 - cb) / cs), 0.0, cs <= 0.0);\n }\n case 10u { return select(1.0 - 2.0 * (1.0 - cb) * (1.0 - cs), 2.0 * cb * cs, cs <= 0.5); } // HardLight\n case 11u { // SoftLight\n if (cs <= 0.5) { return cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb); }\n let d = select(sqrt(cb), ((16.0 * cb - 12.0) * cb + 4.0) * cb, cb <= 0.25);\n return cb + (2.0 * cs - 1.0) * (d - cb);\n }\n case 12u { return abs(cb - cs); } // Difference\n case 13u { return cb + cs - 2.0 * cb * cs; } // Exclusion\n default { return min(cb, cs); } // Darken\n }\n}\n\nfn blendSeparable(mode: u32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {\n return vec3<f32>(blendChannel(mode, cb.x, cs.x), blendChannel(mode, cb.y, cs.y), blendChannel(mode, cb.z, cs.z));\n}\n\n// Non-separable helpers (W3C): operate on the whole color.\nfn lum(c: vec3<f32>) -> f32 {\n return dot(c, vec3<f32>(0.3, 0.59, 0.11));\n}\n\nfn clipColor(input: vec3<f32>) -> vec3<f32> {\n var c = input;\n let l = lum(c);\n let n = min(min(c.x, c.y), c.z);\n let x = max(max(c.x, c.y), c.z);\n\n if (n < 0.0) { c = l + ((c - l) * l) / (l - n); }\n if (x > 1.0) { c = l + ((c - l) * (1.0 - l)) / (x - l); }\n\n return c;\n}\n\nfn setLum(c: vec3<f32>, l: f32) -> vec3<f32> {\n return clipColor(c + (l - lum(c)));\n}\n\nfn sat(c: vec3<f32>) -> f32 {\n return max(max(c.x, c.y), c.z) - min(min(c.x, c.y), c.z);\n}\n\n// Map the channels so min -> 0, max -> s, mid -> proportional (W3C SetSat result).\nfn setSat(c: vec3<f32>, s: f32) -> vec3<f32> {\n let mn = min(min(c.x, c.y), c.z);\n let mx = max(max(c.x, c.y), c.z);\n\n return select(vec3<f32>(0.0), (c - mn) * (s / (mx - mn)), mx > mn);\n}\n\nfn blendNonSeparable(mode: u32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {\n switch mode {\n case 14u { return setLum(setSat(cs, sat(cb)), lum(cb)); } // Hue\n case 15u { return setLum(setSat(cb, sat(cs)), lum(cb)); } // Saturation\n case 16u { return setLum(cs, lum(cb)); } // Color\n default { return setLum(cb, lum(cs)); } // Luminosity\n }\n}\n\nfn blendAdvanced(mode: u32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {\n if (mode >= 14u) { return blendNonSeparable(mode, cb, cs); }\n return blendSeparable(mode, cb, cs);\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let src = textureSample(sourceTexture, sourceSampler, input.texcoord);\n // copyTextureToTexture preserves the target's top-left orientation, so the\n // backdrop is sampled at the same UV as the quad — no V-flip (unlike the\n // WebGL2 framebuffer-blit path, which reads bottom-left order).\n let dst = textureSample(backdropTexture, backdropSampler, input.texcoord);\n\n let alphaSource = src.a;\n // An opaque target (the on-screen root canvas, alphaMode 'opaque') has an\n // unreliable captured alpha; force full backdrop coverage so the blend is\n // not skipped. Offscreen RenderTextures carry real alpha.\n let alphaBackdrop = max(dst.a, blend.opaqueBackdrop);\n let colorSource = unpremultiply(src);\n let colorBackdrop = unpremultiply(dst);\n\n let blended = blendAdvanced(blend.mode, colorBackdrop, colorSource);\n // Cs' = (1 - αb)·Cs + αb·B(Cb, Cs)\n let mixedSource = mix(colorSource, blended, alphaBackdrop);\n\n // Premultiplied blended source; the GPU source-over composites it over the\n // untouched backdrop already in the target (αs = 0 passes the backdrop through).\n return vec4<f32>(mixedSource * alphaSource, alphaSource);\n}\n"}),this._projectionBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this._blendBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this._pipelineLayout=e.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout,this._blendBindGroupLayout]}),this._vertexBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=e.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._blendBuffer=e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._backdropSampler=e.createSampler({magFilter:"nearest",minFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this._projectionBindGroup=e.createBindGroup({layout:this._projectionBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projectionBuffer}}]}),this._blendBindGroup=e.createBindGroup({layout:this._blendBindGroupLayout,entries:[{binding:0,resource:{buffer:this._blendBuffer}}]}))}disconnect(){null!==this._device&&(this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._projectionBuffer?.destroy(),this._blendBuffer?.destroy(),this._backdropTexture?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._projectionBuffer=null,this._blendBuffer=null,this._backdropTexture=null,this._backdropView=null,this._backdropWidth=0,this._backdropHeight=0,this._backdropFormat=null,this._backdropSampler=null,this._projectionBindGroup=null,this._blendBindGroup=null,this._pipelineLayout=null,this._blendBindGroupLayout=null,this._textureBindGroupLayout=null,this._projectionBindGroupLayout=null,this._shaderModule=null,this._pipelines.clear(),this._device=null)}compose(e,t,i,n,r,s,o){if(null===this._device)throw new Error("WebGpuBackdropBlendCompositor: not connected.");if(r<=0||s<=0)return;const a=this._device,h=e.renderTarget;e.flush();const l=e.renderTargetFormat,u=e._getAttachmentPixelSize(h),c=h.root&&h.width>0?u.width/h.width:1,d=h.root&&h.height>0?u.height/h.height:1,_=Math.max(0,Math.floor(i*c)),f=Math.max(0,Math.floor(n*d)),p=Math.max(0,Math.min(Math.round(r*c),u.width-_)),m=Math.max(0,Math.min(Math.round(s*d),u.height-f));if(p<=0||m<=0)return;const g=this._ensureBackdrop(a,p,m,l),y=a.createCommandEncoder();y.copyTextureToTexture({texture:e._renderTargetTexture(h),origin:{x:_,y:f,z:0}},{texture:this._backdropTexture,origin:{x:0,y:0,z:0}},{width:p,height:m,depthOrArrayLayers:1}),a.queue.submit([y.finish()]),this._drawBlend(e,t,g,i,n,r,s,o,h.root)}_ensureBackdrop(e,t,i,n){return null!==this._backdropTexture&&this._backdropWidth===t&&this._backdropHeight===i&&this._backdropFormat===n||(this._backdropTexture?.destroy(),this._backdropTexture=e.createTexture({size:{width:t,height:i},format:n,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this._backdropView=this._backdropTexture.createView(),this._backdropWidth=t,this._backdropHeight=i,this._backdropFormat=n),this._backdropView}_drawBlend(e,t,i,n,r,s,o,a,h){const l=this._device;this._writeQuadVertices(n,r,n+s,r+o),l.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(e.view.getTransform()),l.queue.writeBuffer(this._projectionBuffer,0,this._projectionData),this._blendModeView[0]=a,this._blendOpaqueView[0]=h?1:0,l.queue.writeBuffer(this._blendBuffer,0,this._blendData);const u=e.getTextureBinding(t),c=l.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:u.view},{binding:1,resource:u.sampler},{binding:2,resource:i},{binding:3,resource:this._backdropSampler}]}),d=e.renderTargetFormat,_=e._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,_),p=e._passCoordinator.acquirePass().pass;p.setPipeline(f),p.setBindGroup(0,this._projectionBindGroup),p.setBindGroup(1,c),p.setBindGroup(2,this._blendBindGroup),p.setVertexBuffer(0,this._vertexBuffer),p.setIndexBuffer(this._indexBuffer,"uint16"),p.drawIndexed(6),e.stats.batches++,e.stats.drawCalls++,e._passCoordinator.endPass()}_getOrCreatePipeline(t,i){const n=`${t}|${i?"s":"n"}`,r=this._pipelines.get(n);if(void 0!==r)return r;const s=this._device,o={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t,blend:Ss(e.BlendModes.Normal)}]},primitive:{topology:"triangle-list"}};i&&(o.depthStencil=Ps());const a=s.createRenderPipeline(o);return this._pipelines.set(n,a),a}_writeQuadVertices(e,t,i,n){const r=this._vertexData;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_writeProjectionMatrix(e){const t=this._projectionMatrix.copy(e),i=this._projectionData;i[0]=t.a,i[1]=t.c,i[2]=0,i[3]=0,i[4]=t.b,i[5]=t.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=0,i[15]=1}}class wo{_projectionData=new Float32Array(16);_vertexData=new Float32Array(16);_indexData=new Uint16Array([0,1,2,0,2,3]);_projectionMatrix=new At;_pipelines=new Map;_device=null;_shaderModule=null;_projectionBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_projectionBuffer=null;_projectionBindGroup=null;connect(e){null===this._device&&(this._device=e,this._shaderModule=e.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar contentTexture: texture_2d<f32>;\n@group(1) @binding(1)\nvar contentSampler: sampler;\n@group(1) @binding(2)\nvar maskTexture: texture_2d<f32>;\n@group(1) @binding(3)\nvar maskSampler: sampler;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let contentColor = textureSample(contentTexture, contentSampler, input.texcoord);\n let maskAlpha = textureSample(maskTexture, maskSampler, input.texcoord).a;\n\n return vec4<f32>(contentColor.rgb * maskAlpha, contentColor.a * maskAlpha);\n}\n"}),this._projectionBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:3,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),this._pipelineLayout=e.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout]}),this._vertexBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=e.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._projectionBindGroup=e.createBindGroup({layout:this._projectionBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projectionBuffer}}]}))}disconnect(){null!==this._device&&(this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._projectionBuffer?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._projectionBuffer=null,this._projectionBindGroup=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._projectionBindGroupLayout=null,this._shaderModule=null,this._pipelines.clear(),this._device=null)}compose(e,t,i,n,r,s,o,a){if(null===this._device)throw new Error("WebGpuMaskCompositor: not connected.");if(s<=0||o<=0)return;const h=this._device;this._writeQuadVertices(n,r,n+s,r+o),h.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(e.view.getTransform()),h.queue.writeBuffer(this._projectionBuffer,0,this._projectionData);const l=e.getTextureBinding(t),u=e.getTextureBinding(i),c=h.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:l.view},{binding:1,resource:l.sampler},{binding:2,resource:u.view},{binding:3,resource:u.sampler}]}),d=e.renderTargetFormat,_=e._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,a,_),p=e._passCoordinator.acquirePass().pass;p.setPipeline(f),p.setBindGroup(0,this._projectionBindGroup),p.setBindGroup(1,c),p.setVertexBuffer(0,this._vertexBuffer),p.setIndexBuffer(this._indexBuffer,"uint16"),p.drawIndexed(6),e.stats.batches++,e.stats.drawCalls++,e._passCoordinator.endPass()}_getOrCreatePipeline(e,t,i){const n=`${e}|${t}|${i?"s":"n"}`,r=this._pipelines.get(n);if(void 0!==r)return r;const s=this._device,o={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:Ss(t)}]},primitive:{topology:"triangle-list"}};i&&(o.depthStencil=Ps());const a=s.createRenderPipeline(o);return this._pipelines.set(n,a),a}_writeQuadVertices(e,t,i,n){const r=this._vertexData;r[0]=e,r[1]=t,r[2]=0,r[3]=0,r[4]=i,r[5]=t,r[6]=1,r[7]=0,r[8]=i,r[9]=n,r[10]=1,r[11]=1,r[12]=e,r[13]=n,r[14]=0,r[15]=1}_writeProjectionMatrix(e){const t=this._projectionMatrix.copy(e),i=this._projectionData;i[0]=t.a,i[1]=t.c,i[2]=0,i[3]=0,i[4]=t.b,i[5]=t.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=0,i[15]=1}}class xo{_backend;_stencil=new Ts;_stencilDepths=new Map;_stencilStacks=new Map;_stencilConnected=!1;_stencilWriteInProgress=!1;_stencilLoadOp="load";_stencilRef=0;_active=null;constructor(e){this._backend=e}get activeTarget(){return this._backend.renderTarget}get activeView(){return this._backend.view}get hasActivePass(){return null!==this._active}get activePass(){return this._active}get stencilActive(){return this._stencilWriteInProgress||this._activeTargetDepth()>0}get stencilReference(){return this._stencilRef}acquirePass(){if(null!==this._active)return this._active;const e=this._backend,t=this.stencilActive,i={colorAttachments:[e.createColorAttachment()]};t&&(i.depthStencilAttachment=this._createStencilAttachment(e.renderTarget));const n=e.device.createCommandEncoder(),r=n.beginRenderPass(i);e.stats.renderPasses++;const s=e.getScissorRect();return null!==s&&s.width>0&&s.height>0&&r.setScissorRect(s.x,s.y,s.width,s.height),this._applyViewport(r),t&&r.setStencilReference(this._stencilRef),this._active={encoder:n,pass:r,targetFormat:e.renderTargetFormat,view:e.view,stencilEnabled:t,stencilRef:this._stencilRef},this._active}endPass(){const e=this._active;null!==e&&(this._active=null,e.pass.end(),this._backend.submit(e.encoder.finish()))}beginPass(e){this._backend.setRenderTarget(e.target),this._backend.setView(e.view),"clear"===e.load&&this._backend.clear(e.clearColor??void 0)}withChildPass(e,t){const i=this._backend.renderTarget,n=this._backend.view;this.beginPass(e);try{t()}finally{this._backend.setRenderTarget(i),this._backend.setView(n)}}pushScissorRect(e){this._backend.pushScissorRect(e)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(e,t){const i=this._backend.renderTarget,n=this._stencilDepths.get(i)??0;if(n>=255)throw new Error("Stencil clip nesting exceeds the 255-level limit.");this._connectStencil(),this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=n,this._stencilLoadOp=0===n?"clear":"load";const r=this.acquirePass();this._stencil.draw(r.pass,r.targetFormat,!0,e,t,r.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(i,n+1),this._stencilRef=n+1,this._getStencilStack(i).push({shape:e,transform:(new At).copy(t)})}popStencilClip(){const e=this._backend.renderTarget,t=this._stencilStacks.get(e),i=t?.pop();if(void 0===i)return;const n=this._stencilDepths.get(e)??0;this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=n,this._stencilLoadOp="load";const r=this.acquirePass();this._stencil.draw(r.pass,r.targetFormat,!1,i.shape,i.transform,r.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(e,n-1),this._stencilRef=n-1}resolveLoad(e,t){return t||!this._backend._targetHasContent(e)?"clear":"load"}releaseStencilTarget(e){this._stencilConnected&&this._stencil.releaseAttachment(e),this._stencilDepths.delete(e),this._stencilStacks.delete(e)}resetStencil(){this._stencilDepths.clear(),this._stencilStacks.clear(),this._stencilWriteInProgress=!1,this._stencilRef=0}destroyStencil(){this._stencilConnected&&(this._stencil.disconnect(),this._stencilConnected=!1),this._stencilDepths.clear(),this._stencilStacks.clear(),this._stencilWriteInProgress=!1,this._stencilRef=0}unbalancedStencilClips(){let e=0;for(const t of this._stencilStacks.values())e+=t.length;return e}_activeTargetDepth(){return this._stencilDepths.get(this._backend.renderTarget)??0}_applyViewport(e){const t=this._backend.view.viewport;if(0===t.x&&0===t.y&&1===t.width&&1===t.height)return;const{width:i,height:n}=this._backend._getAttachmentPixelSize(this._backend.renderTarget),r=Math.floor(t.x*i),s=Math.floor(t.y*n),o=Math.max(1,Math.round(t.width*i)),a=Math.max(1,Math.round(t.height*n));e.setViewport(r,s,o,a,0,1)}_connectStencil(){this._stencilConnected||(this._stencil.connect(this._backend.device),this._stencilConnected=!0)}_getStencilStack(e){let t=this._stencilStacks.get(e);return void 0===t&&(t=[],this._stencilStacks.set(e,t)),t}_createStencilAttachment(e){const{width:t,height:i}=this._backend._getAttachmentPixelSize(e),n=this._stencil.getAttachmentView(e,t,i),r=this._stencilLoadOp;return this._stencilLoadOp="load",{view:n,depthReadOnly:!0,stencilLoadOp:r,stencilStoreOp:"store",stencilClearValue:0}}}class vo{_buffer=new ao;_storageBuffer=null;_storageCapacity=0;_storageHash=0;_storageCount=-1;_needsFullUpload=!1;_accountant=null;_accountedBytes=0;get buffer(){return this._buffer}begin(e=0){this._buffer.begin(e)}writeCommand(e,t){const i=e.drawable;this._buffer.write(e.nodeIndex,t??i.getGlobalTransform(),i.tint)}recordSkippedWrite(){this._buffer.recordSkippedWrite()}push(e,t){return this._buffer.push(t??e.getGlobalTransform(),e.tint)}pushValues(e,t){return this._buffer.push(e,t)}reserve(e,t,i){this._accountant=i??this._accountant;const n=12*Math.max(1,t)*Float32Array.BYTES_PER_ELEMENT;null!==this._storageBuffer&&n<=this._storageCapacity||this._growBuffer(e,n)}getBuffer(e,t,i){this._accountant=i??this._accountant;const n=Math.max(1,t),r=12*n*Float32Array.BYTES_PER_ELEMENT,s=this._buffer.commitSnapshot(n);if((null===this._storageBuffer||r>this._storageCapacity)&&this._growBuffer(e,r),s.changed||s.hash!==this._storageHash||s.count!==this._storageCount){const{firstRow:t,rowCount:i}=this._buffer.consumeDirtyRange(s.count),n=12*Float32Array.BYTES_PER_ELEMENT;this._needsFullUpload?(e.queue.writeBuffer(this._storageBuffer,0,this._buffer.data.buffer,this._buffer.data.byteOffset,s.count*n),this._buffer.recordUpload(s.count),this._accountant?.recordBufferUpload(s.count*n),this._needsFullUpload=!1):i>0&&(e.queue.writeBuffer(this._storageBuffer,t*n,this._buffer.data.buffer,this._buffer.data.byteOffset+t*n,i*n),this._buffer.recordUpload(i),this._accountant?.recordBufferUpload(i*n)),this._storageHash=s.hash,this._storageCount=s.count}return{buffer:this._storageBuffer,count:s.count}}destroy(){this._storageBuffer?.destroy(),this._storageBuffer=null,this._storageCapacity=0,this._storageHash=0,this._storageCount=-1,this._accountedBytes>0&&(this._accountant?.free(this._accountedBytes),this._accountedBytes=0)}_growBuffer(e,t){let i=Math.max(this._storageCapacity,12*Float32Array.BYTES_PER_ELEMENT);for(;i<t;)i*=2;this._storageBuffer?.destroy(),this._storageBuffer=e.createBuffer({size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._storageCapacity=i,this._storageHash=0,this._storageCount=-1,this._needsFullUpload=!0,this._accountedBytes=this._accountant?.reallocate(this._accountedBytes,i)??this._accountedBytes}}const bo="rgba8unorm";class So{backendType=e.RenderBackendType.WebGpu;rendererRegistry=new ro;onDeviceLost=new x;onDeviceRestored=new x;_canvas;_rootRenderTarget;_clearColor=new Tt;_deviceLost=!1;_isRecovering=!1;_destroyed=!1;_recoveryAttempt=0;_maxRecoveryAttempts=5;_recoveryBackoffMs=100;_textureStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_clipBoundsStack=[];_clipPixelStack=[];_clipPointA=new it;_clipPointB=new it;_maskCompositor=new wo;_maskCompositorConnected=!1;_backdropBlendCompositor=new yo;_backdropBlendCompositorConnected=!1;_mipmapShaderModule=null;_mipmapBindGroupLayout=null;_mipmapPipelineLayout=null;_mipmapPipeline=null;_mipmapSampler=null;_context=null;_device=null;_format=null;_initializePromise=null;_renderTarget;_snapTransform=new At;_renderer=null;_texture=null;_clearRequested=!1;_hasPresentedFrame=!1;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0,rawFrameDeltaMs:0,gpuMemoryBytes:0,textureUploadBytes:0,bufferUploadBytes:0,downloadBytes:0,downloadCount:0};_accountant=new Js(this._stats);_transformStorage=new vo;_activeDrawCommand=null;_passCoordinatorInstance=null;_drawPlanDepth=0;_planBaseStack=[];_planHashStack=[];constructor(e){const t=e.options.canvas??{},i=t.width??800,n=t.height??600,r=e.options.clearColor;this._canvas=e.canvas,this._rootRenderTarget=new di(i,n,!0),this._renderTarget=this._rootRenderTarget,r&&this._clearColor.copy(r),this.resize(i,n)}get view(){return this._renderTarget.view}get renderTarget(){return this._renderTarget}get device(){if(null===this._device)throw new Error("WebGPU device is not initialized yet.");return this._device}get context(){if(null===this._context)throw new Error("WebGPU canvas context is not initialized yet.");return this._context}get format(){if(null===this._format)throw new Error("WebGPU canvas format is not initialized yet.");return this._format}get renderTargetFormat(){return this._renderTarget===this._rootRenderTarget?this.format:bo}get clearRequested(){return this._clearRequested}get stats(){return this._stats}get accountant(){return this._accountant}get activeDrawCommand(){return this._activeDrawCommand}get _passCoordinator(){return this._passCoordinatorInstance??=new xo(this)}get clearColor(){return this._clearColor}get deviceLost(){return this._deviceLost}setClearColor(e){return this._clearColor.copy(e),this}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(e=>{throw this._initializePromise=null,e})),this._initializePromise}resetStats(){return Qs(this._stats),this._getTransformStorage().buffer.begin(),this}get transformBufferCount(){return this._getTransformStorage().buffer.count}_beginDrawPlan(e){const t=this._getTransformStorage();this._planBaseStack.push(t.buffer.count),this._planHashStack.push(t.buffer.frameHash);const i=t.buffer.count+e;i>0&&null!==this._device&&!this._deviceLost&&t.reserve(this._device,i,this._accountant),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(e,t,i){const n=this._getTransformStorage(),r=t+i;for(let i=t;i<r;i++){const t=e[i];if(t.kind!==Yt.Draw)continue;const r=t.command;ii(r,this)?n.writeCommand(r,this._resolveSnapTransform(r.drawable)):n.recordSkippedWrite()}}_prepareDrawCommand(e){this._activeDrawCommand=e}_endDrawPlan(){this._activeDrawCommand=null;const e=this._planBaseStack.pop()??0,t=this._planHashStack.pop()??0;if(this._drawPlanDepth>0&&this._drawPlanDepth--,this._drawPlanDepth>0&&(this._flushActiveRenderer(),this._getTransformStorage().buffer.rewindTo(e,t)),0===this._drawPlanDepth&&null!==this._passCoordinatorInstance){const e=this._passCoordinatorInstance.unbalancedStencilClips();if(e>0)throw this._passCoordinatorInstance.resetStencil(),new Error(`Unbalanced stencil clip stack at end of frame (${e} unpopped clip(s)).`)}}draw(e){if(this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const t=this.rendererRegistry.resolve(e);return this._setActiveRenderer(t),t.render(e),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(e,t,i,n){if(n<=0||0===e.vertexCount||this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const r=this.rendererRegistry.resolve(e);if(!(r instanceof Rs))throw new Error("drawInstanced requires a mesh handled by the WebGPU mesh renderer.");this._setActiveRenderer(r);const s=this._getTransformStorage(),o=s.pushValues(t[0],i[0]);for(let e=1;e<n;e++)s.pushValues(t[e],i[e]);return r.drawInstancedBatch(e,o,n),this._activeDrawCommand=null,this._stats.submittedNodes+=n,this}execute(e){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._stats.renderPasses++,e.execute(this)),this}setBlendMode(e){return this}setRenderTarget(e){const t=e??this._rootRenderTarget;return this._renderTarget!==t&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=t,this._stats.renderTargetChanges++,t!==this._rootRenderTarget&&this._subscribeRenderTarget(t)),this}pushScissorRect(e){this._flushActiveRenderer(),this._clipBoundsStack.push(e.clone());const t=this._toClipPixels(e),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,n=i?this._intersectClips(i,t):t;return this._clipPixelStack.push(n),this}composeWithAlphaMask(e,t,i,n,r,s,o){return r<=0||s<=0||this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._maskCompositorConnected||(this._maskCompositor.connect(this.device),this._maskCompositorConnected=!0),this._maskCompositor.compose(this,e,t,i,n,r,s,o)),this}composeWithBackdropBlend(e,t,i,n,r,s){return n<=0||r<=0||this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._backdropBlendCompositorConnected||(this._backdropBlendCompositor.connect(this.device),this._backdropBlendCompositorConnected=!0),this._backdropBlendCompositor.compose(this,e,t,i,n,r,s)),this}_renderTargetTexture(e){if(e===this._rootRenderTarget)return this.context.getCurrentTexture();if(e instanceof _i)return this._getTextureState(e).texture;throw new Error("WebGpuBackend._renderTargetTexture: unsupported render target type.")}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const e=this._clipBoundsStack.pop();return e&&e.destroy(),this._clipPixelStack.pop(),this}pushStencilClip(e,t){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._passCoordinator.pushStencilClip(e,t)),this}popStencilClip(){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._passCoordinator.popStencilClip()),this}getScissorRect(){if(0===this._clipPixelStack.length)return null;const e=this._clipPixelStack[this._clipPixelStack.length-1],t=this._renderTarget.root&&this._renderTarget.width>0?this._canvas.width/this._renderTarget.width:1,i=this._renderTarget.root&&this._renderTarget.height>0?this._canvas.height/this._renderTarget.height:1;return{x:Math.floor(e.x*t),y:Math.floor(e.y*i),width:Math.max(0,Math.round(e.width*t)),height:Math.max(0,Math.round(e.height*i))}}acquireRenderTexture(e,t){for(let i=0;i<this._temporaryRenderTextures.length;i++){const n=this._temporaryRenderTextures[i];if(n.width===e&&n.height===t)return this._temporaryRenderTextures.splice(i,1),n}return new _i(e,t)}releaseRenderTexture(e){return this._temporaryRenderTextures.includes(e)||(e.setView(null),this._temporaryRenderTextures.push(e)),this}setView(e){return this._renderTarget.view!==e&&this._flushActiveRenderer(),this._renderTarget.setView(e),this}clear(e){return e&&this.setClearColor(e),this._clearRequested=!0,this}resize(e,t){return this._rootRenderTarget.resize(e,t),this._hasPresentedFrame=!1,this}flush(){return this._device&&this._context?(this._renderer?this._flushActiveRenderer():this._clearRequested&&(this._passCoordinator.acquirePass(),this._passCoordinator.endPass()),this):this}destroy(){this._destroyed=!0,this.onDeviceLost.destroy(),this.onDeviceRestored.destroy(),this._setActiveRenderer(null),this.rendererRegistry.destroy(),this._destroyManagedTextures(),this._destroyTemporaryRenderTextures();for(const e of this._clipBoundsStack)e.destroy();this._clipBoundsStack.length=0,this._clipPixelStack.length=0,this._clipPointA.destroy(),this._clipPointB.destroy(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._backdropBlendCompositorConnected&&(this._backdropBlendCompositor.disconnect(),this._backdropBlendCompositorConnected=!1),this._transformStorage?.destroy(),this._transformStorage=null,this._activeDrawCommand=null,this._passCoordinatorInstance?.destroyStencil(),this._drawPlanDepth=0;for(const e of[...this._renderTargetDestroyHandlers.keys()])this._unsubscribeRenderTarget(e);this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._deviceLost=!1,this._texture=null,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._renderTarget=this._rootRenderTarget,this._clearColor.destroy(),this._rootRenderTarget.destroy()}createColorAttachment(){const e=this._renderTarget;let t;if(e===this._rootRenderTarget)t=this.context.getCurrentTexture().createView();else{if(!(e instanceof _i))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");t=this._syncTexture(e).view}const i=this._passCoordinator.resolveLoad(e,this._clearRequested);return this._clearRequested=!1,{view:t,clearValue:{r:this._clearColor.r/255,g:this._clearColor.g/255,b:this._clearColor.b/255,a:this._clearColor.a},loadOp:i,storeOp:"store"}}submit(e){if(this.device.queue.submit([e]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof _i){const e=this._syncTexture(this._renderTarget);e.hasContent=!0,e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}}_targetHasContent(e){return e===this._rootRenderTarget?this._hasPresentedFrame:e instanceof _i&&this._getTextureState(e).hasContent}_getAttachmentPixelSize(e){return e===this._rootRenderTarget?{width:this._canvas.width,height:this._canvas.height}:{width:e.width,height:e.height}}getTextureBinding(e){const t=this._syncTexture(e);return{view:t.view,sampler:t.sampler}}getTextureFormat(e){return this._getGpuTextureFormat(e)}shouldPremultiplyTextureSample(e){return!(e instanceof _i)&&e.premultiplyAlpha}getTransformStorageBuffer(e){return this._getTransformStorage().getBuffer(this.device,e,this._accountant)}_pushTransform(e){return this._getTransformStorage().push(e,this._resolveSnapTransform(e))}_resolveSnapTransform(e){const t=this._renderTarget,i=t===this._rootRenderTarget,n=i?this._canvas.width:t.width,r=i?this._canvas.height:t.height;return Rn(e,t.view,n,r,this._snapTransform)}_getSnapPixelSize(){return this._getAttachmentPixelSize(this._renderTarget)}_setActiveRenderer(e){this._renderer!==e&&(this._flushActiveRenderer(),this._renderer=e)}_flushActiveRenderer(){this._renderer?.flush()}_getTransformStorage(){return null!==this._transformStorage&&void 0!==this._transformStorage||(this._transformStorage=new vo),this._transformStorage}async _initialize(){const e=this._getGpuNavigator();if(null===e)throw new Error("This browser does not support WebGPU.");if("function"!=typeof e.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof e.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");let t,i;try{t=await e.gpu.requestAdapter()}catch(e){throw this._createInitializationError("Failed to request a WebGPU adapter.",e)}if(null===t)throw new Error("Could not acquire a WebGPU adapter.");if("function"!=typeof t.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");try{i=await t.requestDevice()}catch(e){throw this._createInitializationError("Failed to request a WebGPU device.",e)}if(null===i)throw new Error("Could not acquire a WebGPU device.");const n=this._canvas.getContext("webgpu");if(null===n)throw new Error("Could not create WebGPU canvas context.");const r=e.gpu.getPreferredCanvasFormat();try{n.configure({device:i,format:r,alphaMode:"opaque",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC})}catch(e){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",e)}this._context=n,this._device=i,this._format=r,this._hasPresentedFrame=!1,this._subscribeToDeviceLoss(),this.rendererRegistry.connect(this),this.resize(this._rootRenderTarget.width,this._rootRenderTarget.height);const s=[r,bo];return await this._prewarmRendererPipelines(s),this}_subscribeToDeviceLoss(){if(!this._device)return;const e=this._device;e.lost.then(t=>{this._destroyed||this._device!==e||this._handleDeviceLoss(t)})}_handleDeviceLoss(e){this._deviceLost=!0,this.onDeviceLost.dispatch(e),"destroyed"!==e.reason&&this._attemptRecovery()}async _attemptRecovery(){if(!this._isRecovering&&!this._destroyed){this._isRecovering=!0;try{for(;this._recoveryAttempt<this._maxRecoveryAttempts&&!this._destroyed;){this._recoveryAttempt++,this._teardownDeviceState();try{if(await this._initialize(),this._destroyed)return;return this._deviceLost=!1,this._recoveryAttempt=0,this._initializePromise=Promise.resolve(this),void this.onDeviceRestored.dispatch()}catch{if(this._destroyed)return;const e=this._recoveryBackoffMs*Math.pow(2,this._recoveryAttempt-1);await new Promise(t=>{setTimeout(t,e)})}}}finally{this._isRecovering=!1}}}_teardownDeviceState(){for(const[e,t]of this._textureDestroyHandlers)e.removeDestroyListener(t);this._textureDestroyHandlers.clear(),this._textureStates.clear(),this._temporaryRenderTextures.length=0,this.rendererRegistry.disconnect(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._backdropBlendCompositorConnected&&(this._backdropBlendCompositor.disconnect(),this._backdropBlendCompositorConnected=!1),this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._transformStorage?.destroy(),this._transformStorage=null,this._activeDrawCommand=null,this._passCoordinatorInstance?.destroyStencil(),this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._hasPresentedFrame=!1}async _prewarmRendererPipelines(e){const t=[];for(const i of this.rendererRegistry.renderers()){const n=i;"function"==typeof n.prewarmPipelines&&t.push(n.prewarmPipelines(e))}await Promise.all(t)}_getGpuNavigator(){const e=navigator;return e.gpu?e:null}_createInitializationError(e,t){return t instanceof Error&&t.message.length>0?new Error(`${e} ${t.message}`):new Error(e)}_destroyManagedTextures(){for(const e of[...this._textureStates.keys()])this._evictTexture(e)}_destroyTemporaryRenderTextures(){for(const e of this._temporaryRenderTextures)e.destroy();this._temporaryRenderTextures.length=0}_getTextureState(e){let t=this._textureStates.get(e);if(!t){const i=this.device.createTexture({size:{width:Math.max(e.width,1),height:Math.max(e.height,1)},format:this._getGpuTextureFormat(e),mipLevelCount:this._getMipLevelCount(e),usage:this._getTextureUsage(e)}),n=this._getMipLevelCount(e);t={texture:i,view:i.createView(),sampler:this._createSampler(e),version:-1,width:e.width,height:e.height,mipLevelCount:n,hasContent:!1,accountedBytes:0},t.accountedBytes=this._accountant.reallocate(0,this._estimateTextureBytes(e,n));const r=()=>{this._evictTexture(e)};e.addDestroyListener(r),this._textureDestroyHandlers.set(e,r),this._textureStates.set(e,t)}return t}_syncTexture(e){if(!(e instanceof _i||e instanceof Rr||null!==e.source&&0!==e.width&&0!==e.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const t=this._getTextureState(e),i=e instanceof _i?e.textureVersion:e.version,n=this._getMipLevelCount(e);if(t.version!==i){if(t.width!==e.width||t.height!==e.height||t.mipLevelCount!==n){t.texture.destroy();const i=this.device.createTexture({size:{width:e.width,height:e.height},format:this._getGpuTextureFormat(e),mipLevelCount:n,usage:this._getTextureUsage(e)});t.texture=i,t.view=i.createView(),t.width=e.width,t.height=e.height,t.mipLevelCount=n,t.hasContent=!1,t.accountedBytes=this._accountant.reallocate(t.accountedBytes,this._estimateTextureBytes(e,n))}if(t.sampler=this._createSampler(e),e instanceof Rr){const i=Bo(e.format),n=e._consumeDirtyRegion();if(null===n||n.full||!t.hasContent)this.device.queue.writeTexture({texture:t.texture},e.buffer,{bytesPerRow:e.width*i.bytesPerPixel,rowsPerImage:e.height},{width:e.width,height:e.height}),this._accountant.recordTextureUpload(e.width*e.height*i.bytesPerPixel);else{const r=i.channels,s=i.bytesPerPixel,o=n.width*n.height*s,a=e.buffer instanceof Float32Array?new Float32Array(o/4):new Uint8Array(o),h=e.width*r,l=n.width*r;for(let t=0;t<n.height;t++){const i=(n.y+t)*h+n.x*r,s=t*l;a.set(e.buffer.subarray(i,i+l),s)}this.device.queue.writeTexture({texture:t.texture,origin:{x:n.x,y:n.y}},a,{bytesPerRow:n.width*s,rowsPerImage:n.height},{width:n.width,height:n.height}),this._accountant.recordTextureUpload(n.width*n.height*s)}t.hasContent=!0}else if(!(e instanceof _i)){const i=e.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:t.texture},{width:e.width,height:e.height}),this._accountant.recordTextureUpload(e.width*e.height*4),t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}t.version=i}return t}_evictTexture(e){const t=this._textureStates.get(e),i=this._textureDestroyHandlers.get(e);i&&(e.removeDestroyListener(i),this._textureDestroyHandlers.delete(e)),t&&(t.texture.destroy(),this._accountant.free(t.accountedBytes),t.accountedBytes=0,this._textureStates.delete(e)),this._texture===e&&(this._texture=null)}_subscribeRenderTarget(e){if(!this._renderTargetDestroyHandlers.has(e)){const t=()=>{this._renderTarget===e&&(this._renderTarget=this._rootRenderTarget),this._passCoordinatorInstance?.releaseStencilTarget(e),this._renderTargetDestroyHandlers.delete(e)};e.addDestroyListener(t),this._renderTargetDestroyHandlers.set(e,t)}}_unsubscribeRenderTarget(e){const t=this._renderTargetDestroyHandlers.get(e);t&&(e.removeDestroyListener(t),this._renderTargetDestroyHandlers.delete(e))}_toClipPixels(e){const t=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(e.left,e.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(e.right,e.bottom)),n=Math.min(t.x,i.x),r=Math.max(t.x,i.x),s=Math.min(t.y,i.y),o=Math.max(t.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(n))),u=Math.max(0,Math.min(a,Math.ceil(r))),c=Math.max(0,Math.min(h,Math.floor(s))),d=Math.max(0,Math.min(h,Math.ceil(o)));return{x:l,y:c,width:Math.max(0,u-l),height:Math.max(0,d-c)}}_intersectClips(e,t){const i=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.width,t.x+t.width),s=Math.min(e.y+e.height,t.y+t.height);return{x:i,y:n,width:Math.max(0,r-i),height:Math.max(0,s-n)}}_createSampler(e){const t=e instanceof Rr&&("r32f"===e.format||"rgba32f"===e.format),i=t?"nearest":this._getFilterMode(e.scaleMode);return this.device.createSampler({addressModeU:this._getAddressMode(e.wrapMode),addressModeV:this._getAddressMode(e.wrapMode),magFilter:i,minFilter:i,mipmapFilter:t?"nearest":this._getMipmapFilterMode(e.scaleMode)})}_getGpuTextureFormat(e){if(e instanceof Rr){return Bo(e.format).gpuFormat}return bo}_getTextureUsage(e){const t=this._getMipLevelCount(e)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return e instanceof _i?GPUTextureUsage.COPY_SRC|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|t:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|t}_getAddressMode(t){switch(t){case e.WrapModes.Repeat:return"repeat";case e.WrapModes.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case e.ScaleModes.Nearest:case e.ScaleModes.NearestMipmapNearest:case e.ScaleModes.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case e.ScaleModes.NearestMipmapLinear:case e.ScaleModes.LinearMipmapLinear:return"linear";default:return"nearest"}}_textureBytesPerPixel(e){if(e instanceof Rr){const t=e.format;return to(t)}return 4}_estimateTextureBytes(e,t){return eo(e.width,e.height,this._textureBytesPerPixel(e),t)}_getMipLevelCount(e){if(!e.generateMipMap)return 1;const t=Math.max(e.width,e.height);return t<=1?1:Math.floor(Math.log2(t))+1}_generateMipmaps(e,t){if(t<=1)return;const i=this._getMipmapResources(),n=this.device.createCommandEncoder();for(let r=1;r<t;r++){const t=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:e.createView({baseMipLevel:r-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),s=n.beginRenderPass({colorAttachments:[{view:e.createView({baseMipLevel:r,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});s.setPipeline(i.pipeline),s.setBindGroup(0,t),s.draw(3),s.end()}this.device.queue.submit([n.finish()])}_getMipmapResources(){return null!==this._mipmapShaderModule&&null!==this._mipmapBindGroupLayout&&null!==this._mipmapPipelineLayout&&null!==this._mipmapPipeline&&null!==this._mipmapSampler||(this._mipmapShaderModule=this.device.createShaderModule({code:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@group(0) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(0) @binding(1)\nvar sourceSampler: sampler;\n\n@vertex\nfn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0)\n );\n // Y is flipped vs the position array: NDC Y points up, but texture UV\n // Y points down (UV (0,0) is the top-left of the source). Matching the\n // two ensures that the output texture's top-left pixel samples from the\n // source's top-left, so every mip level has the same orientation as the\n // level above it. Prior to this, odd mip levels were rendered upside\n // down, producing visible texture flips at view-size doublings.\n var texcoords = array<vec2<f32>, 3>(\n vec2<f32>(0.0, 1.0),\n vec2<f32>(2.0, 1.0),\n vec2<f32>(0.0, -1.0)\n );\n var output: VertexOutput;\n\n output.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);\n output.texcoord = texcoords[vertexIndex];\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(sourceTexture, sourceSampler, input.texcoord);\n}\n"}),this._mipmapBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._mipmapPipelineLayout=this.device.createPipelineLayout({bindGroupLayouts:[this._mipmapBindGroupLayout]}),this._mipmapPipeline=this.device.createRenderPipeline({layout:this._mipmapPipelineLayout,vertex:{module:this._mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this._mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:bo,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}}),this._mipmapSampler=this.device.createSampler({minFilter:"linear",magFilter:"linear",mipmapFilter:"nearest"})),{bindGroupLayout:this._mipmapBindGroupLayout,pipeline:this._mipmapPipeline,sampler:this._mipmapSampler}}}function Bo(e){switch(e){case"r8":return{gpuFormat:"r8unorm",bytesPerPixel:1,channels:1};case"r32f":return{gpuFormat:"r32float",bytesPerPixel:4,channels:1};case"rgba8":return{gpuFormat:"rgba8unorm",bytesPerPixel:4,channels:4};case"rgba32f":return{gpuFormat:"rgba32float",bytesPerPixel:16,channels:4}}}class Co extends vr{onStart=new x;onStop=new x;_videoElement;_duration;_volume=1;_playbackRate=1;_loop=!1;_muted=!1;_bus=null;_audioSetup=null;_textureDirty=!0;_lastVideoTime=Number.NaN;_videoFrameCallbackHandle=null;_onMetadataHandler;_onResizeHandler;_onVideoFrameHandler;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this.setupWithAudioContext(e)};constructor(e,t,i){super(new pi(e,i));const{duration:n,volume:r,playbackRate:s,loop:o,muted:a}=e;this._videoElement=e,this._duration=n,this._volume=r,this._playbackRate=s,this._loop=o,this._muted=a,this._onMetadataHandler=this._onVideoMetadataUpdated.bind(this),this._onResizeHandler=this._onVideoMetadataUpdated.bind(this),this._onVideoFrameHandler=this._onVideoFrame.bind(this),0!==this._videoElement.videoWidth&&0!==this._videoElement.videoHeight||(this._videoElement.addEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.addEventListener("resize",this._onResizeHandler)),t&&this.applyOptions(t),U()?this.setupWithAudioContext(L()):I.add(this._onAudioContextReady),this.updateTexture(),this._requestVideoFrameCallback()}get videoElement(){return this._videoElement}get duration(){return this._duration}get progress(){const e=this.currentTime,t=this.duration;return e%t/t}get volume(){return this._volume}set volume(e){this.setVolume(e)}get loop(){return this._loop}set loop(e){this.setLoop(e)}get playbackRate(){return this._playbackRate}set playbackRate(e){this.setPlaybackRate(e)}get currentTime(){return this.getTime()}set currentTime(e){this.setTime(e)}get muted(){return this._muted}set muted(e){this.setMuted(e)}get paused(){return this._videoElement.paused}set paused(e){e?this.pause():this.play()}get playing(){return!this.paused}set playing(e){e?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}get bus(){return this._bus}set bus(e){if(this._bus!==e&&(this._audioSetup&&this._audioSetup.gainNode.disconnect(),this._bus=e,this._audioSetup)){const t=e._getInputNode();t?this._audioSetup.gainNode.connect(t):this._audioSetup.gainNode.connect(this._audioSetup.audioContext.destination)}}play(e){return e&&this.applyOptions(e),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(e){return e&&this.applyOptions(e),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(e){return this.pause(e),this.currentTime=0,this}toggle(e){return this.paused?this.play(e):this.pause(e)}applyOptions(e={}){const{volume:t,loop:i,playbackRate:n,time:r,muted:s}=e;return void 0!==t&&(this.volume=t),void 0!==i&&(this.loop=i),void 0!==n&&(this.playbackRate=n),void 0!==r&&(this.currentTime=r),void 0!==s&&(this.muted=s),this}setVolume(e){const t=Y(e,0,2);if(this._volume===t)return this;if(this._volume=t,this._audioSetup){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(this.muted?0:t,i.currentTime,.01)}return this}setLoop(e){return this._loop!==e&&(this._loop=e,this._videoElement.loop=e),this}setPlaybackRate(e){const t=Y(e,.1,20);return this._playbackRate!==t&&(this._playbackRate=t,this._videoElement.playbackRate=t),this}getTime(){return this._videoElement.currentTime}setTime(e){return this._videoElement.currentTime=Math.max(0,e),this}setMuted(e){if(this._muted!==e&&(this._muted=e,this._audioSetup)){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(e?0:this.volume,i.currentTime,.01)}return this}_collect(e,t){this.visible&&(this._markTextureDirtyOnPlaybackAdvance(),this.updateTexture()),super._collect(e,t)}updateTexture(){const e=this.texture;if(!e||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const t=this.textureFrame.width>0&&this.textureFrame.height>0;return e.updateSource(),e.width>0&&e.height>0&&this.setTextureFrame(et.temp.set(0,0,e.width,e.height),!t),this._textureDirty=!1,this}destroy(){super.destroy(),this.stop(),this._videoElement.removeEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.removeEventListener("resize",this._onResizeHandler),this._cancelVideoFrameCallback(),I.remove(this._onAudioContextReady),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null),this.onStart.destroy(),this.onStop.destroy()}_onVideoMetadataUpdated(){this._textureDirty=!0,this.updateTexture()}_onVideoFrame(e,t){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyOnPlaybackAdvance(){const e=this._videoElement.currentTime;this._lastVideoTime!==e&&(this._lastVideoTime=e,this._textureDirty=!0)}_requestVideoFrameCallback(){const e=this._videoElement;e.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=e.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const e=this._videoElement;e.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(e.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext=e=>{const t=e.createGain();t.gain.setTargetAtTime(this.muted?0:this.volume,e.currentTime,.01);const i=this.bus?._getInputNode()??null;i?t.connect(i):t.connect(e.destination);const n=e.createMediaElementSource(this._videoElement);n.connect(t),this._audioSetup={audioContext:e,gainNode:t,sourceNode:n}}}class To{_objectUrls=[];createObjectUrl(e){const t=URL.createObjectURL(e);return this._objectUrls.push(t),t}revokeObjectUrl(e){URL.revokeObjectURL(e);const t=this._objectUrls.indexOf(e);-1!==t&&this._objectUrls.splice(t,1)}destroy(){for(const e of this._objectUrls)URL.revokeObjectURL(e);this._objectUrls.length=0}}class Mo extends To{storageName="binary";async process(e){return e.arrayBuffer()}async create(e){return e}}function Po(e,t){const i=e.match(new RegExp(`\\b${t}=(-?\\d+)`));return void 0!==i?.[1]?parseInt(i[1],10):0}function Ao(e,t){const i=e.match(new RegExp(`\\b${t}="([^"]*)"`));if(void 0!==i?.[1])return i[1];const n=e.match(new RegExp(`\\b${t}=(\\S+)`));return n?.[1]??""}function Eo(e){const t=e.split(/\r?\n/),i=[],n=new Map,r=new Map;let s=0,o=0;for(const e of t){const t=e.trim();if(0===t.length)continue;switch(t.split(/\s/)[0]??""){case"common":s=Po(t,"lineHeight"),o=Po(t,"base");break;case"page":{const e=Po(t,"id"),n=Ao(t,"file");i[e]=n;break}case"char":{const e=Po(t,"id");n.set(e,{x:Po(t,"x"),y:Po(t,"y"),width:Po(t,"width"),height:Po(t,"height"),xOffset:Po(t,"xoffset"),yOffset:Po(t,"yoffset"),xAdvance:Po(t,"xadvance"),page:Po(t,"page")});break}case"kerning":{const e=Po(t,"first"),i=Po(t,"second"),n=Po(t,"amount");r.set(`${e},${i}`,n);break}}}return{pages:i,chars:n,kernings:r,lineHeight:s,base:o}}class ko extends To{storageName="csv";async process(e){return e.text()}async create(e,t={}){const i=t.delimiter??",",n=[],r=e.replaceAll("\r\n","\n").replaceAll("\r","\n");let s=[],o="",a=!1,h=0;for(;h<r.length;){const e=r[h];a?'"'===e?'"'===r[h+1]?(o+='"',h+=2):(a=!1,h++):(o+=e,h++):'"'===e?(a=!0,h++):e===i?(s.push(o),o="",h++):"\n"===e?(s.push(o),o="",n.push(s),s=[],h++):(o+=e,h++)}return s.push(o),s.some(e=>""!==e)&&n.push(s),n}}class Ro extends To{storageName="font";_addedFontFaces=[];async process(e){return e.arrayBuffer()}async create(e,t){if(!t?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:n,addToDocument:r}=t;if(e.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${e.byteLength}.`);const s=await new FontFace(i,e,n).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${e.byteLength} bytes).`)});return!1!==r&&(document.fonts.add(s),this._addedFontFaces.push(s)),s}destroy(){for(const e of this._addedFontFaces)document.fonts.delete(e);this._addedFontFaces.length=0,super.destroy()}}const Do=[{mimeType:"image/x-icon",pattern:[0,0,1,0],mask:[255,255,255,255]},{mimeType:"image/x-icon",pattern:[0,0,2,0],mask:[255,255,255,255]},{mimeType:"image/bmp",pattern:[66,77],mask:[255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,55,97],mask:[255,255,255,255,255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,57,97],mask:[255,255,255,255,255,255]},{mimeType:"image/webp",pattern:[82,73,70,70,0,0,0,0,87,69,66,80,86,80],mask:[255,255,255,255,0,0,0,0,255,255,255,255,255,255]},{mimeType:"image/png",pattern:[137,80,78,71,13,10,26,10],mask:[255,255,255,255,255,255,255,255]},{mimeType:"image/jpeg",pattern:[255,216,255],mask:[255,255,255]},{mimeType:"@/audio/basic",pattern:[46,115,110,100],mask:[255,255,255,255]},{mimeType:"@/audio/mpeg",pattern:[73,68,51],mask:[255,255,255]},{mimeType:"@/audio/wave",pattern:[82,73,70,70,0,0,0,0,87,65,86,69],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"@/audio/midi",pattern:[77,84,104,100,0,0,0,6],mask:[255,255,255,255,255,255,255,255]},{mimeType:"@/audio/aiff",pattern:[70,79,82,77,0,0,0,0,65,73,70,70],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"video/avi",pattern:[82,73,70,70,0,0,0,0,65,86,73,32],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"application/ogg",pattern:[79,103,103,83,0],mask:[255,255,255,255,255]}],Fo=e=>{const t=new Uint8Array(e);if(!t.length)throw new Error("Cannot determine mime type: No data.");for(const e of Do)if(!(t.length<e.pattern.length)&&e.pattern.every((i,n)=>((t[n]??0)&(e.mask[n]??0))===i))return e.mimeType;return(e=>{const t=new Uint8Array(e),i=new DataView(e).getUint32(0,!1);return!(t.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...t.subarray(4,11))})(e)?"video/mp4":(e=>{const t=new Uint8Array(e),i=[26,69,223,163].every((e,i)=>e===t[i]),n=t.subarray(4,4100),r=n.findIndex((e,t,i)=>66===i[t]&&130===i[t+1]);return!(!i||-1===r)&&"webm"===String.fromCharCode(...n.subarray(r+3,r+7))})(e)?"video/webm":(e=>{if(e.byteLength<12)return!1;const t=new Uint8Array(e);if("ftyp"!==String.fromCharCode(t[4]??0,t[5]??0,t[6]??0,t[7]??0))return!1;const i=String.fromCharCode(t[8]??0,t[9]??0,t[10]??0,t[11]??0);return"avif"===i||"avis"===i})(e)?"image/avif":"text/plain"};class Io extends To{storageName="image";async process(e){return e.arrayBuffer()}async create(e,t={}){const i=new Blob([e],{type:t.mimeType??Fo(e)});if("function"==typeof createImageBitmap)return createImageBitmap(i);const n=this.createObjectUrl(i);return new Promise((e,t)=>{const i=new Image,r=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{r(),e(i)},{once:!0}),i.addEventListener("error",()=>{r(),t(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),t(new Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const Lo={once:!0};class Uo extends To{storageName="music";_audioElements=[];async process(e){return e.arrayBuffer()}async create(e,t={}){const{mimeType:i,loadEvent:n,playbackOptions:r,stallTimeout:s}=t,o=new Blob([e],{type:i??Fo(e)}),a=this.createObjectUrl(o);return new Promise((e,t)=>{const i=document.createElement("audio");let o;this._audioElements.push(i);let h=!1;const l=e=>{h||(h=!0,void 0!==o&&(clearTimeout(o),o=void 0),this.revokeObjectUrl(a),e())};i.addEventListener("error",()=>l(()=>t(new Error("Error loading audio source."))),Lo),i.addEventListener("abort",()=>l(()=>t(new Error("Audio loading was canceled."))),Lo),i.addEventListener("emptied",()=>l(()=>t(new Error("Audio loading was emptied."))),Lo),i.addEventListener(n??"canplaythrough",()=>l(()=>e(new mt(i,r))),Lo),void 0!==s&&i.addEventListener("stalled",()=>{h||(void 0!==o&&clearTimeout(o),o=setTimeout(()=>l(()=>t(new Error("Audio loading stalled."))),s))}),i.preload="auto",i.src=a})}destroy(){for(const e of this._audioElements)e.pause(),e.src="",e.load();this._audioElements.length=0,super.destroy()}}class Go extends To{storageName="sound";async process(e){return e.arrayBuffer()}async create(e,t={}){const i=await G(e);return new lt(i,{...t.playbackOptions,...void 0!==t.poolSize&&{poolSize:t.poolSize},...void 0!==t.sprites&&{sprites:t.sprites}})}}const No=e=>{const t=e.split(":");let i;return i=3===t.length?3600*Number(t[0])+60*Number(t[1])+Number(t[2]):2===t.length?60*Number(t[0])+Number(t[1]):Number(t[0]),i},Oo=new Set(["start","center","end","left","right"]),Vo=new Set(["start","center","end"]),zo=new Set(["auto","line-left","center","line-right"]),qo=(e,t)=>{if(t)for(const i of t.split(/\s+/)){const t=i.indexOf(":");if(-1===t)continue;const n=i.slice(0,t),r=i.slice(t+1);switch(n){case"vertical":"rl"!==r&&"lr"!==r&&""!==r||(e.vertical=r);break;case"line":if("auto"===r)e.line="auto";else{const[t="",i]=r.split(","),n=parseFloat(t);Number.isNaN(n)||(e.line=n),void 0!==i&&Vo.has(i)&&(e.lineAlign=i)}break;case"position":{const[t="",i]=r.split(","),n=parseFloat(t);Number.isNaN(n)||(e.position=n),void 0!==i&&zo.has(i)&&(e.positionAlign=i);break}case"size":{const t=parseFloat(r);Number.isNaN(t)||(e.size=t);break}case"align":Oo.has(r)&&(e.align=r)}}},Wo=e=>{const t=e.trim().replace(",",".").split(":");return 3600*Number(t[0])+60*Number(t[1])+Number(t[2])};class Yo extends To{storageName="subtitle";async process(e){const t=await e.text();return{fmt:(e.url.split("?")[0]??e.url).toLowerCase().endsWith(".srt")?"srt":"vtt",text:t}}async create(e){return"srt"===e.fmt?(e=>{const t=[],i=e.replaceAll("\r\n","\n").replaceAll("\r","\n").split(/\n[ \t]*\n/);for(const e of i){const i=e.trim().split("\n");if(i.length<2)continue;let n=0;/^\d+$/.test((i[0]??"").trim())&&(n=1);const r=i[n];if(!r?.includes("--\x3e"))continue;const s=r.indexOf("--\x3e"),o=Wo(r.slice(0,s)),a=Wo(r.slice(s+3)),h=i.slice(n+1).join("\n");t.push(new VTTCue(o,a,h))}return t})(e.text):(e=>{const t=[],i=e.replaceAll("\r\n","\n").replaceAll("\r","\n").split("\n");let n=0;for(;n<i.length&&!(i[n]??"").includes("--\x3e");)n++;for(;n<i.length;){const e=(i[n]??"").trim();if(e.includes("--\x3e")){const r=e.indexOf("--\x3e"),s=e.slice(0,r).trim(),o=e.slice(r+3).trim().split(/\s+/),a=o[0]??"",h=o.slice(1).join(" "),l=No(s),u=No(a);n++;const c=[];for(;n<i.length;){const e=i[n];if(void 0===e||""===e.trim())break;c.push(e),n++}const d=new VTTCue(l,u,c.join("\n"));qo(d,h),t.push(d)}else n++}return t})(e.text)}}class $o extends To{storageName="svg";async process(e){return e.text()}async create(e,t={}){const{width:i,height:n}=t;let r=e;if(void 0!==i||void 0!==n){const e=r.indexOf("<svg"),t=r.indexOf(">",e);if(-1!==e&&-1!==t){const s=r.slice(0,e),o=r.slice(e+4,t),a=r.slice(t+1);r=`${s}<svg${String(o).replaceAll(/\s+width=(?:"[^"]*"|'[^']*')/g,"").replaceAll(/\s+height=(?:"[^"]*"|'[^']*')/g,"")}${(void 0!==i?` width="${i}"`:"")+(void 0!==n?` height="${n}"`:"")}>${a}`}}const s=new Blob([r],{type:"image/svg+xml"}),o=this.createObjectUrl(s);return new Promise((e,t)=>{const i=new Image,n=()=>{this.revokeObjectUrl(o)};i.addEventListener("load",()=>{n(),e(i)},{once:!0}),i.addEventListener("error",()=>{n(),t(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{n(),t(new Error("Image loading was canceled."))},{once:!0}),i.src=o})}}class Xo extends To{storageName="texture";async process(e){return e.arrayBuffer()}async create(e,t={}){const{mimeType:i,samplerOptions:n}=t,r=new Blob([e],{type:i??Fo(e)});if("function"==typeof createImageBitmap){const e=await createImageBitmap(r);return new pi(e,n)}const s=this.createObjectUrl(r);return new Promise((e,t)=>{const i=new Image,r=()=>{this.revokeObjectUrl(s)};i.addEventListener("load",()=>{r(),e(new pi(i,n))},{once:!0}),i.addEventListener("error",()=>{r(),t(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),t(new Error("Image loading was canceled."))},{once:!0}),i.src=s})}}const Ho={once:!0};class jo extends To{storageName="video";_videoElements=[];async process(e){return e.arrayBuffer()}async create(e,t={}){const{mimeType:i,loadEvent:n,playbackOptions:r,samplerOptions:s,stallTimeout:o}=t,a=new Blob([e],{type:i??Fo(e)}),h=this.createObjectUrl(a);return new Promise((e,t)=>{const i=document.createElement("video");let a;this._videoElements.push(i);let l=!1;const u=e=>{l||(l=!0,void 0!==a&&(clearTimeout(a),a=void 0),this.revokeObjectUrl(h),e())};i.addEventListener("error",()=>u(()=>t(new Error("Video loading error."))),Ho),i.addEventListener("abort",()=>u(()=>t(new Error("Video loading error: cancelled."))),Ho),i.addEventListener("emptied",()=>u(()=>t(new Error("Video loading error: emptied."))),Ho),i.addEventListener(n??"canplaythrough",()=>u(()=>e(new Co(i,r,s))),Ho),void 0!==o&&i.addEventListener("stalled",()=>{l||(void 0!==a&&clearTimeout(a),a=setTimeout(()=>u(()=>t(new Error("Video loading stalled."))),o))}),i.preload="auto",i.src=h})}destroy(){for(const e of this._videoElements)e.pause(),e.src="",e.load();this._videoElements.length=0,super.destroy()}}class Ko extends To{storageName="wasm";async process(e){return e.arrayBuffer()}async create(e){return WebAssembly.compile(e)}}class Qo extends To{storageName="xml";async process(e){return e.text()}async create(e){const t=(new DOMParser).parseFromString(e,"text/xml"),i=t.querySelector("parsererror");if(i)throw new Error(`XML parse error: ${i.textContent.trim()||"unknown error"}`);return t}}class Zo{}class Jo{}class ea{}class ta{}class ia{}class na{}class ra{}class sa{}class oa{}class aa{}function ha(e){return()=>{const t=e();return{async load({source:e,options:i},n){const r=await n.fetchArrayBuffer(e);return t.create(r,i)},createFromBytes:(e,i)=>t.create(e,i),destroy(){t.destroy()}}}}function la(e){return()=>{const t=e();return{async load({source:e,options:i},n){const r=await n.fetchText(e);return t.create(r,i)},createFromBytes:(e,i)=>t.create((new TextDecoder).decode(e),i),destroy(){t.destroy()}}}}function ua(e,t,i){return{type:e,...t,create:i}}const ca=ua(pi,{typeNames:["texture"]},ha(()=>new Xo)),da=ua(lt,{typeNames:["sound"]},ha(()=>new Go)),_a=ua(mt,{typeNames:["music"]},ha(()=>new Uo)),fa=ua(Co,{typeNames:["video"]},ha(()=>new jo)),pa=ua(Zo,{typeNames:["json"]},()=>({load:async({source:e},t)=>t.fetchJson(e),createFromBytes:e=>Promise.resolve(JSON.parse((new TextDecoder).decode(e)))})),ma=ua(Jo,{typeNames:["text"]},()=>({load:async({source:e},t)=>t.fetchText(e),createFromBytes:e=>Promise.resolve((new TextDecoder).decode(e))})),ga=ua(ea,{typeNames:["svg"]},la(()=>new $o)),ya=ua(ta,{typeNames:["vtt","srt"]},()=>{const e=new Yo;return{async load({source:t},i){const n=await i.fetchText(t),r=(t.split("?")[0]??t).toLowerCase().endsWith(".srt")?"srt":"vtt",s=await e.process({text:()=>Promise.resolve(n),url:t});return e.create({...s,fmt:r})},destroy(){e.destroy()}}}),wa=ua(ia,{typeNames:["xml"]},la(()=>new Qo)),xa=ua(na,{typeNames:["csv"]},la(()=>new ko)),va=ua(oa,{typeNames:["binary"]},ha(()=>new Mo)),ba=ua(Sr,{typeNames:["bmFont"],extensions:["fnt"]},e=>({async load({source:t},i){const n=Eo(await i.fetchText(t)),r=await Promise.all(n.pages.map(i=>e.load(pi,function(e,t){if(/^(?:[a-z][a-z\d+.-]*:|\/\/|\/)/i.test(e))return e;try{return new URL(e,t).href}catch{const i="https://exojs.invalid/",n=new URL(e,i+t.replace(/^\/+/,"")).href.slice(i.length);return t.startsWith("/")?`/${n}`:n}}(i,t))));return new Sr(n,r)}})),Sa=[];"undefined"!=typeof FontFace&&Sa.push(ua(sa,{typeNames:["font"],extensions:["woff","woff2","ttf","otf"]},ha(()=>new Ro))),"undefined"!=typeof HTMLImageElement&&Sa.push(ua(ra,{typeNames:["image"]},ha(()=>new Io))),"undefined"!=typeof WebAssembly&&Sa.push(ua(aa,{typeNames:["wasm"]},ha(()=>new Ko)));const Ba=Object.freeze([ca,da,_a,fa,pa,ma,ga,ya,wa,xa,va,ba,...Sa]);class Ca{_config;constructor(e){this._config=e}get type(){return this._config.type}get source(){return this._config.source}}const Ta=Ca,Ma="EXOA";function Pa(e){throw new Error(`Invalid asset container: ${e}.`)}function Aa(e){e.byteLength<12&&Pa(`buffer too small for a 12-byte header (got ${e.byteLength})`);const t=new Uint8Array(e),i=new DataView(e);for(let e=0;e<4;e++)t[e]!==Ma.charCodeAt(e)&&Pa(`bad magic (expected "${Ma}")`);const n=i.getUint32(4,!0);n>1&&Pa(`unsupported version ${n} (this build reads up to 1)`);const r=i.getUint32(8,!0),s=12+r;let o;s>e.byteLength&&Pa(`index length ${r} runs past the buffer (size ${e.byteLength})`);try{o=JSON.parse((new TextDecoder).decode(t.subarray(12,s)))}catch{Pa("index is not valid JSON")}Array.isArray(o)||Pa("index is not an array");const a=e.byteLength-s,h=o.map((e,t)=>function(e,t,i){"object"==typeof e&&null!==e||Pa(`index entry ${t} is not an object`);const n=e,{alias:r,type:s,offset:o,length:a,mime:h}=n;return"string"!=typeof r&&Pa(`index entry ${t} has a non-string "alias"`),"string"!=typeof s&&Pa(`index entry ${t} ("${r}") has a non-string "type"`),("number"!=typeof o||!Number.isFinite(o)||o<0)&&Pa(`index entry "${r}" has an invalid "offset"`),("number"!=typeof a||!Number.isFinite(a)||a<0)&&Pa(`index entry "${r}" has an invalid "length"`),o+a>i&&Pa(`index entry "${r}" runs past the data section (offset ${o} + length ${a} > ${i})`),void 0!==h&&"string"!=typeof h&&Pa(`index entry "${r}" has a non-string "mime"`),{alias:r,type:s,offset:o,length:a,..."string"==typeof h&&{mime:h},...void 0!==n.options&&{options:n.options}}}(e,t,a));return{version:n,entries:h,dataStart:s}}class Ea extends Error{bundle;failures;constructor(e,t){super(`Failed to load bundle "${e}" (${t.length} failure${1===t.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=e,this.failures=t}}function ka(e){return function(e){if(!Ra(e))throw new Error("Invalid asset manifest: manifest must be an object.");if(!Ra(e.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[t,i]of Object.entries(e.bundles)){if(0===t.trim().length)throw new Error("Invalid asset manifest: bundle names must be non-empty strings.");if(!Array.isArray(i))throw new Error(`Invalid asset manifest: bundle "${t}" must be an array of entries.`);const e=new Map;for(const[n,r]of i.entries()){const i=`bundle "${t}" entry[${n}]`;if(!Ra(r))throw new Error(`Invalid asset manifest: ${i} must be an object.`);if("function"!=typeof r.type)throw new Error(`Invalid asset manifest: ${i} has an invalid "type" token.`);Da(r.alias,`${i} has an invalid "alias".`),Da(r.path,`${i} has an invalid "path".`);const s=r.type,o=r.alias;e.has(s)||e.set(s,new Set);const a=e.get(s);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${Fa(s)}, "${o}") in bundle "${t}".`);a.add(o)}}}(e),e}function Ra(e){return"object"==typeof e&&null!==e}function Da(e,t){if("string"!=typeof e||0===e.trim().length)throw new Error(`Invalid asset manifest: ${t}`)}function Fa(e){return e.name.length>0?e.name:"(anonymous type)"}class Ia{entries;constructor(e){if(Object.hasOwn(e,"entries"))throw new Error('An Assets container may not define an asset named "entries": that name is reserved for the spread-composition helper.');const t={};for(const i of Object.keys(e)){const n=e[i],r=n instanceof Ca?n:new Ca(n);t[i]=r,Object.defineProperty(this,i,{value:r,enumerable:!0,configurable:!1,writable:!1})}this.entries=t}}const La=Ia;class Ua{async resolve(e,t){const{storageName:i,key:n,url:r,requestOptions:s,factory:o,options:a}=e;for(const e of t){const t=await e.load(i,n);if(null!=t)try{return await o.create(t,a)}catch{await e.delete(i,n)}}const h=await fetch(r,s);if(!h.ok)throw new Error(`Failed to fetch "${r}" (${h.status} ${h.statusText}).`);const l=await o.process(h),u=await o.create(l,a);for(const e of t)try{await e.save(i,n,l)}catch{}return u}}const Ga=e=>{const t=Object.getPrototypeOf(e.prototype);return t?.constructor??null};class Na{_factories=new io({walk:Ga,dispose:e=>e.destroy()});register(e,t){this._factories.set(e,t)}resolve(e){const t=this._factories.resolve(e);if(!t)throw new Error(`No factory registered for ${e.name}. Register one with loader.register() before loading.`);return t}has(e){return this._factories.has(e)}destroy(){this._factories.destroy()}}class Oa{onProgress;_progress;_promise;constructor(e,t){this.onProgress=new x,this._progress={total:t,loaded:0,pending:t,failed:0},this._promise=e}get progress(){return this._progress}_notifyItem(e){const t=this._progress,i=t.loaded+(e?1:0),n=t.failed+(e?0:1),r=i+n;this._progress={total:t.total,loaded:i,pending:Math.max(0,t.total-r),failed:n},this.onProgress.dispatch(this._progress)}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}}class Va{_registry=new Na;_assetTypeMap=new Map;_resources=new Map;_resourceKeys=new WeakMap;_manifest=new Map;_bundles=new Map;_inFlight=new Map;_typeIds=new WeakMap;_preventStoreKeys=new Set;_stores;_cacheStrategy;_aliasKeyToIdentityKey=new Map;_identityKeyToAliases=new Map;_inFlightByIdentity=new Map;_handlerFunctions=new Map;_extensionMap=new Map;_boundHandlers=[];_basePath;_fetchOptions;_concurrency;_nextTypeId=1;_fgBatchActive=0;_fgBatchLoaded=0;_fgBatchTotal=0;_backgroundQueue=[];_backgroundActive=0;_backgroundTotal=0;_backgroundLoaded=0;_backgroundResolve=null;onProgress=new x;onBundleProgress=new x;onLoaded=new x;onError=new x;onLoadStart=new x;onLoadProgress=new x;onLoadComplete=new x;onLoadError=new x;constructor(e={}){this._basePath=e.basePath??"",this._fetchOptions=e.fetchOptions??{},this._concurrency=e.concurrency??6,this._stores=e.cache?Array.isArray(e.cache)?e.cache:[e.cache]:[],this._cacheStrategy=e.cacheStrategy??new Ua}register(e,t){return this._registry.register(e,t),this}registerAssetType(e,t,i){if("function"==typeof t)this._assetTypeMap.set(e,t),i&&this._registry.register(t,i);else{const i=class{};Object.defineProperty(i,"name",{value:e}),this._assetTypeMap.set(e,i);const n=t.getIdentityKey?.bind(t);this._handlerFunctions.set(i,{load:(e,i)=>t.load(e,i),...void 0!==n&&{getIdentityKey:n}})}return this}registerExtension(e,t){return this._extensionMap.set(e.replace(/^\./,"").toLowerCase(),t),this}add(e,t){const i=e;if("string"==typeof t)this._addManifestEntry(i,t,t);else if(Array.isArray(t)){const e=t;for(const t of e)this._addManifestEntry(i,t,t)}else for(const[e,n]of Object.entries(t))this._addManifestEntry(i,e,n);return this}registerManifest(e){const t=ka(e),i=new Map,n=new Array;for(const[e,r]of Object.entries(t.bundles)){if(this._bundles.has(e))throw new Error(`Bundle "${e}" is already registered.`);const t=new Array;for(const n of r){const r=n.type,s=this._key(r,n.alias),o=i.get(s)??this._getManifestEntry(r,n.alias);if(o&&!this._isManifestDefinitionEquivalent(o,n.path,n.options))throw new Error(`Conflicting asset definition for (${this._describeType(r)}, "${n.alias}") while registering bundle "${e}".`);i.set(s,{path:n.path,options:n.options}),t.push({type:r,alias:n.alias,path:n.path,options:n.options})}n.push([e,t])}for(const[e,t]of n){for(const e of t)this._addManifestEntry(e.type,e.alias,e.path,e.options);this._bundles.set(e,t)}return this}async loadBundle(e,t={}){const i=this._bundles.get(e);if(!i)throw new Error(`Unknown bundle "${e}".`);const n=i.length;let r=0;const s=new Array;if(0!==n){if(await Promise.all(i.map(async i=>{try{await(t.background?this._loadSingleBackground(i.type,i.alias,i.path,i.options):this._loadSingle(i.type,i.alias,i.options,i.path))}catch(e){s.push({type:i.type,alias:i.alias,error:this._normalizeError(e)})}finally{r++,this._emitBundleProgress(e,r,n,t.onProgress)}})),s.length>0)throw new Ea(e,s)}else this._emitBundleProgress(e,0,0,t.onProgress)}async loadContainer(e){const t=await this._contextFetch(e,"__ctx_binary",e=>e.arrayBuffer()),{entries:i,dataStart:n}=Aa(t),r=i.map(t=>{const i=this._assetTypeMap.get(t.type);if(!i)throw new Error(`Container "${e}" references unknown asset type "${t.type}".`);return{entry:t,type:i}});await Promise.all(r.map(({entry:e,type:i})=>{const r=n+e.offset,s=t.slice(r,r+e.length);return this._injectSource(i,e.alias,s,e.options)}))}hasBundle(e){const t=this._bundles.get(e);return!!t&&t.every(e=>this._hasResource(e.type,e.alias))}load(e,t,i){if(e instanceof Ca){const t=e,i=t._config.source;return this._createLoadingQueue([{alias:i,asset:t}],e=>e.get(i))}if(e instanceof Ia){const t=e,i=Object.entries(t.entries).map(([e,t])=>({alias:e,asset:t}));return this._createLoadingQueue(i,e=>{const t={};for(const{alias:n}of i)t[n]=e.get(n);return t})}if("string"==typeof e&&void 0===t){const t=e,i=t.match(/\.([^./?#]+)(?:[?#]|$)/)?.[1]?.toLowerCase(),n=i?this._extensionMap.get(i):void 0;if(void 0===n)throw new Error(`Loader: no type registered for extension ".${i??"?"}" in "${t}". Register one via loader.registerExtension().`);const r=n===sa?{family:(t.split("/").pop()?.split(/[?#]/)[0]??"").replace(/\.[^.]+$/,"")}:void 0;this._onFgBatchStart(t,t);let s=null;const o=this._loadSingle(n,t,r).then(e=>(s?.(!0),this._onFgBatchSettled(t,!0),e),e=>{throw s?.(!1),this._onFgBatchSettled(t,!1,this._normalizeError(e)),e}),a=new Oa(o,1);return s=a._notifyItem.bind(a),a}if("function"==typeof e){const n=e,r=t,s=i;if("string"==typeof r){this._onFgBatchStart(r,r);let e=null;const t=this._loadSingle(n,r,s).then(t=>(e?.(!0),this._onFgBatchSettled(r,!0),t),t=>{throw e?.(!1),this._onFgBatchSettled(r,!1,this._normalizeError(t)),t}),i=new Oa(t,1);return e=i._notifyItem.bind(i),i}if(Array.isArray(r)){const e=r;let t=null;const i=new Array(e.length),o=e.map((e,r)=>(this._onFgBatchStart(e,e),this._loadSingle(n,e,s).then(n=>{i[r]=n,t?.(!0),this._onFgBatchSettled(e,!0)},i=>{throw t?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(i)),i}))),a=Promise.all(o).then(()=>i),h=new Oa(a,e.length);return t=h._notifyItem.bind(h),h}const o=Object.entries(r),a={};let h=null;const l=o.map(([e,t])=>{const i="string"==typeof t?t:t.source,r="string"==typeof t?s:{...t,..."object"==typeof s&&null!==s?s:{}};return this._onFgBatchStart(e,i),this._loadSingle(n,e,r,i).then(t=>{a[e]=t,h?.(!0),this._onFgBatchSettled(e,!0)},t=>{throw h?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t})}),u=Promise.all(l).then(()=>a),c=new Oa(u,o.length);return h=c._notifyItem.bind(c),c}const n=e,r=Object.entries(n).map(([e,t])=>({alias:e,asset:t instanceof Ca?t:new Ta(t)}));return this._createLoadingQueue(r,e=>{const t={};for(const{alias:i}of r)t[i]=e.get(i);return t})}backgroundLoad(){0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0);for(const[e,t]of this._manifest)for(const[i,n]of t){if(this._hasResource(e,i))continue;const t=this._key(e,i);this._inFlight.has(t)||(this._isQueuedInBackground(e,i)||(this._backgroundQueue.push({type:e,alias:i,path:n.path,options:n.options}),this._backgroundTotal++))}this._drainBackground()}loadAll(){return new Promise(e=>{this._backgroundResolve=e,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,e())})}setConcurrency(e){return this._concurrency=e,this}get(e,t){const i=e,n=this._resources.get(i);if(!n?.has(t))throw new Error(`Missing resource "${t}" for type ${i.name}.`);return n.get(t)}peek(e,t){const i=e;return this._resources.get(i)?.get(t)??null}has(e,t){const i=e;return this._resources.get(i)?.has(t)??!1}keyFor(e){return this._resourceKeys.get(e)??null}unload(e,t){if(e instanceof Ca){const t=e,i=this._assetTypeMap.get(t.type);if(!i)return this;const n=this._resolveAssetIdentityKey(i,t),r=this._identityKeyToAliases.get(n);if(r&&r.size>0)for(const e of[...r])this._unloadOne(i,e);else this._unloadOne(i,t._config.source);return this}if(e instanceof Ia){const t=e;for(const[e,i]of Object.entries(t.entries)){const t=i,n=this._assetTypeMap.get(t.type);if(!n)continue;const r=this._resolveAssetIdentityKey(n,t),s=this._identityKeyToAliases.get(r);if(s?.has(e))for(const e of[...s])this._unloadOne(n,e);else this._unloadOne(n,e)}return this}return this._unloadOne(e,t)}_unloadOne(e,t){const i=e,n=this._key(i,t);this._resources.get(i)?.delete(t);const r=this._aliasKeyToIdentityKey.get(n);if((this._inFlight.has(n)||void 0!==r&&this._inFlightByIdentity.has(r))&&this._preventStoreKeys.add(n),void 0!==r){this._aliasKeyToIdentityKey.delete(n);const e=this._identityKeyToAliases.get(r);e&&(e.delete(t),0===e.size&&this._identityKeyToAliases.delete(r))}return this}unloadAll(e){if(e)this._resources.get(e)?.clear();else for(const e of this._resources.values())e.clear();return this}get basePath(){return this._basePath}set basePath(e){this._basePath=e}get fetchOptions(){return this._fetchOptions}set fetchOptions(e){this._fetchOptions=e}bindAsset(e,t){const i=[],n=void 0!==e.typeNames?[...e.typeNames]:[];for(const t of e.extensions??[])i.push(t.replace(/^\./,"").toLowerCase());const r=new Set;for(const e of i){if(r.has(e))throw new Error(`Duplicate extension key ".${e}" within a single asset binding.`);r.add(e)}if(this._handlerFunctions.has(e.type))throw new Error(`An asset handler is already registered for ${e.type.name}.`);for(const e of n)if(this._assetTypeMap.has(e))throw new Error(`Asset type name "${e}" is already registered.`);for(const e of i)if(this._extensionMap.has(e))throw new Error(`File extension ".${e}" is already mapped to an asset type.`);const s=e=>{const{source:t,...i}=e;return 0===Object.keys(i).length?{source:t}:{source:t,options:i}},o=t.getIdentityKey?.bind(t),a=t.createFromBytes?.bind(t);this._handlerFunctions.set(e.type,{load:(e,i)=>t.load(s(e),i),...o&&{getIdentityKey:e=>o(s(e))},...a&&{createFromBytes:(e,t)=>a(e,t)}});for(const t of n)this._assetTypeMap.set(t,e.type);for(const t of i)this._extensionMap.set(t,e.type);this._boundHandlers.push(t)}hasLoadable(e){return this._handlerFunctions.has(e)||this._registry.has(e)}hasAssetType(e){return this._assetTypeMap.has(e)}hasExtension(e){return this._extensionMap.has(e.replace(/^\./,"").toLowerCase())}destroy(){this._registry.destroy();for(const e of this._stores)e.destroy();const e=new Set;for(const t of this._boundHandlers)e.has(t)||(e.add(t),t.destroy?.());this._boundHandlers.length=0,this._resources.clear(),this._manifest.clear(),this._bundles.clear(),this._inFlight.clear(),this._preventStoreKeys.clear(),this._inFlightByIdentity.clear(),this._aliasKeyToIdentityKey.clear(),this._identityKeyToAliases.clear(),this._handlerFunctions.clear(),this._backgroundQueue.length=0,this.onProgress.destroy(),this.onBundleProgress.destroy(),this.onLoaded.destroy(),this.onError.destroy(),this.onLoadStart.destroy(),this.onLoadProgress.destroy(),this.onLoadComplete.destroy(),this.onLoadError.destroy()}async _loadSingle(e,t,i,n){if(this._hasResource(e,t)){const i=this._resources.get(e);if(!0===i?.has(t))return i.get(t)}const r=this._key(e,t);if(this._inFlight.has(r))return this._inFlight.get(r);if(this._boostFromQueue(e,t),this._inFlight.has(r))return this._inFlight.get(r);const s=this._getManifestEntry(e,t),o=n??s?.path??t,a=i??s?.options,h=this._handlerFunctions.get(e);if(h){const i=this._identityKey(e,o),n={source:o};null!=a&&"object"==typeof a&&Object.assign(n,a);const s=this._buildHandlerContext(i);return this._trackInFlight(r,this._fetchWithHandler(e,t,o,n,h.load,s))}return this._trackInFlight(r,this._fetch(e,t,o,a))}_loadSingleBackground(e,t,i,n){if(this._hasResource(e,t)){const i=this._resources.get(e);if(!0===i?.has(t))return Promise.resolve(i.get(t))}const r=this._key(e,t),s=this._inFlight.get(r);if(s)return s;this._isQueuedInBackground(e,t)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:e,alias:t,path:i,options:n}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(r);return o||this._waitForBackgroundEntry(e,t)}_createLoadingQueue(e,t){const i=new Map;let n=null;const r=e.map(({alias:e,asset:t})=>{this._onFgBatchStart(e,t.source);const r=this._assetTypeMap.get(t.type);return r?this._loadSingleAsset(r,e,t).then(t=>{i.set(e,t),n?.(!0),this._onFgBatchSettled(e,!0)},t=>{throw n?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t}):Promise.reject(new Error(`No constructor registered for asset type "${t.type}". Call registerAssetType() first.`)).then(()=>{n?.(!0)},t=>{throw n?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t})}),s=Promise.all(r).then(()=>t(i)),o=new Oa(s,e.length);return n=o._notifyItem.bind(o),o}async _loadSingleAsset(e,t,i){if(this._hasResource(e,t))return this._resources.get(e)?.get(t);const n=i.source,r=i._config,{type:s,source:o,...a}=r,h=this._handlerFunctions.get(e),l=h?.getIdentityKey?.(r)??n,u=`id:${this._getTypeId(e)}:${l}`,c=this._key(e,t);this._aliasKeyToIdentityKey.set(c,u);let d=this._identityKeyToAliases.get(u);d||(d=new Set,this._identityKeyToAliases.set(u,d)),d.add(t);const _=this._inFlightByIdentity.get(u);if(_)return _.then(i=>(this._storeResource(e,t,i),i));let f;if(h){const i={source:n,...a},r=this._buildHandlerContext(u);f=this._fetchWithHandler(e,t,n,i,h.load,r)}else{const i=Object.keys(a).length>0?a:void 0;f=this._fetch(e,t,n,i)}const p=f.finally(()=>{this._inFlightByIdentity.delete(u)}).then(e=>e,t=>{const i=this._identityKeyToAliases.get(u);if(i){for(const t of i){const i=this._key(e,t);this._aliasKeyToIdentityKey.delete(i),this._preventStoreKeys.delete(i)}this._identityKeyToAliases.delete(u)}throw t});return this._inFlightByIdentity.set(u,p),p}async _fetchWithHandler(e,t,i,n,r,s){const o=this._resolveUrl(i);try{const i=await r(n,s);return this._storeResource(e,t,i),i}catch(e){const i=e instanceof Error?e.message:String(e);throw new Error(`Failed to load "${t}" from "${o}": ${i}`,{cause:e})}}_buildHandlerContext(e){return{loader:this,identityKey:e,fetchText:e=>this._contextFetch(e,"__ctx_text",e=>e.text()),fetchArrayBuffer:e=>this._contextFetch(e,"__ctx_binary",e=>e.arrayBuffer()),fetchJson:e=>this._contextFetch(e,"__ctx_json",e=>e.json())}}_contextFetch(e,t,i){const n=this._resolveUrl(e),r={storageName:t,process:i,create:e=>Promise.resolve(e),destroy(){}};return this._cacheStrategy.resolve({storageName:t,key:e,url:n,requestOptions:this._fetchOptions,factory:r,options:void 0},this._stores)}async _injectSource(e,t,i,n){const r=this._handlerFunctions.get(e);let s;if(r?.createFromBytes)s=await r.createFromBytes(i,n);else{if(!this._registry.has(e))throw new Error(`Asset type "${e.name}" cannot be built from container bytes (no createFromBytes handler).`);s=await this._registry.resolve(e).create(i,n)}this._storeResource(e,t,s)}async _fetch(e,t,i,n){const r=this._registry.resolve(e),s=this._resolveUrl(i);try{const o=await this._cacheStrategy.resolve({storageName:r.storageName,key:i,url:s,requestOptions:this._fetchOptions,factory:r,options:n},this._stores);return this._storeResource(e,t,o),o}catch(e){const i=e instanceof Error?e.message:String(e);throw new Error(`Failed to load "${t}" from "${s}": ${i}`,{cause:e})}}_onFgBatchStart(e,t){0===this._fgBatchActive&&(this._fgBatchLoaded=0),this._fgBatchActive++,this._fgBatchTotal++,1===this._fgBatchActive&&this.onLoadStart.dispatch(e,t)}_onFgBatchSettled(e,t,i){t?this._fgBatchLoaded++:void 0!==i&&this.onLoadError.dispatch(e,i),this._fgBatchActive--,this.onLoadProgress.dispatch(this._fgBatchLoaded,this._fgBatchTotal,e),0===this._fgBatchActive&&(this._fgBatchTotal=0,this.onLoadComplete.dispatch())}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const e=this._backgroundQueue.shift();if(!e)continue;const t=this._key(e.type,e.alias);this._hasResource(e.type,e.alias)||this._inFlight.has(t)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(e)}}_boostFromQueue(e,t){const i=this._backgroundQueue.findIndex(i=>i.type===e&&i.alias===t);if(-1===i)return;const[n]=this._backgroundQueue.splice(i,1);void 0!==n&&this._startBackgroundEntry(n)}_isQueuedInBackground(e,t){return this._backgroundQueue.some(i=>i.type===e&&i.alias===t)}_waitForBackgroundEntry(e,t){if(this._hasResource(e,t)){const i=this._resources.get(e);if(!0===i?.has(t))return Promise.resolve(i.get(t))}const i=this._key(e,t),n=this._inFlight.get(i);return n||new Promise((n,r)=>{const s=(i,r,s)=>{i===e&&r===t&&(a(),n(s))},o=(i,n,s)=>{i===e&&n===t&&(a(),r(s))},a=()=>{this.onLoaded.remove(s),this.onError.remove(o)};this.onLoaded.add(s),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(n,r);if(this._hasResource(e,t)){a();const i=this._resources.get(e);n(i?.get(t))}})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const e=this._backgroundResolve;this._backgroundResolve=null,e()}}_startBackgroundEntry(e){const t=this._key(e.type,e.alias);this._backgroundActive++,this._trackInFlight(t,this._fetch(e.type,e.alias,e.path,e.options)).catch(t=>{const i=t instanceof Error?t:new Error(String(t));this.onError.dispatch(e.type,e.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(e,t){const i=t.finally(()=>{this._inFlight.delete(e),this._preventStoreKeys.delete(e)});return this._inFlight.set(e,i),i}_emitBundleProgress(e,t,i,n){this.onBundleProgress.dispatch(e,t,i),n&&n(t,i)}_addManifestEntry(e,t,i,n){this._manifest.has(e)||this._manifest.set(e,new Map);const r=this._manifest.get(e);r&&r.set(t,{path:i,options:n})}_getManifestEntry(e,t){return this._manifest.get(e)?.get(t)}_isManifestDefinitionEquivalent(e,t,i){return e.path===t&&this._areOptionsEquivalent(e.options,i)}_areOptionsEquivalent(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(null===e||null===t)return!1;if("object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!this._areOptionsEquivalent(e[i],t[i]))return!1;return!0}if(Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date)return e.getTime()===t.getTime();if(e instanceof Map||e instanceof Set||e instanceof RegExp||e instanceof ArrayBuffer||ArrayBuffer.isView(e))return!1;const i=e,n=t,r=Object.keys(i),s=Object.keys(n);if(r.length!==s.length)return!1;for(const e of r){if(!Object.hasOwn(n,e))return!1;if(!this._areOptionsEquivalent(i[e],n[e]))return!1}return!0}_normalizeError(e){return e instanceof Error?e:new Error(String(e))}_describeType(e){return e.name.length>0?e.name:"(anonymous type)"}_hasResource(e,t){return this._resources.get(e)?.has(t)??!1}_storeResource(e,t,i){const n=this._key(e,t);if(this._preventStoreKeys.delete(n))return;let r=this._resources.get(e);r||(r=new Map,this._resources.set(e,r)),r.set(t,i),"object"!=typeof i||null===i||this._resourceKeys.has(i)||this._resourceKeys.set(i,{type:e,source:t}),this.onLoaded.dispatch(e,t,i)}_getTypeId(e){let t=this._typeIds.get(e);return void 0===t&&(t=this._nextTypeId++,this._typeIds.set(e,t)),t}_key(e,t){return`${this._getTypeId(e)}:${t}`}_identityKey(e,t){return`id:${this._getTypeId(e)}:${t}`}_resolveAssetIdentityKey(e,t){const i=t._config,n=this._handlerFunctions.get(e),r=n?.getIdentityKey?.(i)??t.source;return`id:${this._getTypeId(e)}:${r}`}_resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//")||e.startsWith("/")?e:`${this._basePath}${e}`}}const za="undefined"!=typeof window,qa="undefined"!=typeof document,Wa="undefined"!=typeof navigator;class Ya{static _readyPromise=null;static get ready(){return null===Ya._readyPromise&&(Ya._readyPromise=Ya._detect()),Ya._readyPromise}webgl2;webgpu;webgpuAdapter;webgpuVendor;webgpuArchitecture;pointer;keyboard;gamepad;touch;maxTouchPoints;audio;fullscreen;vibration;imageBitmap;deviceMemory;offscreenCanvas;webWorkers;devicePixelRatio;constructor(e){this.webgl2=e.webgl2,this.webgpu=e.webgpu,this.webgpuAdapter=e.webgpuAdapter,this.webgpuVendor=e.webgpuVendor,this.webgpuArchitecture=e.webgpuArchitecture,this.pointer=e.pointer,this.keyboard=e.keyboard,this.gamepad=e.gamepad,this.touch=e.touch,this.maxTouchPoints=e.maxTouchPoints,this.audio=e.audio,this.fullscreen=e.fullscreen,this.vibration=e.vibration,this.imageBitmap=e.imageBitmap,this.deviceMemory=e.deviceMemory,this.offscreenCanvas=e.offscreenCanvas,this.webWorkers=e.webWorkers,this.devicePixelRatio=e.devicePixelRatio,Object.freeze(this)}static async _detect(){const[e,t]=await async function(){if(!Xa())return[null,null];const e=navigator.gpu;if(!e||"function"!=typeof e.requestAdapter)return[null,null];try{const t=await e.requestAdapter();if(!t)return[null,null];const i=t;if(i.info)return[t,i.info];if("function"==typeof i.requestAdapterInfo)try{return[t,await i.requestAdapterInfo()]}catch{return[t,null]}return[t,null]}catch{return[null,null]}}();return new Ya({webgl2:$a(),webgpu:Xa(),webgpuAdapter:e,webgpuVendor:t?.vendor??null,webgpuArchitecture:t?.architecture??null,pointer:za&&"PointerEvent"in window,keyboard:za&&"KeyboardEvent"in window,gamepad:Wa&&"function"==typeof navigator.getGamepads,touch:Ha(),maxTouchPoints:ja(),audio:Ka(),fullscreen:Qa(),vibration:Wa&&"function"==typeof navigator.vibrate,imageBitmap:"function"==typeof createImageBitmap,deviceMemory:Za(),offscreenCanvas:za&&void 0!==window.OffscreenCanvas,webWorkers:za&&"function"==typeof window.Worker,devicePixelRatio:za?window.devicePixelRatio:1})}}function $a(){if(!qa)return!1;try{const e=document.createElement("canvas");return null!==e.getContext("webgl2")}catch{return!1}}function Xa(){return Wa&&"gpu"in navigator}function Ha(){return!!za&&("ontouchstart"in window||ja()>0)}function ja(){if(!Wa)return 0;const e=navigator.maxTouchPoints;return"number"==typeof e?e:0}function Ka(){if(!za)return!1;const e=window;return void 0!==e.AudioContext||void 0!==e.webkitAudioContext}function Qa(){if(!qa)return!1;const e=document.documentElement;return"function"==typeof e.requestFullscreen||"function"==typeof e.webkitRequestFullscreen}function Za(){if(!Wa)return 0;const e=navigator.deviceMemory;return"number"==typeof e?e:0}class Ja{_stepMs;_maxSteps;_accumulatorMs=0;constructor(e,t){if(this._stepMs=e,this._maxSteps=t,!(e>0&&Number.isFinite(e)))throw new RangeError(`FixedTimestep: step must be a positive finite number of ms, received ${e}.`)}get stepMs(){return this._stepMs}get alpha(){return this._accumulatorMs/this._stepMs}advance(e){this._accumulatorMs+=e;const t=1e-9*this._stepMs;let i=0;for(;this._accumulatorMs>=this._stepMs-t&&i<this._maxSteps;)this._accumulatorMs-=this._stepMs,i++;return this._accumulatorMs>this._stepMs&&(this._accumulatorMs%=this._stepMs),this._accumulatorMs<0&&(this._accumulatorMs=0),i}reset(){this._accumulatorMs=0}}var eh;e.LogSeverity=void 0,(eh=e.LogSeverity||(e.LogSeverity={}))[eh.Debug=0]="Debug",eh[eh.Info=1]="Info",eh[eh.Warning=2]="Warning",eh[eh.Error=3]="Error";class th{_handlers=[];_warnedKeys=new Set;log(t,i,n,r){if(t<e.LogSeverity.Error)return;const s={severity:t,channel:i,message:n,...void 0!==r?.data&&{data:r.data},...void 0!==r?.error&&{error:r.error}};for(const e of this._handlers)e(s)}debug(t,i,n){this.log(e.LogSeverity.Debug,t,i,n?{data:n}:void 0)}info(t,i,n){this.log(e.LogSeverity.Info,t,i,n?{data:n}:void 0)}warn(t,i,n){this.log(e.LogSeverity.Warning,t,i,n?{data:n}:void 0)}error(t,i,n){this.log(e.LogSeverity.Error,t,i,n?{error:n}:void 0)}warnOnce(e,t,i){this._warnedKeys.has(e)||(this._warnedKeys.add(e),this.warn(t,i))}addHandler(e){return this._handlers.push(e),()=>{const t=this._handlers.indexOf(e);t>=0&&this._handlers.splice(t,1)}}_resetWarnedKeys(){this._warnedKeys.clear()}}const ih=new th;class nh extends Bi{onResize=new x;_screenWidth=0;_screenHeight=0;get screenWidth(){return this._screenWidth}get screenHeight(){return this._screenHeight}_render(e){const t=e.screenView;this._screenWidth===t.width&&this._screenHeight===t.height||(this._screenWidth=t.width,this._screenHeight=t.height,this.onResize.dispatch(t.width,t.height)),e.render(this,{view:t})}destroy(){this.onResize.destroy(),super.destroy()}}class rh{_items=new Set;_order=[];_disposed=!1;get disposed(){return this._disposed}get size(){return this._items.size}track(e){return this._disposed||this._items.has(e)||(this._items.add(e),this._order.push(e)),e}has(e){return this._items.has(e)}untrack(e){if(this._disposed||!this._items.delete(e))return!1;const t=this._order.indexOf(e);return-1!==t&&this._order.splice(t,1),!0}destroy(){if(!this._disposed){this._disposed=!0;for(let e=this._order.length-1;e>=0;e--)try{this._order[e].destroy()}catch(e){}this._items.clear(),this._order.length=0}}}function sh(e,t){"number"==typeof t.x&&(e.x=t.x),"number"==typeof t.y&&(e.y=t.y),"number"==typeof t.rotation&&(e.rotation=t.rotation),"number"==typeof t.scaleX&&(e.scale.x=t.scaleX),"number"==typeof t.scaleY&&(e.scale.y=t.scaleY),"number"==typeof t.skewX&&(e.skewX=t.skewX),"number"==typeof t.skewY&&(e.skewY=t.skewY),"number"==typeof t.originX&&(e.origin.x=t.originX),"number"==typeof t.originY&&(e.origin.y=t.originY),!1===t.visible&&(e.visible=!1),"number"==typeof t.zIndex&&(e.zIndex=t.zIndex),!1===t.cullable&&(e.cullable=!1);const i=t.cullArea;if(Array.isArray(i)&&4===i.length&&(e.cullArea=new et(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"string"==typeof t.name&&(e.name=t.name),e instanceof Si){!0===t.interactive&&(e.interactive=!0),!0===t.draggable&&(e.draggable=!0),!0===t.focusable&&(e.focusable=!0),"number"==typeof t.tabIndex&&(e.tabIndex=t.tabIndex),"string"==typeof t.cursor&&(e.cursor=t.cursor),!0===t.clip&&(e.clip=!0),!0===t.preserveDrawOrder&&(e.preserveDrawOrder=!0),!0===t.cacheAsBitmap&&(e.cacheAsBitmap=!0);const i=t.clipShape;Array.isArray(i)&&4===i.length&&(e.clipShape=new et(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3])))}if(e instanceof Fn){const i=t.tint;Array.isArray(i)&&4===i.length&&(e.tint=new Tt(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"number"==typeof t.blendMode&&(e.blendMode=t.blendMode),"string"==typeof t.pixelSnapMode&&Tn(t.pixelSnapMode)&&(e.pixelSnapMode=t.pixelSnapMode)}}function oh(e,t,i){const n=e[t];return"number"==typeof n&&Number.isFinite(n)?n:i}function ah(e,t,i,n){const r=e[t];return"string"==typeof r&&i.includes(r)?r:n}function hh(e){return"object"!=typeof e||null===e||Array.isArray(e)?null:e}function lh(e){return"object"==typeof e&&null!==e&&"string"==typeof e.type?e:null}function uh(e){return Array.isArray(e)?e.map(e=>"number"==typeof e&&Number.isFinite(e)?e:0):null}const ch=["normal","bold","100","200","300","400","500","600","700","800","900"],dh=["left","center","right","justify"],_h=["stretch","repeat","mirror-repeat"],fh=["clip","round"];function ph(e,t,i,n,r,s){return(i-e)*(s-t)-(n-t)*(r-e)>0}function mh(e,t,i,n,r,s,o,a){const h=(e-r)*(n-s)-(i-r)*(t-s),l=(e-o)*(s-a)-(r-o)*(t-a),u=(e-i)*(a-n)-(o-i)*(t-n);return!((h<0||l<0||u<0)&&(h>0||l>0||u>0))&&0!==h&&0!==l&&0!==u}function gh(e,t,i,n,r,s){const o=e[2*n],a=e[2*n+1],h=e[2*r],l=e[2*r+1],u=e[2*s],c=e[2*s+1];let d=i[s];for(;d!==n;){if(d!==r){if(mh(e[2*d],e[2*d+1],o,a,h,l,u,c))return!1}d=i[d]}return!0}const yh=(e,t,i,n,r)=>{const s=[e,t,i,n],o=r/2,a=new it(e-i,t-n).perp().normalize().multiply(o),h=new it(i-e,n-t).perp().normalize().multiply(o),l=new Float32Array([e-a.x,t-a.y,e+a.x,t+a.y,i-h.x,n-h.y,i+h.x,n+h.y]);a.destroy(),h.destroy();return{vertices:l,indices:new Uint16Array([0,1,3,0,3,2]),points:s}},wh=(e,t)=>{if(e.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const i=t/2,n=new it(e[0],e[1]),r=new it(e[e.length-2],e[e.length-1]),s=e;if(n.x===r.x&&n.y===r.y){(e=[...e]).pop(),e.pop();const[t=0,i=0]=[e[e.length-2],e[e.length-1]];r.set(t,i);const s=r.x+.5*(n.x-r.x),o=r.y+.5*(n.y-r.y);e.unshift(s,o),e.push(s,o)}n.destroy(),r.destroy();const o=e.length/2,a=[];let h,l,u,c,d,_,f=e[0],p=e[1],m=e[2],g=e[3],y=-(p-g),w=f-m,x=Math.sqrt(y*y+w*w);y/=x,w/=x,y*=i,w*=i,a.push(f-y,p-w),a.push(f+y,p+w);for(let t=1;t<o-1;t++){f=e[2*(t-1)],p=e[2*(t-1)+1],m=e[2*t],g=e[2*t+1],h=e[2*(t+1)],l=e[2*(t+1)+1],y=-(p-g),w=f-m,x=Math.sqrt(y*y+w*w),y/=x,w/=x,y*=i,w*=i,u=-(g-l),c=m-h,x=Math.sqrt(u*u+c*c),u/=x,c/=x,u*=i,c*=i;const n=-w+p-(-w+g),r=-y+m-(-y+f),s=(-y+f)*(-w+g)-(-y+m)*(-w+p),o=-c+l-(-c+g),v=-u+m-(-u+h),b=(-u+h)*(-c+g)-(-u+m)*(-c+l),S=n*v-o*r;if(Math.abs(S)<.1){a.push(m-y,g-w),a.push(m+y,g+w);continue}const B=(r*b-v*s)/S,C=(o*s-n*b)/S;(B-m)*(B-m)+(C-g)*(C-g)>196*i*i?(d=y-u,_=w-c,x=Math.sqrt(d*d+_*_),d/=x,_/=x,d*=i,_*=i,a.push(m-d,g-_),a.push(m+d,g+_),a.push(m-d,g-_)):(a.push(B,C),a.push(m-(B-m),g-(C-g)))}f=e[2*(o-2)],p=e[2*(o-2)+1],m=e[2*(o-1)],g=e[2*(o-1)+1],y=-(p-g),w=f-m,x=Math.sqrt(y*y+w*w),y/=x,w/=x,y*=i,w*=i,a.push(m-y,g-w),a.push(m+y,g+w);const v=a.length/2,b=new Float32Array(a),S=v>=3?v-2:0,B=new Uint16Array(3*S);for(let e=0;e<S;e++){const t=3*e;1&e?(B[t]=e+1,B[t+1]=e,B[t+2]=e+2):(B[t]=e,B[t+1]=e+1,B[t+2]=e+2)}return{vertices:b,indices:B,points:s}},xh=(e,t,i)=>{const n=Math.floor(15*Math.sqrt(i+i)),r=2*Math.PI/n,s=[],o=new Float32Array(2*(n+1));o[0]=e,o[1]=t;for(let a=0;a<n;a++){const n=e+Math.sin(r*a)*i,h=t+Math.cos(r*a)*i;s.push(n,h);const l=2*(a+1);o[l]=n,o[l+1]=h}const a=new Uint16Array(3*n);for(let e=0;e<n;e++){const t=3*e;a[t]=0,a[t+1]=e+1,a[t+2]=e+2>n?1:e+2}return{vertices:o,indices:a,points:s}},vh=(e,t,i,n)=>{const r=Math.floor(15*Math.sqrt(i+n)),s=2*Math.PI/r,o=[],a=new Float32Array(2*(r+1));a[0]=e,a[1]=t;for(let h=0;h<r;h++){const r=e+Math.sin(s*h)*i,l=t+Math.cos(s*h)*n;o.push(r,l);const u=2*(h+1);a[u]=r,a[u+1]=l}const h=new Uint16Array(3*r);for(let e=0;e<r;e++){const t=3*e;h[t]=0,h[t+1]=e+1,h[t+2]=e+2>r?1:e+2}return{vertices:a,indices:h,points:o}},bh=e=>{if(e.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const t=e.length/2,i=function(e){const t=e.length>>1;if(t<3)return new Uint32Array(0);if(3===t)return ph(e[0],e[1],e[2],e[3],e[4],e[5])?new Uint32Array([0,1,2]):new Uint32Array([2,1,0]);const i=new Uint32Array(t),n=new Uint32Array(t);for(let e=0;e<t;e++)i[e]=(e+t-1)%t,n[e]=(e+1)%t;if(function(e){const t=e.length>>1;let i=0;for(let n=0;n<t;n++){const r=(n+1)%t,s=e[2*n],o=e[2*n+1],a=e[2*r];i+=s*e[2*r+1]-a*o}return i}(e)<0)for(let e=0;e<t;e++){const t=i[e];i[e]=n[e],n[e]=t}const r=new Uint32Array(3*(t-2));let s=0,o=t,a=0;for(;o>3;){let t=!1;const h=a;do{const h=i[a],l=n[a],u=a;if(ph(e[2*h],e[2*h+1],e[2*u],e[2*u+1],e[2*l],e[2*l+1])&&gh(e,0,n,h,u,l)){r[s++]=h,r[s++]=u,r[s++]=l,n[h]=l,i[l]=h,o--,t=!0,a=l;break}a=n[a]}while(a!==h);if(!t)break}if(3===o){const t=i[a],o=n[a];ph(e[2*t],e[2*t+1],e[2*a],e[2*a+1],e[2*o],e[2*o+1])?(r[s++]=t,r[s++]=a,r[s++]=o):(r[s++]=o,r[s++]=a,r[s++]=t)}return r.subarray(0,s)}(e),n=new Float32Array(e.length);for(let i=0;i<t;i++)n[2*i]=e[2*i],n[2*i+1]=e[2*i+1];return{vertices:n,indices:new Uint16Array(i),points:e}},Sh=(e,t,i,n)=>({vertices:new Float32Array([e,t,e+i,t,e,t+n,e+i,t+n]),indices:new Uint16Array([0,1,2,1,3,2]),points:[e,t,e+i,t,e+i,t+n,e,t+n]}),Bh=(e,t,i,n,r)=>{const s=Math.min(Math.abs(r),i/2,n/2);if(s<=0)return Sh(e,t,i,n);const o=Math.max(1,Math.floor(15*Math.sqrt(s+s)/4)),a=Math.PI/2/o,h=[[e+s,t+s,Math.PI],[e+i-s,t+s,1.5*Math.PI],[e+i-s,t+n-s,0],[e+s,t+n-s,.5*Math.PI]],l=[];for(const[e=0,t=0,i=0]of h)for(let n=0;n<=o;n++){const r=i+a*n,o=e+Math.cos(r)*s,h=t+Math.sin(r)*s,u=l.length;u>=2&&Math.abs(l[u-2]-o)<1e-4&&Math.abs(l[u-1]-h)<1e-4||l.push(o,h)}const u=l.length/2,c=new Float32Array(2*(u+1));c[0]=e+i/2,c[1]=t+n/2;for(let e=0;e<u;e++){const t=2*(e+1);c[t]=l[2*e],c[t+1]=l[2*e+1]}const d=new Uint16Array(3*u);for(let e=0;e<u;e++){const t=3*e;d[t]=0,d[t+1]=e+1,d[t+2]=e+2>u?1:e+2}return{vertices:c,indices:d,points:[...l,l[0],l[1]]}},Ch=(e,t,i,n,r=n/2,s=0)=>{const o=Math.PI/-2+s,a=2*i,h=N/a,l=[];for(let i=0;i<a;i++){const s=o+i*h,a=i%2?r:n;l.push(e+a*Math.cos(s),t+a*Math.sin(s))}return bh(l)},Th={line:yh,path:wh,circle:xh,ellipse:vh,polygon:bh,rectangle:Sh,roundedRectangle:Bh,star:Ch};class Mh extends Bi{_lineWidth=0;_fillColor=new Tt(0,0,0,0);_lineColor=new Tt;_fillStyle=this._fillColor;_strokeStyle=this._lineColor;_fillStyleTexture=null;_strokeStyleTexture=null;_ownedTextures=new Set;_currentPoint=new it(0,0);get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=e}get lineColor(){return this._lineColor}set lineColor(e){this.strokeStyle=e}get fillColor(){return this._fillColor}set fillColor(e){this.fillStyle=e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=this._resolveStyle(e,this._fillColor),this._fillStyleTexture=null}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=this._resolveStyle(e,this._lineColor),this._strokeStyleTexture=null}get currentPoint(){return this._currentPoint}getChildAt(e){return super.getChildAt(e)}addChild(e){if(!(e instanceof In))throw new Error("Graphics can only contain Mesh children.");return super.addChild(e)}addChildAt(e,t){if(!(e instanceof In))throw new Error("Graphics can only contain Mesh children.");return super.addChildAt(e,t)}moveTo(e,t){return this._currentPoint.set(e,t),this}lineTo(e,t){const{x:i,y:n}=this._currentPoint;return this.drawPath([i,n,e,t]),this.moveTo(e,t),this}quadraticCurveTo(e,t,i,n){const{x:r,y:s}=this._currentPoint;return this.drawPath(Q(r,s,e,t,i,n)),this.moveTo(i,n),this}bezierCurveTo(e,t,i,n,r,s){const{x:o,y:a}=this._currentPoint;return this.drawPath(K(o,a,e,t,i,n,r,s)),this.moveTo(r,s),this}arcTo(e,t,i,n,r){const{x:s,y:o}=this._currentPoint,a=Math.abs(r);if(0===a||s===e&&o===t||e===i&&t===n)return this.lineTo(e,t);const h=e-s,l=t-o,u=i-e,c=n-t,d=Math.hypot(h,l),_=Math.hypot(u,c);if(0===d||0===_)return this.lineTo(e,t);const f=h/d,p=l/d,m=u/_,g=c/_,y=Y(f*m+p*g,-1,1),w=Math.acos(y);if(0===w||w===Math.PI)return this.lineTo(e,t);const x=a/Math.tan(w/2);if(!Number.isFinite(x)||x>d||x>_)return this.lineTo(e,t);const v=e-f*x,b=t-p*x,S=e+m*x,B=t+g*x,C=f*g-p*m>0,T=v+(C?-p:p)*a,M=b+(C?f:-f)*a,P=Math.atan2(b-M,v-T),A=Math.atan2(B-M,S-T);return this.lineTo(v,b),this.drawArc(T,M,a,P,A,C)}drawArc(e,t,i,n,r,s=!1){const o=Math.abs(i);if(0===o)return this;let a=r-n;if(!s&&a<0?a+=N:s&&a>0&&(a-=N),0===a)return this;const h=Math.max(2,Math.ceil(Math.abs(a)/(Math.PI/16))),l=[];for(let i=0;i<=h;i++){const r=n+a*(i/h);l.push(e+Math.cos(r)*o,t+Math.sin(r)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(e,t,i,n){const r=yh(e,t,i,n,this._lineWidth);return this.addChild(this._createStrokeMesh(r)),this}drawPath(e){const t=wh(e,this._lineWidth);return this.addChild(this._createStrokeMesh(t)),this}_strokeClosedOutline(e){e.length>=4?this.drawPath([...e,e[0],e[1]]):this.drawPath(e)}drawPolygon(e){const t=bh(e);return this._appendFill(t),this._lineWidth>0&&this._strokeClosedOutline(t.points),this}drawCircle(e,t,i){const n=xh(e,t,i);return this._appendFill(n),this._lineWidth>0&&this._strokeClosedOutline(n.points),this}drawEllipse(e,t,i,n){const r=vh(e,t,i,n);return this._appendFill(r),this._lineWidth>0&&this._strokeClosedOutline(r.points),this}drawRectangle(e,t,i,n){const r=Sh(e,t,i,n);return this._appendFill(r),this._lineWidth>0&&this._strokeClosedOutline(r.points),this}drawRoundedRectangle(e,t,i,n,r){const s=Bh(e,t,i,n,r);return this._appendFill(s),this._lineWidth>0&&this._strokeClosedOutline(s.points),this}drawStar(e,t,i,n,r=n/2,s=0){const o=Ch(e,t,i,n,r,s);return this._appendFill(o),this._lineWidth>0&&this._strokeClosedOutline(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._fillColor.copy(Tt.transparentBlack),this._lineColor.copy(Tt.black),this._fillStyle=this._fillColor,this._strokeStyle=this._lineColor,this._fillStyleTexture=null,this._strokeStyleTexture=null,this._destroyOwnedTextures(),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}_resolveStyle(e,t){return null===e?t:e instanceof Tt?(t.copy(e),t):e.clone()}_appendFill(e){this._fillStyle instanceof Tt&&0===this._fillStyle.a||this.addChild(this._createFillMesh(e))}_createFillMesh(e){return this._fillStyle instanceof Tt?this._createSolidMesh(e,this._fillStyle):(this._fillStyleTexture??=this._rasterizeGradient(this._fillStyle),this._createGradientMesh(e,this._fillStyleTexture))}_createStrokeMesh(e){return this._strokeStyle instanceof Tt?this._createSolidMesh(e,this._strokeStyle):(this._strokeStyleTexture??=this._rasterizeGradient(this._strokeStyle),this._createGradientMesh(e,this._strokeStyleTexture))}_createSolidMesh(e,t){const i=new In({vertices:e.vertices,indices:e.indices});return i.tint=t,i}_createGradientMesh(e,t){return new In({vertices:e.vertices,indices:e.indices,uvs:Ph(e.vertices),texture:t})}_rasterizeGradient(t){const i=t.toTexture(256,256,{samplerOptions:{scaleMode:e.ScaleModes.Linear}});return this._ownedTextures.add(i),i}_destroyOwnedTextures(){for(const e of this._ownedTextures)e.destroy();this._ownedTextures.clear()}}const Ph=e=>{let t=1/0,i=1/0,n=-1/0,r=-1/0;for(let s=0;s<e.length;s+=2){const o=e[s],a=e[s+1];o<t&&(t=o),o>n&&(n=o),a<i&&(i=a),a>r&&(r=a)}const s=n-t,o=r-i,a=s>0?1/s:0,h=o>0?1/o:0,l=new Float32Array(e.length);for(let n=0;n<e.length;n+=2)l[n]=(e[n]-t)*a,l[n+1]=(e[n+1]-i)*h;return l},Ah=-1;function Eh(e,t){if(!Number.isInteger(t)||t!==Ah&&t<1)throw new Error(`AnimatedSprite ${e} has an invalid repeat value (${t}). Must be -1 (infinite) or a positive integer.`)}class kh extends vr{_clips=new Map;_currentClipName=null;_currentFrameIndex=0;_hasAppliedFrame=!1;_playing=!1;_repeatOverride=null;_elapsedFrameTimeMs=0;_completedCycles=0;onComplete=new x;onFrame=new x;constructor(e,t){super(e),t&&this.setClips(t)}get currentClip(){return this._currentClipName}get currentFrame(){return this._currentFrameIndex}get playing(){return this._playing}get repeat(){return null!==this._repeatOverride?this._repeatOverride:this._currentClipName?this._clips.get(this._currentClipName)?.repeat??Ah:Ah}set repeat(e){Eh("repeat",e),this._repeatOverride=e}setClips(e){this._clips.clear();for(const[t,i]of Object.entries(e))this.defineClip(t,i);return this}defineClip(e,t){if(0===e.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");const i=t.frames;if(!Array.isArray(t.frames)||0===i.length)throw new Error(`AnimatedSprite clip "${e}" must define at least one frame.`);const n=t.fps??12;if(!Number.isFinite(n)||n<=0)throw new Error(`AnimatedSprite clip "${e}" has an invalid fps value (${n}).`);const r=t.repeat??Ah;Eh(`clip "${e}"`,r);let s=null;if(t.frameDurations){if(t.frameDurations.length!==i.length)throw new Error(`AnimatedSprite clip "${e}" frameDurations length (${t.frameDurations.length}) must match its frame count (${i.length}).`);for(const i of t.frameDurations)if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${e}" has an invalid frameDurations value (${i}).`);s=[...t.frameDurations]}let o=null;if(t.frameOffsets){if(t.frameOffsets.length!==i.length)throw new Error(`AnimatedSprite clip "${e}" frameOffsets length (${t.frameOffsets.length}) must match its frame count (${i.length}).`);for(const i of t.frameOffsets)if(!Number.isFinite(i.x)||!Number.isFinite(i.y))throw new Error(`AnimatedSprite clip "${e}" has an invalid frameOffsets value (${JSON.stringify(i)}).`);o=t.frameOffsets.map(e=>({x:e.x,y:e.y}))}return this._clips.set(e,{frames:i.map(e=>e.clone()),frameDurationMs:1e3/n,frameDurations:s,frameOffsets:o,repeat:r}),this}_getClipDefinitions(){const e={};for(const[t,i]of this._clips)e[t]={frames:i.frames.map(e=>e.clone()),fps:1e3/i.frameDurationMs,repeat:i.repeat,...i.frameDurations?{frameDurations:[...i.frameDurations]}:{},...i.frameOffsets?{frameOffsets:i.frameOffsets.map(e=>({x:e.x,y:e.y}))}:{}};return e}removeClip(e){return this._currentClipName===e&&this.stop(),this._clips.delete(e),this}play(e,t={}){const i=this._clips.get(e);if(!i)throw new Error(`AnimatedSprite clip "${e}" is not defined.`);void 0!==t.repeat&&Eh("play() options.repeat",t.repeat);const n=this._currentClipName===e,r=t.restart??!0;return n&&!r||(this._currentClipName=e,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._completedCycles=0,this._applyFrame(i,0),this.onFrame.dispatch(e,0)),this._repeatOverride=t.repeat??this._repeatOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const e=this._clips.get(this._currentClipName);return e&&e.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(e,0),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(e){if(!this._playing||null===this._currentClipName)return this;const t=this._clips.get(this._currentClipName);if(!t||t.frames.length<=1)return this;const i="number"==typeof e?e:e.milliseconds;if(i<=0)return this;this._elapsedFrameTimeMs+=i;let n=t.frameDurations?.[this._currentFrameIndex]??t.frameDurationMs;for(;this._elapsedFrameTimeMs>=n;){this._elapsedFrameTimeMs-=n;const e=this._currentFrameIndex+1;if(e>=t.frames.length){const e=this._repeatOverride??t.repeat;let i;if(e===Ah?i=!0:(this._completedCycles++,i=this._completedCycles<e),i){this._currentFrameIndex=0,this._applyFrame(t,0),this.onFrame.dispatch(this._currentClipName,0),n=t.frameDurations?.[this._currentFrameIndex]??t.frameDurationMs;continue}this._currentFrameIndex=t.frames.length-1,this._applyFrame(t,this._currentFrameIndex),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=e,this._applyFrame(t,this._currentFrameIndex),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex),n=t.frameDurations?.[this._currentFrameIndex]??t.frameDurationMs}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const e of this._clips.values())for(const t of e.frames)t.destroy();this._clips.clear()}static fromSpritesheet(e){const t={};for(const[i,n]of e.animations)t[i]={frames:n.map(t=>e.getFrame(t))};return new kh(e.texture,t)}_applyFrame(e,t){if(this._hasAppliedFrame)this.setTextureFrame(e.frames[t],!1);else{const i=this.scale.x,n=this.scale.y;this.setTextureFrame(e.frames[t],!0),this.scale.set(i,n),this._hasAppliedFrame=!0}const i=e.frameOffsets?.[t];i&&(this.getLocalBounds().setPosition(i.x,i.y),this._invalidateBoundsCascade())}}function Rh(e){const t={};for(const[i,n]of Object.entries(e))void 0!==n&&(t[i]=n);return t}const Dh=e=>[e.r,e.g,e.b,e.a],Fh=e=>Array.isArray(e)&&4===e.length?new Tt(Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])):void 0,Ih=(e,t,i,n,r)=>e.r===t&&e.g===i&&e.b===n&&e.a===r;function Lh(e){const t={};return"Arial"!==e.fontFamily&&(t.fontFamily=e.fontFamily),"normal"!==e.fontWeight&&(t.fontWeight=e.fontWeight),"normal"!==e.fontStyle&&(t.fontStyle=e.fontStyle),20!==e.fontSize&&(t.fontSize=e.fontSize),Ih(e.fillColor,255,255,255,1)||(t.fillColor=Dh(e.fillColor)),Ih(e.outlineColor,0,0,0,1)||(t.outlineColor=Dh(e.outlineColor)),0!==e.outlineWidth&&(t.outlineWidth=e.outlineWidth),"left"!==e.align&&(t.align=e.align),1.2!==e.lineHeight&&(t.lineHeight=e.lineHeight),0!==e.leading&&(t.leading=e.leading),Ih(e.shadowColor,0,0,0,1)||(t.shadowColor=Dh(e.shadowColor)),0!==e.shadowOffsetX&&(t.shadowOffsetX=e.shadowOffsetX),0!==e.shadowOffsetY&&(t.shadowOffsetY=e.shadowOffsetY),0!==e.shadowAlpha&&(t.shadowAlpha=e.shadowAlpha),0!==e.shadowBlur&&(t.shadowBlur=e.shadowBlur),null!==e.gradientColors&&(t.gradientColors=[Dh(e.gradientColors[0]),Dh(e.gradientColors[1])]),"vertical"!==e.gradientAxis&&(t.gradientAxis=e.gradientAxis),Object.keys(t).length>0?t:void 0}function Uh(e){if("object"!=typeof e||null===e)return;const t=e,i={};"string"==typeof t.fontFamily&&(i.fontFamily=t.fontFamily);const n=ah(t,"fontWeight",ch);void 0!==n&&(i.fontWeight=n),"italic"!==t.fontStyle&&"normal"!==t.fontStyle||(i.fontStyle=t.fontStyle),"number"==typeof t.fontSize&&(i.fontSize=t.fontSize);const r=Fh(t.fillColor);void 0!==r&&(i.fillColor=r);const s=Fh(t.outlineColor);void 0!==s&&(i.outlineColor=s),"number"==typeof t.outlineWidth&&(i.outlineWidth=t.outlineWidth);const o=ah(t,"align",dh);void 0!==o&&(i.align=o),"number"==typeof t.lineHeight&&(i.lineHeight=t.lineHeight),"number"==typeof t.leading&&(i.leading=t.leading);const a=Fh(t.shadowColor);if(void 0!==a&&(i.shadowColor=a),"number"==typeof t.shadowOffsetX&&(i.shadowOffsetX=t.shadowOffsetX),"number"==typeof t.shadowOffsetY&&(i.shadowOffsetY=t.shadowOffsetY),"number"==typeof t.shadowAlpha&&(i.shadowAlpha=t.shadowAlpha),"number"==typeof t.shadowBlur&&(i.shadowBlur=t.shadowBlur),Array.isArray(t.gradientColors)&&2===t.gradientColors.length){const e=Fh(t.gradientColors[0]),n=Fh(t.gradientColors[1]);void 0!==e&&void 0!==n&&(i.gradientColors=[e,n])}return"horizontal"!==t.gradientAxis&&"vertical"!==t.gradientAxis||(i.gradientAxis=t.gradientAxis),i}const Gh=["visible","clip","ellipsis"],Nh=["ltr","rtl"],Oh=["normal","pre","pre-line"];function Vh(e){if("object"!=typeof e||null===e)return;const t=e,i={},n=oh(t,"maxWidth");void 0!==n&&(i.maxWidth=n);const r=oh(t,"maxHeight");void 0!==r&&(i.maxHeight=r);const s=ah(t,"overflow",Gh);void 0!==s&&(i.overflow=s);const o=oh(t,"letterSpacing");void 0!==o&&(i.letterSpacing=o);const a=ah(t,"direction",Nh);void 0!==a&&(i.direction=a);const h=function(e,t,i){const n=e[t];return"boolean"==typeof n?n:i}(t,"breakWords");void 0!==h&&(i.breakWords=h);const l=ah(t,"whiteSpace",Oh);return void 0!==l&&(i.whiteSpace=l),Object.keys(i).length>0?i:void 0}const zh=e=>Array.isArray(e)?new Float32Array(e.map(Number)):new Float32Array,qh=e=>Array.isArray(e)?new Uint32Array(e.map(Number)):new Uint32Array,Wh=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,Yh=e=>{const t=hh(e);return{left:Wh(t?.left)??0,top:Wh(t?.top)??0,right:Wh(t?.right)??0,bottom:Wh(t?.bottom)??0}},$h=e=>{const t=hh(e);if(null===t)return;const i={},n=ah(t,"edges",_h);void 0!==n&&(i.edges=n);const r=ah(t,"center",_h);void 0!==r&&(i.center=r);const s=ah(t,"top",_h);void 0!==s&&(i.top=s);const o=ah(t,"right",_h);void 0!==o&&(i.right=o);const a=ah(t,"bottom",_h);void 0!==a&&(i.bottom=a);const h=ah(t,"left",_h);void 0!==h&&(i.left=h);const l=ah(t,"edgeFit",fh);void 0!==l&&(i.edgeFit=l);const u=ah(t,"centerFit",fh);return void 0!==u&&(i.centerFit=u),i},Xh={write(e,t){const i={vertices:[...e.vertices]};null!==e.indices&&(i.indices=[...e.indices]),null!==e.uvs&&(i.uvs=[...e.uvs]),null!==e.colors&&(i.colors=[...e.colors]);const n=t.keyFor(e.texture);return null!==n&&(i.texture=n),e.material,i},read(e,t){return new In(Rh({vertices:zh(e.vertices),indices:void 0!==e.indices?(i=e.indices,Array.isArray(i)?new Uint16Array(i.map(Number)):new Uint16Array):void 0,uvs:void 0!==e.uvs?zh(e.uvs):void 0,colors:void 0!==e.colors?qh(e.colors):void 0,texture:t.resolveAsset("string"==typeof e.texture?e.texture:null,pi)}));var i}},Hh={write:(e,t)=>0===e.children.length?{}:{children:e.children.map(e=>t.writeNode(e))},read(e,t){const i=new Mh,n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}},jh={write(e,t){const i={slices:{...e.slices},border:{...e.border},modes:{...e.modes},width:e.width,height:e.height},n=t.keyFor(e.texture);return null!==n&&(i.texture=n),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi);if(null===i)throw new Error("NineSliceSprite deserialize requires its texture to be pre-loaded into the Loader.");return new ur(i,Rh({slices:Yh(e.slices),border:null!==hh(e.border)?Yh(e.border):void 0,modes:$h(e.modes),width:Wh(e.width),height:Wh(e.height)}))}},Kh={write(e,t){const i={width:e.width,height:e.height,modeX:e.modeX,modeY:e.modeY,fitX:e.fitX,fitY:e.fitY,offsetX:e.offsetX,offsetY:e.offsetY},n=t.keyFor(e.texture);return null!==n&&(i.texture=n),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi);if(null===i)throw new Error("RepeatingSprite deserialize requires its texture to be pre-loaded into the Loader.");return new wr(i,Rh({width:Wh(e.width),height:Wh(e.height),modeX:ah(e,"modeX",_h),modeY:ah(e,"modeY",_h),fitX:ah(e,"fitX",fh),fitY:ah(e,"fitY",fh),offsetX:Wh(e.offsetX),offsetY:Wh(e.offsetY)}))}},Qh={write(e,t){const i={},n=t.keyFor(e.texture);null!==n&&(i.texture=n);const r={};for(const[t,i]of Object.entries(e._getClipDefinitions()))r[t]=Rh({frames:i.frames.map(e=>[e.x,e.y,e.width,e.height]),fps:i.fps,repeat:i.repeat,frameDurations:i.frameDurations?[...i.frameDurations]:void 0,frameOffsets:i.frameOffsets?i.frameOffsets.map(e=>[e.x,e.y]):void 0});return i.clips=r,null!==e.currentClip&&(i.currentClip=e.currentClip),e.playing&&(i.playing=!0),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi),n={},r=hh(e.clips);if(null!==r)for(const[e,t]of Object.entries(r)){const i=hh(t);if(null===i)continue;const r=Array.isArray(i.frames)?i.frames.map(e=>{const t=uh(e)??[];return new et(t[0]??0,t[1]??0,t[2]??0,t[3]??0)}):[],s=Array.isArray(i.frameDurations)?uh(i.frameDurations)??void 0:void 0,o=Array.isArray(i.frameOffsets)?i.frameOffsets.map(e=>{const t=uh(e)??[];return{x:t[0]??0,y:t[1]??0}}):void 0;n[e]=Rh({frames:r,fps:Wh(i.fps),repeat:Wh(i.repeat),frameDurations:s,frameOffsets:o})}const s=new kh(i,n);return"string"==typeof e.currentClip&&e.currentClip in n&&(s.play(e.currentClip),!0!==e.playing&&s.pause()),s}},Zh={write(e,t){const i={text:e.text},n=t.keyFor(e.font);null!==n&&(i.font=n),e.msdf&&(i.msdf=!0),1!==e.fontScale&&(i.scale=e.fontScale);const r=Lh(e.style);return void 0!==r&&(i.style=r),Object.keys(e.layout).length>0&&(i.layout={...e.layout}),i},read(e,t){const i=t.resolveAsset("string"==typeof e.font?e.font:null,Sr);if(null===i)throw new Error("BitmapText deserialize requires its BmFont to be pre-loaded into the Loader.");const n=Vh(e.layout);return new Ar("string"==typeof e.text?e.text:"",i,Rh({...Uh(e.style),msdf:!0===e.msdf,scale:Wh(e.scale),layout:n}))}},Jh={write(e){const t={src:e.videoElement.src};return 1!==e.volume&&(t.volume=e.volume),e.loop&&(t.loop=!0),1!==e.playbackRate&&(t.playbackRate=e.playbackRate),e.muted&&(t.muted=!0),e.currentTime>0&&(t.time=e.currentTime),t},read(e){const t=document.createElement("video");return"string"==typeof e.src&&(t.src=e.src),new Co(t,Rh({volume:Wh(e.volume),loop:!0===e.loop||void 0,playbackRate:Wh(e.playbackRate),muted:!0===e.muted||void 0,time:Wh(e.time)}))}};class el extends Bi{_uiWidth=0;_uiHeight=0;_enabled=!0;_uiAnchor=null;_uiAnchorOffsetX=0;_uiAnchorOffsetY=0;_uiAnchorRoot=null;_onAnchorResize=(e,t)=>{this._applyAnchor(e,t)};get uiWidth(){return this._uiWidth}get uiHeight(){return this._uiHeight}setSize(e,t){const i=Math.max(0,e),n=Math.max(0,t);return this._uiWidth===i&&this._uiHeight===n||(this._uiWidth=i,this._uiHeight=n,this._relayout(),null!==this._uiAnchorRoot&&this._applyAnchor(this._uiAnchorRoot.screenWidth,this._uiAnchorRoot.screenHeight)),this}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._onEnabledChanged(e))}anchorIn(e,t,i=0,n=0){return this._uiAnchor=t,this._uiAnchorOffsetX=i,this._uiAnchorOffsetY=n,this._uiAnchorRoot!==e&&(this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=e,e.onResize.add(this._onAnchorResize)),this._applyAnchor(e.screenWidth,e.screenHeight),this}_applyAnchor(e,t){if(null===this._uiAnchor)return;const[i,n]=(e=>{let t=.5,i=.5;return e.endsWith("left")?t=0:e.endsWith("right")&&(t=1),e.startsWith("top")?i=0:e.startsWith("bottom")&&(i=1),[t,i]})(this._uiAnchor);this.setPosition(i*(e-this._uiWidth)+this._uiAnchorOffsetX,n*(t-this._uiHeight)+this._uiAnchorOffsetY)}_relayout(){}_onEnabledChanged(e){}destroy(){this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=null,super.destroy()}}class tl extends el{onClick=new x;_background=new Mh;_label;_colors;_cornerRadius;_state="normal";_pointerInside=!1;constructor(e={}){super(),this._colors={normal:(e.color??new Tt(54,120,220,1)).clone(),hover:(e.hoverColor??new Tt(74,140,240,1)).clone(),pressed:(e.pressedColor??new Tt(40,96,180,1)).clone(),disabled:(e.disabledColor??new Tt(70,76,90,1)).clone()},this._cornerRadius=e.cornerRadius??8,this._label=new Wr(e.label??"",{fillColor:e.textColor??Tt.white,fontSize:e.fontSize??16,align:"center"}),this.addChild(this._background),this.addChild(this._label),this.interactive=!0,this.focusable=!0,this.cursor="pointer",this.onPointerOver.add(this._onPointerOver),this.onPointerOut.add(this._onPointerOut),this.onPointerDown.add(this._onPointerDown),this.onPointerUp.add(this._onPointerUp),this.onPointerTap.add(this._activate),this.onKeyDown.add(this._onKey),this.setSize(e.width??120,e.height??40)}get label(){return this._label.text}set label(e){this._label.text=e,this._positionLabel()}get colors(){return this._colors}get cornerRadius(){return this._cornerRadius}get textColor(){return this._label.style.fillColor}get fontSize(){return this._label.style.fontSize}_onPointerOver=()=>{this._pointerInside=!0,this._refreshState()};_onPointerOut=()=>{this._pointerInside=!1,this._refreshState()};_onPointerDown=()=>{this.enabled&&(this._state="pressed",this._draw())};_onPointerUp=()=>{this._refreshState()};_activate=()=>{this.enabled&&this.onClick.dispatch(this)};_onKey=t=>{const i=t.channel;!this.enabled||i!==e.Keyboard.Enter&&i!==e.Keyboard.Space||(t.preventDefault(),this.onClick.dispatch(this))};_refreshState(){let e="normal";this.enabled?this._pointerInside&&(e="hover"):e="disabled",this._state=e,this._draw()}_onEnabledChanged(e){this.interactive=e,this._refreshState()}_relayout(){this._draw(),this._positionLabel()}_draw(){const e=this._background;e.clear(),this._uiWidth<=0||this._uiHeight<=0||(e.fillColor=this._colors[this._state],e.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_positionLabel(){const e=this._label.getLocalBounds();this._label.setPosition((this._uiWidth-e.width)/2,(this._uiHeight-e.height)/2)}}class il extends el{_text;constructor(e="",t={}){super(),this._text=new Wr(e,{fillColor:Tt.white,fontSize:16,...t}),this.addChild(this._text),this._syncSize()}get text(){return this._text.text}set text(e){this._text.text!==e&&(this._text.text=e,this._syncSize())}get textNode(){return this._text}_syncSize(){const e=this._text.getLocalBounds();this.setSize(e.width,e.height)}}class nl extends el{_background=new Mh;_color;_borderColor;_borderWidth;_cornerRadius;constructor(e={}){super(),this._color=(e.color??new Tt(30,34,45,.92)).clone(),this._borderColor=(e.borderColor??new Tt(255,255,255,.12)).clone(),this._borderWidth=e.borderWidth??0,this._cornerRadius=e.cornerRadius??8,this.addChild(this._background),this.setSize(e.width??0,e.height??0)}get background(){return this._background}get color(){return this._color}get borderColor(){return this._borderColor}get borderWidth(){return this._borderWidth}get cornerRadius(){return this._cornerRadius}_relayout(){const e=this._background;e.clear(),this._uiWidth<=0||this._uiHeight<=0||(this._borderWidth>0&&(e.lineWidth=this._borderWidth,e.lineColor=this._borderColor),e.fillColor=this._color,e.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}}class rl extends el{_track=new Mh;_fill=new Mh;_trackColor;_fillColor;_cornerRadius;_value;constructor(e={}){super(),this._value=Y(e.value??0,0,1),this._trackColor=(e.trackColor??new Tt(255,255,255,.16)).clone(),this._fillColor=(e.fillColor??new Tt(80,220,120,1)).clone(),this._cornerRadius=e.cornerRadius??4,this.addChild(this._track),this.addChild(this._fill),this.setSize(e.width??200,e.height??12)}get value(){return this._value}set value(e){const t=Y(e,0,1);this._value!==t&&(this._value=t,this._drawFill())}get trackColor(){return this._trackColor}get fillColor(){return this._fillColor}get cornerRadius(){return this._cornerRadius}_relayout(){this._drawTrack(),this._drawFill()}_drawTrack(){const e=this._track;e.clear(),this._uiWidth<=0||this._uiHeight<=0||(e.fillColor=this._trackColor,e.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_drawFill(){const e=this._fill;e.clear();const t=this._uiWidth*this._value;t<=0||this._uiHeight<=0||(e.fillColor=this._fillColor,e.drawRoundedRectangle(0,0,t,this._uiHeight,Math.min(this._cornerRadius,t/2)))}}class sl extends el{_direction;_spacing;_padding;constructor(e={}){super(),this._direction=e.direction??"column",this._spacing=e.spacing??8,this._padding=e.padding??0}get direction(){return this._direction}get spacing(){return this._spacing}get padding(){return this._padding}addItem(e){return this.addChild(e),this.layout()}layout(){const e="row"===this._direction;let t=this._padding,i=0,n=!0;for(const r of this.children){const s=r instanceof el?r.uiWidth:r.getLocalBounds().width,o=r instanceof el?r.uiHeight:r.getLocalBounds().height;n||(t+=this._spacing),n=!1,e?(r.setPosition(t,this._padding),t+=s,i=Math.max(i,o)):(r.setPosition(this._padding,t),t+=o,i=Math.max(i,s))}const r=t+this._padding,s=i+2*this._padding;return this.setSize(e?r:s,e?s:r),this}}const ol=e=>"number"==typeof e&&Number.isFinite(e)?e:void 0,al={write(e){const t={text:e.text},i=Lh(e.textNode.style);return void 0!==i&&(t.style=i),e.enabled||(t.enabled=!1),t},read(e){const t=new il("string"==typeof e.text?e.text:"",Uh(e.style));return!1===e.enabled&&(t.enabled=!1),t}},hl={write(e,t){const i={width:e.uiWidth,height:e.uiHeight,color:Dh(e.color),borderColor:Dh(e.borderColor),borderWidth:e.borderWidth,cornerRadius:e.cornerRadius};e.enabled||(i.enabled=!1);const n=e.children.filter(t=>t!==e.background);return n.length>0&&(i.children=n.map(e=>t.writeNode(e))),i},read(e,t){const i=new nl(Rh({width:ol(e.width),height:ol(e.height),color:Fh(e.color),borderColor:Fh(e.borderColor),borderWidth:ol(e.borderWidth),cornerRadius:ol(e.cornerRadius)}));!1===e.enabled&&(i.enabled=!1);const n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}},ll={write(e){const t={width:e.uiWidth,height:e.uiHeight,label:e.label,cornerRadius:e.cornerRadius,color:Dh(e.colors.normal),hoverColor:Dh(e.colors.hover),pressedColor:Dh(e.colors.pressed),disabledColor:Dh(e.colors.disabled),textColor:Dh(e.textColor),fontSize:e.fontSize};return e.enabled||(t.enabled=!1),t},read(e){const t=new tl(Rh({width:ol(e.width),height:ol(e.height),label:"string"==typeof e.label?e.label:void 0,cornerRadius:ol(e.cornerRadius),color:Fh(e.color),hoverColor:Fh(e.hoverColor),pressedColor:Fh(e.pressedColor),disabledColor:Fh(e.disabledColor),textColor:Fh(e.textColor),fontSize:ol(e.fontSize)}));return!1===e.enabled&&(t.enabled=!1),t}},ul={write(e){const t={width:e.uiWidth,height:e.uiHeight,value:e.value,trackColor:Dh(e.trackColor),fillColor:Dh(e.fillColor),cornerRadius:e.cornerRadius};return e.enabled||(t.enabled=!1),t},read(e){const t=new rl(Rh({width:ol(e.width),height:ol(e.height),value:ol(e.value),trackColor:Fh(e.trackColor),fillColor:Fh(e.fillColor),cornerRadius:ol(e.cornerRadius)}));return!1===e.enabled&&(t.enabled=!1),t}},cl={write(e,t){const i={direction:e.direction,spacing:e.spacing,padding:e.padding};return e.enabled||(i.enabled=!1),e.children.length>0&&(i.children=e.children.map(e=>t.writeNode(e))),i},read(e,t){const i=new sl(Rh({direction:"row"===e.direction||"column"===e.direction?e.direction:void 0,spacing:ol(e.spacing),padding:ol(e.padding)}));!1===e.enabled&&(i.enabled=!1);const n=e.children;if(Array.isArray(n)){for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}i.layout()}return i}},dl={write:(e,t)=>e.children.length>0?{children:e.children.map(e=>t.writeNode(e))}:{},read(e,t){const i=new nh,n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}};const _l={write:(e,t)=>0===e.children.length?{}:{children:e.children.map(e=>t.writeNode(e))},read(e,t){const i=new Bi,n=e.children;if(Array.isArray(n))for(const e of n){const n=lh(e);null!==n&&i.addChild(t.readNode(n))}return i}},fl={write(e,t){const i={},n=t.keyFor(e.texture);null!==n&&(i.texture=n),e.material;const r=e.texture,s=e.textureFrame;return null===r||0===s.x&&0===s.y&&s.width===r.width&&s.height===r.height||(i.frame=[s.x,s.y,s.width,s.height]),i},read(e,t){const i=t.resolveAsset("string"==typeof e.texture?e.texture:null,pi),n=new vr(i),r=e.frame;return null!==i&&Array.isArray(r)&&4===r.length&&n.setTextureFrame(et.temp.set(Number(r[0]),Number(r[1]),Number(r[2]),Number(r[3]))),n}},pl={write(e){const t={text:e.text},i=Lh(e.style);return void 0!==i&&(t.style=i),Object.keys(e.layout).length>0&&(t.layout={...e.layout}),e.colorGlyphs&&(t.colorGlyphs=!0),8!==e.sdfRadius&&(t.sdfRadius=e.sdfRadius),t},read(e){const t=Vh(e.layout);return new Wr("string"==typeof e.text?e.text:"",Rh({...Uh(e.style),...t,colorGlyphs:!0===e.colorGlyphs,sdfRadius:"number"==typeof e.sdfRadius?e.sdfRadius:void 0}))}};function ml(e){e.register("Container",Bi,_l),e.register("Sprite",vr,fl),e.register("Text",Wr,pl),function(e){e.register("Mesh",In,Xh),e.register("Graphics",Mh,Hh),e.register("NineSliceSprite",ur,jh),e.register("RepeatingSprite",wr,Kh),e.register("AnimatedSprite",kh,Qh),e.register("BitmapText",Ar,Zh),e.register("Video",Co,Jh)}(e),function(e){e.register("Label",il,al),e.register("Panel",nl,hl),e.register("Button",tl,ll),e.register("ProgressBar",rl,ul),e.register("Stack",sl,cl),e.register("UIRoot",nh,dl)}(e)}const gl=e=>{const t=Object.getPrototypeOf(e);return"function"==typeof t&&t!==Function.prototype?t:null};class yl{_fallback;_byCtor=new io({walk:gl});_byName=new Map;constructor(e=null){this._fallback=e}register(e,t,i){const n=this._byName.get(e);if(void 0!==n&&n.ctor!==t)throw new Error(`A serializer for type name "${e}" is already registered for a different constructor.`);const r={typeName:e,ctor:t,serializer:i};this._byCtor.set(t,r),this._byName.set(e,r)}resolveByNode(e){return this._byCtor.resolve(e.constructor)??this._fallback?.resolveByNode(e)}resolveByName(e){return this._byName.get(e)??this._fallback?.resolveByName(e)}hasType(e){return this._byName.has(e)||(this._fallback?.hasType(e)??!1)}clear(){this._byName.clear(),this._byCtor.destroy()}}const wl=new yl;let xl=!1;function vl(){xl||(xl=!0,ml(wl))}function bl(e,t,i){const n={version:t,loader:e,readNode:e=>Bl(e,n,i),resolveAsset:(t,i)=>{if(null==t||null===e)return null;return e.peek(i,t)}};return n}function Sl(t,i,n){const r=n.resolveByNode(t);if(void 0===r)throw new Error(`No serializer registered for node type "${t.constructor.name}". Register one via registerSerializer().`);const s={type:r.typeName};return function(t,i){if(0!==t.x&&(i.x=t.x),0!==t.y&&(i.y=t.y),0!==t.rotation&&(i.rotation=t.rotation),1!==t.scale.x&&(i.scaleX=t.scale.x),1!==t.scale.y&&(i.scaleY=t.scale.y),0!==t.skewX&&(i.skewX=t.skewX),0!==t.skewY&&(i.skewY=t.skewY),0!==t.origin.x&&(i.originX=t.origin.x),0!==t.origin.y&&(i.originY=t.origin.y),t.visible||(i.visible=!1),0!==t.zIndex&&(i.zIndex=t.zIndex),t.cullable||(i.cullable=!1),null!==t.cullArea&&(i.cullArea=[t.cullArea.x,t.cullArea.y,t.cullArea.width,t.cullArea.height]),null!==t.name&&(i.name=t.name),t instanceof Si){t.interactive&&(i.interactive=!0),t.draggable&&(i.draggable=!0),t.focusable&&(i.focusable=!0),0!==t.tabIndex&&(i.tabIndex=t.tabIndex),null!==t.cursor&&(i.cursor=t.cursor),t.clip&&(i.clip=!0),t.preserveDrawOrder&&(i.preserveDrawOrder=!0),t.cacheAsBitmap&&(i.cacheAsBitmap=!0);const e=t.clipShape;e instanceof et&&(i.clipShape=[e.x,e.y,e.width,e.height])}if(t instanceof Fn){const n=t.tint;255===n.r&&255===n.g&&255===n.b&&1===n.a||(i.tint=[n.r,n.g,n.b,n.a]),t.blendMode!==e.BlendModes.Normal&&(i.blendMode=t.blendMode),"none"!==t.pixelSnapMode&&(i.pixelSnapMode=t.pixelSnapMode)}}(t,s),Object.assign(s,r.serializer.write(t,i)),s}function Bl(e,t,i){const n=i.resolveByName(e.type);if(void 0===n)throw new Error(`No serializer registered for type "${e.type}". Register one via registerSerializer().`);const r=n.serializer.read(e,t);return sh(r,e),r}function Cl(e,t=null,i=wl){return vl(),Sl(e,function(e,t){const i={version:1,loader:e,writeNode:e=>Sl(e,i,t),keyFor:t=>{if(null==t||"object"!=typeof t||null===e)return null;const i=e.keyFor(t);return null===i?null:i.source}};return i}(t,i),i)}function Tl(e,t,i=null,n=wl){vl();const r=bl(i,1,n);e.removeChildren(),sh(e,t);const s=t.children;if(Array.isArray(s))for(const t of s){const i=lh(t);null!==i&&e.addChild(r.readNode(i))}}class Ml{_systems=[];_set=new Set;_pending=[];_ticking=!1;_sorted=!0;onAdd=new x;onRemove=new x;add(e){return this._ticking?this._pending.push({add:!0,system:e}):this._insert(e),e}remove(e){return this._ticking?!!this._set.has(e)&&(this._pending.push({add:!1,system:e}),!0):this._delete(e)}has(e){return this._set.has(e)}get size(){return this._set.size}_tick(e){if(0!==this._systems.length){this._sorted||(this._systems.sort((e,t)=>(e.order??0)-(t.order??0)),this._sorted=!0),this._ticking=!0;for(const t of this._systems)t.update(e);this._ticking=!1,this._drainPending()}}destroy(){for(let e=this._systems.length-1;e>=0;e--)this._systems[e].destroy();this._systems.length=0,this._set.clear(),this._pending.length=0,this.onAdd.destroy(),this.onRemove.destroy()}_insert(e){this._set.has(e)||(this._set.add(e),this._systems.push(e),this._sorted=!1,this.onAdd.dispatch(e))}_delete(e){if(!this._set.delete(e))return!1;const t=this._systems.indexOf(e);return-1!==t&&this._systems.splice(t,1),this.onRemove.dispatch(e),!0}_drainPending(){if(0!==this._pending.length){for(const{add:e,system:t}of this._pending)e?this._insert(t):this._delete(t);this._pending.length=0}}}class Pl{_scene;_bindings=new Set;constructor(e){this._scene=e}onStart(e,t,i){return this._track(this._scene.app.input.onStart(e,t,i))}onActive(e,t,i){return this._track(this._scene.app.input.onActive(e,t,i))}onStop(e,t,i){return this._track(this._scene.app.input.onStop(e,t,i))}onTrigger(e,t,i){return this._track(this._scene.app.input.onTrigger(e,t,i))}destroy(){for(const e of this._bindings)e.unbind();this._bindings.clear()}_track(e){return this._bindings.add(e),e}}class Al{_scene;_tweens=new Set;constructor(e){this._scene=e}create(e){const t=this._scene.app.tweens.create(e);return this._tweens.add(t),t}add(e){return this._scene.app.tweens.add(e),this._tweens.add(e),this}destroy(){for(const e of this._tweens)e.stop();this._tweens.clear()}}class El{_app=null;_root=new Bi;paused=!1;onLoad=new x;onUnload=new x;_inputs=null;_tweens=null;_systems=null;_disposal=new rh;get app(){return this._app}set app(e){this._app=e}get root(){return this._root}get inputs(){if(null===this._inputs){if(null===this._app)throw new Error("Scene.inputs is unavailable before the scene is attached to an Application.");this._inputs=this._disposal.track(new Pl(this))}return this._inputs}get tweens(){if(null===this._tweens){if(null===this._app)throw new Error("Scene.tweens is unavailable before the scene is attached to an Application.");this._tweens=this._disposal.track(new Al(this))}return this._tweens}track(e){return this._disposal.track(e)}get systems(){return null===this._systems&&(this._systems=this._disposal.track(new Ml)),this._systems}_tickSystems(e){this._systems?._tick(e)}_ui=null;get ui(){return null===this._ui&&(this._ui=this._disposal.track(new nh),null!==this._root._getStage()&&this._app?.interaction.attachUIRoot(this._ui)),this._ui}_peekUI(){return this._ui}addChild(e){return this._root.addChild(e),this}removeChild(e){return this._root.removeChild(e),this}serialize(){const e=this._app?.loader??null,t=this._app?.serializers,i={version:1,root:Cl(this._root,e,t)},n=this._peekUI();return null!==n&&(i.ui=Cl(n,e,t)),i}deserialize(e){const t=function(e){const t=hh(e);if(null===t)throw new Error("Cannot deserialize scene: the document is not an object.");const i="number"==typeof t.version?t.version:0;if(i>1)throw new Error(`Cannot deserialize scene: data version ${i} is newer than the supported version 1.`);const n=lh(t.root);if(null===n)throw new Error("Cannot deserialize scene: the document has no valid root node.");const r=lh(t.ui);return null!==r?{version:i,root:n,ui:r}:{version:i,root:n}}(e),i=this._app?.loader??null,n=this._app?.serializers;return Tl(this._root,t.root,i,n),void 0!==t.ui&&Tl(this.ui,t.ui,i,n),this}load(e){}init(e){}update(e){}fixedUpdate(e){}draw(e){}unload(e){}destroy(){this._disposal.destroy(),this._inputs=null,this._tweens=null,this._systems=null,this.onLoad.destroy(),this.onUnload.destroy(),this._root.destroy(),this._app=null}}class kl extends In{render(e){return this.visible&&e.draw(this),this}}class Rl{_app;_activeScene=null;_transitionOverlay=(()=>new kl({vertices:new Float32Array([0,0,1,0,0,1,1,1]),indices:new Uint16Array([0,1,2,1,3,2])}))();_transition=null;onChangeScene=new x;onStartScene=new x;onUpdateScene=new x;onStopScene=new x;_asyncUpdateWarned=new WeakSet;_asyncDrawWarned=new WeakSet;constructor(e){this._app=e}get currentScene(){return this._activeScene}set currentScene(e){this.setScene(e)}async setScene(e,t={}){return await this._runWithTransition(async()=>{if(e===this._activeScene)return;null!==e&&await this._prepareScene(e);const t=this._activeScene;this._activeScene=e,null!==t&&await this._disposeScene(t),this.onChangeScene.dispatch(e),null!==e&&this.onStartScene.dispatch(e)},t.transition),this}update(e){this._advanceTransition(e.milliseconds);const t=this._activeScene;if(null!==t){if(!t.paused){const i=t.update(e);!this._asyncUpdateWarned.has(t)&&i instanceof Promise&&(this._asyncUpdateWarned.add(t),ih.warn("scene","Scene.update() returned a Promise. update() must be synchronous — async logic here breaks frame timing and silently drops errors. Move async work into load() or init() instead.")),t._tickSystems(e)}const i=t.draw(this._app.rendering);!this._asyncDrawWarned.has(t)&&i instanceof Promise&&(this._asyncDrawWarned.add(t),ih.warn("scene","Scene.draw() returned a Promise. draw() must be synchronous — an async draw() produces incomplete frames and silently drops errors.")),t._peekUI()?._render(this._app.rendering)}const i=this._getTransitionAlpha();return i>0&&this._renderTransitionOverlay(i),null!==t&&this.onUpdateScene.dispatch(t),this}fixedUpdate(e){const t=this._activeScene;return null===t||t.paused||t.fixedUpdate(e),this}destroy(){if(this._transition){const e=this._transition;this._transition=null,e.color.destroy(),e.reject(new Error("SceneManager was destroyed while a transition was active."))}this._unloadActiveSceneOnDestroy(),this._transitionOverlay.destroy(),this.onChangeScene.destroy(),this.onStartScene.destroy(),this.onUpdateScene.destroy(),this.onStopScene.destroy()}async _prepareScene(e){e.app=this._app;try{await e.load(this._app.loader),await e.init(this._app.loader),e.root.children.length>0&&e.draw===El.prototype.draw&&ih.warn("scene",`Scene.root has ${e.root.children.length} child(ren) after init() but draw() is not overridden. Scene.root is not auto-rendered — call context.render(this.root) inside draw().`),this._app.interaction.attachRoot(e.root);const t=e._peekUI();null!==t&&this._app.interaction.attachUIRoot(t),e.onLoad.dispatch()}catch(t){let i=null;try{await e.unload(this._app.loader)}catch(e){i=e}if(e.destroy(),e.app=null,i){const e=t instanceof Error?t.message:String(t);let n="unknown cleanup error";throw i instanceof Error?n=i.message:"string"==typeof i&&(n=i),new Error(`Failed to initialize scene: ${e}. Cleanup also failed: ${n}.`,{cause:t})}throw t}}async _disposeScene(e){e.onUnload.dispatch(),this.onStopScene.dispatch(e),await e.unload(this._app.loader);const t=e._peekUI();null!==t&&this._app.interaction.detachUIRoot(t),this._app.interaction.detachRoot(e.root),e.destroy(),e.app=null}async _unloadActiveSceneOnDestroy(){const e=this._activeScene;if(null!==e){this._activeScene=null;try{await this._disposeScene(e)}catch(e){ih.error("scene","SceneManager.destroy() failed to unload the active scene.",e instanceof Error?e:void 0)}}}async _runWithTransition(e,t){if("fade"!==t?.type)return void await e();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,t.duration??220);0!==i?await new Promise((n,r)=>{this._transition={type:"fade",durationMs:i,action:e,resolve:n,reject:r,color:(t.color??Tt.black).clone(),elapsedMs:0,phase:"out"}}):await e()}_advanceTransition(e){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,e)),void(this._transition.elapsedMs>=this._transition.durationMs&&(this._transition.phase="switching",this._executeTransitionAction()))):void("in"===this._transition.phase&&(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,e)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const e=this._transition;if("switching"===e?.phase){try{await e.action()}catch(t){return void(this._transition===e&&(this._transition=null,e.color.destroy(),e.reject(t)))}this._transition===e&&(e.phase="in",e.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const e=this._transition;this._transition=null,e.color.destroy(),e.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const e=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?e:1-e}_renderTransitionOverlay(e){const t=this._transition,i=t?t.color:Tt.black,n=this._app.backend,r=n.view.getBounds(),s=this._transitionOverlay,o=s.vertices;o[0]=r.left,o[1]=r.top,o[2]=r.right,o[3]=r.top,o[4]=r.left,o[5]=r.bottom,o[6]=r.right,o[7]=r.bottom,s.tint.set(i.r,i.g,i.b,Math.max(0,Math.min(1,e))),s.render(n)}}var Dl;e.ApplicationStatus=void 0,(Dl=e.ApplicationStatus||(e.ApplicationStatus={}))[Dl.Loading=1]="Loading",Dl[Dl.Running=2]="Running",Dl[Dl.Halting=3]="Halting",Dl[Dl.Stopped=4]="Stopped";const Fl=1e3/60,Il={type:"auto"},Ll=800,Ul=600,Gl=1,Nl=-1,Ol={method:"GET",mode:"cors",cache:"default"},Vl={debug:!1,spriteRendererBatchSize:4096,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1}},zl={gamepadDefinitions:[],gamepadSlotStrategy:"sticky",pointerDistanceThreshold:10};const ql=Object.freeze({version:"0.15.2",revision:"e3df957",development:!1});const Wl={decodeBase64:function(e){const t=e.replaceAll(/\s+/g,""),i=atob(t),n=i.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=i.charCodeAt(e);return r},decompress:async function(e,t){if("undefined"==typeof DecompressionStream)throw new Error("Codec.decompress requires the native DecompressionStream API.");const i=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(t)).getReader(),n=[];let r=0;for(;;){const{done:e,value:t}=await i.read();if(e)break;n.push(t),r+=t.length}const s=new Uint8Array(r);let o=0;for(const e of n)s.set(e,o),o+=e.length;return s}},Yl="undefined"!=typeof performance,$l={mark:e=>{Yl&&"function"==typeof performance.mark&&performance.mark(e)},measure:(e,t,i)=>{if(Yl&&"function"==typeof performance.measure)try{return performance.measure(e,t,i)}catch{return}},clearMarks:e=>{Yl&&"function"==typeof performance.clearMarks&&performance.clearMarks(e)},clearMeasures:e=>{Yl&&"function"==typeof performance.clearMeasures&&performance.clearMeasures(e)}};class Xl{_descriptor;constructor(e){this._descriptor=e}static from(e,t=null,i){return new Xl(Cl(e,t,i))}static fromJSON(e){return new Xl(e)}instantiate(e=null,t){return function(e,t=null,i=wl){return vl(),Bl(e,bl(t,1,i),i)}(this._descriptor,e,t)}toJSON(){return this._descriptor}}const Hl=new Map([["DPad",[.22,.58]],["DPadUp",[.22,.5]],["DPadDown",[.22,.66]],["DPadLeft",[.14,.58]],["DPadRight",[.3,.58]],["ButtonNorth",[.78,.5]],["ButtonWest",[.7,.58]],["ButtonEast",[.86,.58]],["ButtonSouth",[.78,.66]],["LeftShoulder",[.28,.28]],["RightShoulder",[.72,.28]],["LeftTrigger",[.2,.16]],["RightTrigger",[.8,.16]],["Select",[.46,.5]],["Start",[.54,.5]],["LeftStick",[.38,.66]],["RightStick",[.62,.66]]]),jl=new Map([["ButtonNorth",Li.North],["ButtonWest",Li.West],["ButtonEast",Li.East],["ButtonSouth",Li.South],["LeftShoulder",Li.LeftShoulder],["RightShoulder",Li.RightShoulder],["LeftTrigger",Li.LeftTrigger],["RightTrigger",Li.RightTrigger],["Select",Li.Select],["Start",Li.Start],["LeftStick",Li.LeftStick],["RightStick",Li.RightStick],["DPadUp",Li.DPadUp],["DPadDown",Li.DPadDown],["DPadLeft",Li.DPadLeft],["DPadRight",Li.DPadRight]]),Kl=new Map([["ButtonNorth","North"],["ButtonWest","West"],["ButtonEast","East"],["ButtonSouth","South"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Select"],["Start","Start"],["LeftStick","L3"],["RightStick","R3"]]),Ql=new Map([["ButtonNorth","Y"],["ButtonWest","X"],["ButtonEast","B"],["ButtonSouth","A"],["LeftShoulder","LB"],["RightShoulder","RB"],["LeftTrigger","LT"],["RightTrigger","RT"],["Select","View"],["Start","Menu"],["LeftStick","L3"],["RightStick","R3"]]),Zl=new Map([["ButtonNorth","Triangle"],["ButtonWest","Square"],["ButtonEast","Circle"],["ButtonSouth","Cross"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Create"],["Start","Options"],["LeftStick","L3"],["RightStick","R3"]]),Jl=new Map([["ButtonNorth","X"],["ButtonWest","Y"],["ButtonEast","A"],["ButtonSouth","B"],["LeftShoulder","L"],["RightShoulder","R"],["LeftTrigger","ZL"],["RightTrigger","ZR"],["Select","Minus"],["Start","Plus"],["LeftStick","L3"],["RightStick","R3"]]),eu=new Map([[e.GamepadMappingFamily.GenericDualAnalog,Kl],[e.GamepadMappingFamily.Xbox,Ql],[e.GamepadMappingFamily.PlayStation,Zl],[e.GamepadMappingFamily.SwitchPro,Jl],[e.GamepadMappingFamily.JoyConLeft,Jl],[e.GamepadMappingFamily.JoyConRight,Jl],[e.GamepadMappingFamily.GameCube,Kl],[e.GamepadMappingFamily.SteamController,Kl],[e.GamepadMappingFamily.SteamDeck,Kl],[e.GamepadMappingFamily.ArcadeStick,Kl]]);let tu=null;class iu{static collisionSegments=32;collisionType=e.CollisionType.Circle;_position;_collisionVertices=null;_verticesDirty=!0;_normals=null;_normalsDirty=!0;_radius;constructor(e=0,t=0,i=0){this._position=new it(e,t),this._radius=i}get position(){return this._position}set position(e){this._position.copy(e),this._verticesDirty=!0,this._normalsDirty=!0}get x(){return this._position.x}set x(e){this._position.x!==e&&(this._position.x=e,this._verticesDirty=!0,this._normalsDirty=!0)}get y(){return this._position.y}set y(e){this._position.y!==e&&(this._position.y=e,this._verticesDirty=!0,this._normalsDirty=!0)}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,this._verticesDirty=!0,this._normalsDirty=!0)}setPosition(e,t){return this._position.set(e,t),this._verticesDirty=!0,this._normalsDirty=!0,this}setRadius(e){return this._radius!==e&&(this._radius=e,this._verticesDirty=!0,this._normalsDirty=!0),this}set(e,t,i){return this._position.set(e,t),this._radius=i,this._verticesDirty=!0,this._normalsDirty=!0,this}copy(e){return this._position.copy(e.position),this._radius=e.radius,this._verticesDirty=!0,this._normalsDirty=!0,this}clone(){return new iu(this.x,this.y,this.radius)}equals({x:e,y:t,radius:i}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t||void 0!==i&&this.radius!==i)}getBounds(){return new et(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){if(this._normalsDirty){const e=this.getCollisionVertices();null===this._normals&&(this._normals=e.map(()=>new it));for(let t=0;t<e.length;t++){const i=e[t],n=e[(t+1)%e.length];this._normals[t].set(n.x-i.x,n.y-i.y).rperp().normalize()}this._normalsDirty=!1}return this._normals}project(e,t=new me){const i=e.dot(this.x,this.y),n=this.radius*e.length;return t.set(i-n,i+n)}contains(e,t){return ve(it.temp.set(e,t),this)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Ee(t.getBounds(),this);case e.CollisionType.Rectangle:return Ee(t,this);case e.CollisionType.Polygon:return Ge(this,t);case e.CollisionType.Circle:return De(this,t);case e.CollisionType.Ellipse:return Fe(this,t);case e.CollisionType.Line:return Te(t,this);case e.CollisionType.Point:return ve(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return We(this,t.getBounds());case e.CollisionType.Rectangle:return We(this,t);case e.CollisionType.Polygon:return Xe(t,this,!0);case e.CollisionType.Circle:return qe(this,t);case e.CollisionType.Ellipse:return $e(t,this,!0);default:return null}}destroy(){if(this._position.destroy(),null!==this._collisionVertices){for(const e of this._collisionVertices)e.destroy();this._collisionVertices=null}if(null!==this._normals){for(const e of this._normals)e.destroy();this._normals=null}}getCollisionVertices(){if(this._verticesDirty){const e=iu.collisionSegments;if(null===this._collisionVertices){this._collisionVertices=new Array(e);for(let t=0;t<e;t++)this._collisionVertices[t]=new it}for(let t=0;t<e;t++){const i=2*t*Math.PI/e-Math.PI/2,n=Math.cos(i)*this._radius,r=Math.sin(i)*this._radius;this._collisionVertices[t].set(this._radius+n,this._radius+r)}this._verticesDirty=!1}return this._collisionVertices}static get temp(){return null===tu&&(tu=new iu),tu}}class nu{collisionType=e.CollisionType.Ellipse;_position;_radius;constructor(e=0,t=0,i=0,n=i){this._position=new it(e,t),this._radius=new it(i,n)}get position(){return this._position}set position(e){this._position.copy(e)}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get radius(){return this._radius}set radius(e){this._radius.copy(e)}get rx(){return this._radius.x}set rx(e){this._radius.x=e}get ry(){return this._radius.y}set ry(e){this._radius.y=e}setPosition(e,t){return this._position.set(e,t),this}setRadius(e,t=e){return this._radius.set(e,t),this}set(e,t,i,n){return this._position.set(e,t),this._radius.set(i,n),this}copy(e){return this._position.copy(e.position),this._radius.copy(e.radius),this}clone(){return new nu(this.x,this.y,this.rx,this.ry)}getBounds(){return new et(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(e,t=new me){const i=this.x*e.x+this.y*e.y,n=Math.sqrt((this.rx*e.x)**2+(this.ry*e.y)**2);return t.set(i-n,i+n)}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return ke(t.getBounds(),this);case e.CollisionType.Rectangle:return ke(t,this);case e.CollisionType.Polygon:return Oe(this,t);case e.CollisionType.Circle:return Fe(t,this);case e.CollisionType.Ellipse:return Ne(this,t);case e.CollisionType.Line:return Me(t,this);case e.CollisionType.Point:return be(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Ye(this,t.getBounds());case e.CollisionType.Rectangle:return Ye(this,t);case e.CollisionType.Circle:return $e(this,t);case e.CollisionType.Polygon:return je(this,t);case e.CollisionType.Ellipse:return He(this,t);default:return null}}contains(e,t){return be(it.temp.set(e,t),this)}equals({x:e,y:t,rx:i,ry:n}={}){return!(void 0!==e&&this.x!==e||void 0!==t&&this.y!==t||void 0!==i&&this.rx!==i||void 0!==n&&this.ry!==n)}destroy(){this._position.destroy(),this._radius.destroy()}}let ru=null;class su{collisionType=e.CollisionType.Line;_fromPosition;_toPosition;constructor(e=0,t=0,i=0,n=0){this._fromPosition=new it(e,t),this._toPosition=new it(i,n)}get fromPosition(){return this._fromPosition}set fromPosition(e){this._fromPosition.copy(e)}get fromX(){return this._fromPosition.x}set fromX(e){this._fromPosition.x=e}get fromY(){return this._fromPosition.y}set fromY(e){this._fromPosition.y=e}get toPosition(){return this._toPosition}set toPosition(e){this._toPosition.copy(e)}get toX(){return this._toPosition.x}set toX(e){this._toPosition.x=e}get toY(){return this._toPosition.y}set toY(e){this._toPosition.y=e}set(e,t,i,n){return this._fromPosition.set(e,t),this._toPosition.set(i,n),this}copy(e){return this._fromPosition.copy(e.fromPosition),this.toPosition.copy(e.toPosition),this}clone(){return new su(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:e,fromY:t,toX:i,toY:n}=this,r=Math.min(e,i),s=Math.min(t,n);return new et(r,s,Math.max(e,i)-r,Math.max(t,n)-s)}getNormals(){return[]}project(e,t=new me){return t}intersectsWith(t){switch(t.collisionType){case e.CollisionType.SceneNode:return Ce(this,t.getBounds());case e.CollisionType.Rectangle:return Ce(this,t);case e.CollisionType.Polygon:return Pe(this,t);case e.CollisionType.Circle:return Te(this,t);case e.CollisionType.Ellipse:return Me(this,t);case e.CollisionType.Line:return Be(this,t);case e.CollisionType.Point:return we(t,this);default:return!1}}collidesWith(e){return null}contains(e,t,i=.1){return we(it.temp.set(e,t),this,i)}equals({fromX:e,fromY:t,toX:i,toY:n}={}){return!(void 0!==e&&this.fromX!==e||void 0!==t&&this.fromY!==t||void 0!==i&&this.toX!==i||void 0!==n&&this.toY!==n)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===ru&&(ru=new su),ru}}class ou{radius;phi;constructor(e=0,t=0){this.radius=e,this.phi=t}static fromVector(e){return new ou(e.length,e.angle)}toVector(){return it.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}let au=null;class hu{_startPoint;_endPoint;constructor(e=0,t=0,i=0,n=0){this._startPoint=new it(e,t),this._endPoint=new it(i,n)}get startPoint(){return this._startPoint}set startPoint(e){this._startPoint.copy(e)}get startX(){return this._startPoint.x}set startX(e){this._startPoint.x=e}get startY(){return this._startPoint.y}set startY(e){this._startPoint.y=e}get endPoint(){return this._endPoint}set endPoint(e){this._endPoint.copy(e)}get endX(){return this._endPoint.x}set endX(e){this._endPoint.x=e}get endY(){return this._endPoint.y}set endY(e){this._endPoint.y=e}set(e,t,i,n){return this._startPoint.set(e,t),this._endPoint.set(i,n),this}copy(e){return this._startPoint.copy(e.startPoint),this._endPoint.copy(e.endPoint),this}clone(){return new hu(this.startX,this.startY,this.endX,this.endY)}equals({startX:e,startY:t,endX:i,endY:n}={}){return!(void 0!==e&&this.startX!==e||void 0!==t&&this.startY!==t||void 0!==i&&this.endX!==i||void 0!==n&&this.endY!==n)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===au&&(au=new hu),au}}function lu(e,t,i,n){const r=e.x,s=e.x+e.width,o=e.y,a=e.y+e.height,h=n.x,l=n.x+n.width,u=n.y,c=n.y+n.height;let d=-1/0,_=1/0;if(t>0)d=(h-s)/t,_=(l-r)/t;else if(t<0)d=(l-r)/t,_=(h-s)/t;else if(s<=h||r>=l)return null;let f=-1/0,p=1/0;if(i>0)f=(u-a)/i,p=(c-o)/i;else if(i<0)f=(c-o)/i,p=(u-a)/i;else if(a<=u||o>=c)return null;const m=Math.max(d,f),g=Math.min(_,p);if(m>g||g<0||m>1)return null;const y=Math.max(0,m),w=e.x+t*y,x=e.y+i*y;let v=0,b=0;if(m<=0){Math.min(s-h,l-r)<Math.min(a-u,c-o)?v=r<h?-1:1:b=o<u?-1:1}else d>f?v=t>0?-1:1:b=i>0?-1:1;return{t:y,x:w,y:x,normalX:v,normalY:b}}function uu(e,t,i,n){const r=e.x-n.x,s=e.y-n.y,o=e.radius+n.radius,a=t*t+i*i,h=2*(r*t+s*i),l=r*r+s*s-o*o;if(l<=0){const t=Math.sqrt(r*r+s*s),i=t>0?r/t:1,n=t>0?s/t:0;return{t:0,x:e.x,y:e.y,normalX:i,normalY:n}}if(0===a)return null;const u=h*h-4*a*l;if(u<0)return null;const c=(-h-Math.sqrt(u))/(2*a);if(c<0||c>1)return null;const d=e.x+t*c,_=e.y+i*c;return{t:c,x:d,y:_,normalX:(d-n.x)/o,normalY:(_-n.y)/o}}const cu={rectangle:lu,circleVsRectangle:function(e,t,i,n){const r=e.radius,s=e.x,o=e.y,a=n.x,h=n.x+n.width,l=n.y,u=n.y+n.height,c=s-Math.max(a,Math.min(s,h)),d=o-Math.max(l,Math.min(o,u));if(c*c+d*d<=r*r){const e=Math.sqrt(c*c+d*d);if(e>0)return{t:0,x:s,y:o,normalX:c/e,normalY:d/e};const t=s-a,i=h-s,n=o-l,r=u-o;return Math.min(t,i)<=Math.min(n,r)?{t:0,x:s,y:o,normalX:t<i?-1:1,normalY:0}:{t:0,x:s,y:o,normalX:0,normalY:n<r?-1:1}}if(0===t&&0===i)return null;let _=1/0,f=0,p=0;const m=(e,t,i)=>{e>=0&&e<=1&&e<_&&(_=e,f=t,p=i)};if(0!==t){const e=(a-r-s)/t;if(e>=0&&e<=1){const t=o+i*e;t>=l&&t<=u&&m(e,-1,0)}const n=(h+r-s)/t;if(n>=0&&n<=1){const e=o+i*n;e>=l&&e<=u&&m(n,1,0)}}if(0!==i){const e=(l-r-o)/i;if(e>=0&&e<=1){const i=s+t*e;i>=a&&i<=h&&m(e,0,-1)}const n=(u+r-o)/i;if(n>=0&&n<=1){const e=s+t*n;e>=a&&e<=h&&m(n,0,1)}}const g=t*t+i*i,y=[a,h,a,h],w=[l,l,u,u];for(let e=0;e<4;e++){const n=y[e],a=w[e],h=s-n,l=o-a,u=2*(h*t+l*i),c=u*u-4*g*(h*h+l*l-r*r);if(c<0)continue;const d=(-u-Math.sqrt(c))/(2*g);if(d<0||d>1)continue;m(d,(s+t*d-n)/r,(o+i*d-a)/r)}return _>1?null:{t:_,x:s+t*_,y:o+i*_,normalX:f,normalY:p}},circleVsCircle:uu,rectangleAgainst:function(e,t,i,n){if(0===n.length)return null;const r=Math.min(e.x,e.x+t),s=Math.max(e.x+e.width,e.x+e.width+t),o=Math.min(e.y,e.y+i),a=Math.max(e.y+e.height,e.y+e.height+i);let h=null;for(const l of n){if(s<=l.x||r>=l.x+l.width||a<=l.y||o>=l.y+l.height)continue;const n=lu(e,t,i,l);null!==n&&(null===h||n.t<h.t)&&(h=n)}return h},circleAgainst:function(e,t,i,n){if(0===n.length)return null;const r=Math.min(e.x,e.x+t)-e.radius,s=Math.max(e.x,e.x+t)+e.radius,o=Math.min(e.y,e.y+i)-e.radius,a=Math.max(e.y,e.y+i)+e.radius;let h=null;for(const l of n){if(s<=l.x-l.radius||r>=l.x+l.radius||a<=l.y-l.radius||o>=l.y+l.radius)continue;const n=uu(e,t,i,l);null!==n&&(null===h||n.t<h.t)&&(h=n)}return h},substep:function*(e,t,i,n,r){const s=Math.hypot(i,n),o=Math.max(1,Math.ceil(s/r));for(let r=0;r<=o;r++){const s=r/o;yield{x:e+i*s,y:t+n*s,t:s}}}};class du{_context;target;view;constructor(e,t,i){this._context=e,this.target=t,this.view=i}get backend(){return this._context.backend}clear(e){this._context.clear(e)}render(e,t){this._context.render(e,{view:t?.view??this.view})}renderTo(e,t){this._context.renderTo(e,t)}drawGeometry(e,t,i){this._context.drawGeometry(e,t,{...i,view:i?.view??this.view})}drawBatch(e,t){this._context.drawBatch(e,{...t,view:t?.view??this.view})}}class _u{enabled;label;_pipelineOwner=null;constructor(e){this.enabled=e?.enabled??!0,this.label=e?.label??new.target.name}resize(e,t){}destroy(){}}class fu extends _u{_passes=[];_executing=!1;_destroyed=!1;constructor(e){super(e)}get size(){return this._passes.length}addPass(e){return this._admit(e),this._passes.push(e),e._pipelineOwner=this,this}insertPass(e,t){this._admit(e);const i=Math.max(0,Math.min(t,this._passes.length));return this._passes.splice(i,0,e),e._pipelineOwner=this,this}removePass(e){this._assertLive(),this._assertNotExecuting();const t=this._passes.indexOf(e);return-1!==t&&(this._passes.splice(t,1),e._pipelineOwner=null,!0)}clear(){this._assertLive(),this._assertNotExecuting();for(const e of this._passes)e._pipelineOwner=null;return this._passes.length=0,this}hasPass(e){return e._pipelineOwner===this}indexOf(e){return this._passes.indexOf(e)}at(e){return this._passes[e]}[Symbol.iterator](){return this._passes[Symbol.iterator]()}execute(e){if(this.enabled){if(this._assertLive(),this._executing)throw new Error("RenderPipeline.execute is not re-entrant.");this._executing=!0;try{for(const t of this._passes)t.enabled&&t.execute(e)}finally{this._executing=!1}}}resize(e,t){for(const i of this._passes)i.resize(e,t)}destroy(){if(this._destroyed)return;this._assertNotExecuting(),this._destroyed=!0;const e=this._passes.splice(0,this._passes.length),t=[];for(const i of e){i._pipelineOwner=null;try{i.destroy()}catch(e){t.push(e)}}if(t.length>0)throw t[0]}_admit(e){if(this._assertLive(),this._assertNotExecuting(),null!==e._pipelineOwner)throw new Error("RenderPass already belongs to a RenderPipeline; remove it from its current pipeline first.");if(e instanceof fu&&e._reaches(this))throw new Error("RenderPipeline cannot contain itself, directly or indirectly (cycle).")}_reaches(e){if(this===e)return!0;for(const t of this._passes)if(t instanceof fu&&t._reaches(e))return!0;return!1}_assertLive(){if(this._destroyed)throw new Error("RenderPipeline has been destroyed and can no longer be used.")}_assertNotExecuting(){if(this._executing)throw new Error("RenderPipeline cannot be mutated while it is executing.")}}class pu{destroy(){}}const mu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);class gu extends pu{uniforms;_fragmentSource;_vertexSource;_shader=null;_connection=null;constructor(e){if(super(),!e.fragmentSource)throw new Error("WebGl2ShaderFilter requires fragmentSource for the WebGL2 backend.");const t=!1!==e.autoUpgrade;var i;this._fragmentSource=t?(i=e.fragmentSource,/^\s*#version\s+300\s+es/.test(i)?i:"#version 300 es\nprecision highp float;\nout vec4 fragColor;\n"+i.replace(/^\s*#version[^\n]*\n/,"").replaceAll(/\bgl_FragColor\b/g,"fragColor").replaceAll(/\btexture2D(?=\s*\()/g,"texture").replaceAll(/\btextureCube(?=\s*\()/g,"texture").replaceAll(/\btexture2DProj(?=\s*\()/g,"textureProj").replaceAll(/\bvarying\b/g,"in")):e.fragmentSource,this._vertexSource=e.vertexSource??"#version 300 es\nin vec2 aPosition;\nin vec2 aUv;\nout vec2 vUv;\nvoid main() {\n vUv = aUv;\n gl_Position = vec4(aPosition, 0.0, 1.0);\n}\n",this.uniforms={...e.uniforms??{}}}apply(t,i,n){if(t.backendType===e.RenderBackendType.WebGpu)throw new Error("WebGl2ShaderFilter requires the WebGL2 backend. Use WebGpuShaderFilter on WebGPU.");const r=t;this._ensureConnected(r);const s=this._shader;t.execute(new vi(t=>{const r=t;r.bindShader(s),r.bindTexture(i,0),s.uniforms.has("uTexture")&&s.getUniform("uTexture").setValue(new Int32Array([0])),s.uniforms.has("uResolution")&&s.getUniform("uResolution").setValue(new Float32Array([n.width,n.height]));let o=1;for(const[e,t]of Object.entries(this.uniforms)){if(!s.uniforms.has(e))continue;const i=s.getUniform(e);t instanceof pi?(r.bindTexture(t,o),i.setValue(new Int32Array([o])),o++):i.setValue(this._marshalValue(t))}s.sync();const a=this._connection;r.bindVertexArrayObject(a.vao),a.vao.draw(4,0,e.RenderingPrimitives.TriangleStrip)},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){null!==this._connection&&(this._connection.vertexBuffer.destroy(),this._connection.vao.destroy(),this._connection=null),null!==this._shader&&(this._shader.destroy(),this._shader=null);for(const e of Object.keys(this.uniforms))delete this.uniforms[e]}_ensureConnected(e){if(null!==this._shader)return;const t=e.context,i=new Yr(this._vertexSource,this._fragmentSource);i.connect(ts(t)),i.sync();const n=t.createVertexArray();if(null===n)throw new Error("WebGl2ShaderFilter: could not create vertex array object.");const r=this._createVertexBuffer(t),s=this._createVao(t,n,i,r);this._shader=i,this._connection={gl:t,vertexBuffer:r,vao:s}}_createVertexBuffer(t){const i=t.createBuffer();if(null===i)throw new Error("WebGl2ShaderFilter: could not create vertex buffer.");const n=new Hr(e.BufferTypes.ArrayBuffer,mu,e.BufferUsage.StaticDraw);return n.connect({bind:()=>{t.bindBuffer(t.ARRAY_BUFFER,i)},upload:(e,n)=>{t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,e.data,e.usage)},destroy:e=>{t.deleteBuffer(i),e.disconnect()}}),n}_createVao(t,i,n,r){let s=-1;const o=new ns(e.RenderingPrimitives.TriangleStrip);return n.attributes.has("aPosition")&&o.addAttribute(r,n.getAttribute("aPosition"),t.FLOAT,!1,16,0),n.attributes.has("aUv")&&o.addAttribute(r,n.getAttribute("aUv"),t.FLOAT,!1,16,8),o.connect({bind:e=>{if(t.bindVertexArray(i),s!==e.version){let i=null;for(const n of e.attributes){const e=n.buffer;i!==e&&(e.bind(),i=e),t.vertexAttribPointer(n.location,n.size,n.type,n.normalized,n.stride,n.start),t.enableVertexAttribArray(n.location)}s=e.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,r)=>{t.drawArrays(r,n,i)},destroy:e=>{t.deleteVertexArray(i),e.disconnect()}}),o}_marshalValue(e){return e instanceof Float32Array||e instanceof Int32Array?e:"number"==typeof e?new Float32Array([e]):new Float32Array(e)}}const yu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);function wu(e){return e instanceof pi||"object"==typeof e&&null!==e&&"width"in e&&"height"in e&&!(e instanceof Float32Array)&&!(e instanceof Int32Array)&&!Array.isArray(e)}class xu extends pu{uniforms;_fragmentSource;_vertexSource;_connection=null;constructor(e){if(super(),!e.fragmentSource)throw new Error("WebGpuShaderFilter requires fragmentSource.");this._fragmentSource=e.fragmentSource,this._vertexSource=e.vertexSource??"\nstruct VsOut {\n @builtin(position) position: vec4<f32>,\n @location(0) vUv: vec2<f32>,\n};\n\n@vertex\nfn main(@location(0) aPosition: vec2<f32>, @location(1) aUv: vec2<f32>) -> VsOut {\n var out: VsOut;\n out.position = vec4<f32>(aPosition, 0.0, 1.0);\n out.vUv = aUv;\n return out;\n}\n",this.uniforms={...e.uniforms??{}}}apply(t,i,n){if(t.backendType!==e.RenderBackendType.WebGpu)throw new Error("WebGpuShaderFilter requires the WebGPU backend. Use WebGl2ShaderFilter on WebGL2.");const r=t;this._ensureConnected(r,n);const s=this._connection;t.execute(new vi(e=>{const t=e,r=s.device,o=new Float32Array([n.width,n.height,0,0]);r.queue.writeBuffer(s.resolutionBuffer,0,o);const a=t.getTextureBinding(i),h=r.createBindGroup({layout:s.autoBindGroupLayout,entries:[{binding:0,resource:{buffer:s.resolutionBuffer}},{binding:1,resource:a.view},{binding:2,resource:s.sampler}]}),l=this._buildUserBindGroup(t,s),u=t._passCoordinator.acquirePass().pass;u.setPipeline(s.pipeline),u.setVertexBuffer(0,s.vertexBuffer),u.setBindGroup(0,h),u.setBindGroup(1,l),u.draw(4),t.stats.drawCalls++,t._passCoordinator.endPass()},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){null!==this._connection&&(this._connection.vertexBuffer.destroy(),this._connection.resolutionBuffer.destroy(),this._connection.userUniformBuffer?.destroy(),this._connection=null);for(const e of Object.keys(this.uniforms))delete this.uniforms[e]}_ensureConnected(e,t){if(null!==this._connection)return;const i=e.device,n=i.createShaderModule({code:this._vertexSource}),r=i.createShaderModule({code:this._fragmentSource}),s=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT|GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,texture:{}},{binding:2,visibility:GPUShaderStage.FRAGMENT,sampler:{}}]}),o=this._buildUserBindGroupLayout(i),a=i.createPipelineLayout({bindGroupLayouts:[s,o]}),h=e.getTextureFormat(t),l=i.createRenderPipeline({layout:a,vertex:{module:n,entryPoint:"main",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:r,entryPoint:"main",targets:[{format:h}]},primitive:{topology:"triangle-strip"}}),u=i.createBuffer({size:yu.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});i.queue.writeBuffer(u,0,yu);const c=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),d=i.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"});this._connection={device:i,vertexBuffer:u,resolutionBuffer:c,autoBindGroupLayout:s,userBindGroupLayout:o,pipelineLayout:a,pipeline:l,sampler:d,userUniformBuffer:null}}_buildUserBindGroupLayout(e){const t=[];Object.values(this.uniforms).some(e=>!wu(e))&&t.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});let i=1;for(const e of Object.values(this.uniforms))wu(e)&&(t.push({binding:i,visibility:GPUShaderStage.FRAGMENT,texture:{}}),i++,t.push({binding:i,visibility:GPUShaderStage.FRAGMENT,sampler:{}}),i++);return 0===t.length&&t.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),e.createBindGroupLayout({entries:t})}_buildUserBindGroup(e,t){const i=t.device,n=[],r=Object.entries(this.uniforms).filter(([,e])=>!wu(e));if(r.length>0){const e=16*r.length,s=new Float32Array(e/4);let o=0;for(const[,e]of r){const t=4*o;if("number"==typeof e)s[t]=e;else if(e instanceof Float32Array)s.set(e,t);else if(e instanceof Int32Array)for(let i=0;i<e.length;i++)s[t+i]=e[i];else{const i=e;for(let e=0;e<i.length;e++)s[t+e]=i[e]}o++}(null===t.userUniformBuffer||t.userUniformBuffer.size<e)&&(t.userUniformBuffer?.destroy(),t.userUniformBuffer=i.createBuffer({size:e,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),i.queue.writeBuffer(t.userUniformBuffer,0,s),n.push({binding:0,resource:{buffer:t.userUniformBuffer}})}else null===t.userUniformBuffer&&(t.userUniformBuffer=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),n.push({binding:0,resource:{buffer:t.userUniformBuffer}});let s=1;for(const[,t]of Object.entries(this.uniforms)){if(!wu(t))continue;const i=e.getTextureBinding(t);n.push({binding:s,resource:i.view}),s++,n.push({binding:s,resource:i.sampler}),s++}return i.createBindGroup({layout:t.userBindGroupLayout,entries:n})}}class vu extends pu{static identityLut1D(t=256){const i=document.createElement("canvas");i.width=t,i.height=1;const n=i.getContext("2d");if(null===n)throw new Error("LutFilter.identityLut1D: 2D canvas context unavailable.");const r=n.createImageData(t,1);for(let e=0;e<t;e++){const i=Math.round(e/(t-1)*255),n=4*e;r.data[n]=i,r.data[n+1]=i,r.data[n+2]=i,r.data[n+3]=255}return n.putImageData(r,0,0),new pi(i,{scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,generateMipMap:!1})}static identityLut3D(t=17){const i=t*t,n=document.createElement("canvas");n.width=i,n.height=t;const r=n.getContext("2d");if(null===r)throw new Error("LutFilter.identityLut3D: 2D canvas context unavailable.");const s=r.createImageData(i,t),o=t-1;for(let e=0;e<t;e++){const n=Math.round(e/o*255);for(let r=0;r<t;r++){const a=Math.round(r/o*255);for(let h=0;h<t;h++){const l=Math.round(h/o*255),u=4*(r*i+(e*t+h));s.data[u]=l,s.data[u+1]=a,s.data[u+2]=n,s.data[u+3]=255}}}return r.putImageData(s,0,0),new pi(n,{scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,generateMipMap:!1})}static fromImage(t){return new pi(t,{scaleMode:e.ScaleModes.Linear,wrapMode:e.WrapModes.ClampToEdge,generateMipMap:!1})}_mode;_size;_lut;_backendFilter=null;constructor(e={}){super(),this._mode=e.mode??"3d",this._size=Math.max(2,Math.floor(e.size??17)),this._lut="1d"===this._mode?vu.identityLut1D():vu.identityLut3D(this._size)}get mode(){return this._mode}get size(){return this._size}get lut(){return this._lut}setLut(e){return this._lut=e,null!==this._backendFilter&&(this._backendFilter.uniforms.uLut=e),this}apply(e,t,i){null===this._backendFilter&&(this._backendFilter=this._createBackendFilter(e)),this._backendFilter.apply(e,t,i)}destroy(){null!==this._backendFilter&&(this._backendFilter.destroy(),this._backendFilter=null)}_createBackendFilter(t){const i="3d"===this._mode,n={uLut:this._lut};return i&&(n.uLutSize=this._size),t.backendType===e.RenderBackendType.WebGpu?new xu({fragmentSource:i?"\nstruct Uniforms {\n uLutSize: f32,\n};\n\n@group(0) @binding(1) var uTexture: texture_2d<f32>;\n@group(0) @binding(2) var uSampler: sampler;\n@group(1) @binding(0) var<uniform> uniforms: Uniforms;\n@group(1) @binding(1) var uLut: texture_2d<f32>;\n\nfn sampleLut3d(c: vec3<f32>) -> vec3<f32> {\n let n = uniforms.uLutSize;\n let scaled = clamp(c.b, 0.0, 1.0) * (n - 1.0);\n let bLow = floor(scaled);\n let bHigh = min(bLow + 1.0, n - 1.0);\n let bFrac = scaled - bLow;\n let invN2 = 1.0 / (n * n);\n let invN = 1.0 / n;\n let halfPx = 0.5 / (n * n);\n let halfRow = 0.5 / n;\n let rOff = clamp(c.r, 0.0, 1.0) * (n - 1.0) * invN2;\n let gOff = clamp(c.g, 0.0, 1.0) * (n - 1.0) * invN + halfRow;\n let uLow = bLow * invN + rOff + halfPx;\n let uHigh = bHigh * invN + rOff + halfPx;\n let lo = textureSample(uLut, uSampler, vec2<f32>(uLow, gOff)).rgb;\n let hi = textureSample(uLut, uSampler, vec2<f32>(uHigh, gOff)).rgb;\n return mix(lo, hi, bFrac);\n}\n\n@fragment\nfn fragMain(@location(0) vUv: vec2<f32>) -> @location(0) vec4<f32> {\n let src = textureSample(uTexture, uSampler, vUv);\n return vec4<f32>(sampleLut3d(src.rgb), src.a);\n}\n":"\n@group(0) @binding(1) var uTexture: texture_2d<f32>;\n@group(0) @binding(2) var uSampler: sampler;\n@group(1) @binding(1) var uLut: texture_2d<f32>;\n\n@fragment\nfn fragMain(@location(0) vUv: vec2<f32>) -> @location(0) vec4<f32> {\n let src = textureSample(uTexture, uSampler, vUv);\n let graded = textureSample(uLut, uSampler, vec2<f32>(src.r, 0.5)).rgb;\n return vec4<f32>(graded, src.a);\n}\n",uniforms:n}):new gu({fragmentSource:i?"#version 300 es\nprecision mediump float;\nuniform sampler2D uTexture;\nuniform sampler2D uLut;\nuniform float uLutSize;\nin vec2 vUv;\nout vec4 fragColor;\n\nvec3 sampleLut3d(vec3 c) {\n float n = uLutSize;\n float scaled = clamp(c.b, 0.0, 1.0) * (n - 1.0);\n float bLow = floor(scaled);\n float bHigh = min(bLow + 1.0, n - 1.0);\n float bFrac = scaled - bLow;\n float invN2 = 1.0 / (n * n);\n float invN = 1.0 / n;\n float halfPx = 0.5 / (n * n);\n float halfRow = 0.5 / n;\n float rOff = clamp(c.r, 0.0, 1.0) * (n - 1.0) * invN2;\n float gOff = clamp(c.g, 0.0, 1.0) * (n - 1.0) * invN + halfRow;\n float uLow = bLow * invN + rOff + halfPx;\n float uHigh = bHigh * invN + rOff + halfPx;\n vec3 lo = texture(uLut, vec2(uLow, gOff)).rgb;\n vec3 hi = texture(uLut, vec2(uHigh, gOff)).rgb;\n return mix(lo, hi, bFrac);\n}\n\nvoid main() {\n vec4 src = texture(uTexture, vUv);\n fragColor = vec4(sampleLut3d(src.rgb), src.a);\n}\n":"#version 300 es\nprecision mediump float;\nuniform sampler2D uTexture;\nuniform sampler2D uLut;\nin vec2 vUv;\nout vec4 fragColor;\nvoid main() {\n vec4 src = texture(uTexture, vUv);\n vec3 graded = texture(uLut, vec2(src.r, 0.5)).rgb;\n fragColor = vec4(graded, src.a);\n}\n",uniforms:n})}}const bu={f32:4,u8:1,u16:2,u32:4,i32:4},Su=new Set(["triangle-list","triangle-strip"]),Bu=new Set(["static","dynamic","stream"]),Cu=new Set(["a_position","position"]),Tu=new WeakMap;let Mu=1;const Pu=(e,t)=>{const{byteLength:i}=e;if(i%t!==0)throw new Error(`Geometry vertexData byteLength ${i} must be divisible by stride ${t}.`);return i/t},Au=(e,t,i,n)=>{switch(t){case"f32":return e.getFloat32(i,!0);case"u8":{const t=e.getUint8(i);return n?t/255:t}case"u16":{const t=e.getUint16(i,!0);return n?t/65535:t}case"u32":{const t=e.getUint32(i,!0);return n?t/4294967295:t}case"i32":{const t=e.getInt32(i,!0);return n?Math.max(t/2147483647,-1):t}default:return 0}};const Eu=(e,t)=>e.offset-t.offset;class ku{_stops;_sample=new Float32Array(4);constructor(e){this._stops=ku._normalizeStops(e)}get stops(){return this._stops}copy(e){return this._stops=e._stops.map(e=>({offset:e.offset,color:e.color.clone()})),this._copyGeometry(e),this}equals(e){if(this===e)return!0;if(this.type!==e.type||this._stops.length!==e._stops.length)return!1;for(let t=0;t<this._stops.length;t++){const i=this._stops[t],n=e._stops[t];if(i.offset!==n.offset||!i.color.equals(n.color))return!1}return this._geometryEquals(e)}toTexture(e,t,i={}){if(!Number.isInteger(e)||!Number.isInteger(t)||e<=0||t<=0)throw new Error("Gradient.toTexture() width/height must be positive integers.");return"rgba32f"===i.format?this._toRgba32fTexture(e,t,i):this._toRgba8Texture(e,t,i)}destroy(){for(const e of this._stops)e.color.destroy();this._stops=[]}sampleAt(e,t){const i=Y(e,0,1),n=this._stops[0];let r=n.offset,s=n.color;for(let e=1;e<this._stops.length;e++){const n=this._stops[e];if(i<=n.offset){const e=Math.max(n.offset-r,1e-6),o=Y((i-r)/e,0,1);return t[0]=s.r/255+(n.color.r/255-s.r/255)*o,t[1]=s.g/255+(n.color.g/255-s.g/255)*o,t[2]=s.b/255+(n.color.b/255-s.b/255)*o,void(t[3]=s.a+(n.color.a-s.a)*o)}r=n.offset,s=n.color}t[0]=s.r/255,t[1]=s.g/255,t[2]=s.b/255,t[3]=s.a}static _normalizeStops(e){if(e.length<2)throw new Error("Gradient requires at least 2 color stops.");return e.map(e=>{if(!Number.isFinite(e.offset))throw new Error("Gradient stop offset must be a finite number.");return{offset:Y(e.offset,0,1),color:e.color.clone()}}).sort(Eu)}_toRgba8Texture(e,t,i){const n=new Rr({width:e,height:t,format:"rgba8",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),r=n.buffer;let s=0;for(let i=0;i<t;i++){const n=1===t?0:i/(t-1);for(let t=0;t<e;t++){const i=1===e?0:t/(e-1);this.sampleAt(this.resolveT(i,n),this._sample),r[s]=Ru(this._sample[0]),r[s+1]=Ru(this._sample[1]),r[s+2]=Ru(this._sample[2]),r[s+3]=Ru(this._sample[3]),s+=4}}return n.commit(),n}_toRgba32fTexture(e,t,i){const n=new Rr({width:e,height:t,format:"rgba32f",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),r=n.buffer;let s=0;for(let i=0;i<t;i++){const n=1===t?0:i/(t-1);for(let t=0;t<e;t++){const i=1===e?0:t/(e-1);this.sampleAt(this.resolveT(i,n),this._sample),r[s]=this._sample[0],r[s+1]=this._sample[1],r[s+2]=this._sample[2],r[s+3]=this._sample[3],s+=4}}return n.commit(),n}}const Ru=e=>255*Y(e,0,1)+.5|0;class Du extends ku{type="linear";_start;_end;constructor(e,t=[0,0],i=[1,0]){super(e),this._start=[t[0],t[1]],this._end=[i[0],i[1]]}get start(){return[this._start[0],this._start[1]]}get end(){return[this._end[0],this._end[1]]}clone(){return new Du(this.stops,this._start,this._end)}resolveT(e,t){const i=this._end[0]-this._start[0],n=this._end[1]-this._start[1],r=i*i+n*n;return r<=1e-6?0:((e-this._start[0])*i+(t-this._start[1])*n)/r}_copyGeometry(e){this._start=[e._start[0],e._start[1]],this._end=[e._end[0],e._end[1]]}_geometryEquals(e){return e instanceof Du&&this._start[0]===e._start[0]&&this._start[1]===e._start[1]&&this._end[0]===e._end[0]&&this._end[1]===e._end[1]}}class Fu extends ku{type="radial";_center;_radius;constructor(e,t=[.5,.5],i=.5){super(e),this._center=[t[0],t[1]],this._radius=Math.max(0,i)}get center(){return[this._center[0],this._center[1]]}get radius(){return this._radius}clone(){return new Fu(this.stops,this._center,this._radius)}resolveT(e,t){if(this._radius<=1e-6)return 1;const i=e-this._center[0],n=t-this._center[1];return Math.sqrt(i*i+n*n)/this._radius}_copyGeometry(e){this._center=[e._center[0],e._center[1]],this._radius=e._radius}_geometryEquals(e){return e instanceof Fu&&this._center[0]===e._center[0]&&this._center[1]===e._center[1]&&this._radius===e._radius}}const Iu=new WeakMap;let Lu=1;const Uu=e=>{const t=Iu.get(e);if(void 0!==t)return t;const i=Lu++;return Iu.set(e,i),i},Gu=new Map;let Nu=1;const Ou=new Map;let Vu=1;const zu=(e,t,i)=>{const n=e.get(t);if(void 0!==n)return n;const r=i();return e.set(t,r),r},qu=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&!ArrayBuffer.isView(e);let Wu=1;class Yu{shader;uniforms;textures;blendMode;sampler;_id;_disposeCallbacks=new Set;constructor(t){if(void 0===t.shader||null===t.shader)throw new Error("Material requires a `shader` ShaderSource.");this.shader=t.shader,this.uniforms={...t.uniforms??{}},this.textures={...t.textures??{}},this.blendMode=t.blendMode??e.BlendModes.Normal,this.sampler=t.sampler??null,this._id=Wu++}get pipelineKey(){return((e,t,i)=>{const n=`${e}|${t}|${(e=>null===e?"-":[e.scaleMode,e.wrapMode,e.premultiplyAlpha?1:0,e.generateMipMap?1:0,e.flipY?1:0].join(":"))(i)}`;return zu(Gu,n,()=>Nu++)})(this.shader.id,this.blendMode,this.sampler)}get bindKey(){return((e,t,i)=>{const n=[];for(const e of Object.keys(i))n.push(`t:${e}=${Uu(i[e])}`);for(const e of Object.keys(t)){const i=t[e];qu(i)&&n.push(`u:${e}=${Uu(i)}`)}n.sort();const r=`${e}|${n.join(",")}`;return zu(Ou,r,()=>Vu++)})(this._id,this.uniforms,this.textures)}setUniform(e,t){return this.uniforms[e]=t,this}setTexture(e,t){return this.textures[e]=t,this}destroy(){for(const e of this._disposeCallbacks)e();this._disposeCallbacks.clear()}_onDispose(e){this._disposeCallbacks.add(e)}}let $u=1;class Xu{glsl;wgsl;_id;constructor(e){if(void 0===e.glsl&&void 0===e.wgsl)throw new Error("ShaderSource requires at least one of `glsl` or `wgsl`.");if(void 0!==e.glsl){if("string"!=typeof e.glsl.vertex||0===e.glsl.vertex.length)throw new Error("ShaderSource.glsl.vertex must be a non-empty string.");if("string"!=typeof e.glsl.fragment||0===e.glsl.fragment.length)throw new Error("ShaderSource.glsl.fragment must be a non-empty string.")}if(void 0!==e.wgsl&&("string"!=typeof e.wgsl||0===e.wgsl.length))throw new Error("ShaderSource.wgsl must be a non-empty string.");this.glsl=e.glsl??null,this.wgsl=e.wgsl??null,this._id=$u++}get id(){return this._id}getDeclaredUniforms(){return{glsl:null!==this.glsl?Zu(this.glsl.vertex,this.glsl.fragment):{},wgsl:null!==this.wgsl?Ju(this.wgsl):{}}}detectUniformDrift(){if(null===this.glsl||null===this.wgsl)return{onlyInGlsl:[],onlyInWgsl:[]};const e=this.getDeclaredUniforms(),t=new Set(Object.keys(e.glsl).filter(e=>!Hu.has(e))),i=new Set(Object.keys(e.wgsl).filter(e=>!Hu.has(e))),n=[],r=[];for(const e of t)i.has(e)||n.push(e);for(const e of i)t.has(e)||r.push(e);return{onlyInGlsl:n,onlyInWgsl:r}}}const Hu=new Set(["u_projection","u_translation","u_tint","u_texture","u_mesh"]),ju=/\buniform\s+(?:mediump\s+|highp\s+|lowp\s+|)(\w+)\s+(\w+)[^;]*;/g,Ku=/@group\(\s*2\s*\)\s*@binding\(\s*\d+\s*\)\s*var(?:<[^>]+>|)\s+(\w+)\s*:\s*([^;]+);/g;function Qu(e){return e.replaceAll(/\/\*[\s\S]*?\*\//g,"").replaceAll(/\/\/[^\n]*/g,"")}function Zu(e,t){const i={};for(const n of[e,t]){const e=Qu(n);let t;for(ju.lastIndex=0;null!==(t=ju.exec(e));){const[,e,n]=t;void 0!==e&&void 0!==n&&(i[n]=e)}}return i}function Ju(e){const t={},i=Qu(e);let n;for(Ku.lastIndex=0;null!==(n=Ku.exec(i));){const[,e,i]=n;void 0!==e&&void 0!==i&&(t[e]=i.trim())}return t}class ec extends Yu{target="mesh";constructor(e){super(e)}static from(e,t,i){if(e instanceof Xu){return new ec({shader:e,...void 0!==t?t:{}})}const n=new Xu({glsl:{vertex:e,fragment:t},...void 0!==i?.wgsl?{wgsl:i.wgsl}:{}});return new ec({shader:n,...void 0!==i?.uniforms?{uniforms:i.uniforms}:{},...void 0!==i?.blendMode?{blendMode:i.blendMode}:{},...void 0!==i?.sampler?{sampler:i.sampler}:{}})}}class tc extends Yu{target="sprite";constructor(e){super(e)}static from(e,t,i){if(e instanceof Xu){return new tc({shader:e,...void 0!==t?t:{}})}const n=new Xu({glsl:{vertex:e,fragment:t},...void 0!==i?.wgsl?{wgsl:i.wgsl}:{}});return new tc({shader:n,...void 0!==i?.uniforms?{uniforms:i.uniforms}:{},...void 0!==i?.blendMode?{blendMode:i.blendMode}:{},...void 0!==i?.sampler?{sampler:i.sampler}:{}})}}const ic={woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};class nc extends Bi{_html;_css;_width;_height;_resolution;_canvas;_ctx;_texture;_mesh;_destroyed=!1;_renderVersion=0;_activeRender=null;_fonts=[];constructor(e,t={}){super(),this._html=e,this._css=t.css??"",this._width=t.width??256,this._height=t.height??128,this._resolution=t.resolution??1;const[i,n]=nc._makeCanvas(Math.ceil(this._width*this._resolution),Math.ceil(this._height*this._resolution));this._canvas=i,this._ctx=n,this._texture=new pi(i),this._texture.setSize(this._width,this._height),this._mesh=this._buildMesh(),this.addChild(this._mesh),e.length>0&&this._schedule()}get html(){return this._html}set html(e){this._html!==e&&(this._html=e,this._schedule())}get css(){return this._css}set css(e){this._css!==e&&(this._css=e,this._schedule())}get width(){return this._width}set width(e){this.resize(e,this._height)}get height(){return this._height}set height(e){this.resize(this._width,e)}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this._resizeCanvas(),this._schedule())}get ready(){return this._activeRender??Promise.resolve()}addFont(e,t,i="woff2"){const n=`data:${ic[i]};base64,${nc._toBase64(t)}`,r=this._fonts.findIndex(t=>t.family===e);return r>=0?this._fonts[r]={family:e,dataUri:n}:this._fonts.push({family:e,dataUri:n}),this._schedule(),this}removeFont(e){const t=this._fonts.findIndex(t=>t.family===e);return t>=0&&(this._fonts.splice(t,1),this._schedule()),this}resize(e,t){return this._width===e&&this._height===t||(this._width=e,this._height=t,this._resizeCanvas(),this._rebuildMesh(),this._schedule()),this}destroy(){this._destroyed=!0,this._renderVersion++,this._activeRender=null,this._texture.destroy(),super.destroy()}_schedule(){const t=++this._renderVersion;this._activeRender=this._render(t).catch(t=>{ih.log(e.LogSeverity.Warning,"rendering","HTMLText render failed.",t instanceof Error?{error:t}:void 0)})}async _render(e){if("undefined"==typeof Blob||"undefined"==typeof Image)return;const t=new Blob([this._buildSvg()],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(t),n=new Image;try{await new Promise((e,t)=>{n.onload=()=>e(),n.onerror=()=>t(new Error("HTMLText: SVG render failed")),n.src=i})}finally{URL.revokeObjectURL(i)}if(this._destroyed||e!==this._renderVersion)return;const r=Math.ceil(this._width*this._resolution),s=Math.ceil(this._height*this._resolution);this._ctx.clearRect(0,0,r,s),this._ctx.drawImage(n,0,0,r,s),this._texture.updateSource()}_buildSvg(){const e=this._width,t=this._height,i=this._fonts.map(({family:e,dataUri:t})=>`@font-face{font-family:'${e.replaceAll("\\","\\\\").replaceAll("'","\\'")}';src:url('${t}');}`).join(""),n=this._css.replaceAll(/<\/style>/gi,"<\\/style>");return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="width:${e}px;height:${t}px;overflow:hidden;box-sizing:border-box;">${i||n?`<style>${i}${n}</style>`:""}${this._html}</div></foreignObject></svg>`}_buildMesh(){const e=this._width,t=this._height;return new In({vertices:new Float32Array([0,0,e,0,e,t,0,t]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint16Array([0,1,2,0,2,3]),texture:this._texture})}_rebuildMesh(){this.removeChild(this._mesh),this._mesh.destroy(),this._mesh=this._buildMesh(),this.addChild(this._mesh)}_resizeCanvas(){const e=Math.ceil(this._width*this._resolution),t=Math.ceil(this._height*this._resolution);this._canvas.width=e,this._canvas.height=t,this._texture.updateSource()}static _toBase64(e){const t=new Uint8Array(e);let i="";for(let e=0;e<t.length;e++)i+=String.fromCharCode(t[e]);return btoa(i)}static _makeCanvas(e,t){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(e,t),n=i.getContext("2d");if(!n)throw new Error("HTMLText: could not obtain 2D context.");return[i,n]}const i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");if(!n)throw new Error("HTMLText: could not obtain 2D context.");return[i,n]}}const rc=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"];class sc{name;version;_storeNames;_migrations;_onCloseHandler=this.disconnect.bind(this);_connected=!1;_database=null;get connected(){return this._connected}constructor(e,t=1,i=rc,n){if(!f)throw new Error("This browser does not support indexedDB!");this.name=e,this.version=t,this._storeNames=i,this._migrations=n}async getObjectStore(e,t="readonly"){return await this.connect(),this._database.transaction([e],t).objectStore(e)}async connect(){return!(!this._connected||!this._database)||new Promise((e,t)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",e=>{const n=i.result,r=i.transaction,s=[...r.objectStoreNames],{oldVersion:o,newVersion:a}=e;if(n.addEventListener("error",()=>t(new Error("An error occurred while opening the database."))),n.addEventListener("abort",()=>t(new Error("The database opening was aborted."))),this._migrations){const e=Object.keys(this._migrations).map(Number).filter(e=>e>o&&e<=(a??this.version)).sort((e,t)=>e-t);for(const t of e){const e=this._migrations[t];if(void 0===e)continue;if(!e(n,r))return void r.abort()}}else{for(const e of s)this._storeNames.includes(e)||n.deleteObjectStore(e);for(const e of this._storeNames)s.includes(e)||n.createObjectStore(e,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,e(!0)}),i.addEventListener("error",()=>t(new Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>t(new Error("The request for the database connection has been blocked.")))})}async disconnect(){return this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close(),this._database=null,this._connected=!1),!0}async load(e,t){const i=await this.getObjectStore(e);return new Promise((e,n)=>{const r=i.get(t);r.addEventListener("success",()=>e(r.result?.data??null)),r.addEventListener("error",()=>n(new Error("An error occurred while loading an item.")))})}async save(e,t,i){const n=await this.getObjectStore(e,"readwrite");return new Promise((e,r)=>{const s=n.put({name:t,data:i});s.addEventListener("success",()=>e()),s.addEventListener("error",()=>r(new Error("An error occurred while saving an item.")))})}async delete(e,t){const i=await this.getObjectStore(e,"readwrite");return new Promise((e,n)=>{const r=i.delete(t);r.addEventListener("success",()=>e(!0)),r.addEventListener("error",()=>n(new Error("An error occurred while deleting an item.")))})}async clearStorage(e){const t=await this.getObjectStore(e,"readwrite");return new Promise((e,i)=>{const n=t.clear();n.addEventListener("success",()=>e(!0)),n.addEventListener("error",()=>i(new Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((e,t)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>e(!0)),i.addEventListener("error",()=>t(new Error("An error occurred while deleting a storage.")))})}destroy(){this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close()),this._database=null,this._connected=!1}}class oc{_db;constructor(e){const t="string"==typeof e?{name:e}:e;this._db=new sc(t.name,t.version??1,t.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"],t.migrations)}async load(e,t){return this._db.load(e,t)}async save(e,t,i){return this._db.save(e,t,i)}async delete(e,t){return this._db.delete(e,t)}async clear(e){return this._db.clearStorage(e)}destroy(){this._db.destroy()}}return e.AbstractAssetFactory=To,e.AbstractText=br,e.AnimatedSprite=kh,e.Application=class{options;canvas;loader;input;focus;interaction;scene;random;tweens=new a;systems=new Ml;serializers=new yl(wl);onResize=new x;onFrame=new x;onFixedFrame=new x;onCanvasFocusChange=new x;onVisibilityChange=new x;onBackendLost=new x;onBackendRestored=new x;onError=new x;pauseOnHidden=!1;_updateHandler;_startupClock=new Ri;_activeClock=new Ri;_frameClock=new Ri;_fixed;_fixedTime;_frameAlpha=0;_status=e.ApplicationStatus.Stopped;_pixelRatio=Gl;_designWidth=Ll;_designHeight=Ul;_frameCount=0;_frameRequest=0;_backendType;_backend;_rendering;_snapshot;_capabilities=null;_documentVisible=!0;_cursor="default";_visibilityChangeHandler=this._onDocumentVisibilityChange.bind(this);_resizeObserver=null;_sizingMode="fixed";_audio=new ft;constructor(e={}){const t=e.canvas??{},i=e.loader??{},n=e.rendering??{},r=e.input??{},s=t.element??document.createElement("canvas"),o=t.width??Ll,a=t.height??Ul;this._pixelRatio=t.pixelRatio??(()=>{const e=globalThis.devicePixelRatio;return"number"==typeof e&&e>0?Math.min(e,2):1})(),this._designWidth=o,this._designHeight=a,this.canvas=s,this._applyCanvasSize(o,a),void 0!==t.tabIndex?this.canvas.tabIndex=t.tabIndex:this.canvas.hasAttribute("tabindex")||(this.canvas.tabIndex=Nl),void 0!==t.imageRendering&&(this.canvas.style.imageRendering=t.imageRendering),this._mountCanvas(t.mount),this._sizingMode=t.sizingMode??"fixed",this._applySizingMode(this._sizingMode),this.options={clearColor:e.clearColor??Tt.cornflowerBlue,backend:e.backend??Il,canvas:{element:this.canvas,width:o,height:a,pixelRatio:this._pixelRatio,tabIndex:this.canvas.tabIndex,...void 0!==t.imageRendering&&{imageRendering:t.imageRendering}},loader:{basePath:i.basePath??"",fetchOptions:i.fetchOptions??{...Ol},...void 0!==i.cache&&{cache:i.cache},...void 0!==i.cacheStrategy&&{cacheStrategy:i.cacheStrategy},...void 0!==i.concurrency&&{concurrency:i.concurrency}},rendering:{debug:n.debug??Vl.debug,webglAttributes:n.webglAttributes??Vl.webglAttributes,spriteRendererBatchSize:n.spriteRendererBatchSize??Vl.spriteRendererBatchSize},input:{gamepadDefinitions:r.gamepadDefinitions??[...zl.gamepadDefinitions],gamepadSlotStrategy:r.gamepadSlotStrategy??zl.gamepadSlotStrategy,pointerDistanceThreshold:r.pointerDistanceThreshold??zl.pointerDistanceThreshold},...void 0!==e.seed&&{seed:e.seed},...void 0!==e.fixedTimeStep&&{fixedTimeStep:e.fixedTimeStep}},this._snapshot=void 0===e.extensions?function(){if(0===bt?.revision)return bt.snapshot;const e=vt([...St.values()]);return bt={revision:0,snapshot:e},e}():vt([...e.extensions??[]]),this.loader=new Va(this.options.loader);try{!function(e,t){const i=new Set,n=new Set,r=new Set;for(const s of t){if(i.has(s.type)||e.hasLoadable(s.type))throw new Error(`An asset handler is already registered for ${s.type.name}.`);for(const t of s.typeNames??[]){if(n.has(t)||e.hasAssetType(t))throw new Error(`Asset type name "${t}" is already registered. Remove the conflicting binding.`);n.add(t)}for(const t of s.extensions??[]){const i=t.replace(/^\./,"").toLowerCase();if(r.has(i)||e.hasExtension(i))throw new Error(`File extension ".${i}" is already mapped to an asset type. Remove the conflicting binding.`);r.add(i)}i.add(s.type)}for(const i of t){const t=i.create(e);e.bindAsset({type:i.type,...void 0!==i.typeNames&&{typeNames:i.typeNames},...void 0!==i.extensions&&{extensions:i.extensions}},t)}}(this.loader,[...Ba,...this._snapshot.assets]),function(e,t){for(const i of t)e.register(i.typeName,i.target,i.serializer)}(this.serializers,this._snapshot.serializers)}catch(e){try{this.loader.destroy()}catch{}throw e}this._backendType=this.resolveInitialBackendType(),this._backend=this.createBackend(this._backendType,this._snapshot),this._rendering=new Zs(this._backend),this.input=new yn(this),this.focus=new Ai(this),this.interaction=new vn(this),this.scene=new Rl(this),this.random=new Bn(this.options.seed),this._updateHandler=this.update.bind(this);const h=void 0!==this.options.fixedTimeStep?1e3*this.options.fixedTimeStep:Fl;this._fixed=new Ja(h,5),this._fixedTime=new ki(h),this.systems.add(this.input),this.systems.add(this.interaction),this.systems.add(this._audio),this.systems.add(this.tweens),this.systems.add(this._rendering),this._startupClock.start(),"undefined"!=typeof document&&(this._documentVisible="visible"===document.visibilityState,document.addEventListener("visibilitychange",this._visibilityChangeHandler)),this.input.onCanvasFocusChange.add(e=>{this.onCanvasFocusChange.dispatch(e)}),this.onVisibilityChange.add(e=>{this._audio._applyVisibility(e)})}get status(){return this._status}get startupTime(){return this._startupClock.elapsedTime}get activeTime(){return this._activeClock.elapsedTime}get frameTime(){return this._frameClock.elapsedTime}get frameCount(){return this._frameCount}get frameAlpha(){return this._frameAlpha}get fixedTimeStep(){return this._fixed.stepMs/1e3}get backend(){return this._backend}get rendering(){return this._rendering}get capabilities(){if(null===this._capabilities)throw new Error("Application.capabilities is unavailable before start() resolves. Use `await Capabilities.ready` for pre-start checks.");return this._capabilities}get canvasFocused(){return this.input.canvasFocused}get documentVisible(){return this._documentVisible}get cursor(){return this._cursor}set cursor(e){this.setCursor(e)}get sizingMode(){return this._sizingMode}set sizingMode(e){e!==this._sizingMode&&(this._resizeObserver?.disconnect(),this._resizeObserver=null,this._sizingMode=e,this._applySizingMode(e))}get clearColor(){return this._backend.clearColor}set clearColor(e){this._backend.clearColor.copy(e)}get audio(){return this._audio}get width(){return this._designWidth}get height(){return this._designHeight}get pixelRatio(){return this._pixelRatio}screenToWorld(e,t){return this._rendering.view.screenToWorld(e,t)}_backingStoreToDesign(e,t){const i=this.canvas.width||1,n=this.canvas.height||1;return{x:e/i*this._designWidth,y:t/n*this._designHeight}}async start(t){if(this._status===e.ApplicationStatus.Stopped){this._status=e.ApplicationStatus.Loading;const i=Ya.ready;try{await this.initializeBackend(),this._capabilities=await i,await this.scene.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._fixed.reset(),this._activeClock.start(),this._status=e.ApplicationStatus.Running}catch(t){throw this._status=e.ApplicationStatus.Stopped,t}}return this}update(){if(this._status===e.ApplicationStatus.Running){if(this.pauseOnHidden&&!this._documentVisible)return this._frameClock.restart(),this._fixed.reset(),this._frameRequest=requestAnimationFrame(this._updateHandler),this;const e=this._frameClock.elapsedTime.milliseconds,t=Math.min(e,100),i=ki.temp.set(t),n=performance.now();this.backend.resetStats(),this.backend.stats.rawFrameDeltaMs=e,this.systems._tick(i);const r=this._fixed.advance(t);for(let e=0;e<r;e++)this.scene.fixedUpdate(this._fixedTime),this.onFixedFrame.dispatch(this._fixedTime);this._frameAlpha=this._fixed.alpha,this.scene.update(i),this.onFrame.dispatch(i),this.backend.flush(),this.backend.stats.frameTimeMs=performance.now()-n,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===e.ApplicationStatus.Running&&(this._status=e.ApplicationStatus.Halting,cancelAnimationFrame(this._frameRequest),this.scene.setScene(null).catch(e=>{ih.error("core","Application.stop() failed to unload the active scene.",e instanceof Error?e:void 0),this.onError?.dispatch(e instanceof Error?e:new Error(String(e)))}),this._activeClock.stop(),this._frameClock.stop(),this._status=e.ApplicationStatus.Stopped),this}resize(e,t){return this._designWidth=e,this._designHeight=t,this._applyCanvasSize(e,t),this.options.canvas={...this.options.canvas??{},width:e,height:t,pixelRatio:this._pixelRatio},this.backend.resize(e,t),this._rendering.resize(e,t),this.onResize.dispatch(e,t,this),this}_mountCanvas(e){if(void 0===e||"undefined"==typeof document)return;const t="string"==typeof e?document.querySelector(e):e;t?.append(this.canvas)}_applySizingMode(e){const t=this.canvas.style;switch(e){case"fill":{const e=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!e)break;this._resizeObserver=new ResizeObserver(()=>{const t=e.clientWidth,i=e.clientHeight;t>0&&i>0&&this.resize(t,i)}),this._resizeObserver.observe(e);break}case"letterbox":{const e=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!e)break;const t=e.style;t.display="flex",t.alignItems="center",t.justifyContent="center",t.overflow="hidden",t.background="#000",this._resizeObserver=new ResizeObserver(()=>{const t=e.clientWidth,i=e.clientHeight;t>0&&i>0&&this._applyLetterboxLayout(t,i)}),this._resizeObserver.observe(e);break}case"fit":t.width="100%",t.height="100%",t.objectFit="contain";break;case"shrink":t.maxWidth="100%",t.maxHeight="100%",t.objectFit="contain"}}_applyLetterboxLayout(e,t){const i=((e,t,i,n,r)=>{const s=Math.min(e/i,t/n),o=i*s,a=n*s;return{contentWidthCss:o,contentHeightCss:a,backingWidth:Math.max(1,Math.round(o*r)),backingHeight:Math.max(1,Math.round(a*r))}})(e,t,this._designWidth,this._designHeight,this._pixelRatio);this.canvas.width=i.backingWidth,this.canvas.height=i.backingHeight,this.canvas.style.width=`${i.contentWidthCss}px`,this.canvas.style.height=`${i.contentHeightCss}px`}setCursor(e){const t=e instanceof pi?e.source:e;if(null===t)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof t?t:`url(${w(t)}), auto`,this.canvas.style.cursor=this._cursor,this}capture(e,t){return this._rendering.capture(e,t)}destroy(){"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this._visibilityChangeHandler),this._resizeObserver?.disconnect(),this._resizeObserver=null,this.stop(),this.loader.destroy(),this.focus.destroy(),this.systems.destroy(),this._backend.destroy(),this.scene.destroy(),this._startupClock.destroy(),this._activeClock.destroy(),this._frameClock.destroy(),this.onResize.destroy(),this.onFrame.destroy(),this.onFixedFrame.destroy(),this.onCanvasFocusChange.destroy(),this.onVisibilityChange.destroy(),this.onBackendLost.destroy(),this.onBackendRestored.destroy(),this.onError.destroy()}_onDocumentVisibilityChange(){const e="visible"===document.visibilityState;e!==this._documentVisible&&(this._documentVisible=e,this.onVisibilityChange.dispatch(e))}resolveInitialBackendType(){const e=this.options.backend?.type;return"webgl2"===e?"webgl2":"webgpu"===e||this.canUseWebGpu()?"webgpu":"webgl2"}createBackend(t,i){const n=function(t){const i=t.spriteRendererBatchSize??4096,n={[e.RenderBackendType.WebGl2]:()=>new ys(i),[e.RenderBackendType.WebGpu]:()=>new Ws},r={[e.RenderBackendType.WebGl2]:()=>new ss,[e.RenderBackendType.WebGpu]:()=>new Rs},s={[e.RenderBackendType.WebGl2]:()=>new vs,[e.RenderBackendType.WebGpu]:()=>new Hs},o={[e.RenderBackendType.WebGl2]:()=>new hs(i),[e.RenderBackendType.WebGpu]:()=>new Us},a={[e.RenderBackendType.WebGl2]:()=>new ps(i),[e.RenderBackendType.WebGpu]:()=>new Os};return[{targets:[vr],create:e=>n[e.backendType]?.()},{targets:[In],create:e=>r[e.backendType]?.()},{targets:[Wr,Ar],create:e=>s[e.backendType]?.()},{targets:[ur],create:e=>o[e.backendType]?.()},{targets:[wr],create:e=>a[e.backendType]?.()}]}(this.options.rendering??{}),r=[...n,...i.renderers];if("webgpu"===t){const e=new So(this);e.onDeviceLost.add(()=>{this.onBackendLost.dispatch()}),e.onDeviceRestored.add(()=>{this.onBackendRestored.dispatch()});try{Bt(e,r)}catch(t){try{e.destroy()}catch{}throw t}return e}const s=new mo(this);s.onContextLost.add(()=>{this.onBackendLost.dispatch()}),s.onContextRestored.add(()=>{this.onBackendRestored.dispatch()});try{Bt(s,r)}catch(e){try{s.destroy()}catch{}throw e}return s}async initializeBackend(){try{await this._backend.initialize()}catch(e){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw e;this._backend.destroy(),this._backendType="webgl2",this._backend=this.createBackend(this._backendType,this._snapshot);const t=this._rendering;this.systems.remove(t),t.destroy(),this._rendering=new Zs(this._backend),this.systems.add(this._rendering),await this._backend.initialize()}}canUseWebGpu(){return!!navigator.gpu}_applyCanvasSize(e,t){const i=Math.round(e*this._pixelRatio),n=Math.round(t*this._pixelRatio);this.canvas.width=i,this.canvas.height=n,this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`}},e.ArcadeStickGamepadMapping=Oi,e.Asset=Ta,e.Assets=La,e.AudioBus=J,e.AudioEffect=ee,e.AudioGenerator=ut,e.AudioInput=ct,e.AudioListener=dt,e.AudioManager=ft,e.AudioStream=mt,e.BinaryAsset=oa,e.BinaryFactory=Mo,e.BiquadEffect=class extends ee{_node=null;_type;_frequency;_resonance;_gain;_detune;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(e={}){super(),this._type=e.type??"lowpass",this._frequency=e.frequency??1e3,this._resonance=e.resonance??1,this._gain=e.gain??0,this._detune=e.detune??0,U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._node)throw new Error("BiquadEffect not yet initialized.");return this._node}get outputNode(){if(!this._node)throw new Error("BiquadEffect not yet initialized.");return this._node}get type(){return this._type}set type(e){this._type=e,this._node&&(this._node.type=e)}get frequency(){return this._frequency}set frequency(e){this._frequency=e,this._node&&this._node.frequency.setTargetAtTime(e,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(e){this._resonance=e,this._node&&this._node.Q.setTargetAtTime(e,this._node.context.currentTime,.01)}get gain(){return this._gain}set gain(e){this._gain=e,this._node&&this._node.gain.setTargetAtTime(e,this._node.context.currentTime,.01)}get detune(){return this._detune}set detune(e){this._detune=e,this._node&&this._node.detune.setTargetAtTime(e,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(e){const t=e.createBiquadFilter();t.type=this._type,t.frequency.setValueAtTime(this._frequency,e.currentTime),t.Q.setValueAtTime(this._resonance,e.currentTime),t.gain.setValueAtTime(this._gain,e.currentTime),t.detune.setValueAtTime(this._detune,e.currentTime),this._node=t}},e.BitmapText=Ar,e.BlurFilter=class extends pu{_sprite=new vr(null);_sampleTint=Tt.white.clone();_radius=2;_quality=1;constructor(e={}){super(),this._radius=Math.max(0,e.radius??2),this._quality=Math.max(1,Math.floor(e.quality??1))}get radius(){return this._radius}set radius(e){this._radius=Math.max(0,e)}get quality(){return this._quality}set quality(e){this._quality=Math.max(1,Math.floor(e))}apply(t,i,n){const r=this._radius,s=this._quality,o=Math.max(1,2*s+1),a=1/(r<=0?1:2*o);this._sampleTint.set(255,255,255,a),this._sprite.setTexture(i).setBlendMode(e.BlendModes.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=n.width,this._sprite.height=n.height,t.execute(new vi(()=>{if(r<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<o;e++){const i=(2*(1===o?0:e/(o-1))-1)*r;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}},e.BmFont=Sr,e.BmFontAdapter=Pr,e.BmFontLoaderFactory=class extends To{storageName="bmfont";_loader;constructor(e){super(),this._loader=e}async process(e){return{text:await e.text(),url:e.url}}async create(e){const{text:t,url:i}=e,n=Eo(t),r=await Promise.all(n.pages.map(e=>this._loader.load(pi,new URL(e,i).href)));return new Sr(n,r)}},e.Bounds=Rt,e.BundleLoadError=Ea,e.Button=tl,e.CacheFirstStrategy=Ua,e.CallbackRenderPass=class extends _u{_callback;_clear;_target;_view;_redirect;_activeContext=null;_executing=!1;constructor(e,t){super(t),this._callback=e,this._clear=t?.clear??null,this._target=t?.target??null,this._view=t?.view??null,this._redirect=null!==this._target?new vi(()=>this._runCallback(),{target:this._target,view:this._view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(e){if(this._executing)throw new Error("CallbackRenderPass.execute is not re-entrant.");this._executing=!0;try{if(null!==this._redirect){this._activeContext=e;try{e.backend.execute(this._redirect)}finally{this._activeContext=null}return}null!==this._clear&&e.backend.clear(this._clear),this._callback(new du(e,e.backend.renderTarget,e.backend.view))}finally{this._executing=!1}}_runCallback(){null!==this._activeContext&&null!==this._target&&this._callback(new du(this._activeContext,this._target,this._view??this._target.view))}},e.Capabilities=Ya,e.Circle=iu,e.Clock=Ri,e.Codec=Wl,e.Collision=Ke,e.Color=Tt,e.ColorFilter=class extends pu{_color;_sprite=new vr(null);constructor(e=Tt.white){super(),this._color=e.clone()}get color(){return this._color}apply(t,i,n){this._sprite.setTexture(i).setBlendMode(e.BlendModes.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=n.width,this._sprite.height=n.height,t.execute(new vi(()=>{this._sprite.render(t)},{target:n,view:n.view,clearColor:Tt.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}},e.Container=Bi,e.CsvAsset=na,e.CsvFactory=ko,e.DataTexture=Rr,e.DisposalScope=rh,e.Drawable=Fn,e.Ease=i,e.Ellipse=nu,e.Envelope=class{attackMs;decayMs;sustainLevel;releaseMs;constructor(e={}){this.attackMs=Math.max(0,e.attackMs??10),this.decayMs=Math.max(0,e.decayMs??100),this.sustainLevel=Math.max(0,Math.min(1,e.sustainLevel??.7)),this.releaseMs=Math.max(0,e.releaseMs??200)}trigger(e,t){const i=t+this.attackMs/1e3,n=i+this.decayMs/1e3;e.cancelScheduledValues(t),e.setValueAtTime(0,t),e.linearRampToValueAtTime(1,i),e.linearRampToValueAtTime(this.sustainLevel,n)}release(e,t){this.releaseMs,e.cancelScheduledValues(t),e.setTargetAtTime(0,t,this.releaseMs/1e3/3)}get totalDurationMs(){return this.attackMs+this.decayMs+this.releaseMs}destroy(){}},e.Filter=pu,e.Flags=Mt,e.FocusManager=Ai,e.FontAsset=sa,e.FontFactory=Ro,e.GameCubeGamepadMapping=Wi,e.Gamepad=Ii,e.GamepadAxis=Vi,e.GamepadButton=Li,e.GamepadMapping=Ni,e.GamepadPromptLayouts=class{static controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];static getControlPosition(e){return Hl.get(e)??[.5,.5]}static getControlLabels(e){return eu.get(e)??Kl}static getControlChannelMap(){return jl}},e.GenericDualAnalogGamepadMapping=qi,e.Geometry=class{attributes;stride;topology;usage;indices;vertexData;_version=0;_localBounds=new et;_localBoundsDirty=!0;_positionAttribute;_disposeCallbacks=new Set;constructor(e){const{attributes:t,vertexData:i,stride:n,indices:r=null,topology:s="triangle-list",usage:o="static"}=e;if(0===t.length)throw new Error("Geometry attributes must be a non-empty array.");if(!Number.isInteger(n)||n<=0)throw new Error(`Geometry stride must be a positive integer (got ${n}).`);if(!Su.has(s))throw new Error(`Geometry topology must be one of: triangle-list, triangle-strip (got ${String(s)}).`);if(!Bu.has(o))throw new Error(`Geometry usage must be one of: static, dynamic, stream (got ${String(o)}).`);const a=[],h=new Set;for(const e of t){if("string"!=typeof e.name||0===e.name.length)throw new Error("Geometry attribute name must be a non-empty string.");if(h.has(e.name))throw new Error(`Geometry attribute "${e.name}" is declared more than once.`);if(h.add(e.name),!Number.isInteger(e.size)||e.size<1||e.size>4)throw new Error(`Geometry attribute "${e.name}" size must be an integer in [1..4] (got ${e.size}).`);if(!Number.isInteger(e.offset)||e.offset<0)throw new Error(`Geometry attribute "${e.name}" offset must be a non-negative integer (got ${e.offset}).`);const t=bu[e.type],i=e.offset+t*e.size;if(i>n)throw new Error(`Geometry attribute "${e.name}" range [${e.offset}, ${i}) exceeds stride ${n}.`);for(const t of a)if(e.offset<t.end&&i>t.start)throw new Error(`Geometry attribute "${e.name}" overlaps attribute "${t.name}" in the interleaved layout.`);a.push({name:e.name,start:e.offset,end:i})}const l=(e=>{const t=e.find(e=>Cu.has(e.name));if(t)return t;const i=e.find(e=>e.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Geometry requires a position attribute named `a_position` or `position`.")})(t);if(l.size<2)throw new Error(`Geometry position attribute "${l.name}" must declare at least 2 components.`);const u=Pu(i,n);if(null!==r)for(let e=0;e<r.length;e++){const t=r[e];if(t>=u)throw new Error(`Geometry index ${t} at position ${e} is out of range for vertex count ${u}.`)}this.attributes=(e=>e.map(e=>({...e})))(t),this.vertexData=i,this.stride=n,this.indices=r,this.topology=s,this.usage=o,this._positionAttribute={...l}}get vertexCount(){return Pu(this.vertexData,this.stride)}get indexCount(){return this.indices?.length??this.vertexCount}get version(){return this._version}get id(){return(e=>{const t=Tu.get(e);if(void 0!==t)return t;const i=Mu++;return Tu.set(e,i),i})(this)}invalidate(){return this._version++,this._localBoundsDirty=!0,this}getLocalBounds(e=this._localBounds){return this._localBoundsDirty&&this.recomputeLocalBounds(),e===this._localBounds?this._localBounds:e.copy(this._localBounds)}recomputeLocalBounds(){const e=this.vertexCount;if(0===e)return this._localBounds.set(0,0,0,0),this._localBoundsDirty=!1,this;const t=this.vertexData instanceof Float32Array?new DataView(this.vertexData.buffer,this.vertexData.byteOffset,this.vertexData.byteLength):new DataView(this.vertexData),i=bu[this._positionAttribute.type];let n=1/0,r=1/0,s=-1/0,o=-1/0;for(let a=0;a<e;a++){const e=a*this.stride+this._positionAttribute.offset,h=Au(t,this._positionAttribute.type,e,this._positionAttribute.normalized),l=Au(t,this._positionAttribute.type,e+i,this._positionAttribute.normalized);h<n&&(n=h),h>s&&(s=h),l<r&&(r=l),l>o&&(o=l)}return this._localBounds.set(n,r,s-n,o-r),this._localBoundsDirty=!1,this}destroy(){for(const e of this._disposeCallbacks)e();this._disposeCallbacks.clear()}_onDispose(e){this._disposeCallbacks.add(e)}},e.GlyphAtlas=Or,e.Gradient=ku,e.Graphics=Mh,e.HTMLText=nc,e.HighpassFilter=class extends ee{_node=null;_frequency;_resonance;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(e={}){super(),this._frequency=e.frequency??1e3,this._resonance=e.resonance??1,U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._node)throw new Error("HighpassFilter not yet initialized.");return this._node}get outputNode(){if(!this._node)throw new Error("HighpassFilter not yet initialized.");return this._node}get frequency(){return this._frequency}set frequency(e){this._frequency=Math.max(20,Math.min(2e4,e)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(e){this._resonance=Math.max(1e-4,e),this._node&&this._node.Q.setTargetAtTime(this._resonance,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(e){const t=e.createBiquadFilter();t.type="highpass",t.frequency.setValueAtTime(this._frequency,e.currentTime),t.Q.setValueAtTime(this._resonance,e.currentTime),this._node=t}},e.ImageAsset=ra,e.ImageFactory=Io,e.IndexedDbDatabase=sc,e.IndexedDbKeyValueStore=class{_storeName;_store;constructor(e="exojs-kv-store"){const t="string"==typeof e?{name:e}:e,i=t.storeName??"__kv_store";this._storeName=i,this._store=new oc({name:t.name,...void 0!==t.version&&{version:t.version},...void 0!==t.migrations&&{migrations:t.migrations},storeNames:[i]})}async get(e){return await this._store.load(this._storeName,e)}async set(e,t){await this._store.save(this._storeName,e,t)}async has(e){return null!==await this._store.load(this._storeName,e)}async delete(e){return this._store.delete(this._storeName,e)}async clear(){return this._store.clear(this._storeName)}destroy(){this._store.destroy()}},e.IndexedDbStore=oc,e.InputBinding=Fi,e.InputManager=yn,e.InteractionEvent=xn,e.InteractionManager=vn,e.Interval=me,e.JoyConLeftGamepadMapping=Yi,e.JoyConRightGamepadMapping=$i,e.Json=Zo,e.JsonFactory=class extends To{storageName="json";async process(e){return e.json()}async create(e){return e}},e.KeyEvent=Ci,e.Label=il,e.Line=su,e.LinearGradient=Du,e.Loader=Va,e.LoadingQueue=Oa,e.Logger=th,e.LowpassFilter=class extends ee{_node=null;_frequency;_resonance;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};constructor(e={}){super(),this._frequency=e.frequency??1e3,this._resonance=e.resonance??1,U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._node)throw new Error("LowpassFilter not yet initialized.");return this._node}get outputNode(){if(!this._node)throw new Error("LowpassFilter not yet initialized.");return this._node}get frequency(){return this._frequency}set frequency(e){this._frequency=Math.max(20,Math.min(2e4,e)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(e){this._resonance=Math.max(1e-4,e),this._node&&this._node.Q.setTargetAtTime(this._resonance,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(e){const t=e.createBiquadFilter();t.type="lowpass",t.frequency.setValueAtTime(this._frequency,e.currentTime),t.Q.setValueAtTime(this._resonance,e.currentTime),this._node=t}},e.LutFilter=vu,e.Material=Yu,e.MathUtils=Z,e.Matrix=At,e.MemoryStore=class{_map=new Map;get(e){return Promise.resolve(this._map.has(e)?this._map.get(e):null)}set(e,t){return this._map.set(e,t),Promise.resolve()}has(e){return Promise.resolve(this._map.has(e))}delete(e){return Promise.resolve(this._map.delete(e))}clear(){return this._map.clear(),Promise.resolve(!0)}},e.Mesh=In,e.MeshBuilder=Th,e.MeshMaterial=ec,e.MusicFactory=Uo,e.NetworkOnlyStrategy=class{async resolve(e,t){const{url:i,requestOptions:n,factory:r,options:s}=e,o=await fetch(i,n);if(!o.ok)throw new Error(`Failed to fetch "${i}" (${o.status} ${o.statusText}).`);const a=await r.process(o);return r.create(a,s)}},e.NineSliceSprite=ur,e.ObservableSize=li,e.ObservableVector=Qe,e.Panel=nl,e.PassContext=du,e.Perf=$l,e.PlayStationGamepadMapping=Xi,e.Pointer=pn,e.PolarVector=ou,e.Polygon=kt,e.Prefab=Xl,e.ProgressBar=rl,e.Quadtree=wn,e.RadialGradient=Fu,e.Random=Bn,e.Rectangle=et,e.RenderBatch=class{geometry;material;_transforms=[];_tints=[];_count=0;constructor(e,t=null){if("static"!==e.usage)throw new Error(`RenderBatch requires geometry with usage='static' (got '${e.usage}').`);if(null!==t&&"mesh"!==t.target)throw new Error(`RenderBatch material must target 'mesh' (got '${String(t.target)}').`);this.geometry=e,this.material=t}get count(){return this._count}add(e,t=null){let i=this._transforms[this._count];void 0===i&&(i=new At,this._transforms[this._count]=i),i.copy(e);let n=this._tints[this._count];return void 0===n&&(n=new Tt,this._tints[this._count]=n),n.copy(t??Tt.white),this._count++,this}clear(){return this._count=0,this}destroy(){for(const e of this._transforms)e.destroy();for(const e of this._tints)e.destroy();this._transforms.length=0,this._tints.length=0,this._count=0}get _instanceTransforms(){return this._transforms}get _instanceTints(){return this._tints}},e.RenderNode=Si,e.RenderNodePass=class extends _u{_node;_target;_clear;_renderOptions;_redirect;constructor(e,t){super(t),this._node=e,this._target=t?.target??null,this._clear=t?.clear??null,this._renderOptions=void 0!==t?.view?{view:t.view}:{},this._redirect=null!==this._target?new vi(e=>wi(this._node,e),{target:this._target,view:t?.view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(e){null===this._redirect?(null!==this._clear&&e.backend.clear(this._clear),e.render(this._node,this._renderOptions)):e.backend.execute(this._redirect)}},e.RenderPass=_u,e.RenderPipeline=fu,e.RenderTarget=di,e.RenderTexture=_i,e.RenderingContext=Zs,e.RepeatingSprite=wr,e.SERIALIZATION_VERSION=1,e.Sampler=class{_context;_sampler;_scaleMode;_wrapMode;constructor(e,t){const{scaleMode:i,wrapMode:n}=t;this._context=e,this._sampler=e.createSampler(),this._scaleMode=i,this._wrapMode=n,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(e){this.setScaleMode(e)}get wrapMode(){return this._wrapMode}set wrapMode(e){this.setWrapMode(e)}setScaleMode(e){return this._scaleMode!==e&&(this._scaleMode=e,this.updateScaleModeParameters()),this}setWrapMode(e){return this._wrapMode!==e&&(this._wrapMode=e,this.updateWrapModeParameters()),this}bind(e){return this._context.bindSampler(e,this._sampler),this}destroy(){this._context.deleteSampler(this._sampler)}updateScaleModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const e=this._context;e.samplerParameteri(this._sampler,e.TEXTURE_MAG_FILTER,this._scaleMode),e.samplerParameteri(this._sampler,e.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const e=this._context;e.samplerParameteri(this._sampler,e.TEXTURE_WRAP_S,this._wrapMode),e.samplerParameteri(this._sampler,e.TEXTURE_WRAP_T,this._wrapMode)}},e.Scene=El,e.SceneManager=Rl,e.SceneNode=Lt,e.ScrollContainer=class extends el{content;_direction;_scrollX=0;_scrollY=0;_onWheel=e=>{const t=this._stage?.app?.input.getPrimaryPointerPosition();if(null==t)return;this.getBounds().contains(t.x,t.y)&&this.scrollBy("vertical"!==this._direction?e.x:0,"horizontal"!==this._direction?e.y:0)};constructor(e){super(),this._direction=e.direction??"vertical",this.content=new Bi,this.clip=!0,this.interactive=!0,this.addChild(this.content),this.setSize(e.width,e.height)}get scrollX(){return this._scrollX}get scrollY(){return this._scrollY}scrollBy(e,t){this.scrollTo(this._scrollX+e,this._scrollY+t)}scrollTo(e,t){const i=this.content.getBounds(),n=Math.max(0,i.width-this._uiWidth),r=Math.max(0,i.height-this._uiHeight);this._scrollX=Math.max(0,Math.min(e,n)),this._scrollY=Math.max(0,Math.min(t,r)),this.content.setPosition(-this._scrollX,-this._scrollY)}_relayout(){this.scrollTo(this._scrollX,this._scrollY)}_setStage(e){const t=this._stage?.app,i=e?.app;super._setStage(e),t!==i&&(t?.input.onMouseWheel.remove(this._onWheel),i?.input.onMouseWheel.add(this._onWheel))}destroy(){this._stage?.app?.input.onMouseWheel.remove(this._onWheel),super.destroy()}},e.Segment=hu,e.SerializationRegistry=yl,e.Shader=Yr,e.ShaderAttribute=Qr,e.ShaderSource=Xu,e.ShaderUniform=Zr,e.Signal=x,e.Size=l,e.Sound=lt,e.SoundFactory=Go,e.Sprite=vr,e.SpriteMaterial=tc,e.Spritesheet=class{texture;frames=new Map;sprites=new Map;animations=new Map;constructor(e,t){this.texture=e,this.parse(t)}parse(e,t=!1){t||this.clear();for(const[t,i]of Object.entries(e.frames))this.addFrame(t,i);if(e.animations)for(const[t,i]of Object.entries(e.animations))this.defineAnimation(t,i)}addFrame(e,t){const{x:i,y:n,w:r,h:s}=t.frame,o=new et(i,n,r,s),a=new vr(this.texture);a.setTextureFrame(o),this.frames.set(e,o),this.sprites.set(e,a)}defineAnimation(e,t){if(0===e.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(0===t.length)throw new Error(`Spritesheet animation "${e}" must reference at least one frame.`);for(const i of t)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${e}" references missing frame "${i}".`);return this.animations.set(e,[...t]),this}getFrame(e){const t=this.frames.get(e);if(!t)throw new Error(`Spritesheet frame named ${e} is not available!`);return t}getAnimationFrameNames(e){const t=this.animations.get(e);if(!t)throw new Error(`Spritesheet animation named ${e} is not available!`);return t}getFrameSprite(e){const t=this.sprites.get(e);if(!t)throw new Error(`Spritesheet frame named ${e} is not available!`);return t}clear(){for(const e of this.frames.values())e.destroy();this.frames.clear();for(const e of this.sprites.values())e.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}},e.Stack=sl,e.SteamControllerGamepadMapping=Hi,e.SteamDeckGamepadMapping=ji,e.SubtitleAsset=ta,e.SubtitleFactory=Yo,e.SvgAsset=ea,e.SvgFactory=$o,e.Sweep=cu,e.SwitchProGamepadMapping=Ki,e.SystemRegistry=Ml,e.Text=Wr,e.TextAsset=Jo,e.TextFactory=class extends To{storageName="text";async process(e){return e.text()}async create(e){return e}},e.TextStyle=Mr,e.Texture=pi,e.TextureFactory=Xo,e.TextureRegion=Wn,e.Time=ki,e.Timer=Di,e.Tooltip=class{_target;_offsetX;_offsetY;_delayMs;_background;_textColor;_padding;_fontSize;_text;_node=null;_timer=null;_onPointerOver=e=>{this._scheduleShow(e.worldX,e.worldY)};_onPointerOut=()=>{this._hide()};constructor(e,t){this._target=e,this._text=t.text,this._offsetX=t.offsetX??12,this._offsetY=t.offsetY??-28,this._delayMs=1e3*(t.delay??.3),this._background=t.background??2236962,this._textColor=t.textColor??16777215,this._padding=t.padding??6,this._fontSize=t.fontSize??12,e.onPointerOver.add(this._onPointerOver),e.onPointerOut.add(this._onPointerOut)}destroy(){this._hide(),this._target.onPointerOver.remove(this._onPointerOver),this._target.onPointerOut.remove(this._onPointerOut)}_scheduleShow(e,t){this._cancelTimer(),this._timer=setTimeout(()=>{this._show(e,t)},this._delayMs)}_show(e,t){this._removeNode();const i=this._findUIRoot();if(null===i)return;const n=e=>new Tt(e>>16&255,e>>8&255,255&e,1),r=new Wr(this._text,{fillColor:n(this._textColor),fontSize:this._fontSize}),s=r.getLocalBounds(),o=s.width+2*this._padding,a=s.height+2*this._padding,h=new Mh;h.fillColor=n(this._background),h.drawRoundedRectangle(0,0,o,a,4),r.setPosition(this._padding,this._padding);const l=new Bi;l.addChild(h),l.addChild(r),l.setPosition(e+this._offsetX,t+this._offsetY),this._node=l,i.addChild(l)}_hide(){this._cancelTimer(),this._removeNode()}_removeNode(){if(null!==this._node){const e=this._node.parent;null!==e&&e.removeChild(this._node),this._node=null}}_cancelTimer(){null!==this._timer&&(clearTimeout(this._timer),this._timer=null)}_findUIRoot(){let e=this._target.parent;for(;null!==e;){if(e instanceof nh)return e;e=e.parent}return null}},e.Tween=s,e.TweenManager=a,e.TweenSequencer=o,e.UIRoot=nh,e.Vector=it,e.Video=Co,e.VideoFactory=jo,e.View=ci,e.WasmAsset=aa,e.WasmFactory=Ko,e.WebGl2ShaderFilter=gu,e.WebGpuShaderFilter=xu,e.WebStorageStore=class{_storage;_prefix;constructor(e,t={}){this._storage=e,this._prefix=t.prefix??""}get(e){const t=this._storage.getItem(this._prefix+e);if(null===t)return Promise.resolve(null);try{return Promise.resolve(JSON.parse(t))}catch{return Promise.reject(new Error(`WebStorageStore.get() failed: stored value for key "${e}" is not valid JSON.`))}}set(e,t){let i;try{i=JSON.stringify(t)}catch{return Promise.reject(new Error("WebStorageStore.set() failed: value is not JSON-serializable."))}return this._storage.setItem(this._prefix+e,i),Promise.resolve()}has(e){return Promise.resolve(null!==this._storage.getItem(this._prefix+e))}delete(e){const t=this._prefix+e,i=null!==this._storage.getItem(t);return this._storage.removeItem(t),Promise.resolve(i)}clear(){if(""===this._prefix)return this._storage.clear(),Promise.resolve(!0);const e=[];for(let t=0;t<this._storage.length;t++){const i=this._storage.key(t);!0===i?.startsWith(this._prefix)&&e.push(i)}for(const t of e)this._storage.removeItem(t);return Promise.resolve(!0)}},e.Widget=el,e.WorkletEffect=class extends ee{_inputGain=null;_outputGain=null;_dryGain=null;_wetGain=null;_dryDelay=null;_workletNode=null;_ready=null;_wet=1;_onAudioContextReady=e=>{I.remove(this._onAudioContextReady),this._setup(e)};get _workletOptions(){return{numberOfInputs:1,numberOfOutputs:1}}get _dryLatencySeconds(){return 0}get _wetMakeupGain(){return 1}get _sampleRate(){return this._outputGain?.context.sampleRate??48e3}constructor(){super(),U()?this._setup(L()):I.add(this._onAudioContextReady)}get inputNode(){if(!this._inputGain)throw new Error(`${this.constructor.name}: input node accessed before audio context is ready.`);return this._inputGain}get outputNode(){if(!this._outputGain)throw new Error(`${this.constructor.name}: output node accessed before audio context is ready.`);return this._outputGain}get wet(){return this._wet}set wet(e){if(this._wet=Math.max(0,Math.min(1,e)),this._dryGain&&this._wetGain){const e=this._wetGain.context;this._dryGain.gain.setTargetAtTime(1-this._wet,e.currentTime,.01),this._wetGain.gain.setTargetAtTime(this._wet*this._wetMakeupGain,e.currentTime,.01)}}get ready(){return this._ready??Promise.resolve()}destroy(){I.remove(this._onAudioContextReady),this._workletNode?.disconnect(),this._inputGain?.disconnect(),this._outputGain?.disconnect(),this._dryGain?.disconnect(),this._wetGain?.disconnect(),this._dryDelay?.disconnect(),this._workletNode=null,this._inputGain=null,this._outputGain=null,this._dryGain=null,this._wetGain=null,this._dryDelay=null,this._ready=null}_setAudioParam(e,t){if(!this._workletNode)return;const i=this._workletNode.parameters.get(e);i&&i.setTargetAtTime(t,this._workletNode.context.currentTime,.01)}_setup(e){const t=e.createGain(),i=e.createGain(),n=e.createGain(),r=e.createGain();this._inputGain=t,this._outputGain=i,t.connect(n),n.connect(i),n.gain.setValueAtTime(1,e.currentTime),r.gain.setValueAtTime(0,e.currentTime),r.connect(i),this._dryGain=n,this._wetGain=r,this._ready=wt(e,this._workletName,this._workletSource).then(()=>{if(!this._inputGain||!this._dryGain||!this._wetGain)return;const t=this._dryLatencySeconds;if(t>0){const i=e.createDelay(Math.max(1,2*t));i.delayTime.setValueAtTime(t,e.currentTime),this._dryDelay=i,this._inputGain.disconnect(this._dryGain),this._inputGain.connect(i),i.connect(this._dryGain)}const i=new AudioWorkletNode(e,this._workletName,this._workletOptions);this._workletNode=i,this._inputGain.connect(i),i.connect(this._wetGain),this.wet=this._wet,this._onWorkletReady?.(e)})}},e.XboxGamepadMapping=Qi,e.XmlAsset=ia,e.XmlFactory=Qo,e.buildInfo=ql,e.createRenderStats=Ks,e.crossFade=async function(e,t,i,n={}){const r=Y(n.toVolume??1,0,1),s=n.stopAfter??!0;return t.fade(r,i),s?e.stop(i):e.fade(0,i),new Promise(e=>{setTimeout(e,Math.max(0,i))})},e.decodeAudioData=G,e.defineAssetManifest=ka,e.getAudioContext=L,e.getOfflineAudioContext=()=>E(),e.isAdvancedBlendMode=Gt,e.isAudioContextReady=U,e.logger=ih,e.maxPointers=16,e.onAudioContextReady=I,e.pointerSlotSize=16,e.registerAudioWorkletProcessor=wt,e.registerSerializer=function(e,t,i,n=wl){n.register(e,t,i)},e.resetRenderStats=Qs,e}({});
2
2
  //# sourceMappingURL=exo.iife.min.js.map