@codexo/exojs 0.14.0 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +183 -0
- package/README.md +2 -4
- package/dist/esm/animation/Tween.d.ts.map +1 -1
- package/dist/esm/animation/Tween.js +0 -1
- package/dist/esm/animation/Tween.js.map +1 -1
- package/dist/esm/animation/TweenManager.d.ts +44 -5
- package/dist/esm/animation/TweenManager.d.ts.map +1 -1
- package/dist/esm/animation/TweenManager.js +57 -5
- package/dist/esm/animation/TweenManager.js.map +1 -1
- package/dist/esm/animation/TweenSequencer.d.ts +139 -0
- package/dist/esm/animation/TweenSequencer.d.ts.map +1 -0
- package/dist/esm/animation/TweenSequencer.js +305 -0
- package/dist/esm/animation/TweenSequencer.js.map +1 -0
- package/dist/esm/animation/index.d.ts +1 -0
- package/dist/esm/animation/index.d.ts.map +1 -1
- package/dist/esm/audio/Playable.d.ts +6 -1
- package/dist/esm/audio/Playable.d.ts.map +1 -1
- package/dist/esm/audio/WorkletEffect.d.ts +34 -20
- package/dist/esm/audio/WorkletEffect.d.ts.map +1 -1
- package/dist/esm/audio/WorkletEffect.js +92 -25
- package/dist/esm/audio/WorkletEffect.js.map +1 -1
- package/dist/esm/core/Application.d.ts +43 -5
- package/dist/esm/core/Application.d.ts.map +1 -1
- package/dist/esm/core/Application.js +83 -9
- package/dist/esm/core/Application.js.map +1 -1
- package/dist/esm/core/BuildInfo.js +2 -2
- package/dist/esm/core/Codec.d.ts +41 -0
- package/dist/esm/core/Codec.d.ts.map +1 -0
- package/dist/esm/core/Codec.js +79 -0
- package/dist/esm/core/Codec.js.map +1 -0
- package/dist/esm/core/FixedTimestep.d.ts +28 -0
- package/dist/esm/core/FixedTimestep.d.ts.map +1 -0
- package/dist/esm/core/FixedTimestep.js +62 -0
- package/dist/esm/core/FixedTimestep.js.map +1 -0
- package/dist/esm/core/Scene.d.ts +14 -0
- package/dist/esm/core/Scene.d.ts.map +1 -1
- package/dist/esm/core/Scene.js +18 -0
- package/dist/esm/core/Scene.js.map +1 -1
- package/dist/esm/core/SceneManager.d.ts +7 -0
- package/dist/esm/core/SceneManager.d.ts.map +1 -1
- package/dist/esm/core/SceneManager.js +20 -4
- package/dist/esm/core/SceneManager.js.map +1 -1
- package/dist/esm/core/SceneNode.d.ts +46 -7
- package/dist/esm/core/SceneNode.d.ts.map +1 -1
- package/dist/esm/core/SceneNode.js +73 -12
- package/dist/esm/core/SceneNode.js.map +1 -1
- package/dist/esm/core/Stage.d.ts +7 -0
- package/dist/esm/core/Stage.d.ts.map +1 -1
- package/dist/esm/core/SystemRegistry.d.ts +5 -0
- package/dist/esm/core/SystemRegistry.d.ts.map +1 -1
- package/dist/esm/core/SystemRegistry.js +10 -0
- package/dist/esm/core/SystemRegistry.js.map +1 -1
- package/dist/esm/core/index.d.ts +4 -0
- package/dist/esm/core/index.d.ts.map +1 -1
- package/dist/esm/core/logging.d.ts +34 -0
- package/dist/esm/core/logging.d.ts.map +1 -0
- package/dist/esm/core/logging.js +59 -0
- package/dist/esm/core/logging.js.map +1 -0
- package/dist/esm/core/serialization/commonFields.d.ts.map +1 -1
- package/dist/esm/core/serialization/commonFields.js +6 -0
- package/dist/esm/core/serialization/commonFields.js.map +1 -1
- package/dist/esm/core/serialization/renderingSerializers.d.ts.map +1 -1
- package/dist/esm/core/serialization/renderingSerializers.js +14 -5
- package/dist/esm/core/serialization/renderingSerializers.js.map +1 -1
- package/dist/esm/debug/BoundingBoxesLayer.d.ts.map +1 -1
- package/dist/esm/debug/BoundingBoxesLayer.js +2 -1
- package/dist/esm/debug/BoundingBoxesLayer.js.map +1 -1
- package/dist/esm/debug/HitTestLayer.js +4 -4
- package/dist/esm/debug/HitTestLayer.js.map +1 -1
- package/dist/esm/debug/PerformanceLayer.js +1 -1
- package/dist/esm/debug/PerformanceLayer.js.map +1 -1
- package/dist/esm/debug/RenderPassInspectorLayer.js +2 -2
- package/dist/esm/debug/RenderPassInspectorLayer.js.map +1 -1
- package/dist/esm/index.js +7 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/input/Gamepad.d.ts +10 -0
- package/dist/esm/input/Gamepad.d.ts.map +1 -1
- package/dist/esm/input/Gamepad.js +12 -0
- package/dist/esm/input/Gamepad.js.map +1 -1
- package/dist/esm/input/InputManager.d.ts.map +1 -1
- package/dist/esm/input/InputManager.js +5 -0
- package/dist/esm/input/InputManager.js.map +1 -1
- package/dist/esm/input/InteractionManager.js +4 -4
- package/dist/esm/input/InteractionManager.js.map +1 -1
- package/dist/esm/math/AbstractVector.d.ts +4 -3
- package/dist/esm/math/AbstractVector.d.ts.map +1 -1
- package/dist/esm/math/AbstractVector.js +5 -4
- package/dist/esm/math/AbstractVector.js.map +1 -1
- package/dist/esm/math/ObservableVector.d.ts +2 -0
- package/dist/esm/math/ObservableVector.d.ts.map +1 -1
- package/dist/esm/math/ObservableVector.js +9 -0
- package/dist/esm/math/ObservableVector.js.map +1 -1
- package/dist/esm/math/Polygon.d.ts.map +1 -1
- package/dist/esm/math/Polygon.js +4 -1
- package/dist/esm/math/Polygon.js.map +1 -1
- package/dist/esm/math/collision-detection.d.ts.map +1 -1
- package/dist/esm/math/collision-detection.js +14 -14
- package/dist/esm/math/collision-detection.js.map +1 -1
- package/dist/esm/math/collision-primitives.d.ts +1 -1
- package/dist/esm/math/collision-primitives.d.ts.map +1 -1
- package/dist/esm/math/collision-primitives.js +4 -1
- package/dist/esm/math/collision-primitives.js.map +1 -1
- package/dist/esm/rendering/BackendTargetPass.d.ts +1 -1
- package/dist/esm/rendering/BackendTargetPass.d.ts.map +1 -1
- package/dist/esm/rendering/CallbackRenderPass.d.ts +14 -10
- package/dist/esm/rendering/CallbackRenderPass.d.ts.map +1 -1
- package/dist/esm/rendering/CallbackRenderPass.js +16 -11
- package/dist/esm/rendering/CallbackRenderPass.js.map +1 -1
- package/dist/esm/rendering/DrawContext.d.ts +48 -0
- package/dist/esm/rendering/DrawContext.d.ts.map +1 -0
- package/dist/esm/rendering/PassContext.d.ts +42 -0
- package/dist/esm/rendering/PassContext.d.ts.map +1 -0
- package/dist/esm/rendering/PassContext.js +48 -0
- package/dist/esm/rendering/PassContext.js.map +1 -0
- package/dist/esm/rendering/RenderBackend.d.ts +14 -0
- package/dist/esm/rendering/RenderBackend.d.ts.map +1 -1
- package/dist/esm/rendering/RenderNode.d.ts.map +1 -1
- package/dist/esm/rendering/RenderNode.js +2 -2
- package/dist/esm/rendering/RenderNode.js.map +1 -1
- package/dist/esm/rendering/RenderNodePass.d.ts +1 -1
- package/dist/esm/rendering/RenderNodePass.d.ts.map +1 -1
- package/dist/esm/rendering/RenderingContext.d.ts +47 -16
- package/dist/esm/rendering/RenderingContext.d.ts.map +1 -1
- package/dist/esm/rendering/RenderingContext.js +134 -36
- package/dist/esm/rendering/RenderingContext.js.map +1 -1
- package/dist/esm/rendering/TransformBuffer.d.ts +23 -0
- package/dist/esm/rendering/TransformBuffer.d.ts.map +1 -1
- package/dist/esm/rendering/TransformBuffer.js +58 -0
- package/dist/esm/rendering/TransformBuffer.js.map +1 -1
- package/dist/esm/rendering/View.d.ts +38 -0
- package/dist/esm/rendering/View.d.ts.map +1 -1
- package/dist/esm/rendering/View.js +37 -0
- package/dist/esm/rendering/View.js.map +1 -1
- package/dist/esm/rendering/filters/WebGpuShaderFilter.d.ts.map +1 -1
- package/dist/esm/rendering/filters/WebGpuShaderFilter.js +9 -2
- package/dist/esm/rendering/filters/WebGpuShaderFilter.js.map +1 -1
- package/dist/esm/rendering/material/MeshMaterial.d.ts +20 -1
- package/dist/esm/rendering/material/MeshMaterial.d.ts.map +1 -1
- package/dist/esm/rendering/material/MeshMaterial.js +17 -0
- package/dist/esm/rendering/material/MeshMaterial.js.map +1 -1
- package/dist/esm/rendering/material/SpriteMaterial.d.ts +20 -1
- package/dist/esm/rendering/material/SpriteMaterial.d.ts.map +1 -1
- package/dist/esm/rendering/material/SpriteMaterial.js +17 -0
- package/dist/esm/rendering/material/SpriteMaterial.js.map +1 -1
- package/dist/esm/rendering/plan/RenderEffectExecutor.d.ts.map +1 -1
- package/dist/esm/rendering/plan/RenderEffectExecutor.js +7 -2
- package/dist/esm/rendering/plan/RenderEffectExecutor.js.map +1 -1
- package/dist/esm/rendering/plan/RenderInstruction.d.ts +5 -2
- package/dist/esm/rendering/plan/RenderInstruction.d.ts.map +1 -1
- package/dist/esm/rendering/plan/RenderPlanBuilder.d.ts.map +1 -1
- package/dist/esm/rendering/plan/RenderPlanBuilder.js +23 -5
- package/dist/esm/rendering/plan/RenderPlanBuilder.js.map +1 -1
- package/dist/esm/rendering/plan/RenderScope.d.ts +7 -0
- package/dist/esm/rendering/plan/RenderScope.d.ts.map +1 -1
- package/dist/esm/rendering/primitives/Graphics.d.ts +17 -1
- package/dist/esm/rendering/primitives/Graphics.d.ts.map +1 -1
- package/dist/esm/rendering/primitives/Graphics.js +50 -15
- package/dist/esm/rendering/primitives/Graphics.js.map +1 -1
- package/dist/esm/rendering/public.d.ts +5 -5
- package/dist/esm/rendering/public.d.ts.map +1 -1
- package/dist/esm/rendering/sprite/AnimatedSprite.d.ts +57 -19
- package/dist/esm/rendering/sprite/AnimatedSprite.d.ts.map +1 -1
- package/dist/esm/rendering/sprite/AnimatedSprite.js +138 -31
- package/dist/esm/rendering/sprite/AnimatedSprite.js.map +1 -1
- package/dist/esm/rendering/sprite/Sprite.d.ts.map +1 -1
- package/dist/esm/rendering/sprite/Sprite.js +8 -0
- package/dist/esm/rendering/sprite/Sprite.js.map +1 -1
- package/dist/esm/rendering/text/BitmapText.d.ts.map +1 -1
- package/dist/esm/rendering/text/BitmapText.js +2 -0
- package/dist/esm/rendering/text/BitmapText.js.map +1 -1
- package/dist/esm/rendering/text/HTMLText.d.ts.map +1 -1
- package/dist/esm/rendering/text/HTMLText.js +2 -2
- package/dist/esm/rendering/text/HTMLText.js.map +1 -1
- package/dist/esm/rendering/text/Text.d.ts.map +1 -1
- package/dist/esm/rendering/text/Text.js +2 -0
- package/dist/esm/rendering/text/Text.js.map +1 -1
- package/dist/esm/rendering/text/TextLayout.d.ts.map +1 -1
- package/dist/esm/rendering/text/TextLayout.js +2 -3
- package/dist/esm/rendering/text/TextLayout.js.map +1 -1
- package/dist/esm/rendering/types.d.ts +37 -13
- package/dist/esm/rendering/types.d.ts.map +1 -1
- package/dist/esm/rendering/types.js +37 -13
- package/dist/esm/rendering/types.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2BackdropBlendCompositor.d.ts +41 -0
- package/dist/esm/rendering/webgl2/WebGl2BackdropBlendCompositor.d.ts.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2BackdropBlendCompositor.js +222 -0
- package/dist/esm/rendering/webgl2/WebGl2BackdropBlendCompositor.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2Backend.d.ts +34 -1
- package/dist/esm/rendering/webgl2/WebGl2Backend.d.ts.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2Backend.js +108 -60
- package/dist/esm/rendering/webgl2/WebGl2Backend.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2TextRenderer.d.ts.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2TextRenderer.js +50 -11
- package/dist/esm/rendering/webgl2/WebGl2TextRenderer.js.map +1 -1
- package/dist/esm/rendering/webgl2/glsl/backdrop-blend.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/backdrop-blend.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/backdrop-blend.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/backdrop-blend.vert.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/text.vert.js +1 -1
- package/dist/esm/rendering/webgpu/WebGpuBackdropBlendCompositor.d.ts +72 -0
- package/dist/esm/rendering/webgpu/WebGpuBackdropBlendCompositor.d.ts.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuBackdropBlendCompositor.js +494 -0
- package/dist/esm/rendering/webgpu/WebGpuBackdropBlendCompositor.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuBackend.d.ts +27 -0
- package/dist/esm/rendering/webgpu/WebGpuBackend.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuBackend.js +157 -60
- package/dist/esm/rendering/webgpu/WebGpuBackend.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuBlendState.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuBlendState.js +5 -29
- package/dist/esm/rendering/webgpu/WebGpuBlendState.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.d.ts +2 -0
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.js +2 -1
- package/dist/esm/rendering/webgpu/WebGpuMaskCompositor.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuMeshRenderer.d.ts +4 -0
- package/dist/esm/rendering/webgpu/WebGpuMeshRenderer.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuMeshRenderer.js +3 -1
- package/dist/esm/rendering/webgpu/WebGpuMeshRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuNineSliceSpriteRenderer.d.ts +2 -0
- package/dist/esm/rendering/webgpu/WebGpuNineSliceSpriteRenderer.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuNineSliceSpriteRenderer.js +2 -1
- package/dist/esm/rendering/webgpu/WebGpuNineSliceSpriteRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuPassCoordinator.d.ts +8 -0
- package/dist/esm/rendering/webgpu/WebGpuPassCoordinator.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuPassCoordinator.js +20 -0
- package/dist/esm/rendering/webgpu/WebGpuPassCoordinator.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuRepeatingSpriteRenderer.d.ts +6 -0
- package/dist/esm/rendering/webgpu/WebGpuRepeatingSpriteRenderer.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuRepeatingSpriteRenderer.js +4 -1
- package/dist/esm/rendering/webgpu/WebGpuRepeatingSpriteRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.d.ts +2 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js +2 -1
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuStencilClipper.d.ts +2 -0
- package/dist/esm/rendering/webgpu/WebGpuStencilClipper.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuStencilClipper.js +2 -1
- package/dist/esm/rendering/webgpu/WebGpuStencilClipper.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuTextRenderer.d.ts +2 -0
- package/dist/esm/rendering/webgpu/WebGpuTextRenderer.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuTextRenderer.js +3 -2
- package/dist/esm/rendering/webgpu/WebGpuTextRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuTransformStorage.d.ts +3 -1
- package/dist/esm/rendering/webgpu/WebGpuTransformStorage.d.ts.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuTransformStorage.js +29 -5
- package/dist/esm/rendering/webgpu/WebGpuTransformStorage.js.map +1 -1
- package/dist/esm/resources/Loader.d.ts +13 -0
- package/dist/esm/resources/Loader.d.ts.map +1 -1
- package/dist/esm/resources/Loader.js +67 -7
- package/dist/esm/resources/Loader.js.map +1 -1
- package/dist/esm/resources/coreAssetBindings.d.ts +11 -0
- package/dist/esm/resources/coreAssetBindings.d.ts.map +1 -1
- package/dist/esm/resources/coreAssetBindings.js +10 -2
- package/dist/esm/resources/coreAssetBindings.js.map +1 -1
- package/dist/esm/ui/ScrollContainer.d.ts +63 -0
- package/dist/esm/ui/ScrollContainer.d.ts.map +1 -0
- package/dist/esm/ui/ScrollContainer.js +99 -0
- package/dist/esm/ui/ScrollContainer.js.map +1 -0
- package/dist/esm/ui/Tooltip.d.ts +67 -0
- package/dist/esm/ui/Tooltip.d.ts.map +1 -0
- package/dist/esm/ui/Tooltip.js +133 -0
- package/dist/esm/ui/Tooltip.js.map +1 -0
- package/dist/esm/ui/index.d.ts +4 -0
- package/dist/esm/ui/index.d.ts.map +1 -1
- package/dist/exo.debug.esm.js +1 -1
- package/dist/exo.debug.esm.js.map +1 -1
- package/dist/exo.esm.js +1 -1
- package/dist/exo.esm.js.map +1 -1
- package/dist/exo.iife.js +45273 -0
- package/dist/exo.iife.js.map +1 -0
- package/dist/exo.iife.min.js +2 -0
- package/dist/exo.iife.min.js.map +1 -0
- package/package.json +15 -3
- package/dist/esm/rendering/Camera.d.ts +0 -34
- package/dist/esm/rendering/Camera.d.ts.map +0 -1
- package/dist/esm/rendering/Camera.js +0 -38
- package/dist/esm/rendering/Camera.js.map +0 -1
package/dist/exo.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const t=t=>{const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375};class e{static linear=t=>t;static quadIn=t=>t*t;static quadOut=t=>t*(2-t);static quadInOut=t=>t<.5?2*t*t:(4-2*t)*t-1;static cubicIn=t=>t*t*t;static cubicOut=t=>--t*t*t+1;static cubicInOut=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;static quartIn=t=>t*t*t*t;static quartOut=t=>1- --t*t*t*t;static quartInOut=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;static quintIn=t=>t*t*t*t*t;static quintOut=t=>1+--t*t*t*t*t;static quintInOut=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;static sineIn=t=>1-Math.cos(t*Math.PI/2);static sineOut=t=>Math.sin(t*Math.PI/2);static sineInOut=t=>-(Math.cos(Math.PI*t)-1)/2;static expoIn=t=>0===t?0:Math.pow(2,10*t-10);static expoOut=t=>1===t?1:1-Math.pow(2,-10*t);static expoInOut=t=>0===t?0:1===t?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2;static circIn=t=>1-Math.sqrt(1-Math.pow(t,2));static circOut=t=>Math.sqrt(1-Math.pow(t-1,2));static circInOut=t=>t<.5?(1-Math.sqrt(1-Math.pow(2*t,2)))/2:(Math.sqrt(1-Math.pow(-2*t+2,2))+1)/2;static backIn=t=>{const e=1.70158;return 2.70158*t*t*t-e*t*t};static backOut=t=>{const e=1.70158;return 1+2.70158*Math.pow(t-1,3)+e*Math.pow(t-1,2)};static backInOut=t=>{const e=2.5949095;return t<.5?Math.pow(2*t,2)*(7.189819*t-e)/2:(Math.pow(2*t-2,2)*((e+1)*(2*t-2)+e)+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=t=>{if(0===t)return 0;if(1===t)return 1;const e=2*Math.PI/3;return-Math.pow(2,10*t-10)*Math.sin((10*t-10.75)*e)};static elasticOut=t=>{if(0===t)return 0;if(1===t)return 1;const e=2*Math.PI/3;return Math.pow(2,-10*t)*Math.sin((10*t-.75)*e)+1};static elasticInOut=t=>{if(0===t)return 0;if(1===t)return 1;const e=2*Math.PI/4.5;return t<.5?-Math.pow(2,20*t-10)*Math.sin((20*t-11.125)*e)/2:Math.pow(2,-20*t+10)*Math.sin((20*t-11.125)*e)/2+1}}var i;!function(t){t.Idle="idle",t.Active="active",t.Paused="paused",t.Complete="complete",t.Stopped="stopped"}(i||(i={}));class s{_target;_state=i.Idle;_properties={};_startValues=null;_duration=0;_delay=0;_easing=e.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(t){this._target=t}get target(){return this._target}get state(){return this._state}get progress(){if(0===this._duration)return 1;const t=Math.min(this._elapsed/this._duration,1),e=1===this._direction?t:1-t;return this._easing(e)}to(t,e){return this._properties={...t},this._duration=e,this._startValues=null,this}delay(t){return this._delay=t,this}easing(t){return this._easing=t,this}repeat(t){return this._repeatTotal=t,this}yoyo(t=!0){return this._yoyo=t,this}onStart(t){return this._onStart=t,this}onUpdate(t){return this._onUpdate=t,this}onComplete(t){return this._onComplete=t,this}onRepeat(t){return this._onRepeat=t,this}start(){return this._state=i.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===i.Active&&(this._state=i.Paused),this}resume(){return this._state===i.Paused&&(this._state=i.Active),this}stop(){return this._state!==i.Active&&this._state!==i.Paused||(this._state=i.Stopped,this._manager?.remove(this)),this}chain(t){return this._chained=t,t}_attachManager(t){this._manager=t}update(t){if(this._state===i.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 t=this._elapsed-this._duration;this._elapsed=t>0?Math.min(t,this._duration):0,t>0&&this._applyProgress()}else this._complete()}}}_captureStartValues(){const t={},e=Object.keys(this._properties);for(const i of e){const e=this._target[i];"number"==typeof e?t[String(i)]=e:console.warn(`Tween: property "${String(i)}" is not a number on target (got ${typeof e}). It will be skipped.`)}this._startValues=t}_applyProgress(){if(null===this._startValues)return;const t=0===this._duration?1:Math.min(this._elapsed/this._duration,1),e=1===this._direction?t:1-t,i=this._easing(e),s=Object.keys(this._startValues),n=this._properties;for(const t of s){const e=this._startValues[t],s=n[t];void 0!==e&&void 0!==s&&(this._target[t]=e+(s-e)*i)}this._onUpdate?.(i)}_complete(){this._elapsed=this._duration,this._applyProgress(),this._state=i.Complete,this._manager?.remove(this),this._onComplete?.(),this._chained?.start()}}class n{order=400;_tweens=[];_destroyed=!1;create(t){const e=new s(t);return e._attachManager(this),this._tweens.push(e),e}sequence(t){const[e]=t;if(void 0===e)throw new Error("[ExoJS] TweenManager.sequence() requires at least one tween.");for(let e=0;e<t.length-1;e++){const i=t[e],s=t[e+1];void 0!==i&&void 0!==s&&i.chain(s)}for(const e of t)this.add(e);return e}add(t){return t._attachManager(this),this._tweens.includes(t)||this._tweens.push(t),this}remove(t){const e=this._tweens.indexOf(t);return-1!==e&&this._tweens.splice(e,1),this}update(t){if(this._destroyed)return;const e=[...this._tweens];for(const i of e)i.update(t.seconds)}clear(){return this._tweens=[],this}destroy(){this.clear(),this._destroyed=!0}}let r=null;class o{_width;_height;constructor(t=0,e=0){this._width=t,this._height=e}get width(){return this._width}set width(t){this._width=t}get height(){return this._height}set height(t){this._height=t}set(t,e=t){return this._width=t,this._height=e,this}add(t,e=t){return this._width+=t,this._height+=e,this}subtract(t,e=t){return this._width-=t,this._height-=e,this}scale(t,e=t){return this._width*=t,this._height*=e,this}divide(t,e=t){return this._width/=t,this._height/=e,this}copy(t){return this._width=t.width,this._height=t.height,this}clone(){return new o(this._width,this._height)}equals({width:t,height:e}={}){return!(void 0!==t&&this.width!==t||void 0!==e&&this.height!==e)}destroy(){}static zero=new o(0,0);static get temp(){return null===r&&(r=new o),r}}let a=null,h=null;const l=()=>{if("undefined"==typeof document)throw new Error("Canvas operations require a document context.");return null===a&&(a=document.createElement("canvas")),a},u=t=>{t.preventDefault(),t.stopImmediatePropagation()},c="undefined"!=typeof indexedDB,d=()=>performance.now(),_=new ArrayBuffer(0),f=(t,e,i)=>{if(e<t.length&&i>0){const s=e+i>t.length?t.length-e:i,n=t.length-s;for(let i=e;i<n;i++)t[i]=t[i+s];t.length=n}return t},p=t=>{const e=t;return t instanceof HTMLImageElement?o.temp.set(t.naturalWidth,t.naturalHeight):t instanceof HTMLVideoElement?o.temp.set(t.videoWidth,t.videoHeight):t instanceof SVGElement?o.temp.copy(t.getBoundingClientRect()):"number"==typeof e.displayWidth&&"number"==typeof e.displayHeight?o.temp.set(e.displayWidth,e.displayHeight):"number"==typeof e.width&&"number"==typeof e.height?o.temp.set(e.width,e.height):o.zero},g=t=>{const{width:e,height:i}=p(t),s=l();return s.width=e,s.height=i,(()=>{if(null===h){const t=l().getContext("2d");if(!t)throw new Error("Could not create a 2D canvas context.");h=t}return h})().drawImage(t,0,0,e,i),s.toDataURL()};class m{_handlers=[];_dispatching=!1;_pendingRemoves=null;get count(){return this._handlers.length}has(t){return this._handlers.includes(t)}add(t){return this._handlers.includes(t)||this._handlers.push(t),this}once(t){const e=(...i)=>{this.remove(e),t(...i)};return this._handlers.push(e),this}remove(t){if(this._dispatching)(this._pendingRemoves??=[]).push(t);else{const e=this._handlers.indexOf(t);-1!==e&&f(this._handlers,e,1)}return this}clear(){return this._dispatching?this._pendingRemoves=[...this._handlers]:this._handlers.length=0,this}dispatch(...t){const e=this._handlers.length;if(!e)return this;this._dispatching=!0;for(let i=0;i<e&&!1!==this._handlers[i](...t);i++);if(this._dispatching=!1,null!==this._pendingRemoves){for(const t of this._pendingRemoves){const e=this._handlers.indexOf(t);-1!==e&&f(this._handlers,e,1)}this._pendingRemoves=null}return this}destroy(){this._handlers.length=0,this._pendingRemoves=null}}const y=["mousedown","touchstart","touchend","keydown"];let w=null,x=null,v=!1,b=!1,S=!1;const B=()=>"undefined"!=typeof document,C=()=>w,T=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===w&&(w=new AudioContext),w},M=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===x){const t=T();x=new OfflineAudioContext(1,2,t.sampleRate)}return x},P=()=>{const t=C();"running"!==t?.state||S||(S=!0,(()=>{if(v&&B()){for(const t of y)document.removeEventListener(t,R,!1);v=!1}})(),k.dispatch(t))},A=()=>{P()},E=()=>{const t=T();b||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",A),b=!0),P(),S||(()=>{if(!v&&B()){for(const t of y)document.addEventListener(t,R,!1);v=!0}})()},R=()=>{const t=T();"running"!==t.state?t.resume().then(()=>{P()}):P()};const k=new class extends m{add(t){return super.add(t),E(),this}once(t){return super.once(t),E(),this}},D=()=>{const t=T();return E(),t},I=()=>{const t=C();return null!==t&&"running"===t.state},L=()=>M(),U=async t=>M().decodeAudioData(t),F=2*Math.PI,G=Math.PI/180,N=180/Math.PI;var O;!function(t){t[t.left=-1]="left",t[t.middle=0]="middle",t[t.right=1]="right"}(O||(O={}));const V=t=>{const e=t%360;return e<0?e+360:e},z=t=>t*G,q=(t,e,i)=>Math.min(i,Math.max(e,t)),Y=(t,e,i)=>(1-i)*t+i*e,W=t=>0!==t&&!(t&t-1),$=(t,e,i)=>t>=Math.min(e,i)&&t<=Math.max(e,i),X=(t,e,i,s)=>{const n=t-i,r=e-s;return Math.sqrt(n*n+r*r)},j=(t,e,i,s,n,r,o,a,h=[],l=20)=>{h.push(t,e);for(let u=1;u<=l;u++){const c=u/l,d=1-c,_=d*d,f=_*d,p=c*c,g=p*c;h.push(f*t+3*_*c*i+3*d*p*n+g*o,f*e+3*_*c*s+3*d*p*r+g*a)}return h},H=(t,e,i,s,n,r,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push(Y(Y(t,i,l),Y(i,n,l),l),Y(Y(e,s,l),Y(s,r,l),l))}return o},K={tau:F,clamp:q,sign:t=>t&&(t<0?-1:1),lerp:Y,inRange:$,isPowerOfTwo:W,distance:X,trimRotation:V,degreesToRadians:z,radiansToDegrees:t=>t*N,bezierCurveTo:j,quadraticCurveTo:H};class Q{name;_parent;_volume;_muted;_pan;_effects=[];_setup=null;_scheduledStopId=null;_onAudioContextReady=t=>{k.remove(this._onAudioContextReady),this._setupAudio(t)};constructor(t,e={}){if(!t||"string"!=typeof t)throw new Error("AudioBus requires a non-empty string name.");this.name=t,this._parent=e.parent??null,this._volume=q(e.volume??1,0,2),this._muted=e.muted??!1,this._pan=q(e.pan??0,-1,1),e.effects&&this._effects.push(...e.effects),I()?this._setupAudio(D()):k.add(this._onAudioContextReady)}get parent(){return this._parent}get volume(){return this._volume}set volume(t){const e=q(t,0,2);this._volume!==e&&(this._volume=e,this._applyVolume())}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this._applyVolume())}get pan(){return this._pan}set pan(t){const e=q(t,-1,1);this._pan!==e&&(this._pan=e,this._setup&&this._setup.panNode.pan.setTargetAtTime(e,this._setup.audioContext.currentTime,.01))}get inputNode(){return this._setup?.inputNode??null}addEffect(t){return this._effects.push(t),this._rebuildEffectChain(),this}removeEffect(t){const e=this._effects.indexOf(t);return-1!==e&&(this._effects.splice(e,1),this._rebuildEffectChain()),this}fadeIn(t){if(this._clearScheduledStop(),t<=0||!this._setup)return this;const e=this._setup.audioContext,i=this._setup.outputNode,s=this._muted?0:this._volume;return i.gain.cancelScheduledValues(e.currentTime),i.gain.setValueAtTime(0,e.currentTime),i.gain.linearRampToValueAtTime(s,e.currentTime+t/1e3),this}fadeOut(t,e={}){const i=e.stopAfter??!0;if(this._clearScheduledStop(),t<=0||!this._setup)return i&&(this.muted=!0),this;const s=this._setup.audioContext,n=this._setup.outputNode;return n.gain.cancelScheduledValues(s.currentTime),n.gain.setValueAtTime(n.gain.value,s.currentTime),n.gain.linearRampToValueAtTime(0,s.currentTime+t/1e3),i&&(this._scheduledStopId=setTimeout(()=>{this._scheduledStopId=null,this.muted=!0},t)),this}destroy(){k.remove(this._onAudioContextReady),this._clearScheduledStop();for(const t of this._effects)t.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(t){const e=t.createGain(),i=t.createStereoPanner(),s=t.createGain();s.gain.setTargetAtTime(this._muted?0:this._volume,t.currentTime,.01),i.pan.setTargetAtTime(this._pan,t.currentTime,.01),this._setup={audioContext:t,inputNode:e,outputNode:s,panNode:i},this._rebuildEffectChain(),this._connectUpstream()}_connectUpstream(){if(this._setup)if(this._parent){const t=this._parent._getInputNode();t?this._setup.outputNode.connect(t):this._parent.onceSetup(()=>{if(this._setup&&this._parent){const t=this._parent._getInputNode();t&&this._setup.outputNode.connect(t)}})}else this._setup.outputNode.connect(this._setup.audioContext.destination)}onceSetup(t){this._setup?t():k.once(()=>{this._setup&&t()})}_rebuildEffectChain(){if(!this._setup)return;const{inputNode:t,panNode:e}=this._setup;t.disconnect();for(const t of this._effects)t.inputNode.disconnect(),t.outputNode.disconnect();e.disconnect();let i=t;for(const t of this._effects)i.connect(t.inputNode),i=t.outputNode;i.connect(e),e.connect(this._setup.outputNode)}_applyVolume(){if(!this._setup)return;const t=this._muted?0:this._volume;this._setup.outputNode.gain.setTargetAtTime(t,this._setup.audioContext.currentTime,.01)}_clearScheduledStop(){null!==this._scheduledStopId&&(clearTimeout(this._scheduledStopId),this._scheduledStopId=null)}}class Z{get ready(){return Promise.resolve()}}class J{get angle(){return Math.atan2(this.x,this.y)}set angle(t){const e=this.length;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(t){const e=this.angle;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(t){this.length=Math.sqrt(t)}set(t,e=t){return this.x=t,this.y=e,this}equals({x:t,y:e}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e)}add(t,e=t){return this.x+=t,this.y+=e,this}subtract(t,e=t){return this.x-=t,this.y-=e,this}multiply(t,e=t){return this.x*=t,this.y*=e,this}divide(t,e=t){return 0!==t&&0!==e&&(this.x/=t,this.y/=e),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(t){return this.set(this.x*t.a+this.y*t.b+t.x,this.x*t.c+this.y*t.d+t.y)}transformInverse(t){const e=t.a*t.d-t.b*t.c,i=this.x-t.x,s=this.y-t.y;return this.set((t.d*i-t.b*s)/e,(t.a*s-t.c*i)/e)}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(t,e){return this.x*t+this.y*e}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){return X(this.x,this.y,t.x,t.y)}}var tt;!function(t){t[t.Point=0]="Point",t[t.Line=1]="Line",t[t.Rectangle=2]="Rectangle",t[t.Circle=3]="Circle",t[t.Ellipse=4]="Ellipse",t[t.Polygon=5]="Polygon",t[t.SceneNode=6]="SceneNode"}(tt||(tt={}));const et=1e-10,it=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),st=({x:t,y:e,rx:i,ry:s})=>{if(i<=0||s<=0)return[];const n=it(i,s),r=2*Math.PI/n,o=[];for(let a=0;a<n;a++){const n=a*r;o.push({x:t+Math.cos(n)*i,y:e+Math.sin(n)*s})}return o},nt=({x:t,y:e},{x:i,y:s},{x:n,y:r})=>t<=Math.max(i,n)+et&&t>=Math.min(i,n)-et&&e<=Math.max(s,r)+et&&e>=Math.min(s,r)-et,rt=({x:t,y:e},{x:i,y:s},{x:n,y:r})=>{const o=(s-e)*(n-i)-(i-t)*(r-s);return Math.abs(o)<=et?0:o>0?1:2},ot=(t,e,i,s)=>{const n=rt(t,e,i),r=rt(t,e,s),o=rt(i,s,t),a=rt(i,s,e);return n!==r&&o!==a||(!(0!==n||!nt(i,t,e))||(!(0!==r||!nt(s,t,e))||(!(0!==o||!nt(t,i,s))||!(0!==a||!nt(e,i,s)))))},at=({x:t,y:e},i)=>{const s=i.length;if(s<3)return!1;let n=!1;for(let r=0,o=s-1;r<s;o=r++){const s=i[o],a=i[r];a.y>e!=s.y>e&&t<(s.x-a.x)*((e-a.y)/(s.y-a.y))+a.x&&(n=!n)}return n},ht=(t,e)=>{if(0===t.length||0===e.length)return!1;for(let i=0;i<t.length;i++){const s=t[i],n=t[(i+1)%t.length];for(let t=0;t<e.length;t++){const i=e[t],r=e[(t+1)%e.length];if(ot(s,n,i,r))return!0}}return at(t[0],e)||at(e[0],t)},lt=({x:t,y:e},{x:i,y:s},{x:n,y:r},o=.1)=>{const a=X(t,e,i,s),h=X(t,e,n,r),l=X(i,s,n,r);return a+h>=l-o&&a+h<=l+o},ut=(t,e,i,s)=>{const n=(e.x-t.x)*(s.y-i.y)-(s.x-i.x)*(e.y-t.y);if(Math.abs(n)<=et)return!1;const r=((s.x-i.x)*(t.y-i.y)-(s.y-i.y)*(t.x-i.x))/n,o=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/n;return r>=0&&r<=1&&o>=0&&o<=1},ct=(t,e)=>Math.sqrt(t*t+e*e),dt=(t,e,i,s)=>{const n=i*t+s*e;const r=(o=t)*o+(a=e)*a;var o,a;return n<0?O.left:n>r?O.right:O.middle};let _t=null;class ft{min;max;constructor(t=0,e=t){this.min=t,this.max=e}set(t,e){return this.min=t,this.max=e,this}copy(t){return this.set(t.min,t.max)}clone(){return new ft(this.min,this.max)}containsInterval(t){return t.min>this.min&&t.max<this.max}includes(t){return t<=this.max&&t>=this.min}overlaps(t){return!(this.min>t.max||t.min>this.max)}getOverlap(t){return this.max<t.max?this.max-t.min:t.max-this.min}destroy(){}static zero=new ft(0,0);static get temp(){return null===_t&&(_t=new ft),_t}}const pt=(t,e)=>{const i=t.getNormals(),s=e.getNormals(),n=new ft,r=new ft;for(const s of i)if(t.project(s,n),e.project(s,r),!n.overlaps(r))return!1;for(const i of s)if(t.project(i,n),e.project(i,r),!n.overlaps(r))return!1;return!0},gt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:s},n=0)=>X(t,e,i,s)<=n)(t,e,i),mt=(t,e,i=.1)=>lt(t,e.fromPosition,e.toPosition,i),yt=(t,e)=>(({x:t,y:e},{x:i,y:s,width:n,height:r})=>$(t,i,i+n)&&$(e,s,s+r))(t,e),wt=(t,e)=>(({x:t,y:e},{x:i,y:s,radius:n})=>n>0&&X(t,e,i,s)<=n)(t,e),xt=(t,e)=>(({x:t,y:e},{x:i,y:s,rx:n,ry:r})=>{if(n<=0||r<=0)return!1;const o=(t-i)/n,a=(e-s)/r;return o*o+a*a<=1})(t,e),vt=(t,e)=>((t,{points:e})=>at(t,e))(t,e),bt=(t,e)=>ut(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),St=(t,e)=>{const{x:i,y:s,width:n,height:r}=e,o={x:i,y:s},a={x:i+n,y:s},h={x:i,y:s+r},l={x:i+n,y:s+r};return ut(t.fromPosition,t.toPosition,o,h)||ut(t.fromPosition,t.toPosition,a,l)||ut(t.fromPosition,t.toPosition,o,a)||ut(t.fromPosition,t.toPosition,h,l)},Bt=(t,e)=>{if(wt(t.fromPosition,e)||wt(t.toPosition,e))return!0;const{fromX:i,fromY:s,toX:n,toY:r}=t,{x:o,y:a,radius:h}=e,l=X(i,s,n,r);if(0===l)return!1;const u=((o-i)*(n-i)+(a-s)*(r-s))/(l*l),c=i+u*(n-i),d=s+u*(r-s);return!!lt({x:c,y:d},t.fromPosition,t.toPosition)&&X(c,d,o,a)<=h},Ct=(t,e)=>{const{x:i,y:s,rx:n,ry:r}=e;if(n<=0||r<=0)return!1;const o=(t.fromX-i)/n,a=(t.fromY-s)/r,h=(t.toX-i)/n-o,l=(t.toY-s)/r-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),g=(-c+f)/(2*u);return p>=0&&p<=1||g>=0&&g<=1},Tt=(t,e)=>{const{x:i,y:s,points:n}=e,r=n.length;for(let e=0;e<r;e++){const o=n[e],a=n[(e+1)%r];if(ut(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+s},{x:a.x+i,y:a.y+s}))return!0}return!1},Mt=(t,e)=>(({x:t,y:e,width:i,height:s},{x:n,y:r,width:o,height:a})=>!(n>t+i||r>e+s||t>n+o||e>r+a))(t,e),Pt=({x:t,y:e,width:i,height:s},{x:n,y:r,radius:o})=>{const a=q(n,t,t+i),h=q(r,e,e+s);return X(n,r,a,h)<=o},At=(t,e)=>ht((({x:t,y:e,width:i,height:s})=>[{x:t,y:e},{x:t+i,y:e},{x:t+i,y:e+s},{x:t,y:e+s}])(t),st(e)),Et=(t,e)=>pt(t,e),Rt=({x:t,y:e,radius:i},{x:s,y:n,radius:r})=>X(t,e,s,n)<=i+r,kt=(t,e)=>ht((({x:t,y:e,radius:i})=>{if(i<=0)return[];const s=it(i),n=2*Math.PI/s,r=[];for(let o=0;o<s;o++){const s=o*n;r.push({x:t+Math.cos(s)*i,y:e+Math.sin(s)*i})}return r})(t),st(e)),Dt=(t,e,i,s,n,r,o,a,h)=>{if(dt(a,h,n,r)!==O.left)return!1;return dt(s.x,s.y,t-i.x,e-i.y)===O.right&&ct(n,r)>o},It=(t,e,i,s,n,r,o,a,h)=>{if(dt(a,h,n,r)!==O.right)return!1;return dt(s.x,s.y,t-i.x,e-i.y)===O.left&&ct(n,r)>o},Lt=(t,e,i,s,n)=>{const r=n,o=-s,a=ct(r,o);if(0===a)return!1;const h=(t*r+e*o)/a;return h>0&&Math.abs(h)>i},Ut=({x:t,y:e,radius:i},{x:s,y:n,points:r,edges:o})=>{const a=s-t,h=n-e,l=r.length;for(let t=0;t<l;t++){const e=r[t],s=a-e.x,n=h-e.y,u=0===t?l-1:t-1,c=(t+1)%l,d=o[t];if(Dt(a,h,r[u],o[u],s,n,i,d.x,d.y))return!1;if(It(a,h,r[c],o[c],s,n,i,d.x,d.y))return!1;if(Lt(s,n,i,d.x,d.y))return!1}return!0},Ft=(t,e)=>ht(st(t),st(e)),Gt=(t,e)=>ht(st(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:s})=>({x:i+t,y:s+e})))(e)),Nt=(t,e)=>pt(t,e),Ot=(t,e)=>{if(e.left>t.right||e.top>t.bottom)return null;if(t.left>e.right||t.top>e.bottom)return null;const i=Math.min(t.right,e.right)-Math.max(t.left,e.left),s=Math.min(t.bottom,e.bottom)-Math.max(t.top,e.top),n=t.left+.5*t.width,r=t.top+.5*t.height,o=e.left+.5*e.width,a=e.top+.5*e.height;let h,l,u;i<s?(u=i,h=o<n?-1:1,l=0):(u=s,h=0,l=a<r?-1:1);const c=new te(h,l),d=new te(h*u,l*u);return{shapeA:t,shapeB:e,overlap:u,shapeAinB:e.containsRect(t),shapeBinA:t.containsRect(e),projectionN:c,projectionV:d}},Vt=(t,e)=>{const i=e.position.clone().subtract(t.x,t.y),s=i.length,n=t.radius+e.radius-s;if(n<0)return i.destroy(),null;const r=i.clone().normalize(),o=i.multiply(n);return{shapeA:t,shapeB:e,overlap:n,shapeAinB:t.radius<=e.radius&&s<=e.radius-t.radius,shapeBinA:e.radius<=t.radius&&s<=t.radius-e.radius,projectionN:r,projectionV:o}},zt=(t,e,i=!1)=>{const s=t.radius,n=Math.max(e.left,Math.min(t.x,e.right)),r=Math.max(e.top,Math.min(t.y,e.bottom)),o=t.x-n,a=t.y-r,h=o*o+a*a;if(h>s*s)return null;const l=Math.sqrt(h),u=s-l,c=e.width/2,d=e.height/2,_=Math.min(c,d),f=Math.max(c,d),p=X(t.x,t.y,e.left+c,e.top+d),g=s<=_&&p<=_-s,m=f<=s&&p<=s-f;let y,w;if(l>0)y=o/l,w=a/l;else{const i=t.x-e.left,s=e.right-t.x,n=t.y-e.top,r=e.bottom-t.y;Math.min(i,s)<Math.min(n,r)?(y=i<s?-1:1,w=0):(y=0,w=n<r?-1:1)}const x=i?-y:y,v=i?-w:w,b=t.position.clone().set(x,v),S=t.position.clone().set(x*u,v*u);return{shapeA:i?e:t,shapeB:i?t:e,overlap:u,shapeAinB:i?m:g,shapeBinA:i?g:m,projectionN:b,projectionV:S}},qt=(t,e,i=!1)=>{if(!At(e,t))return null;const s=Math.max(e.left,Math.min(t.x,e.right)),n=Math.max(e.top,Math.min(t.y,e.bottom)),r=t.x-s,o=t.y-n,a=Math.sqrt(r*r+o*o);let h,l,u;if(a>0){h=r/a,l=o/a;u=1/Math.sqrt(h*h/(t.rx*t.rx)+l*l/(t.ry*t.ry))-a}else{const i=t.x-e.left,s=e.right-t.x,n=t.y-e.top,r=e.bottom-t.y,o=Math.min(i,s),a=Math.min(n,r);o<a?(h=i<s?-1:1,l=0,u=o+t.rx):(h=0,l=n<r?-1:1,u=a+t.ry)}const c=i?-h:h,d=i?-l:l,_=t.position.clone().set(c,d),f=t.position.clone().set(c*u,d*u);return{shapeA:i?e:t,shapeB:i?t:e,overlap:u,shapeAinB:!1,shapeBinA:!1,projectionN:_,projectionV:f}},Yt=(t,e,i=!1)=>{if(!kt(e,t))return null;const s=t.x-e.x,n=t.y-e.y,r=Math.sqrt(s*s+n*n);let o,a,h;if(r>0){o=s/r,a=n/r;h=1/Math.sqrt(o*o/(t.rx*t.rx)+a*a/(t.ry*t.ry))+e.radius-r}else t.rx<=t.ry?(o=1,a=0,h=t.rx+e.radius):(o=0,a=1,h=t.ry+e.radius);const l=i?-o:o,u=i?-a:a,c=t.position.clone().set(l,u),d=t.position.clone().set(l*h,u*h);return{shapeA:i?e:t,shapeB:i?t:e,overlap:h,shapeAinB:!1,shapeBinA:!1,projectionN:c,projectionV:d}},Wt=(t,e,i=!1)=>{const s=e.radius,n=t.points,r=e.x-t.x,o=e.y-t.y,a=e.position.clone().set(0,0),h=n.length;let l=!0,u=!0,c=1/0;for(let t=0;t<h;t++){const e=n[t],i=n[(t+1)%h],d=i.x-e.x,_=i.y-e.y,f=r-e.x,p=o-e.y,g=dt(d,_,f,p),m=ct(f,p);if(m>s&&(l=!1),g===O.left){const i=n[0===t?h-1:t-1],l=e.x-i.x,d=e.y-i.y,_=r-i.x,g=o-i.y;if(dt(l,d,_,g)===O.right){if(m>s)return a.destroy(),null;const t=s-m;Math.abs(t)<Math.abs(c)&&(c=t,a.set(f,p).normalize()),u=!1}}else if(g===O.right){const e=n[(t+2)%h],l=e.x-i.x,d=e.y-i.y,_=r-i.x,f=o-i.y,p=ct(_,f);if(dt(l,d,_,f)===O.left){if(p>s)return a.destroy(),null;const t=s-p;Math.abs(t)<Math.abs(c)&&(c=t,a.set(_,f).normalize()),u=!1}}else{const t=_,e=-d,i=ct(t,e),n=0===i?0:(f*t+p*e)/i;if(n>0&&Math.abs(n)>s)return a.destroy(),null;(n>=0||s-n<2*s)&&(u=!1);const r=s-n;Math.abs(r)<Math.abs(c)&&(c=r,a.set(t,e).normalize())}}const d=a.clone().multiply(c);return{shapeA:i?e:t,shapeB:i?t:e,overlap:c,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:d}},$t=(t,e)=>{if(!Ft(t,e))return null;const i=t.x-e.x,s=t.y-e.y,n=Math.sqrt(i*i+s*s);let r,o,a;if(n>0){r=i/n,o=s/n;a=Math.sqrt((r*t.rx)**2+(o*t.ry)**2)+Math.sqrt((r*e.rx)**2+(o*e.ry)**2)-n}else t.rx<=t.ry?(r=1,o=0,a=t.rx+e.rx):(r=0,o=1,a=t.ry+e.ry);if(a<=0)return null;const h=t.position.clone().set(r,o),l=t.position.clone().set(r*a,o*a);return{shapeA:t,shapeB:e,overlap:a,shapeAinB:!1,shapeBinA:!1,projectionN:h,projectionV:l}},Xt=(t,e)=>{const i=t.getNormals(),s=e.getNormals(),n=(i[0]||s[0]).clone(),r=new ft,o=new ft;let a,h,l,u=1/0,c=!0,d=!0;for(const s of i){if(t.project(s,r),e.project(s,o),!r.overlaps(o))return n.destroy(),null;l=r.getOverlap(o),a=o.containsInterval(r),h=r.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(r.min-o.min),Math.abs(r.max-o.max))),l<u&&(u=l,n.copy(s))}for(const i of s){if(t.project(i,r),e.project(i,o),!r.overlaps(o))return n.destroy(),null;l=r.getOverlap(o),a=o.containsInterval(r),h=r.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(r.min-o.min),Math.abs(r.max-o.max))),l<u&&(u=l,n.copy(i))}const _=n.clone().multiply(u,u);return{shapeA:t,shapeB:e,overlap:u,shapeAinB:c,shapeBinA:d,projectionN:n,projectionV:_}},jt={intersects:{circleCircle:Rt,circleEllipse:kt,circlePoly:Ut,ellipseEllipse:Ft,ellipsePoly:Gt,lineCircle:Bt,lineEllipse:Ct,lineLine:bt,linePoly:Tt,lineRect:St,pointCircle:wt,pointEllipse:xt,pointLine:mt,pointPoint:gt,pointPoly:vt,pointRect:yt,polyPoly:Nt,rectCircle:Pt,rectEllipse:At,rectPoly:Et,rectRect:Mt},resolve:{circleCircle:Vt,circleRectangle:zt,ellipseCircle:Yt,ellipseEllipse:$t,ellipseRectangle:qt,polygonCircle:Wt,rectangleRectangle:Ot}};class Ht extends J{_x;_y;_owner;_channel;constructor(t,e=0,i=0,s=0){super(),this._x=i,this._y=s,this._owner=t,this._channel=e}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._owner?._onObservableChange(this._channel))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._owner?._onObservableChange(this._channel))}set angle(t){const e=this.length;this.set(Math.cos(t)*e,Math.sin(t)*e)}set length(t){const e=this.angle;this.set(Math.cos(e)*t,Math.sin(e)*t)}set(t=this._x,e=this._y){return this._x===t&&this._y===e||(this._x=t,this._y=e,this._owner?._onObservableChange(this._channel)),this}add(t,e=t){return this.set(this._x+t,this._y+e)}subtract(t,e=t){return this.set(this._x-t,this._y-e)}scale(t,e=t){return this.set(this._x*t,this._y*e)}divide(t,e=t){return 0!==t&&0!==e?this.set(this._x/t,this._y/e):this}clone(){return new Ht(this._owner,this._channel,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){this._owner=null}}let Kt=null;const Qt=new Ht(null);class Zt{collisionType=tt.Rectangle;_position;_size;_normals=null;_normalsDirty=!1;constructor(t=0,e=t,i=0,s=i){this._position=new Ht(this,0,t,e),this._size=new o(i,s)}_onObservableChange(){this._normalsDirty=!0}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get size(){return this._size}set size(t){this._size.copy(t),this._normalsDirty=!0}get width(){return this._size.width}set width(t){this._size.width=t,this._normalsDirty=!0}get height(){return this._size.height}set height(t){this._size.height=t,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(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setSize(t,e){return this._size.set(t,e),this._normalsDirty=!0,this}set(t,e,i,s){return this.setPosition(t,e),this.setSize(i,s),this}copy(t){return this.position=t.position,this.size=t.size,this}clone(){return new Zt(this.x,this.y,this.width,this.height)}equals({x:t,y:e,width:i,height:s}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.width!==i||void 0!==s&&this.height!==s)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new te,new te,new te,new te])),this._normalsDirty=!1),this._normals}project(t,e=new ft){const i=t.dot(this.left,this.top),s=t.dot(this.right,this.top),n=t.dot(this.right,this.bottom),r=t.dot(this.left,this.bottom);return e.set(Math.min(i,s,n,r),Math.max(i,s,n,r))}transform(t,e=this){const i=Qt.set(this.left,this.top).transform(t);let s=i.x,n=i.x,r=i.y,o=i.y;return i.set(this.left,this.bottom).transform(t),s=Math.min(s,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(t),s=Math.min(s,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(t),s=Math.min(s,i.x),r=Math.min(r,i.y),n=Math.max(n,i.x),o=Math.max(o,i.y),e.set(s,r,n-s,o-r)}contains(t,e){return yt(Qt.set(t,e),this)}containsRect(t){return $(t.left,this.left,this.right)&&$(t.right,this.left,this.right)&&$(t.top,this.top,this.bottom)&&$(t.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case tt.SceneNode:return t.isAlignedBox?Mt(this,t.getBounds()):pt(this,t);case tt.Rectangle:return Mt(this,t);case tt.Polygon:return Et(this,t);case tt.Circle:return Pt(this,t);case tt.Ellipse:return At(this,t);case tt.Line:return St(t,this);case tt.Point:return yt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case tt.SceneNode:return t.isAlignedBox?Ot(this,t.getBounds()):Xt(this,t);case tt.Rectangle:return Ot(this,t);case tt.Polygon:return Xt(this,t);case tt.Circle:return zt(t,this,!0);case tt.Ellipse:return qt(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(t){t[0].set(this.right-this.left,0).rperp().normalize(),t[1].set(0,this.bottom-this.top).rperp().normalize(),t[2].set(this.left-this.right,0).rperp().normalize(),t[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===Kt&&(Kt=new Zt),Kt}}let Jt=null;class te extends J{collisionType=tt.Point;x;y;constructor(t=0,e=0){super(),this.x=t,this.y=e}clone(){return new te(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(t){switch(t.collisionType){case tt.SceneNode:return yt(this,t.getBounds());case tt.Rectangle:return yt(this,t);case tt.Polygon:return vt(this,t);case tt.Circle:return wt(this,t);case tt.Ellipse:return xt(this,t);case tt.Line:return mt(this,t);case tt.Point:return gt(this,t);default:return!1}}collidesWith(t){return null}getBounds(){return Zt.temp.set(this.x,this.y,0,0)}contains(t,e){return gt(te.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new ft){return e}destroy(){}static get temp(){return null===Jt&&(Jt=new te),Jt}static zero=new te(0,0);static one=new te(1,1);static add(t,e){return new te(t.x+e.x,t.y+e.y)}static subtract(t,e){return new te(t.x-e.x,t.y-e.y)}static multiply(t,e){return new te(t.x*e.x,t.y*e.y)}static divide(t,e){return new te(t.x/e.x,t.y/e.y)}}const ee={distanceModel:"linear",refDistance:50,maxDistance:1e3,rolloffFactor:1};class ie{_audioContext;_output;_manager;_bus;_volume;_ended=!1;_stopTimer=null;onEnd=new m;_spatialConfig;_panner=null;_position=null;_followNode=null;_spatialRegistered=!1;_effects=[];constructor(t){this._audioContext=t.audioContext,this._output=t.output,this._bus=t.bus,this._manager=t.manager,this._volume=q(t.volume,0,1),this._spatialConfig={...ee,...t.spatial},this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01),!1!==t.autoConnect&&this._connectOutput()}get ended(){return this._ended}get output(){return this._output}get volume(){return this._volume}set volume(t){this._volume=q(t,0,1),this._ended||this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01)}get bus(){return this._bus}set bus(t){t!==this._bus&&(this._ended?this._bus=t:(this._tail().disconnect(),this._bus=t,this._connectOutput()))}addEffect(t){return this._ended||(this._effects.push(t),this._rebuildEffectChain()),this}removeEffect(t){const e=this._effects.indexOf(t);return-1!==e&&(this._effects.splice(e,1),t.outputNode.disconnect(),this._rebuildEffectChain()),this}fade(t,e){if(this._ended)return;const i=q(t,0,1);this._volume=i;const s=this._audioContext,n=this._output;e<=0?n.gain.setTargetAtTime(i,s.currentTime,.01):(n.gain.cancelScheduledValues(s.currentTime),n.gain.setValueAtTime(n.gain.value,s.currentTime),n.gain.linearRampToValueAtTime(i,s.currentTime+e/1e3))}stop(t){if(!this._ended){if(void 0!==t&&t>0){const e=this._audioContext,i=this._output;return i.gain.cancelScheduledValues(e.currentTime),i.gain.setValueAtTime(i.gain.value,e.currentTime),i.gain.linearRampToValueAtTime(0,e.currentTime+t/1e3),this._clearStopTimer(),void(this._stopTimer=setTimeout(()=>{this._stopTimer=null,this._finish()},t))}this._finish()}}get position(){return this._position}set position(t){this._ended||(null!==t?(null===this._position?this._position=new te(t.x,t.y):this._position.set(t.x,t.y),this._ensurePanner(),this._tickSpatial()):null!==this._position&&(this._position.destroy(),this._position=null))}follow(t){this._ended||(this._followNode=t,null!==t&&(this._ensurePanner(),this._tickSpatial()))}_tickSpatial(){if(null===this._panner||this._ended)return;let t,e;if(null!==this._followNode){const i=this._followNode.getGlobalTransform();t=i.x,e=i.y}else{if(null===this._position)return;t=this._position.x,e=this._position.y}const i=this._panner,s=this._audioContext.currentTime;i.positionX?(i.positionX.setValueAtTime(t,s),i.positionY.setValueAtTime(e,s),i.positionZ.setValueAtTime(0,s)):i.setPosition&&i.setPosition(t,e,0)}_tail(){const t=this._effects[this._effects.length-1];return void 0!==t?t.outputNode:this._output}_connectOutput(){this._connectTail(this._tail())}_connectTail(t){const e=this._bus._getInputNode();null===e?(t.connect(this._audioContext.destination),this._bus.onceSetup(()=>{if(this._ended)return;const t=this._bus._getInputNode();if(null!==t){const e=this._tail();e.disconnect(),e.connect(t)}})):t.connect(e)}_rebuildEffectChain(){if(this._ended)return;this._output.disconnect();for(const t of this._effects)t.outputNode.disconnect();let t=this._output;for(const e of this._effects)t.connect(e.inputNode),t=e.outputNode;this._connectTail(t)}_clearStopTimer(){null!==this._stopTimer&&(clearTimeout(this._stopTimer),this._stopTimer=null)}_ensurePanner(){if(null!==this._panner||this._ended)return;const t=this._audioContext.createPanner();t.panningModel="equalpower",t.distanceModel=this._spatialConfig.distanceModel,t.refDistance=this._spatialConfig.refDistance,t.maxDistance=this._spatialConfig.maxDistance,t.rolloffFactor=this._spatialConfig.rolloffFactor,this._routeThroughPanner(t),this._panner=t,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 t of this._effects)t.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 se extends ie{_oscillator;_envelopeGain;_envelope;_frequency;_type;_detune;_playbackRate=1;constructor(t){super(t);const e=this._audioContext,i=e.currentTime;this._frequency=t.frequency,this._type=t.type,this._detune=t.detune,this._envelope=t.envelope,this._envelopeGain=e.createGain(),this._envelopeGain.connect(this._output);const s=e.createOscillator();s.type=t.type,s.frequency.value=t.frequency,s.detune.value=t.detune,s.connect(this._envelopeGain),s.onended=()=>this._finish(),this._envelope?this._envelope.trigger(this._envelopeGain.gain,i):this._envelopeGain.gain.value=1,s.start(i),this._oscillator=s}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._ended||this._oscillator.frequency.setTargetAtTime(t,this._audioContext.currentTime,.01)}get type(){return this._type}set type(t){this._type=t,this._ended||(this._oscillator.type=t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t}get detune(){return this._detune}set detune(t){this._detune=t,this._ended||this._oscillator.detune.setTargetAtTime(t,this._audioContext.currentTime,.01)}stop(t){if(!this._ended)if(void 0!==t&&t>0)super.stop(t);else{if(this._envelope){const t=this._audioContext.currentTime;this._envelope.release(this._envelopeGain.gain,t);const e=t+this._envelope.releaseMs/1e3;try{this._oscillator.stop(e)}catch{}return}super.stop()}}_routeThroughPanner(t){this._envelopeGain.disconnect(),this._envelopeGain.connect(t),t.connect(this._output)}_teardownSource(){this._oscillator.onended=null;try{this._oscillator.stop(0)}catch{}this._oscillator.disconnect(),this._envelopeGain.disconnect()}}class ne{onEnd=new m;_bus;_output=null;constructor(t){this._bus=t}get ended(){return!0}get output(){return this._output??=D().createGain()}get volume(){return 0}set volume(t){}get bus(){return this._bus}set bus(t){}fade(t,e){}stop(t){}addEffect(t){return this}removeEffect(t){return this}}class re extends ie{_buffer;_window;_source;_loop;_playbackRate;_detune;_offsetAtStart;_startedAt;constructor(t){super(t),this._buffer=t.buffer,this._window=t.window,this._loop=t.loop,this._playbackRate=t.playbackRate,this._detune=t.detune,this._offsetAtStart=t.offset,this._startedAt=this._audioContext.currentTime,this._source=this._startSource(t.offset)}get duration(){return this._window.end-this._window.base}get time(){if(this._ended)return 0;const t=this.duration,e=(this._audioContext.currentTime-this._startedAt)*this._playbackRate;let i=this._offsetAtStart-this._window.base+e;return this._loop&&t>0&&(i%=t,i<0&&(i+=t)),q(i,0,t)}set time(t){this.seek(t)}seek(t){if(this._ended)return;const e=this._window.base+q(t,0,this.duration);this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect(),this._source=this._startSource(e),this._offsetAtStart=e,this._startedAt=this._audioContext.currentTime}get loop(){return this._loop}set loop(t){this._loop===t||this._ended?this._loop=t:(this._loop=t,this._source.loop=t,t&&(this._source.loopStart=this._window.loopStart,this._source.loopEnd=this._window.loopEnd))}get playbackRate(){return this._playbackRate}set playbackRate(t){const e=q(t,.1,20);if(this._playbackRate===e||this._ended)return void(this._playbackRate=e);const i=this.time;this._playbackRate=e,this._offsetAtStart=this._window.base+i,this._startedAt=this._audioContext.currentTime,this._source.playbackRate.setTargetAtTime(e,this._audioContext.currentTime,.01)}get detune(){return this._detune}set detune(t){this._detune=t,this._ended||this._source.detune.setTargetAtTime(t,this._audioContext.currentTime,.01)}_routeThroughPanner(t){this._source.disconnect(),this._source.connect(t),t.connect(this._output)}_teardownSource(){this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect()}_startSource(t){const e=this._audioContext.createBufferSource();e.buffer=this._buffer,e.loop=this._loop,e.playbackRate.value=this._playbackRate,e.detune.value=this._detune,this._loop&&(e.loopStart=this._window.loopStart,e.loopEnd=this._window.loopEnd),e.connect(this._panner??this._output),e.onended=()=>this._finish();const i=this._loop?void 0:this._window.end-t;return!this._loop&&void 0!==i&&i>0?e.start(0,t,i):e.start(0,t),e}}var oe;!function(t){t.FirstInFirstOut="fifo",t.LeastRecentlyUsed="lru",t.LowestPriority="priority"}(oe||(oe={}));class ae{_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(t){this.setPoolSize(t)}get poolStrategy(){return this._poolStrategy}set poolStrategy(t){this._poolStrategy=t}get priority(){return this._priority}set priority(t){this._priority=t}get position(){return this._position}set position(t){null!==t?null===this._position?this._position=new te(t.x,t.y):this._position.set(t.x,t.y):null!==this._position&&(this._position.destroy(),this._position=null)}get velocity(){return this._velocity}set velocity(t){null===t?null!==this._velocity&&(this._velocity.destroy(),this._velocity=null):null===this._velocity?this._velocity=new te(t.x,t.y):this._velocity.set(t.x,t.y)}get distanceModel(){return this._distanceModel}set distanceModel(t){this._distanceModel=t}get refDistance(){return this._refDistance}set refDistance(t){this._refDistance=Math.max(0,t)}get maxDistance(){return this._maxDistance}set maxDistance(t){this._maxDistance=Math.max(0,t)}get rolloffFactor(){return this._rolloffFactor}set rolloffFactor(t){this._rolloffFactor=Math.max(0,t)}constructor(t,e={}){this._audioBuffer=t,this._clipEnd=t.duration;const{poolSize:i,poolStrategy:s,priority:n,sprites:r,volume:o,loop:a,playbackRate:h,muted:l,distanceModel:u,refDistance:c,maxDistance:d,rolloffFactor:_}=e;this.volume=q(o??1,0,1),this.loop=a??!1,this.playbackRate=q(h??1,.1,20),this.muted=l??!1,this._poolSize=Math.max(1,Math.floor(i??8)),this._poolStrategy=s??oe.FirstInFirstOut,this._priority=n??0,void 0!==u&&(this._distanceModel=u),void 0!==c&&(this._refDistance=Math.max(0,c)),void 0!==d&&(this._maxDistance=Math.max(0,d)),void 0!==_&&(this._rolloffFactor=Math.max(0,_)),r&&this.setSprites(r)}setPoolSize(t){const e=Math.max(1,Math.floor(t));return this._poolSize===e||(this._poolSize=e,this._trimActiveVoices()),this}setSprites(t){this._sprites.clear();for(const[e,i]of Object.entries(t))this.defineSprite(e,i);return this}defineSprite(t,e){if(0===t.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=e.start,s=e.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${t}" has an invalid start time (${i}).`);if(!Number.isFinite(s)||s<=i)throw new Error(`Sound sprite "${t}" has an invalid end time (${s}).`);if(s>this.duration)throw new Error(`Sound sprite "${t}" ends at ${s}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(t,{start:i,end:s,loop:e.loop??!1}),this}hasSprite(t){return this._sprites.has(t)}removeSprite(t){return this._sprites.delete(t),this}clip(t,e){const i=q(t,0,this._audioBuffer.duration),s=q(i+e,i,this._audioBuffer.duration),n=new ae(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 n._clipStart=i,n._clipEnd=s,n}_createVoice(t,e){const i=this._clipStart+Math.max(0,e.time??0);return i>=this._clipEnd?new ne(e.bus??t.sound):this._buildVoice(t,e,i,{base:this._clipStart,end:this._clipEnd,loopStart:this._clipStart,loopEnd:this._clipEnd})}_createSpriteVoice(t,e,i={}){const s=this._sprites.get(e);if(!s)throw new Error(`Sound sprite "${e}" is not defined.`);const n=Math.max(0,i.time??0),r=s.start+n;if(r>=s.end)throw new Error(`Sound sprite "${e}" offset (${n}s) exceeds clip duration (${s.end-s.start}s).`);const o=i.loop??s.loop;return this._buildVoice(t,{...i,loop:o},r,{base:s.start,end:s.end,loopStart:s.start,loopEnd:s.end})}_buildVoice(t,e,i,s){const n=e.loop??this.loop,r=q(e.playbackRate??this.playbackRate,.1,20),o=e.detune??0,a=q(e.muted?0:e.volume??(this.muted?0:this.volume),0,1),h=e.bus??t.sound;if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const t=this._pickEvictionVictim(),e=this._activeVoices[t];e&&(this._activeVoices.splice(t,1),e.voice.stop())}const l=D(),u=l.createGain(),c=new re({audioContext:l,output:u,bus:h,manager:t,volume:a,spatial:{distanceModel:this._distanceModel,refDistance:this._refDistance,maxDistance:this._maxDistance,rolloffFactor:this._rolloffFactor},buffer:this._audioBuffer,loop:n,playbackRate:r,detune:o,offset:i,window:s});null!==this._position&&(c.position=this._position);const d={voice:c,startedAt:l.currentTime,effectiveDuration:n?1/0:s.end-i};return c.onEnd.add(()=>{const t=this._activeVoices.indexOf(d);-1!==t&&this._activeVoices.splice(t,1)}),this._activeVoices.push(d),c}_stopAllVoices(){const t=[...this._activeVoices];this._activeVoices.length=0;for(const e of t)e.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 t=this._activeVoices.length-1;t>=0;t--)!0===this._activeVoices[t]?.voice.ended&&this._activeVoices.splice(t,1)}_pickEvictionVictim(){switch(this._poolStrategy){case oe.LeastRecentlyUsed:return this._pickClosestToEnd();case oe.LowestPriority:case oe.FirstInFirstOut:default:return 0}}_pickClosestToEnd(){const t=I()?D().currentTime:0;let e=1/0,i=0;for(let s=0;s<this._activeVoices.length;s++){const n=this._activeVoices[s];if(void 0===n)continue;const r=t-n.startedAt,o=n.effectiveDuration-r;o<e&&(e=o,i=s)}return i}_trimActiveVoices(){for(;this._activeVoices.length>this._poolSize;){const t=this._pickEvictionVictim(),e=this._activeVoices[t];if(!e)break;this._activeVoices.splice(t,1),e.voice.stop()}}}class he{frequency;type;detune;envelope;volume;muted;_poolSize;_poolStrategy;priority;_activeVoices=[];get poolSize(){return this._poolSize}set poolSize(t){this._poolSize=Math.max(1,Math.floor(t))}get poolStrategy(){return this._poolStrategy}set poolStrategy(t){this._poolStrategy=t}constructor(t={}){this.frequency=t.frequency??440,this.type=t.type??"sine",this.detune=t.detune??0,this.envelope=t.envelope??null,this.volume=q(t.volume??1,0,1),this.muted=t.muted??!1,this._poolSize=Math.max(1,Math.floor(t.poolSize??8)),this._poolStrategy=t.poolStrategy??oe.FirstInFirstOut,this.priority=t.priority??0}setNote(t){return this.frequency=he.midiToFrequency(t),this}static midiToFrequency(t){return 440*Math.pow(2,(t-69)/12)}_createVoice(t,e){const i=e.bus??t.sound;if(!I())return new ne(i);if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const t=this._pickEvictionVictim(),e=this._activeVoices[t];e&&(this._activeVoices.splice(t,1),e.voice.stop())}const s=D(),n=s.createGain(),r=e.detune??this.detune,o=q(e.muted?0:e.volume??(this.muted?0:this.volume),0,1),a=new se({audioContext:s,output:n,bus:i,manager:t,volume:o,frequency:this.frequency,type:this.type,detune:r,envelope:this.envelope}),h={voice:a,startedAt:s.currentTime};return a.onEnd.add(()=>{const t=this._activeVoices.indexOf(h);-1!==t&&this._activeVoices.splice(t,1)}),this._activeVoices.push(h),a}stopAll(){const t=[...this._activeVoices];this._activeVoices.length=0;for(const e of t)e.voice.stop();return this}destroy(){this.stopAll()}_pruneEndedVoices(){for(let t=this._activeVoices.length-1;t>=0;t--)!0===this._activeVoices[t]?.voice.ended&&this._activeVoices.splice(t,1)}_pickEvictionVictim(){if(this._poolStrategy===oe.LeastRecentlyUsed){let t=0,e=1/0;for(let i=0;i<this._activeVoices.length;i++){const s=this._activeVoices[i];void 0!==s&&s.startedAt<e&&(e=s.startedAt,t=i)}return t}return 0}}class le{_stream;constructor(t){this._stream=t}get stream(){return this._stream}static async open(t={}){if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("AudioInput.open: getUserMedia is not available in this environment.");const e={};void 0!==t.deviceId&&(e.deviceId=t.deviceId),void 0!==t.echoCancellation&&(e.echoCancellation=t.echoCancellation),void 0!==t.noiseSuppression&&(e.noiseSuppression=t.noiseSuppression),void 0!==t.autoGainControl&&(e.autoGainControl=t.autoGainControl);const i=await navigator.mediaDevices.getUserMedia({audio:!(Object.keys(e).length>0)||e});return new le(i)}close(){for(const t of this._stream.getTracks())t.stop()}}class ue{position=new te(0,0);velocity=new te(0,0);target=null;_audioListener=null;_ctx=null;_onAudioContextReady=t=>{k.remove(this._onAudioContextReady),this._setup(t)};constructor(){I()?this._setup(D()):k.add(this._onAudioContextReady)}_tick(){if(null!==this.target&&this._readTargetPosition(),null!==this._audioListener&&null!==this._ctx){const t=this._ctx.currentTime,e=this._audioListener;e.positionX&&e.positionY&&e.positionZ?(e.positionX.setValueAtTime(this.position.x,t),e.positionY.setValueAtTime(this.position.y,t),e.positionZ.setValueAtTime(0,t)):e.setPosition&&e.setPosition(this.position.x,this.position.y,0)}}destroy(){k.remove(this._onAudioContextReady),this.position.destroy(),this.velocity.destroy(),this.target=null,this._audioListener=null,this._ctx=null}_readTargetPosition(){const t=this.target;if(null===t)return;const e=t;if("function"==typeof e.getGlobalTransform){const t=e.getGlobalTransform();return void this.position.set(t.x,t.y)}const i=t;if(void 0!==i.center&&"object"==typeof i.center)return void this.position.set(i.center.x,i.center.y);const s=t;this.position.set(s.x,s.y)}_setup(t){this._ctx=t,this._audioListener=t.listener;const e=t.currentTime,i=t.listener;i.forwardX&&i.forwardY&&i.forwardZ&&i.upX&&i.upY&&i.upZ?(i.forwardX.setValueAtTime(0,e),i.forwardY.setValueAtTime(0,e),i.forwardZ.setValueAtTime(-1,e),i.upX.setValueAtTime(0,e),i.upY.setValueAtTime(1,e),i.upZ.setValueAtTime(0,e)):i.setOrientation&&i.setOrientation(0,0,-1,0,1,0)}}class ce extends ie{_sourceNode;_stream;constructor(t){super({...t,autoConnect:!1}),this._sourceNode=t.sourceNode,this._stream=t.stream,this._sourceNode.connect(this._output)}routeTo(t){return this._ended||(this._tail().disconnect(),this._bus=t,this._connectOutput()),this}async record(t){const e=new MediaRecorder(this._stream),i=[];return e.addEventListener("dataavailable",t=>{t.data.size>0&&i.push(t.data)}),new Promise((s,n)=>{e.addEventListener("stop",()=>{(async()=>{try{const t=new Blob(i,{type:e.mimeType||"audio/webm"}),n=await U(await t.arrayBuffer());s(new ae(n))}catch(t){n(t instanceof Error?t:new Error(String(t)))}})()}),e.addEventListener("error",()=>n(new Error("Recording failed."))),e.start(),setTimeout(()=>{"inactive"!==e.state&&e.stop()},Math.max(0,t))})}_routeThroughPanner(t){this._sourceNode.disconnect(),this._sourceNode.connect(t),t.connect(this._output)}_teardownSource(){this._sourceNode.disconnect()}}class de{order=300;master;music;sound;listener;onUnlock=new m;_registered=new Map;_spatial=new Set;_muteOnHidden=!1;constructor(){this.master=new Q("master",{parent:null}),this.music=new Q("music",{parent:this.master}),this.sound=new Q("sound",{parent:this.master}),this.listener=new ue,this._registered.set("master",this.master),this._registered.set("music",this.music),this._registered.set("sound",this.sound),k.add(()=>{this.onUnlock.dispatch()})}get muteOnHidden(){return this._muteOnHidden}set muteOnHidden(t){this._muteOnHidden=t}get locked(){return!I()}play(t,e){return t._createVoice(this,e??{})}open(t){const e=D(),i=e.createMediaStreamSource(t.stream),s=e.createGain();return new ce({audioContext:e,output:s,bus:this.sound,manager:this,volume:1,sourceNode:i,stream:t.stream})}update(t){this.listener._tick();for(const t of this._spatial)t.ended?this._spatial.delete(t):t._tickSpatial()}_registerSpatial(t){this._spatial.add(t)}_applyVisibility(t){this._muteOnHidden&&(this.master.muted=!t)}registerBus(t){if(this._registered.has(t.name))throw new Error(`Audio bus "${t.name}" is already registered.`);return this._registered.set(t.name,t),this}unregisterBus(t){if(t===this.master||t===this.music||t===this.sound)throw new Error(`Cannot unregister built-in bus "${t.name}".`);return this._registered.get(t.name)!==t||(this._registered.delete(t.name),t.destroy()),this}getBus(t){const e=this._registered.get(t);if(!e)throw new Error(`Audio bus "${t}" is not registered.`);return e}hasBus(t){return this._registered.has(t)}destroy(){this.listener.destroy(),this._spatial.clear();for(const t of this._registered.values())t.destroy();this._registered.clear()}}class _e extends ie{_element;_sourceNode;_detune=0;_onEnded=()=>this._finish();_unlockHandler=null;constructor(t){super(t),this._element=t.element,this._sourceNode=t.sourceNode,this._sourceNode.connect(this._output),this._element.loop=t.loop,this._element.playbackRate=t.playbackRate,void 0!==t.startTime&&(this._element.currentTime=Math.max(0,t.startTime)),this._element.addEventListener("ended",this._onEnded),this._startPlayback()}get duration(){return this._element.duration}get time(){return this._element.currentTime}set time(t){this.seek(t)}seek(t){this._ended||(this._element.currentTime=Math.max(0,t))}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(t){this._element.loop=t}get playbackRate(){return this._element.playbackRate}set playbackRate(t){this._element.playbackRate=q(t,.1,20)}get detune(){return this._detune}set detune(t){this._detune=t}_routeThroughPanner(t){this._sourceNode.disconnect(),this._sourceNode.connect(t),t.connect(this._output)}_teardownSource(){this._element.removeEventListener("ended",this._onEnded),this._clearUnlockHandler(),this._element.pause(),this._sourceNode.disconnect()}_startPlayback(){I()?this._element.play():(this._unlockHandler=()=>{this._clearUnlockHandler(),this._ended||this._element.play()},k.add(this._unlockHandler))}_clearUnlockHandler(){null!==this._unlockHandler&&(k.remove(this._unlockHandler),this._unlockHandler=null)}}class fe{_audioElement;volume;loop;playbackRate;muted;_sourceNode=null;_activeVoice=null;constructor(t,e){this._audioElement=t,this.volume=q(e?.volume??1,0,1),this.loop=e?.loop??!1,this.playbackRate=q(e?.playbackRate??1,.1,20),this.muted=e?.muted??!1,void 0!==e?.time&&(this._audioElement.currentTime=Math.max(0,e.time))}get audioElement(){return this._audioElement}get duration(){return this._audioElement.duration}_createVoice(t,e){const i=e.bus??t.music,s=D();null===this._activeVoice||this._activeVoice.ended||this._activeVoice.stop(),null===this._sourceNode?this._sourceNode=s.createMediaElementSource(this._audioElement):this._sourceNode.disconnect();const n=s.createGain(),r=e.loop??this.loop,o=q(e.playbackRate??this.playbackRate,.1,20),a=q(e.muted?0:e.volume??(this.muted?0:this.volume),0,1),h=new _e({audioContext:s,output:n,bus:i,manager:t,volume:a,element:this._audioElement,sourceNode:this._sourceNode,loop:r,playbackRate:o,...void 0!==e.time&&{startTime:e.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)}}class pe extends Z{_node=null;_type;_frequency;_resonance;_gain;_detune;_onAudioContextReady=t=>{k.remove(this._onAudioContextReady),this._setup(t)};constructor(t={}){super(),this._type=t.type??"lowpass",this._frequency=t.frequency??1e3,this._resonance=t.resonance??1,this._gain=t.gain??0,this._detune=t.detune??0,I()?this._setup(D()):k.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(t){this._type=t,this._node&&(this._node.type=t)}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._node&&this._node.frequency.setTargetAtTime(t,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(t){this._resonance=t,this._node&&this._node.Q.setTargetAtTime(t,this._node.context.currentTime,.01)}get gain(){return this._gain}set gain(t){this._gain=t,this._node&&this._node.gain.setTargetAtTime(t,this._node.context.currentTime,.01)}get detune(){return this._detune}set detune(t){this._detune=t,this._node&&this._node.detune.setTargetAtTime(t,this._node.context.currentTime,.01)}destroy(){k.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(t){const e=t.createBiquadFilter();e.type=this._type,e.frequency.setValueAtTime(this._frequency,t.currentTime),e.Q.setValueAtTime(this._resonance,t.currentTime),e.gain.setValueAtTime(this._gain,t.currentTime),e.detune.setValueAtTime(this._detune,t.currentTime),this._node=e}}async function ge(t,e,i,s={}){const n=q(s.toVolume??1,0,1),r=s.stopAfter??!0;return e.fade(n,i),r?t.stop(i):t.fade(0,i),new Promise(t=>{setTimeout(t,Math.max(0,i))})}class me{attackMs;decayMs;sustainLevel;releaseMs;constructor(t={}){this.attackMs=Math.max(0,t.attackMs??10),this.decayMs=Math.max(0,t.decayMs??100),this.sustainLevel=Math.max(0,Math.min(1,t.sustainLevel??.7)),this.releaseMs=Math.max(0,t.releaseMs??200)}trigger(t,e){const i=e+this.attackMs/1e3,s=i+this.decayMs/1e3;t.cancelScheduledValues(e),t.setValueAtTime(0,e),t.linearRampToValueAtTime(1,i),t.linearRampToValueAtTime(this.sustainLevel,s)}release(t,e){this.releaseMs,t.cancelScheduledValues(e),t.setTargetAtTime(0,e,this.releaseMs/1e3/3)}get totalDurationMs(){return this.attackMs+this.decayMs+this.releaseMs}destroy(){}}class ye extends Z{_node=null;_frequency;_resonance;_onAudioContextReady=t=>{k.remove(this._onAudioContextReady),this._setup(t)};constructor(t={}){super(),this._frequency=t.frequency??1e3,this._resonance=t.resonance??1,I()?this._setup(D()):k.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(t){this._frequency=Math.max(20,Math.min(2e4,t)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(t){this._resonance=Math.max(1e-4,t),this._node&&this._node.Q.setTargetAtTime(this._resonance,this._node.context.currentTime,.01)}destroy(){k.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(t){const e=t.createBiquadFilter();e.type="highpass",e.frequency.setValueAtTime(this._frequency,t.currentTime),e.Q.setValueAtTime(this._resonance,t.currentTime),this._node=e}}class we extends Z{_node=null;_frequency;_resonance;_onAudioContextReady=t=>{k.remove(this._onAudioContextReady),this._setup(t)};constructor(t={}){super(),this._frequency=t.frequency??1e3,this._resonance=t.resonance??1,I()?this._setup(D()):k.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(t){this._frequency=Math.max(20,Math.min(2e4,t)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(t){this._resonance=Math.max(1e-4,t),this._node&&this._node.Q.setTargetAtTime(this._resonance,this._node.context.currentTime,.01)}destroy(){k.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(t){const e=t.createBiquadFilter();e.type="lowpass",e.frequency.setValueAtTime(this._frequency,t.currentTime),e.Q.setValueAtTime(this._resonance,t.currentTime),this._node=e}}const xe=new WeakMap,ve=new WeakMap;async function be(t,e,i){let s=xe.get(t);if(s||(s=new Set,xe.set(t,s)),s.has(e))return;let n=ve.get(t);n||(n=new Map,ve.set(t,n));const r=n.get(e);if(r)return r;const o=new Blob([i],{type:"application/javascript"}),a=URL.createObjectURL(o),h=t.audioWorklet.addModule(a).finally(()=>{URL.revokeObjectURL(a)}).then(()=>{s.add(e),n.delete(e)}).catch(t=>{throw n.delete(e),t});return n.set(e,h),h}class Se extends Z{_inputGain=null;_outputGain=null;_workletNode=null;_ready=null;_onAudioContextReady=t=>{k.remove(this._onAudioContextReady),this._setup(t)};get _workletOptions(){return{numberOfInputs:1,numberOfOutputs:1}}constructor(){super(),I()?this._setup(D()):k.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 ready(){return this._ready??Promise.resolve()}destroy(){k.remove(this._onAudioContextReady),this._workletNode?.disconnect(),this._inputGain?.disconnect(),this._outputGain?.disconnect(),this._workletNode=null,this._inputGain=null,this._outputGain=null,this._ready=null}_setAudioParam(t,e){if(!this._workletNode)return;const i=this._workletNode.parameters.get(t);i&&i.setTargetAtTime(e,this._workletNode.context.currentTime,.01)}_setup(t){const e=t.createGain(),i=t.createGain();e.connect(i),this._inputGain=e,this._outputGain=i,this._ready=be(t,this._workletName,this._workletSource).then(()=>{if(!this._inputGain||!this._outputGain)return;const e=new AudioWorkletNode(t,this._workletName,this._workletOptions);this._workletNode=e,this._inputGain.disconnect(),this._inputGain.connect(e),e.connect(this._outputGain),this._onWorkletReady?.(t)})}}const Be=Object.freeze({extensions:Object.freeze([]),renderers:Object.freeze([]),assets:Object.freeze([]),serializers:Object.freeze([])});function Ce(t){if(0===t.length)return Be;const e=new Map,i=new Set,s=new Set,n=[],r=[];function o(t){const a=e.get(t.id);if(void 0!==a&&a!==t)throw new Error(`Extension "${t.id}" was provided by multiple descriptor objects.`);if(void 0===a&&e.set(t.id,t),!s.has(t)){if(i.has(t)){const e=[...n.slice(n.indexOf(t)),t].map(t=>t.id).join(" → ");throw new Error(`Extension dependency cycle detected: ${e}`)}i.add(t),n.push(t);for(const e of t.dependencies??[])o(e);n.pop(),i.delete(t),s.add(t),r.push(t)}}for(const e of t)o(e);const a=[],h=[],l=[];for(const t of r){if(t.renderers)for(const e of t.renderers)a.push(e);if(t.assets)for(const e of t.assets)h.push(e);if(t.serializers)for(const e of t.serializers)l.push(e)}return Object.freeze({extensions:Object.freeze(r),renderers:Object.freeze(a),assets:Object.freeze(h),serializers:Object.freeze(l)})}let Te,Me=new Map;function Pe(t,e){const i=new Set;for(const s of e){if(0===s.targets.length)throw new Error("A RendererBinding must declare at least one target.");for(const t of s.targets){if(i.has(t))throw new Error(`Two bindings target the same drawable type ${t.name}. Remove one of the conflicting bindings.`);i.add(t)}const e=s.create(t);void 0!==e&&t.rendererRegistry.bindRenderer(s.targets,e)}}const Ae=t=>0|q(t,0,255);class Ee{_r;_g;_b;_a;_rgba=null;_array=null;constructor(t=0,e=0,i=0,s=1){this._r=Ae(t),this._g=Ae(e),this._b=Ae(i),this._a=q(s,0,1)}get r(){return this._r}set r(t){this._r=Ae(t),this._rgba=null}get g(){return this._g}set g(t){this._g=Ae(t),this._rgba=null}get b(){return this._b}set b(t){this._b=Ae(t),this._rgba=null}get a(){return this._a}set a(t){this._a=q(t,0,1),this._rgba=null}set(t=this._r,e=this._g,i=this._b,s=this._a){return this._r=Ae(t),this._g=Ae(e),this._b=Ae(i),this._a=q(s,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new Ee(this._r,this._g,this._b,this._a)}equals({r:t,g:e,b:i,a:s}={}){return!(void 0!==t&&this.r!==t||void 0!==e&&this.g!==e||void 0!==i&&this.b!==i||void 0!==s&&this.a!==s)}toArray(t=!1){return this._array||(this._array=new Float32Array(4)),t?(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(t=!0){return`${t?"#":""}${(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 Ee(240,248,255,1);static antiqueWhite=new Ee(250,235,215,1);static aqua=new Ee(0,255,255,1);static aquamarine=new Ee(127,255,212,1);static azure=new Ee(240,255,255,1);static beige=new Ee(245,245,220,1);static bisque=new Ee(255,228,196,1);static black=new Ee(0,0,0,1);static blanchedAlmond=new Ee(255,235,205,1);static blue=new Ee(0,0,255,1);static blueViolet=new Ee(138,43,226,1);static brown=new Ee(165,42,42,1);static burlyWood=new Ee(222,184,135,1);static cadetBlue=new Ee(95,158,160,1);static chartreuse=new Ee(127,255,0,1);static chocolate=new Ee(210,105,30,1);static coral=new Ee(255,127,80,1);static cornflowerBlue=new Ee(100,149,237,1);static cornsilk=new Ee(255,248,220,1);static crimson=new Ee(220,20,60,1);static cyan=new Ee(0,255,255,1);static darkBlue=new Ee(0,0,139,1);static darkCyan=new Ee(0,139,139,1);static darkGoldenrod=new Ee(184,134,11,1);static darkGray=new Ee(169,169,169,1);static darkGreen=new Ee(0,100,0,1);static darkKhaki=new Ee(189,183,107,1);static darkMagenta=new Ee(139,0,139,1);static darkOliveGreen=new Ee(85,107,47,1);static darkOrange=new Ee(255,140,0,1);static darkOrchid=new Ee(153,50,204,1);static darkRed=new Ee(139,0,0,1);static darkSalmon=new Ee(233,150,122,1);static darkSeaGreen=new Ee(143,188,139,1);static darkSlateBlue=new Ee(72,61,139,1);static darkSlateGray=new Ee(47,79,79,1);static darkTurquoise=new Ee(0,206,209,1);static darkViolet=new Ee(148,0,211,1);static deepPink=new Ee(255,20,147,1);static deepSkyBlue=new Ee(0,191,255,1);static dimGray=new Ee(105,105,105,1);static dodgerBlue=new Ee(30,144,255,1);static firebrick=new Ee(178,34,34,1);static floralWhite=new Ee(255,250,240,1);static forestGreen=new Ee(34,139,34,1);static fuchsia=new Ee(255,0,255,1);static gainsboro=new Ee(220,220,220,1);static ghostWhite=new Ee(248,248,255,1);static gold=new Ee(255,215,0,1);static goldenrod=new Ee(218,165,32,1);static gray=new Ee(128,128,128,1);static green=new Ee(0,128,0,1);static greenYellow=new Ee(173,255,47,1);static honeydew=new Ee(240,255,240,1);static hotPink=new Ee(255,105,180,1);static indianRed=new Ee(205,92,92,1);static indigo=new Ee(75,0,130,1);static ivory=new Ee(255,255,240,1);static khaki=new Ee(240,230,140,1);static lavender=new Ee(230,230,250,1);static lavenderBlush=new Ee(255,240,245,1);static lawnGreen=new Ee(124,252,0,1);static lemonChiffon=new Ee(255,250,205,1);static lightBlue=new Ee(173,216,230,1);static lightCoral=new Ee(240,128,128,1);static lightCyan=new Ee(224,255,255,1);static lightGoldenrodYellow=new Ee(250,250,210,1);static lightGray=new Ee(211,211,211,1);static lightGreen=new Ee(144,238,144,1);static lightPink=new Ee(255,182,193,1);static lightSalmon=new Ee(255,160,122,1);static lightSeaGreen=new Ee(32,178,170,1);static lightSkyBlue=new Ee(135,206,250,1);static lightSlateGray=new Ee(119,136,153,1);static lightSteelBlue=new Ee(176,196,222,1);static lightYellow=new Ee(255,255,224,1);static lime=new Ee(0,255,0,1);static limeGreen=new Ee(50,205,50,1);static linen=new Ee(250,240,230,1);static magenta=new Ee(255,0,255,1);static maroon=new Ee(128,0,0,1);static mediumAquamarine=new Ee(102,205,170,1);static mediumBlue=new Ee(0,0,205,1);static mediumOrchid=new Ee(186,85,211,1);static mediumPurple=new Ee(147,112,219,1);static mediumSeaGreen=new Ee(60,179,113,1);static mediumSlateBlue=new Ee(123,104,238,1);static mediumSpringGreen=new Ee(0,250,154,1);static mediumTurquoise=new Ee(72,209,204,1);static mediumVioletRed=new Ee(199,21,133,1);static midnightBlue=new Ee(25,25,112,1);static mintCream=new Ee(245,255,250,1);static mistyRose=new Ee(255,228,225,1);static moccasin=new Ee(255,228,181,1);static navajoWhite=new Ee(255,222,173,1);static navy=new Ee(0,0,128,1);static oldLace=new Ee(253,245,230,1);static olive=new Ee(128,128,0,1);static oliveDrab=new Ee(107,142,35,1);static orange=new Ee(255,165,0,1);static orangeRed=new Ee(255,69,0,1);static orchid=new Ee(218,112,214,1);static paleGoldenrod=new Ee(238,232,170,1);static paleGreen=new Ee(152,251,152,1);static paleTurquoise=new Ee(175,238,238,1);static paleVioletRed=new Ee(219,112,147,1);static papayaWhip=new Ee(255,239,213,1);static peachPuff=new Ee(255,218,185,1);static peru=new Ee(205,133,63,1);static pink=new Ee(255,192,203,1);static plum=new Ee(221,160,221,1);static powderBlue=new Ee(176,224,230,1);static purple=new Ee(128,0,128,1);static red=new Ee(255,0,0,1);static rosyBrown=new Ee(188,143,143,1);static royalBlue=new Ee(65,105,225,1);static saddleBrown=new Ee(139,69,19,1);static salmon=new Ee(250,128,114,1);static sandyBrown=new Ee(244,164,96,1);static seaGreen=new Ee(46,139,87,1);static seaShell=new Ee(255,245,238,1);static sienna=new Ee(160,82,45,1);static silver=new Ee(192,192,192,1);static skyBlue=new Ee(135,206,235,1);static slateBlue=new Ee(106,90,205,1);static slateGray=new Ee(112,128,144,1);static snow=new Ee(255,250,250,1);static springGreen=new Ee(0,255,127,1);static steelBlue=new Ee(70,130,180,1);static tan=new Ee(210,180,140,1);static teal=new Ee(0,128,128,1);static thistle=new Ee(216,191,216,1);static tomato=new Ee(255,99,71,1);static transparentBlack=new Ee(0,0,0,0);static transparentWhite=new Ee(255,255,255,0);static turquoise=new Ee(64,224,208,1);static violet=new Ee(238,130,238,1);static wheat=new Ee(245,222,179,1);static white=new Ee(255,255,255,1);static whiteSmoke=new Ee(245,245,245,1);static yellow=new Ee(255,255,0,1);static yellowGreen=new Ee(154,205,50,1)}class Re{_value=0;get value(){return this._value}constructor(...t){t.length&&this.push(...t)}push(...t){for(const e of t)this._value|=e;return this}pop(t){const e=this.has(t);return this.remove(t),e}remove(...t){for(const e of t)this._value&=~e;return this}has(...t){return t.some(t=>0!==(this._value&t))}clear(){return this._value=0,this}destroy(){this.clear()}}let ke=null;class De{a;b;x;c;d;y;e;f;z;_array=null;constructor(t=1,e=0,i=0,s=0,n=1,r=0,o=0,a=0,h=1){this.a=t,this.b=e,this.x=i,this.c=s,this.d=n,this.y=r,this.e=o,this.f=a,this.z=h}set(t=this.a,e=this.b,i=this.x,s=this.c,n=this.d,r=this.y,o=this.e,a=this.f,h=this.z){return this.a=t,this.b=e,this.x=i,this.c=s,this.d=n,this.y=r,this.e=o,this.f=a,this.z=h,this}copy(t){return this.a=t.a,this.b=t.b,this.x=t.x,this.c=t.c,this.d=t.d,this.y=t.y,this.e=t.e,this.f=t.f,this.z=t.z,this}clone(){return new De(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:t,b:e,x:i,c:s,d:n,y:r,e:o,f:a,z:h}={}){return!(void 0!==t&&this.a!==t||void 0!==e&&this.b!==e||void 0!==i&&this.x!==i||void 0!==s&&this.c!==s||void 0!==n&&this.d!==n||void 0!==r&&this.y!==r||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(t){return this.set(this.a*t.a+this.c*t.b+this.e*t.x,this.b*t.a+this.d*t.b+this.f*t.x,this.x*t.a+this.y*t.b+this.z*t.x,this.a*t.c+this.c*t.d+this.e*t.y,this.b*t.c+this.d*t.d+this.f*t.y,this.x*t.c+this.y*t.d+this.z*t.y,this.a*t.e+this.c*t.f+this.e*t.z,this.b*t.e+this.d*t.f+this.f*t.z,this.x*t.e+this.y*t.f+this.z*t.z)}getInverse(t=this){const e=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===e?t.copy(De.identity):t.set((this.d*this.z-this.y*this.f)/e,(this.x*this.f-this.b*this.z)/e,(this.b*this.y-this.x*this.d)/e,(this.y*this.e-this.c*this.z)/e,(this.a*this.z-this.x*this.e)/e,(this.x*this.c-this.a*this.y)/e,(this.c*this.f-this.d*this.e)/e,(this.b*this.e-this.a*this.f)/e,(this.a*this.d-this.b*this.c)/e)}translate(t,e=t){return this.combine(De.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const s=z(t),n=Math.cos(s),r=Math.sin(s);return this.combine(De.temp.set(n,-r,e*(1-n)+i*r,r,n,i*(1-n)-e*r,0,0,1))}scale(t,e=t,i=0,s=i){return this.combine(De.temp.set(t,0,i*(1-t),0,e,s*(1-e),0,0,1))}toArray(t=!1){const e=this._array||(this._array=new Float32Array(9));return t?(e[0]=this.a,e[1]=this.b,e[2]=this.x,e[3]=this.c,e[4]=this.d,e[5]=this.y,e[6]=this.e,e[7]=this.f,e[8]=this.z):(e[0]=this.a,e[1]=this.c,e[2]=this.e,e[3]=this.b,e[4]=this.d,e[5]=this.f,e[6]=this.x,e[7]=this.y,e[8]=this.z),e}destroy(){this._array&&(this._array=null)}static identity=new De(1,0,0,0,1,0,0,0,1);static get temp(){return null===ke&&(ke=new De),ke}}class Ie{_minX=1/0;_minY=1/0;_maxX=-1/0;_maxY=-1/0;_dirty=!0;_rect=new Zt;get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(t,e){return this._minX=Math.min(this._minX,t),this._minY=Math.min(this._minY,e),this._maxX=Math.max(this._maxX,t),this._maxY=Math.max(this._maxY,e),this._dirty=!0,this}addRect(t,e){return e&&(t=t.transform(e,Zt.temp)),this.addCoords(t.left,t.top).addCoords(t.right,t.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 Le,Ue,Fe;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Skew=32]="Skew",t[t.Transform=47]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.GlobalTransform=256]="GlobalTransform",t[t.BoundsRect=512]="BoundsRect"}(Le||(Le={})),function(t){t[t.Position=0]="Position",t[t.Scale=1]="Scale",t[t.Origin=2]="Origin",t[t.Anchor=3]="Anchor"}(Ue||(Ue={}));class Ge{collisionType=tt.SceneNode;flags=new Re(Le.Transform|Le.GlobalTransform|Le.BoundsRect);_bounds=new Ie;_transform=new De;_position=new Ht(this,Ue.Position,0,0);_scale=new Ht(this,Ue.Scale,1,1);_origin=new Ht(this,Ue.Origin,0,0);_rotation=0;_skewX=0;_skewY=0;_sin=0;_cos=1;_stage=null;_visible=!0;_globalTransform=new De;_localBounds=new Zt;_anchor=new Ht(this,Ue.Anchor,0,0);_parentNode=null;_zIndex=0;_cullable=!0;name=null;get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get origin(){return this._origin}set origin(t){this._origin.copy(t)}get anchor(){return this._anchor}set anchor(t){this._anchor.copy(t)}get parent(){return this._parentNode}set parent(t){this._parentNode=t}get visible(){return this._visible}set visible(t){this._visible=t}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t)}get cullable(){return this._cullable}set cullable(t){this._cullable=t}get skewX(){return this._skewX}set skewX(t){this._skewX!==t&&(this._skewX=t,this._setSkewDirty())}get skewY(){return this._skewY}set skewY(t){this._skewY!==t&&(this._skewY=t,this._setSkewDirty())}get isAlignedBox(){return this.rotation%90==0&&0===this._skewX&&0===this._skewY}setPosition(t,e=t){return this._position.set(t,e),this}setRotation(t){const e=V(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}setScale(t,e=t){return this._scale.set(t,e),this}setSkew(t,e=t){return this.skewX=t,this.skewY=e,this}setOrigin(t,e=t){return this._origin.set(t,e),this}move(t,e){return this.setPosition(this.x+t,this.y+e)}rotate(t){return this.setRotation(this._rotation+t)}getTransform(){return this.flags.has(Le.Transform)&&(this.updateTransform(),this.flags.remove(Le.Transform)),this._transform}updateTransform(){if(this.flags.has(Le.Rotation)){const t=z(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}if(this.flags.has(Le.Rotation|Le.Scaling|Le.Skew)){const{x:t,y:e}=this._scale;if(0!==this._skewX||0!==this._skewY){const i=Math.tan(z(this._skewX)),s=Math.tan(z(this._skewY));this._transform.a=t*this._cos+i*this._sin,this._transform.b=e*this._sin+s*this._cos,this._transform.c=-t*this._sin+i*this._cos,this._transform.d=-s*this._sin+e*this._cos}else this._transform.a=t*this._cos,this._transform.b=e*this._sin,this._transform.c=-t*this._sin,this._transform.d=e*this._cos}if(this._rotation||0!==this._skewX||0!==this._skewY){const{x:t,y:e}=this._origin;this._transform.x=t*-this._transform.a-e*this._transform.b+this._position.x,this._transform.y=t*-this._transform.c-e*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(t,e=t){return this._anchor.set(t,e),this}getLocalBounds(){return this._localBounds}getBounds(){return this.flags.has(Le.BoundsRect)&&(this.updateBounds(),this.flags.remove(Le.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(Le.GlobalTransform)&&(this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this.flags.remove(Le.GlobalTransform)),this._globalTransform}getNormals(){return this.getBounds().getNormals()}project(t,e=new ft){return this.getBounds().project(t,e)}intersectsWith(t){if(this.isAlignedBox)return this.getBounds().intersectsWith(t);switch(t.collisionType){case tt.SceneNode:case tt.Rectangle:case tt.Polygon:return pt(this,t);case tt.Circle:return Pt(this.getBounds(),t);case tt.Ellipse:return At(this.getBounds(),t);case tt.Line:return St(t,this.getBounds());case tt.Point:return yt(t,this.getBounds());default:return!1}}collidesWith(t){if(this.isAlignedBox)return this.getBounds().collidesWith(t);switch(t.collisionType){case tt.SceneNode:case tt.Rectangle:case tt.Polygon:case tt.Circle:return Xt(this,t);default:return null}}contains(t,e){if(this.isAlignedBox)return this.getBounds().contains(t,e);const i=this.getGlobalTransform(),s=i.a*i.d-i.b*i.c;if(0===s)return!1;const n=t-i.x,r=e-i.y,o=(i.d*n-i.b*r)/s,a=(i.a*r-i.c*n)/s;return this.getLocalBounds().contains(o,a)}inView(t){return!this._cullable||t.getBounds().intersectsWith(this.getBounds())}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()}_setStage(t){this._stage=t}_getStage(){return this._stage}_onObservableChange(t){switch(t){case Ue.Position:this._setPositionDirty();break;case Ue.Scale:this._setScalingDirty();break;case Ue.Origin:this._setOriginDirty();break;case Ue.Anchor:this._updateOrigin()}}_invalidateSubtreeTransform(){this.flags.push(Le.GlobalTransform|Le.BoundsRect),this._invalidateChildrenTransform()}_invalidateChildrenTransform(){}_invalidateBoundsCascade(){this.flags.push(Le.BoundsRect),this._stage?.interaction._notifyBoundsInvalidated(this);let t=this._parentNode;for(;null!==t&&!t.flags.has(Le.BoundsRect);)t.flags.push(Le.BoundsRect),t._stage?.interaction._notifyBoundsInvalidated(t),t=t.parent}_setPositionDirty(){this.flags.push(Le.Translation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setRotationDirty(){this.flags.push(Le.Rotation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setScalingDirty(){this.flags.push(Le.Scaling),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setOriginDirty(){this.flags.push(Le.Origin),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setSkewDirty(){this.flags.push(Le.Skew),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_updateOrigin(){const{x:t,y:e}=this._anchor,{width:i,height:s}=this.getBounds();this.setOrigin(i*t,s*e)}}!function(t){t[t.Draw=0]="Draw",t[t.Group=1]="Group",t[t.Barrier=2]="Barrier"}(Fe||(Fe={}));const Ne=new WeakMap,Oe=new WeakMap,Ve=new WeakMap,ze=new WeakMap;let qe=1,Ye=1,We=1;const $e=(t,e,i)=>{const s=t.get(e);if(void 0!==s)return s;const n=i();return t.set(e,n),n},Xe=t=>t.material??null,je=(t,e,i)=>{const s=((t,e)=>{const i=e?.rendererRegistry;if(i&&"function"==typeof i.resolve)try{const e=i.resolve(t);if(e&&"object"==typeof e)return $e(Ne,e,()=>qe++)}catch{}const s=t.constructor;return s&&"function"==typeof s?$e(Oe,s,()=>qe++):0})(e,i),n=e.blendMode,r=(t=>{const e=t.texture;return e&&"object"==typeof e?$e(Ve,e,()=>Ye++):-1})(e),o=(t=>{const e=t.shader;return e&&"object"==typeof e?$e(ze,e,()=>We++):-1})(e),a=Xe(e);return t.rendererId=s,t.blendMode=n,t.textureId=r,t.shaderId=o,t.pipelineKey=null!==a?a.pipelineKey:31*s+n,t.bindKey=null!==a?a.bindKey:31*s+(r>0?r:0),t},He=(t,e)=>{const i=e.rendererRegistry;if(!i||"function"!=typeof i.resolve)return!0;try{return!1!==i.resolve(t.drawable)._consumesSharedTransform}catch{return!0}};class Ke{passes=[];nodeCount=0;reset(){this.passes.length=0,this.nodeCount=0}}var Qe;!function(t){t[t.None=0]="None",t[t.Rect=1]="Rect",t[t.Stencil=2]="Stencil"}(Qe||(Qe={}));class Ze{static _available=[];static _active=[];static acquire(){const t=Ze._available.pop()??new Ze;return Ze._active.push(t),t}static release(t){const e=Ze._active.lastIndexOf(t);-1!==e&&(Ze._active.splice(e,1),t._resetRuntimeState(),Ze._available.push(t))}backend;_view=null;_plan=new Ke;_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(t,e){this.backend=e,this._view=null,this._plan.reset(),this._groupPoolCursor=0,this._commandPoolCursor=0,this._drawEntryPoolCursor=0,this._groupEntryPoolCursor=0,this._barrierEntryPoolCursor=0,this._scopeStack.length=0,this._hasPending=!1,this._nodeIndex=0;const i=this._acquireGroupScope(!1);return this._scopeStack.push(i),t._collect(this),this._scopeStack.pop(),i.entries.length>0&&this._plan.passes.push({target:null,view:this.view,clearColor:null,root:i}),this._plan.nodeCount=this._nodeIndex,this._plan}get view(){return null===this._view&&(this._view=this.backend.view),this._view}emitNode(t,e){this._reserveEntryPlacement(e,t.zIndex);const i=this._reservedSeq,s=this._reservedZ;if(t._renderPlanHasBarrierEffects()){const e=this._createEffectDescriptor(t),n=null!==e.maskSource&&!(e.maskSource instanceof Zt);let r=0,o=0,a=0,h=0;if(e.cacheAsBitmap||e.filters.length>0||n){const e=t.getBounds();if(e.width<=0||e.height<=0)return;r=Math.floor(e.left),o=Math.floor(e.top),a=Math.max(1,Math.ceil(e.width)),h=Math.max(1,Math.ceil(e.height))}const l=e.cacheAsBitmap&&t._renderPlanCanReuseBitmapCache(r,o,a,h)?null:this._acquireGroupScope(this._resolvePreserveDrawOrder(t)),u={kind:Fe.Barrier,node:t,effect:e,childPlan:l,left:r,top:o,width:a,height:h};if(this._pushBarrierEntry(i,s,u),null!==l){this._scopeStack.push(l);try{t._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}return}if(t._isDrawableForRenderPlan()){this._hasPending=!0,this._pendingSeq=i,this._pendingZ=s;try{t._collectForRenderPlan(this)}finally{this._hasPending=!1}return}const n=this._acquireGroupScope(this._resolvePreserveDrawOrder(t));this._pushGroupEntry(i,s,n),this._scopeStack.push(n);try{t._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}emitDraw(t,e){const i=this._hasPending,s=this._pendingSeq,n=this._pendingZ;i&&(this._hasPending=!1);const r=i?n:t.zIndex;this._reserveEntryPlacement(e??(i?s:void 0),r);const o=this._reservedSeq,a=this._reservedZ,h=t.getBounds(),l=this._acquireDrawCommand();l.drawable=t,l.nodeIndex=this._nodeIndex++,l.seq=o,l.zIndex=a,l.groupIndex=void 0,l.material=t._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(t){const e=this._groupPool[this._groupPoolCursor]??{kind:Fe.Group,entries:[],hasMixedZ:!1,preserveDrawOrder:!1,_nextSeq:0,firstZ:null};return this._groupPool[this._groupPoolCursor]=e,this._groupPoolCursor++,e.entries.length=0,e.hasMixedZ=!1,e.preserveDrawOrder=t,e._nextSeq=0,e.firstZ=null,e}_acquireDrawCommand(){const t=this._commandPool[this._commandPoolCursor];if(void 0!==t)return this._commandPoolCursor++,t;const e={kind:Fe.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]=e,this._commandPoolCursor++,e}_pushDrawEntry(t,e,i){let s=this._drawEntryPool[this._drawEntryPoolCursor];void 0===s?(s={kind:Fe.Draw,seq:t,zIndex:e,command:i},this._drawEntryPool[this._drawEntryPoolCursor]=s):(s.seq=t,s.zIndex=e,s.command=i),this._drawEntryPoolCursor++,this._currentScope().entries.push(s)}_pushGroupEntry(t,e,i){let s=this._groupEntryPool[this._groupEntryPoolCursor];void 0===s?(s={kind:Fe.Group,seq:t,zIndex:e,scope:i},this._groupEntryPool[this._groupEntryPoolCursor]=s):(s.seq=t,s.zIndex=e,s.scope=i),this._groupEntryPoolCursor++,this._currentScope().entries.push(s)}_pushBarrierEntry(t,e,i){let s=this._barrierEntryPool[this._barrierEntryPoolCursor];void 0===s?(s={kind:Fe.Barrier,seq:t,zIndex:e,scope:i},this._barrierEntryPool[this._barrierEntryPoolCursor]=s):(s.seq=t,s.zIndex=e,s.scope=i),this._barrierEntryPoolCursor++,this._currentScope().entries.push(s)}_reserveEntryPlacement(t,e){const i=this._currentScope(),s=t??i._nextSeq;s>=i._nextSeq&&(i._nextSeq=s+1),null===i.firstZ?i.firstZ=e:i.hasMixedZ||i.firstZ===e||(i.hasMixedZ=!0),this._reservedSeq=s,this._reservedZ=e}_currentScope(){const t=this._scopeStack[this._scopeStack.length-1];if(!t)throw new Error("RenderPlanBuilder scope stack is empty.");return t}_resolvePreserveDrawOrder(t){return t.preserveDrawOrder}_createEffectDescriptor(t){const e=t._renderPlanGetMaskSource();let i=Qe.None,s=null;if(t.clip){const e=t.clipShape;null===e||e instanceof Zt?(i=Qe.Rect,s=e):(i=Qe.Stencil,s=e)}return{filters:t._renderPlanGetFilters(),clip:i,clipShape:s,maskSource:e,cacheAsBitmap:t.cacheAsBitmap,blendMode:t._renderPlanGetBlendMode()}}}const Je=t=>`${t.pipelineKey}:${t.bindKey}`,ti=(t,e)=>t.minX<e.maxX&&t.maxX>e.minX&&t.minY<e.maxY&&t.maxY>e.minY;class ei{static optimize(t){for(const e of t.passes)this._optimizeGroup(e.root)}static _optimizeGroup(t){if(t.hasMixedZ){const e=t.entries.map((t,e)=>({entry:t,index:e}));e.sort((t,e)=>t.entry.zIndex-e.entry.zIndex||t.entry.seq-e.entry.seq||t.index-e.index);for(let i=0;i<e.length;i++)t.entries[i]=e[i].entry}this._applyMaterialGrouping(t);for(const e of t.entries)e.kind===Fe.Group?this._optimizeGroup(e.scope):e.kind===Fe.Barrier&&null!==e.scope.childPlan&&this._optimizeGroup(e.scope.childPlan)}static _applyMaterialGrouping(t){const e=t.entries,i=e.length;if(0===i)return;let s=0;for(let n=0;n<=i;n++){const r=n<i?e[n]:null,o=null===r||r.kind===Fe.Group||r.kind===Fe.Barrier;if(o&&n>s){const i=n;i-s>=1&&this._materialGroupSegment(e,s,i,t.preserveDrawOrder),s=n+1}else o&&(s=n+1)}this._assignGroupIndices(t)}static _assignGroupIndices(t){let e=1,i=null,s=null;for(const n of t.entries){if(n.kind!==Fe.Draw){i=null,s=null;continue}const t=Je(n.command.material),r=n.zIndex;null!==i&&null!==s&&t===i&&r===s||(e++,i=t,s=r),n.command.groupIndex=e}}static _materialGroupSegment(t,e,i,s){if(i-e<=1)return;const n=[];for(let s=e;s<i;s++){const e=t[s];e.kind===Fe.Draw&&n.push({entry:e,origIdx:s})}if(!(n.length<=1||s)){const s=new Map;for(const t of n){const e=t.entry.zIndex,i=s.get(e)??[];i.push(t),s.set(e,i)}for(const n of s.values())n.length>1&&this._overlapAwareGroup(n,t,e,i)}}static _overlapAwareGroup(t,e,i,s){const n=new Map;for(const e of t){const t=Je(e.entry.command.material),i=n.get(t)??[];i.push(e),n.set(t,i)}if(n.size<=1)return;const r=new Map;for(let t=i;t<s;t++)r.set(e[t],t);for(const t of n.values()){if(t.length<=1)continue;const n=[];for(const e of t){const t=r.get(e.entry);void 0!==t&&n.push(t)}if(n.sort((t,e)=>t-e),0===n.length)continue;const o=n[0],a=n[n.length-1];if(a-o+1===n.length)continue;let h=!1;for(let i=o+1;i<a&&!h;i++){const s=e[i];if(s.kind!==Fe.Draw)continue;if(Je(s.command.material)!==Je(t[0].entry.command.material))for(const e of t)if(ti(e.entry.command,s.command)){h=!0;break}}if(h)continue;const l=[];for(let t=i;t<o;t++)l.push(e[t]);const u=[];for(let t=a+1;t<s;t++)u.push(e[t]);const c=new Set(t.map(t=>t.entry)),d=[];for(let t=o;t<=a;t++){const i=e[t];c.has(i)||d.push(i)}const _=t.map(t=>t.entry),f=[...l,..._,...d,...u];for(let t=i;t<s;t++)e[t]=f[t-i];break}}}class ii extends o{_callback;constructor(t,e=0,i=0){super(e,i),this._callback=t}get width(){return this._width}set width(t){this._width!==t&&(this._width=t,this._callback())}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this._callback())}set(t=this._width,e=this._height){return this._width===t&&this._height===e||(this._width=t,this._height=e,this._callback()),this}add(t,e=t){return this.set(this._width+t,this._height+e)}subtract(t,e=t){return this.set(this._width-t,this._height-e)}scale(t,e=t){return this.set(this._width*t,this._height*e)}divide(t,e=t){return this.set(this._width/t,this._height/e)}copy(t){return this.set(t.width,t.height)}clone(){return new ii(this._callback,this._width,this._height)}}var si,ni,ri,oi,ai,hi,li,ui;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint"}(si||(si={}));class ci{_center;_size;_viewport=new Zt(0,0,1,1);_transform=new De;_inverseTransform=new De;_bounds=new Ie;_flags=new Re;_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,e,i,s){this._center=new Ht(this,0,t,e),this._size=new ii(this._setScalingDirty.bind(this),i,s),this._zoomBaseWidth=i,this._zoomBaseHeight=s,this._flags.push(si.Transform,si.TransformInverse,si.BoundingBox)}_onObservableChange(){this._setPositionDirty()}get center(){return this._center}set center(t){this._center.copy(t)}get size(){return this._size}set size(t){this._size.copy(t)}get width(){return this._size.width}set width(t){this._size.width=t}get height(){return this._size.height}set height(t){this._size.height=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get viewport(){return this._viewport}set viewport(t){this._viewport.equals(t)||(this._viewport.copy(t),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(t,e){return this._center.set(t,e),this}resize(t,e){return this._zoomBaseWidth=t,this._zoomBaseHeight=e,this._zoomLevel=1,this._size.set(t,e),this}setRotation(t){const e=V(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}move(t,e){return this.setCenter(this._center.x+t,this._center.y+e),this}zoom(t){return this.resize(this._size.width*t,this._size.height*t),this}setZoom(t){const e=Math.max(1e-4,t);return this._zoomLevel=e,this._size.set(this._zoomBaseWidth/e,this._zoomBaseHeight/e),this}zoomIn(t=.1){return this.setZoom(this._zoomLevel+t)}zoomOut(t=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-t))}follow(t,e={}){return this._followTarget=t,this._followLerp=q(e.lerp??1,0,1),this._followOffsetX=e.offsetX??0,this._followOffsetY=e.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(t){return null===t?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=t.clone():this._boundsConstraint.copy(t),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(t,e,i={}){return this._shakeIntensity=Math.max(0,t),this._shakeDurationMs=Math.max(0,e),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(t){return this._updateFollowTarget(),this._updateShake(t),this._applyBoundsConstraint(),this}rotate(t){return this.setRotation(this._rotation+t),this}reset(t,e,i,s){return this._zoomBaseWidth=i,this._zoomBaseHeight=s,this._zoomLevel=1,this._size.set(i,s),this._center.set(t,e),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(si.Transform),this}getTransform(){return this._flags.has(si.Transform)&&(this.updateTransform(),this._flags.remove(si.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=2/this.width,s=-2/this.height;if(this._flags.has(si.Rotation)){const t=z(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}return this._flags.has(si.Rotation|si.Scaling)&&(this._transform.a=i*this._cos,this._transform.b=i*this._sin,this._transform.c=-s*this._sin,this._transform.d=s*this._cos),this._transform.x=i*-this._transform.a-s*this._transform.b+-i*t,this._transform.y=i*-this._transform.c-s*this._transform.d+-s*e,this}getInverseTransform(){return this._flags.has(si.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(si.TransformInverse)),this._inverseTransform}screenToWorld(t,e,i,s){let n,r;if(void 0===i||void 0===s){n=t/(this.width||1)*2-1,r=1-e/(this.height||1)*2}else{const o=this._viewport.width*i,a=this._viewport.height*s;n=(t-this._viewport.x*i)/o*2-1,r=1-(e-this._viewport.y*s)/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=n-o.x,l=r-o.y;return{x:(h*o.d-l*o.b)/a,y:(l*o.a-h*o.c)/a}}worldToScreen(t,e,i,s){const n=this.getTransform(),r=n.a*t+n.b*e+n.x,o=n.c*t+n.d*e+n.y;if(void 0===i||void 0===s)return{x:(r+1)/2*this.width,y:(1-o)/2*this.height};const a=this._viewport.x*i,h=this._viewport.y*s;return{x:a+(r+1)/2*this._viewport.width*i,y:h+(1-o)/2*this._viewport.height*s}}getBounds(){return this._flags.has(si.BoundingBox)&&(this.updateBounds(),this._flags.remove(si.BoundingBox)),this._bounds.getRect()}updateBounds(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=this.width/2,s=this.height/2;return this._bounds.reset().addCoords(t-i,e-s).addCoords(t+i,e+s),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(si.TransformInverse,si.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(si.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(si.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(si.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;let t,e;if(this._followTarget instanceof Ge){const i=this._followTarget.getGlobalTransform();t=i.x+this._followOffsetX,e=i.y+this._followOffsetY}else t=this._followTarget.x+this._followOffsetX,e=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(t,e):this.setCenter(this._center.x+(t-this._center.x)*this._followLerp,this._center.y+(e-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const t=this._boundsConstraint,e=this.width/2,i=this.height/2,s=t.left+e,n=t.right-e,r=t.top+i,o=t.bottom-i,a=s>n?(t.left+t.right)/2:q(this._center.x,s,n),h=r>o?(t.top+t.bottom)/2:q(this._center.y,r,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(t){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,t));const e=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-e):this._shakeIntensity;this._shakePhase+=Math.max(0,t)/1e3*this._shakeFrequency*Math.PI*2;const s=Math.sin(1.7*this._shakePhase)*i,n=Math.cos(1.3*this._shakePhase)*i;s===this._shakeOffsetX&&n===this._shakeOffsetY||(this._shakeOffsetX=s,this._shakeOffsetY=n,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}class di{needsStencil=!1;_root;_destroyListeners=new Set;_version=0;_size;_viewport=new Zt;_defaultView;_view;constructor(t,e,i=!1){this._size=new o(t,e),this._root=i,this._defaultView=new ci(t/2,e/2,t,e),this._view=this._defaultView}get view(){return this._view}set view(t){this.setView(t)}get size(){return this._size}set size(t){this.resize(t.width,t.height)}get width(){return this._size.width}set width(t){this.resize(t,this.height)}get height(){return this._size.height}set height(t){this.resize(this.width,t)}get root(){return this._root}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setView(t){const e=t||this._defaultView;return this._view!==e&&(this._view=e,this._touch()),this}resize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}getViewport(t=this._view){const{x:e,y:i,width:s,height:n}=t.viewport;return this._viewport.set(Math.round(e*this.width),Math.round(i*this.height),Math.round(s*this.width),Math.round(n*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(t,e=this._view){const i=this.getViewport(e);return new te(2*(t.x-i.left)/i.width-1,1-2*(t.y-i.top)/i.height).transform(e.getInverseTransform())}mapCoordsToPixel(t,e=this._view){const i=this.getViewport(e),s=t.clone().transform(e.getTransform());return s.set((s.x+1)/2*i.width+i.left|0,(1-s.y)/2*i.height+i.top|0)}destroy(){for(const t of[...this._destroyListeners])t();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}!function(t){t[t.Normal=0]="Normal",t[t.Additive=1]="Additive",t[t.Subtract=2]="Subtract",t[t.Multiply=3]="Multiply",t[t.Screen=4]="Screen",t[t.Darken=5]="Darken",t[t.Lighten=6]="Lighten"}(ni||(ni={})),function(t){t[t.Nearest=9728]="Nearest",t[t.Linear=9729]="Linear",t[t.NearestMipmapNearest=9984]="NearestMipmapNearest",t[t.LinearMipmapNearest=9985]="LinearMipmapNearest",t[t.NearestMipmapLinear=9986]="NearestMipmapLinear",t[t.LinearMipmapLinear=9987]="LinearMipmapLinear"}(ri||(ri={})),function(t){t[t.Repeat=10497]="Repeat",t[t.ClampToEdge=33071]="ClampToEdge",t[t.MirroredRepeat=33648]="MirroredRepeat"}(oi||(oi={})),function(t){t[t.Points=0]="Points",t[t.Lines=1]="Lines",t[t.LineLoop=2]="LineLoop",t[t.LineStrip=3]="LineStrip",t[t.Triangles=4]="Triangles",t[t.TriangleStrip=5]="TriangleStrip",t[t.TriangleFan=6]="TriangleFan"}(ai||(ai={})),function(t){t[t.ArrayBuffer=34962]="ArrayBuffer",t[t.ElementArrayBuffer=34963]="ElementArrayBuffer",t[t.CopyReadBuffer=36662]="CopyReadBuffer",t[t.CopyWriteBuffer=36663]="CopyWriteBuffer",t[t.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",t[t.UniformBuffer=35345]="UniformBuffer",t[t.PixelPackBuffer=35051]="PixelPackBuffer",t[t.PixelUnpackBuffer=35052]="PixelUnpackBuffer"}(hi||(hi={})),function(t){t[t.StaticDraw=35044]="StaticDraw",t[t.StaticRead=35045]="StaticRead",t[t.StaticCopy=35046]="StaticCopy",t[t.DynamicDraw=35048]="DynamicDraw",t[t.DynamicRead=35049]="DynamicRead",t[t.DynamicCopy=35050]="DynamicCopy",t[t.StreamDraw=35040]="StreamDraw",t[t.StreamRead=35041]="StreamRead",t[t.StreamCopy=35042]="StreamCopy"}(li||(li={})),function(t){t[t.Int=5124]="Int",t[t.IntVec2=35667]="IntVec2",t[t.IntVec3=35668]="IntVec3",t[t.IntVec4=35669]="IntVec4",t[t.UnsignedInt=5125]="UnsignedInt",t[t.UnsignedIntVec2=36294]="UnsignedIntVec2",t[t.UnsignedIntVec3=36295]="UnsignedIntVec3",t[t.UnsignedIntVec4=36296]="UnsignedIntVec4",t[t.Float=5126]="Float",t[t.FloatVec2=35664]="FloatVec2",t[t.FloatVec3=35665]="FloatVec3",t[t.FloatVec4=35666]="FloatVec4",t[t.Bool=35670]="Bool",t[t.BoolVec2=35671]="BoolVec2",t[t.BoolVec3=35672]="BoolVec3",t[t.BoolVec4=35673]="BoolVec4",t[t.FloatMat2=35674]="FloatMat2",t[t.FloatMat3=35675]="FloatMat3",t[t.FloatMat4=35676]="FloatMat4",t[t.Sampler2D=35678]="Sampler2D"}(ui||(ui={}));class _i extends di{static defaultSamplerOptions={scaleMode:ri.Linear,wrapMode:oi.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};_source=null;_textureVersion=0;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;constructor(t,e,i){super(t,e,!1);const{scaleMode:s,wrapMode:n,premultiplyAlpha:r,generateMipMap:o,flipY:a}={..._i.defaultSamplerOptions,...i};this._scaleMode=s,this._wrapMode=n,this._premultiplyAlpha=r,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(t){this.setSource(t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return W(this.width)&&W(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touchTexture()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touchTexture()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touchTexture()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._defaultView.resize(t,e),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}const fi=(t={})=>{const{canvas:e,fillStyle:i,width:s,height:n}=t,r=e??document.createElement("canvas"),o=r.getContext("2d");return r.width=s??10,r.height=n??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,r.width,r.height),r};class pi{static _black=null;static _white=null;static defaultSamplerOptions={scaleMode:ri.Linear,wrapMode:oi.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 o(0,0);_destroyListeners=new Set;_scaleMode;_wrapMode;_premultiplyAlpha=!1;_generateMipMap=!1;_flipY=!1;constructor(t=null,e){const{scaleMode:i,wrapMode:s,premultiplyAlpha:n,generateMipMap:r,flipY:o}={...pi.defaultSamplerOptions,...e};this._scaleMode=i,this._wrapMode=s,this._premultiplyAlpha=n,this._generateMipMap=r,this._flipY=o,null!==t&&this.setSource(t)}get source(){return this._source}set source(t){this.setSource(t)}get size(){return this._size}set size(t){this.setSize(t.width,t.height)}get width(){return this._size.width}set width(t){this.setSize(t,this.height)}get height(){return this._size.height}set height(t){this.setSize(this.width,t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return W(this.width)&&W(this.height)}get version(){return this._version}_bumpVersion(){this._version++}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touch()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touch()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touch()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){const{width:t,height:e}=null===(i=this._source)?o.zero:p(i);var i;return this.setSize(t,e),this._touch(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}destroy(){for(const t of[...this._destroyListeners])t();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}class gi{static play(t,e,i){const{node:s,effect:n}=t,r=n.filters.length>0,o=n.cacheAsBitmap,{left:a,top:h,width:l,height:u}=t;if(!r&&!o)return void this._withClip(s,e,t,()=>{null!==t.childPlan&&i(t.childPlan)});if(o&&null===t.childPlan){const i=s._renderPlanGetCacheTexture();return void(null!==i&&this._withClip(s,e,t,()=>{s._renderPlanDrawTexture(e,i,a,h,l,u,n.blendMode)}))}const c=o?s._renderPlanEnsureCacheTexture(l,u):null;let d=null;try{const _=o&&!r?c:e.acquireRenderTexture(l,u);_!==c&&(d=_),s._renderPlanRenderToTexture(e,_,a,h,l,u,()=>{null!==t.childPlan&&i(t.childPlan)});let f=_;if(r)for(let t=0;t<n.filters.length;t++){const i=t===n.filters.length-1&&o?c:e.acquireRenderTexture(l,u);try{n.filters[t].apply(e,f,i)}catch(t){throw i!==c&&e.releaseRenderTexture(i),t}null!==d&&(e.releaseRenderTexture(d),d=null),f=i,i!==c&&(d=i)}o&&s._renderPlanStoreCacheTexture(c,a,h,l,u),this._withClip(s,e,t,()=>{s._renderPlanDrawTexture(e,f,a,h,l,u,n.blendMode)})}finally{null!==d&&e.releaseRenderTexture(d)}}static _withClip(t,e,i,s){if(i.effect.clip!==Qe.Stencil)this._withRectClip(t,e,i,s);else{e.pushStencilClip(i.effect.clipShape,t.getGlobalTransform());try{this._withRectClip(t,e,i,s)}finally{e.popStencilClip()}}}static _withRectClip(t,e,i,s){if(i.effect.clip===Qe.Rect){const n=i.effect.clipShape??t.getBounds();if(n.width<=0||n.height<=0)return;e.pushScissorRect(n);try{this._withMask(t,e,i,s)}finally{e.popScissorRect()}return}this._withMask(t,e,i,s)}static _withMask(t,e,i,s){const n=i.effect.maskSource;if(null===n)return void s();if(n instanceof Zt){if(n.width<=0||n.height<=0)return;e.pushScissorRect(n);try{s()}finally{e.popScissorRect()}return}const r=e.acquireRenderTexture(i.width,i.height),o=[r];try{t._renderPlanRenderToTexture(e,r,i.left,i.top,i.width,i.height,s);const a=this._resolveMaskTexture(t,e,n,i,o);e.composeWithAlphaMask(r,a,i.left,i.top,i.width,i.height,i.effect.blendMode)}finally{for(const t of o)e.releaseRenderTexture(t)}}static _resolveMaskTexture(t,e,i,s,n){if(!(i instanceof pi||i instanceof _i)){const r=e.acquireRenderTexture(s.width,s.height);return n.push(r),t._renderPlanRenderToTexture(e,r,s.left,s.top,s.width,s.height,()=>{i.render(e)}),r}return i}}const mi=(t,e)=>{const i=t[e].command.groupIndex;if(void 0===i)return 1;let s=1;for(let n=e+1;n<t.length;n++){const e=t[n];if(e.kind!==Fe.Draw||e.command.groupIndex!==i)break;s++}return s};class yi{static play(t,e){const i=e;i._beginDrawPlan?.(t.nodeCount);try{for(const s of t.passes)null!==s.target&&e.renderTarget!==s.target&&e.setRenderTarget(s.target),e.view!==s.view&&e.setView(s.view),null!==s.clearColor&&e.clear(s.clearColor),this._playScope(s.root,e,i,this._createPlaybackContext())}finally{i._endDrawPlan?.()}}static playScope(t,e){const i=e;this._playScope(t,e,i,this._createPlaybackContext())}static _playScope(t,e,i,s){t.kind!==Fe.Barrier?this._playGroup(t,e,i,s):gi.play(t,e,t=>{this._playScope(t,e,i,s)})}static _playGroup(t,e,i,s){const n=t.entries;if(void 0!==i._prepareRenderGroupUpload){let t=s.passInstructionIndex,e=0;for(let r=0;r<n.length;){if(n[r].kind!==Fe.Draw){r++;continue}const o=mi(n,r);i._prepareRenderGroupUpload(n,r,o,this._createRenderGroupPlaybackContext(o,t,s.passGroupIndex+e)),t+=o,e++,r+=o}}let r=-1,o=0,a=0;for(let t=0;t<n.length;t++){const h=n[t];if(h.kind===Fe.Draw){if(-1===r&&(r=t,o=mi(n,t),a=0,i._beginRenderGroup?.(n,r,o),s.passGroupIndex++),void 0!==i._prepareRenderInstructionSlot){const t=this._createRenderInstructionSlot(a,s.passInstructionIndex);i._prepareRenderInstructionSlot(h.command,t)}i._prepareDrawCommand?.(h.command),e.draw(h.command.drawable),a++,s.passInstructionIndex++,a===o&&(i._endRenderGroup?.(n,r,o),r=-1,o=0,a=0)}else h.kind===Fe.Group?this._playGroup(h.scope,e,i,s):gi.play(h.scope,e,t=>{this._playScope(t,e,i,s)})}}static _createPlaybackContext(){return{passInstructionIndex:0,passGroupIndex:0}}static _createRenderGroupPlaybackContext(t,e,i){return Object.freeze({groupInstructionCount:t,firstPassInstructionIndex:e,lastPassInstructionIndex:e+t-1,passGroupIndex:i})}static _createRenderInstructionSlot(t,e){return Object.freeze({groupInstructionIndex:t,passInstructionIndex:e})}}function wi(t,e){const i=Ze.acquire();try{const s=i.build(t,e);ei.optimize(s),yi.play(s,e)}finally{Ze.release(i)}}var xi;!function(t){t[t.None=0]="None",t[t.Enabled=1]="Enabled"}(xi||(xi={}));class vi{_callback;_target;_view;_clearColor;constructor(t,e={}){this._callback=t,this._target=e.target??null,this._view=e.view??null,this._clearColor=e.clearColor??null}execute(t){const e=t._passCoordinator;if(e)return void e.withChildPass({target:this._target,view:this._view,load:null!==this._clearColor?"clear":"load",clearColor:this._clearColor,stencil:xi.None},()=>{this._callback(t)});const i=t.renderTarget,s=t.view;t.setRenderTarget(this._target),t.setView(this._view),null!==this._clearColor&&t.clear(this._clearColor);try{this._callback(t)}finally{t.setRenderTarget(i),t.setView(s)}}}const bi=t=>"destroy"in t&&"function"==typeof t.destroy;class Si extends Ge{static _spriteFactory=null;_interactive=!1;cursor=null;get interactive(){return this._interactive}set interactive(t){this._interactive!==t&&(this._interactive=t,this._stage?.interaction._notifyInteractiveChanged(this,t))}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(t){const e=this._signals??=new Map;let i=e.get(t);return void 0===i&&(i=new m,e.set(t,i)),i}_peekInteractionSignal(t){return this._signals?.get(t)??null}focusable=!1;tabIndex=0;_onFocus=null;_onBlur=null;_onKeyDown=null;_onKeyUp=null;get onFocus(){return this._onFocus??=new m}get onBlur(){return this._onBlur??=new m}get onKeyDown(){return this._onKeyDown??=new m}get onKeyUp(){return this._onKeyUp??=new m}_peekFocusSignal(t){return"focus"===t?this._onFocus:this._onBlur}_peekKeySignal(t){return"keydown"===t?this._onKeyDown:this._onKeyUp}focus(){return this._stage?.focus.focus(this),this}blur(){return this._stage?.focus.blur(this),this}_filters=[];_cacheBounds=new Zt;_cacheSprite=null;_captureView=null;_mask=null;_cacheAsBitmap=!1;_cacheDirty=!0;_cacheTexture=null;get filters(){return this._filters}set filters(t){this._filters.length=0,this._filters.push(...t),this.invalidateCache()}get mask(){return this._mask}set mask(t){if(t===this)throw new Error("A RenderNode cannot use itself as its own mask source.");this._mask!==t&&(this._mask=t,this.invalidateCache())}render(t){return wi(this,t),this}_collect(t,e){this.visible&&(this.inView(t.view)?t.emitNode(this,e):t.backend.stats.culledNodes++)}_collectForRenderPlan(t){this._collectContent(t)}_isDrawableForRenderPlan(){return!1}_collectContent(t){}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(t){this._cacheAsBitmap!==t&&(this._cacheAsBitmap=t,this.invalidateCache(),t||this._destroyCacheTexture())}addFilter(t){return this._filters.push(t),this.invalidateCache()}removeFilter(t){const e=this._filters.indexOf(t);return-1!==e&&(this._filters.splice(e,1),this.invalidateCache()),this}static setInternalSpriteFactory(t){Si._spriteFactory=t}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}_renderPlanGetMaskSource(){return this._mask}_renderPlanGetFilters(){return this._filters}_renderPlanGetBlendMode(){return ni.Normal}_renderPlanCanReuseBitmapCache(t,e,i,s){return this._cacheAsBitmap&&!this._cacheDirty&&null!==this._cacheTexture&&this._cacheBounds.equals({x:t,y:e,width:i,height:s})}_renderPlanGetCacheTexture(){return this._cacheTexture}_renderPlanEnsureCacheTexture(t,e){return this._ensureCacheTexture(t,e)}_renderPlanStoreCacheTexture(t,e,i,s,n){this._cacheTexture=t,this._cacheBounds.set(e,i,s,n),this._cacheDirty=!1}_renderPlanRenderToTexture(t,e,i,s,n,r,o){this._renderContentToTexture(t,e,i,s,n,r,o)}_renderPlanDrawTexture(t,e,i,s,n,r,o){this._drawTexture(t,e,i,s,n,r,o)}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const t of this._filters)bi(t)&&t.destroy();if(this._filters.length=0,this._mask=null,null!==this._signals){for(const t of this._signals.values())t.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(t,e,i,s,n,r,o){null===this._captureView?this._captureView=new ci(i+n/2,s+r/2,n,r):this._captureView.reset(i+n/2,s+r/2,n,r),t.execute(new vi(()=>{o()},{target:e,view:this._captureView,clearColor:Ee.transparentBlack}))}_drawTexture(t,e,i,s,n,r,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(Ee.white).setPosition(i,s).setRotation(0).setScale(1,1),a.width=n,a.height=r,a.render(t)}_ensureCacheTexture(t,e){return null===this._cacheTexture?this._cacheTexture=new _i(t,e):this._cacheTexture.width===t&&this._cacheTexture.height===e||this._cacheTexture.setSize(t,e),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(t){this.scale.x=t/this.getBounds().width}get height(){return Math.abs(this.scale.y)*this.getBounds().height}set height(t){this.scale.y=t/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(...t){for(const e of t)this.addChildAt(e,this._children.length);return this}addChildAt(t,e){if(e<0||e>this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return t===this||(t.parent&&t.parent.removeChild(t),t.parent=this,this._children.splice(e,0,t),this.invalidateCache(),t._invalidateSubtreeTransform(),this._invalidateBoundsCascade(),t._setStage(this._stage),this._stage?.interaction._notifyNodeAdded(t)),this}swapChildren(t,e){if(t!==e){const i=this.getChildIndex(t),s=this.getChildIndex(e);this._children[i]=e,this._children[s]=t,this.invalidateCache()}return this}getChildIndex(t){const e=this._children.indexOf(t);if(-1===e)throw new Error("Drawable is not a child of the container.");return e}setChildIndex(t,e){if(e<0||e>=this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return f(this._children,this.getChildIndex(t),1),this._children.splice(e,0,t),this.invalidateCache(),this}getChildAt(t){if(t<0||t>=this._children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this._children[t]}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&this.removeChildAt(e),this}removeChildAt(t){const e=this._children[t];return f(this._children,t,1),e?.parent===this&&(this._invalidateBoundsCascade(),e.parent=null,e._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(e),this._stage?.focus._notifyNodeRemoved(e),e._setStage(null)),this.invalidateCache(),this}removeChildren(t=0,e=this._children.length){const i=e-t;if(i<0||i>e)throw new Error("Values are outside the acceptable range.");i>0&&this._invalidateBoundsCascade();for(let i=t;i<e;i++){const t=this._children[i];t?.parent===this&&(t.parent=null,t._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(t),this._stage?.focus._notifyNodeRemoved(t),t._setStage(null))}return f(this._children,t,i),this.invalidateCache(),this}_setStage(t){if(this._stage!==t){this._stage=t;for(const e of this._children)e._setStage(t)}}_collectContent(t){if(0!==this._children.length)for(let e=0;e<this._children.length;e++)this._children[e]._collect(t,e)}contains(t,e){const i=this._children;for(let s=0;s<i.length;s++)if(i[s].contains(t,e))return!0;return!1}_invalidateChildrenTransform(){for(const t of this._children)t._invalidateSubtreeTransform()}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const t of this._children)t.visible&&this._bounds.addRect(t.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}}class Ci{type;channel;target;_defaultPrevented=!1;constructor(t,e,i){this.type=t,this.channel=e,this.target=i}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}}var Ti,Mi;!function(t){t[t.Container=768]="Container",t[t.Category=256]="Category",t[t.Gamepad=64]="Gamepad"}(Ti||(Ti={})),function(t){t[t.Keyboard=0]="Keyboard",t[t.Pointers=256]="Pointers",t[t.Gamepads=512]="Gamepads"}(Mi||(Mi={}));const Pi=16,Ai=16;var Ei;!function(t){t[t.Backspace=8]="Backspace",t[t.Tab=9]="Tab",t[t.Clear=12]="Clear",t[t.Enter=13]="Enter",t[t.Shift=16]="Shift",t[t.Control=17]="Control",t[t.Alt=18]="Alt",t[t.Pause=19]="Pause",t[t.CapsLock=20]="CapsLock",t[t.Escape=27]="Escape",t[t.Space=32]="Space",t[t.PageUp=33]="PageUp",t[t.PageDown=34]="PageDown",t[t.End=35]="End",t[t.Home=36]="Home",t[t.Left=37]="Left",t[t.Up=38]="Up",t[t.Right=39]="Right",t[t.Down=40]="Down",t[t.Insert=45]="Insert",t[t.Delete=46]="Delete",t[t.Help=47]="Help",t[t.Zero=48]="Zero",t[t.One=49]="One",t[t.Two=50]="Two",t[t.Three=51]="Three",t[t.Four=52]="Four",t[t.Five=53]="Five",t[t.Six=54]="Six",t[t.Seven=55]="Seven",t[t.Eight=56]="Eight",t[t.Nine=57]="Nine",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.NumPad0=96]="NumPad0",t[t.NumPad1=97]="NumPad1",t[t.NumPad2=98]="NumPad2",t[t.NumPad3=99]="NumPad3",t[t.NumPad4=100]="NumPad4",t[t.NumPad5=101]="NumPad5",t[t.NumPad6=102]="NumPad6",t[t.NumPad7=103]="NumPad7",t[t.NumPad8=104]="NumPad8",t[t.NumPad9=105]="NumPad9",t[t.NumPadMultiply=106]="NumPadMultiply",t[t.NumPadAdd=107]="NumPadAdd",t[t.NumPadEnter=108]="NumPadEnter",t[t.NumPadSubtract=109]="NumPadSubtract",t[t.NumPadDecimal=110]="NumPadDecimal",t[t.NumPadDivide=111]="NumPadDivide",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NumLock=144]="NumLock",t[t.ScrollLock=145]="ScrollLock",t[t.Colon=186]="Colon",t[t.Equals=187]="Equals",t[t.Comma=188]="Comma",t[t.Dash=189]="Dash",t[t.Period=190]="Period",t[t.QuestionMark=191]="QuestionMark",t[t.Tilde=192]="Tilde",t[t.OpenBracket=219]="OpenBracket",t[t.BackwardSlash=220]="BackwardSlash",t[t.ClosedBracket=221]="ClosedBracket",t[t.Quotes=222]="Quotes"}(Ei||(Ei={}));class Ri{_app;_focused=null;_shiftDown=!1;_scopeStack=[];_onKeyDownHandler;_onKeyUpHandler;constructor(t){this._app=t,this._onKeyDownHandler=this._handleKeyDown.bind(this),this._onKeyUpHandler=this._handleKeyUp.bind(this),t.input.onKeyDown.add(this._onKeyDownHandler),t.input.onKeyUp.add(this._onKeyUpHandler)}get focused(){return this._focused}focus(t){t!==this._focused&&t.focusable&&(this.blur(),this._focused=t,t._peekFocusSignal("focus")?.dispatch(t))}blur(t){const e=this._focused;null===e||void 0!==t&&t!==e||(this._focused=null,e._peekFocusSignal("blur")?.dispatch(e))}pushScope(t){this._scopeStack.push(t)}popScope(){this._scopeStack.pop()}focusNext(){this._step(1)}focusPrevious(){this._step(-1)}_notifyNodeRemoved(t){let e=this._focused;for(;null!==e;){if(e===t)return void this.blur();e=e.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===Ei.Shift&&(this._shiftDown=!0);const e=this._focused;let i=!1;if(null!==e){const s=new Ci("keydown",t,e);e._peekKeySignal("keydown")?.dispatch(s),i=s.defaultPrevented}i||t!==Ei.Tab||(this._shiftDown?this.focusPrevious():this.focusNext())}_handleKeyUp(t){t===Ei.Shift&&(this._shiftDown=!1);const e=this._focused;null!==e&&e._peekKeySignal("keyup")?.dispatch(new Ci("keyup",t,e))}_step(t){const e=this._collectFocusables();if(0===e.length)return;const i=null===this._focused?-1:e.indexOf(this._focused),s=e.length;let n;n=-1===i?1===t?0:s-1:(i+t+s)%s;const r=e[n];void 0!==r&&this.focus(r)}_collectFocusables(){const t=this._scopeStack.at(-1)??this._app.scene.currentScene?.root??null;if(null===t)return[];const e=[];return this._collectInto(t,e),e.map((t,e)=>({node:t,index:e})).sort((t,e)=>t.node.tabIndex-e.node.tabIndex||t.index-e.index).map(t=>t.node)}_collectInto(t,e){if(t.visible&&(t.focusable&&e.push(t),t instanceof Bi))for(const i of t.children)this._collectInto(i,e)}}let ki=null;class Di{_milliseconds;constructor(t=0,e=Di.milliseconds){this._milliseconds=t*e}get milliseconds(){return this._milliseconds}set milliseconds(t){this._milliseconds=t}get seconds(){return this._milliseconds/Di.seconds}set seconds(t){this._milliseconds=t*Di.seconds}get minutes(){return this._milliseconds/Di.minutes}set minutes(t){this._milliseconds=t*Di.minutes}get hours(){return this._milliseconds/Di.hours}set hours(t){this._milliseconds=t*Di.hours}set(t=0,e=Di.milliseconds){return this._milliseconds=t*e,this}setMilliseconds(t){return this.milliseconds=t,this}setSeconds(t){return this.seconds=t,this}setMinutes(t){return this.minutes=t,this}setHours(t){return this.hours=t,this}equals({milliseconds:t,seconds:e,minutes:i,hours:s}={}){return!(void 0!==t&&this.milliseconds!==t||void 0!==e&&this.seconds!==e||void 0!==i&&this.minutes!==i||void 0!==s&&this.hours!==s)}greaterThan(t){return this._milliseconds>t.milliseconds}lessThan(t){return this._milliseconds<t.milliseconds}clone(){return new Di(this._milliseconds)}copy(t){return this._milliseconds=t.milliseconds,this}add(t=0,e=Di.milliseconds){return this._milliseconds+=t*e,this}addTime(t){return this._milliseconds+=t.milliseconds,this}subtract(t=0,e=Di.milliseconds){return this._milliseconds-=t*e,this}subtractTime(t){return this._milliseconds-=t.milliseconds,this}destroy(){}static milliseconds=1;static seconds=1e3;static minutes=6e4;static hours=36e5;static now(){return new Di(performance.now())}static fromMilliseconds(t){return new Di(t,Di.milliseconds)}static fromSeconds(t){return new Di(t,Di.seconds)}static fromMinutes(t){return new Di(t,Di.minutes)}static fromHours(t){return new Di(t,Di.hours)}static zero=new Di(0);static oneMillisecond=new Di(1);static oneSecond=new Di(1,Di.seconds);static oneMinute=new Di(1,Di.minutes);static oneHour=new Di(1,Di.hours);static get temp(){return null===ki&&(ki=new Di),ki}}class Ii{_startTime;_elapsedTime=new Di(0);_running=!1;constructor(t=Di.zero,e=!1){this._startTime=t.clone(),e&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const t=d();this._elapsedTime.add(t-this._startTime.milliseconds),this._startTime.milliseconds=t}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=d()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(d()-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 Li extends Ii{_limit;constructor(t,e=!1){super(),this._limit=t.clone(),e&&this.restart()}get limit(){return this._limit}set limit(t){this._limit.copy(t)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/Di.seconds}get remainingMinutes(){return this.remainingMilliseconds/Di.minutes}get remainingHours(){return this.remainingMilliseconds/Di.hours}}class Ui{static defaultTriggerThreshold=300;channels;onStart=new m;onActive=new m;onStop=new m;onTrigger=new m;_triggerTimer;_detacher;_value=0;_unbound=!1;constructor(t,e={},i=null){this.channels=t,this._triggerTimer=new Li(Di.fromMilliseconds(e.threshold??Ui.defaultTriggerThreshold)),this._detacher=i}get value(){return this._value}get active(){return this._value>0}update(t){if(this._unbound)return;let e=0;for(const i of this.channels){const s=t[i];void 0!==s&&Math.abs(s)>Math.abs(e)&&(e=s)}this._value=e,0!==e?(this._triggerTimer.running||(this._triggerTimer.restart(),this.onStart.dispatch(e)),this.onActive.dispatch(e)):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 Fi{onConnect=new m;onDisconnect=new m;onButtonDown=new m;onButtonUp=new m;onAxisChange=new m;onPadReassigned=new m;_slot;_channels;_bindings=new Set;_detacher={detach:t=>{this._bindings.delete(t)}};_channelOffset;_mapping=null;_info=null;_browserGamepad=null;constructor(t,e){this._slot=t,this._channels=e,this._channelOffset=Mi.Gamepads+t*Ti.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(t){return this._mapping?.hasChannel(t)??!1}async vibrate(t){const e=this._browserGamepad?.vibrationActuator;e?.playEffect&&await e.playEffect("dual-rumble",{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1,startDelay:t.startDelay??0})}stopVibration(){this._browserGamepad?.vibrationActuator?.reset?.()}onStart(t,e,i){const s=this._createBinding(t,i);return s.onStart.add(e),s}onActive(t,e,i){const s=this._createBinding(t,i);return s.onActive.add(e),s}onStop(t,e,i){const s=this._createBinding(t,i);return s.onStop.add(e),s}onTrigger(t,e,i){const s=this._createBinding(t,i);return s.onTrigger.add(e),s}_bind(t,e){this._browserGamepad=t,this._mapping=e.mapping,this._info={name:e.name,label:e.descriptor.label,vendorId:e.descriptor.vendorId,productId:e.descriptor.productId,productKey:e.descriptor.productKey},this.onConnect.dispatch()}_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(t){const e=t._browserGamepad,i=t._mapping,s=t._info;this._clearMappedChannels(),t._clearMappedChannels(),t._browserGamepad=null,t._mapping=null,t._info=null,this._browserGamepad=e,this._mapping=i,this._info=s}update(){if(null===this._browserGamepad||null===this._mapping)return void this._updateBindings();const t=this._channels,{buttons:e,axes:i}=this._browserGamepad;for(const i of this._mapping.buttons){const s=e[i.index];if(void 0===s)continue;const n=this._resolveOffset(i.channel),r=t[n],o=i.transformValue(s.value)||0;r!==o&&(t[n]=o,0===r&&0!==o?this.onButtonDown.dispatch(i,o):0!==r&&0===o&&this.onButtonUp.dispatch(i,o))}for(const e of this._mapping.axes){const s=i[e.index];if(void 0===s)continue;const n=this._resolveOffset(e.channel),r=t[n],o=e.transformValue(s)||0;r!==o&&(t[n]=o,this.onAxisChange.dispatch(e,o))}this._updateBindings()}destroy(){for(const t of[...this._bindings])t.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(t){return this._resolveOffset(t)}static resolveChannelOffset(t,e){return Mi.Gamepads+t*Ti.Gamepad+(e^Mi.Gamepads)}_resolveOffset(t){return this._channelOffset+(t^Mi.Gamepads)}_clearMappedChannels(){if(null!==this._mapping){for(const t of this._mapping.buttons)this._channels[this._resolveOffset(t.channel)]=0;for(const t of this._mapping.axes)this._channels[this._resolveOffset(t.channel)]=0}}_createBinding(t,e={}){const i=(Array.isArray(t)?t:[t]).map(t=>this._resolveExternalChannel(t)),s=new Ui(i,e,this._detacher);return this._bindings.add(s),s}_resolveExternalChannel(t){return t>=Mi.Gamepads&&t<Mi.Gamepads+Ti.Category?this._resolveOffset(t):t}_updateBindings(){for(const t of this._bindings)t.update(this._channels)}}class Gi{index;channel;invert;threshold;constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.threshold=q(i.threshold??.2,0,1)}transformValue(t){let e=q(t,0,1);return this.invert&&(e=1-e),e>this.threshold?e:0}}const Ni=t=>Mi.Gamepads+t;var Oi;!function(t){t.South=Ni(0),t.East=Ni(1),t.West=Ni(2),t.North=Ni(3),t.LeftShoulder=Ni(4),t.RightShoulder=Ni(5),t.LeftTrigger=Ni(6),t.RightTrigger=Ni(7),t.Select=Ni(8),t.Start=Ni(9),t.LeftStick=Ni(10),t.RightStick=Ni(11),t.DPadUp=Ni(12),t.DPadDown=Ni(13),t.DPadLeft=Ni(14),t.DPadRight=Ni(15),t.Guide=Ni(16),t.Share=Ni(17),t.Capture=Ni(18),t.Touchpad=Ni(19),t.Paddle1=Ni(20),t.Paddle2=Ni(21),t.Paddle3=Ni(22),t.Paddle4=Ni(23)}(Gi||(Gi={})),function(t){t.GenericDualAnalog="genericDualAnalog",t.Xbox="xbox",t.PlayStation="playStation",t.SwitchPro="switchPro",t.JoyConLeft="joyConLeft",t.JoyConRight="joyConRight",t.GameCube="gameCube",t.SteamController="steamController",t.SteamDeck="steamDeck",t.ArcadeStick="arcadeStick"}(Oi||(Oi={}));class Vi{buttons;axes;constructor(t,e){this.buttons=t,this.axes=e}hasChannel(t){for(const e of this.buttons)if(e.channel===t)return!0;for(const e of this.axes)if(e.channel===t)return!0;return!1}destroy(){this.buttons.length=0,this.axes.length=0}}class zi extends Vi{family=Oi.ArcadeStick;constructor(){super([new Gi(0,Gi.South),new Gi(1,Gi.East),new Gi(2,Gi.West),new Gi(3,Gi.North),new Gi(4,Gi.LeftShoulder),new Gi(5,Gi.RightShoulder),new Gi(6,Gi.LeftTrigger),new Gi(7,Gi.RightTrigger),new Gi(8,Gi.Select),new Gi(9,Gi.Start),new Gi(12,Gi.DPadUp),new Gi(13,Gi.DPadDown),new Gi(14,Gi.DPadLeft),new Gi(15,Gi.DPadRight),new Gi(16,Gi.Guide)],[])}}class qi{index;channel;invert;normalize;threshold;bipolar;constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=q(i.threshold??.2,0,1),this.bipolar=i.bipolar??!1}transformValue(t){let e=q(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),this.bipolar?Math.abs(e)>this.threshold?e:0:e>this.threshold?e:0}}const Yi=t=>Mi.Gamepads+t;!function(t){t.LeftStickLeft=Yi(32),t.LeftStickRight=Yi(33),t.LeftStickUp=Yi(34),t.LeftStickDown=Yi(35),t.RightStickLeft=Yi(36),t.RightStickRight=Yi(37),t.RightStickUp=Yi(38),t.RightStickDown=Yi(39),t.LeftStickX=Yi(40),t.LeftStickY=Yi(41),t.RightStickX=Yi(42),t.RightStickY=Yi(43),t.TouchpadX=Yi(44),t.TouchpadY=Yi(45),t.Touchpad2X=Yi(46),t.Touchpad2Y=Yi(47),t.AuxiliaryAxis0Negative=Yi(48),t.AuxiliaryAxis0Positive=Yi(49),t.AuxiliaryAxis1Negative=Yi(50),t.AuxiliaryAxis1Positive=Yi(51),t.AuxiliaryAxis2Negative=Yi(52),t.AuxiliaryAxis2Positive=Yi(53),t.AuxiliaryAxis3Negative=Yi(54),t.AuxiliaryAxis3Positive=Yi(55)}(qi||(qi={}));class Wi extends Vi{family=Oi.GenericDualAnalog;constructor(){super([new Gi(0,Gi.South),new Gi(1,Gi.East),new Gi(2,Gi.West),new Gi(3,Gi.North),new Gi(4,Gi.LeftShoulder),new Gi(5,Gi.RightShoulder),new Gi(6,Gi.LeftTrigger),new Gi(7,Gi.RightTrigger),new Gi(8,Gi.Select),new Gi(9,Gi.Start),new Gi(10,Gi.LeftStick),new Gi(11,Gi.RightStick),new Gi(12,Gi.DPadUp),new Gi(13,Gi.DPadDown),new Gi(14,Gi.DPadLeft),new Gi(15,Gi.DPadRight),new Gi(16,Gi.Guide),new Gi(17,Gi.Share),new Gi(18,Gi.Capture),new Gi(19,Gi.Touchpad),new Gi(20,Gi.Paddle1)],[new qi(0,qi.LeftStickLeft,{invert:!0}),new qi(0,qi.LeftStickRight),new qi(1,qi.LeftStickUp,{invert:!0}),new qi(1,qi.LeftStickDown),new qi(2,qi.RightStickLeft,{invert:!0}),new qi(2,qi.RightStickRight),new qi(3,qi.RightStickUp,{invert:!0}),new qi(3,qi.RightStickDown),new qi(0,qi.LeftStickX,{bipolar:!0}),new qi(1,qi.LeftStickY,{bipolar:!0}),new qi(2,qi.RightStickX,{bipolar:!0}),new qi(3,qi.RightStickY,{bipolar:!0}),new qi(4,qi.AuxiliaryAxis0Negative,{invert:!0}),new qi(4,qi.AuxiliaryAxis0Positive),new qi(5,qi.AuxiliaryAxis1Negative,{invert:!0}),new qi(5,qi.AuxiliaryAxis1Positive),new qi(6,qi.AuxiliaryAxis2Negative,{invert:!0}),new qi(6,qi.AuxiliaryAxis2Positive),new qi(7,qi.AuxiliaryAxis3Negative,{invert:!0}),new qi(7,qi.AuxiliaryAxis3Positive)])}}class $i extends Wi{family=Oi.GameCube}class Xi extends Vi{family=Oi.JoyConLeft;constructor(){super([new Gi(0,Gi.South),new Gi(1,Gi.East),new Gi(2,Gi.West),new Gi(3,Gi.North),new Gi(4,Gi.LeftShoulder),new Gi(5,Gi.RightShoulder),new Gi(8,Gi.Select),new Gi(10,Gi.LeftStick),new Gi(16,Gi.Capture)],[new qi(0,qi.LeftStickLeft,{invert:!0}),new qi(0,qi.LeftStickRight),new qi(1,qi.LeftStickUp,{invert:!0}),new qi(1,qi.LeftStickDown),new qi(0,qi.LeftStickX,{bipolar:!0}),new qi(1,qi.LeftStickY,{bipolar:!0})])}}class ji extends Vi{family=Oi.JoyConRight;constructor(){super([new Gi(0,Gi.South),new Gi(1,Gi.East),new Gi(2,Gi.West),new Gi(3,Gi.North),new Gi(4,Gi.LeftShoulder),new Gi(5,Gi.RightShoulder),new Gi(9,Gi.Start),new Gi(10,Gi.LeftStick),new Gi(16,Gi.Guide)],[new qi(0,qi.LeftStickLeft,{invert:!0}),new qi(0,qi.LeftStickRight),new qi(1,qi.LeftStickUp,{invert:!0}),new qi(1,qi.LeftStickDown),new qi(0,qi.LeftStickX,{bipolar:!0}),new qi(1,qi.LeftStickY,{bipolar:!0})])}}class Hi extends Wi{family=Oi.PlayStation}class Ki extends Wi{family=Oi.SteamController}class Qi extends Vi{family=Oi.SteamDeck;constructor(){super([new Gi(2,Gi.Capture),new Gi(3,Gi.South),new Gi(4,Gi.East),new Gi(5,Gi.West),new Gi(6,Gi.North),new Gi(7,Gi.LeftShoulder),new Gi(8,Gi.RightShoulder),new Gi(11,Gi.Select),new Gi(12,Gi.Start),new Gi(13,Gi.Guide),new Gi(14,Gi.LeftStick),new Gi(15,Gi.RightStick),new Gi(16,Gi.DPadUp),new Gi(17,Gi.DPadDown),new Gi(18,Gi.DPadLeft),new Gi(19,Gi.DPadRight),new Gi(20,Gi.Paddle2),new Gi(21,Gi.Paddle1),new Gi(22,Gi.Paddle4),new Gi(23,Gi.Paddle3)],[new qi(0,qi.LeftStickLeft,{invert:!0}),new qi(0,qi.LeftStickRight),new qi(1,qi.LeftStickUp,{invert:!0}),new qi(1,qi.LeftStickDown),new qi(2,qi.RightStickLeft,{invert:!0}),new qi(2,qi.RightStickRight),new qi(3,qi.RightStickUp,{invert:!0}),new qi(3,qi.RightStickDown),new qi(0,qi.LeftStickX,{bipolar:!0}),new qi(1,qi.LeftStickY,{bipolar:!0}),new qi(2,qi.RightStickX,{bipolar:!0}),new qi(3,qi.RightStickY,{bipolar:!0}),new qi(8,qi.AuxiliaryAxis0Positive,{normalize:!0}),new qi(9,qi.AuxiliaryAxis1Positive,{normalize:!0})])}}class Zi extends Wi{family=Oi.SwitchPro}class Ji extends Wi{family=Oi.Xbox}const ts=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,es=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,is=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,ss=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,ns=(t,e,i)=>({...void 0!==i&&{ids:i},name:t,resolve:()=>({name:t,mapping:e()})}),rs=t=>t.trim().toLowerCase(),os=t=>{const e=t.replace(es,"").replace(ts,"").replace(ss,"").replace(is,"").replaceAll(/\s+/g," ").trim();return e.length>0?e:null},as=(t,e)=>{if(!e)return!0;for(const i of(t=>t?(Array.isArray(t)?t:[t]).map(rs):[])(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},hs=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=es.exec(t)||ts.exec(t)||ss.exec(t)||is.exec(t);if(!e)return null;const[,i,s]=e;return void 0===i||void 0===s?null:`${i.toLowerCase()}:${s.toLowerCase()}`})(e),s=i?.slice(0,4)??null,n=i?.slice(5)??null;return{id:t.id,index:t.index,label:e,vendorId:s,productId:n,productKey:i,name:os(e)}},ls=(t,e)=>as(e,t.ids)?((t,e)=>{const i=t.resolve(e);return null==i?null:"mapping"in i?{descriptor:e,name:i.name??t.name??e.name??e.label,mapping:i.mapping}:{descriptor:e,name:t.name??e.name??e.label,mapping:i}})(t,e):null,us=[...[ns("Xbox 360 Controller",()=>new Ji,"045e:028e"),ns("Xbox One Controller",()=>new Ji,["045e:02d1","045e:02dd"]),ns("Xbox Wireless Controller",()=>new Ji,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),ns("Xbox One Elite Controller",()=>new Ji,"045e:02e3"),ns("Xbox Elite Wireless Controller Series 2",()=>new Ji,["045e:0b00","045e:0b05","045e:0b22"]),ns("Xbox Series Controller",()=>new Ji,["045e:0b12","045e:0b13"]),ns("PlayStation 3 Controller",()=>new Hi,"054c:0268"),ns("DualShock 4 Controller",()=>new Hi,["054c:05c4","054c:09cc","054c:0ba0"]),ns("DualSense Controller",()=>new Hi,"054c:0ce6"),ns("DualSense Edge Controller",()=>new Hi,"054c:0df2"),ns("GameCube Controller Adapter",()=>new $i,"057e:0337"),ns("Joy-Con (L)",()=>new Xi,"057e:2006"),ns("Joy-Con (R)",()=>new ji,"057e:2007"),ns("Joy-Con Charging Grip",()=>new Zi,"057e:200e"),ns("Switch Pro Controller",()=>new Zi,"057e:2009"),ns("Joy-Con 2 (L)",()=>new Xi,"057e:2066"),ns("Joy-Con 2 (R)",()=>new ji,"057e:2067"),ns("Switch 2 Pro Controller",()=>new Zi,"057e:2069"),ns("Switch 2 GameCube Controller",()=>new $i,"057e:2073"),ns("Steam Controller",()=>new Ki,["28de:1102","28de:1142"]),ns("Steam Virtual Gamepad",()=>new Wi,"28de:11ff"),ns("Steam Deck",()=>new Qi,"28de:1205"),ns("F310 Gamepad",()=>new Wi,"046d:c216"),ns("F710 Gamepad",()=>new Wi,["046d:c219","046d:c21f"]),ns("8BitDo P30 Controller",()=>new Wi,["2dc8:5107","2dc8:5108"]),ns("8BitDo SF30 Pro Controller",()=>new Zi,["2dc8:3000","2dc8:6100","2dc8:6101"]),ns("8BitDo SN30 Controller",()=>new Zi,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),ns("8BitDo NES30 Controller",()=>new Wi,"2dc8:ab12"),ns("PowerA Switch Controller",()=>new Zi,"20d6:a713"),ns("PowerA OPS Pro Wireless Controller",()=>new Wi,"20d6:4033"),ns("PowerA OPS Wireless Controller",()=>new Wi,"20d6:4026"),ns("Nacon Revolution 3 Controller",()=>new Hi,"146b:0611"),ns("Nacon Revolution Unlimited Pro Controller",()=>new Hi,"146b:0d08"),ns("Nacon Revolution Infinity Controller",()=>new Hi,"146b:0d10"),ns("Nacon Revolution 5 Pro Controller",()=>new Hi,["3285:0d17","3285:0d19"]),ns("Razer Raiju Controller",()=>new Hi,"1532:1000"),ns("Razer Raiju Mobile Controller",()=>new Hi,["1532:0705","1532:0707"]),ns("Razer Raiju Tournament Edition Controller",()=>new Hi,["1532:1007","1532:100a"]),ns("Razer Raiju Ultimate Controller",()=>new Hi,["1532:1004","1532:1009"]),ns("Razer Raion Controller",()=>new zi,"1532:1100")],...[ns("Microsoft Controller",()=>new Ji,"045e"),ns("Sony Controller",()=>new Hi,"054c"),ns("Valve Controller",()=>new Qi,"28de")],ns("Generic Gamepad",()=>new Wi)];class cs{onPinch;onRotate;onLongPress;touchPointers=new Map;longPressEntries=new Map;prevDistance=-1;prevAngle=0;centerVec=new te;constructor(t,e,i,s){this.onPinch=e,this.onRotate=i,this.onLongPress=s}onPointerDown(t){"touch"===t.type&&(this.touchPointers.set(t.id,t),this._resetTwoTouchBaseline());const e=setTimeout(()=>{this.longPressEntries.delete(t.id),this.onLongPress.dispatch(t)},500);this.longPressEntries.set(t.id,{pointerId:t.id,pointer:t,timerId:e,startX:t.x,startY:t.y})}onPointerMove(t,e){const i=this.longPressEntries.get(t.id);if(i){const s=t.x-i.startX,n=t.y-i.startY;Math.sqrt(s*s+n*n)>e&&(clearTimeout(i.timerId),this.longPressEntries.delete(t.id))}"touch"===t.type&&(this.touchPointers.size<2||this._processTwoTouchGestures())}onPointerUp(t){this._cancelLongPress(t.id)}onPointerLeave(t){this._cancelLongPress(t.id),"touch"===t.type&&(this.touchPointers.delete(t.id),this._resetTwoTouchBaseline())}onPointerCancel(t){this._cancelLongPress(t.id),"touch"===t.type&&(this.touchPointers.delete(t.id),this._resetTwoTouchBaseline())}destroy(){for(const t of this.longPressEntries.values())clearTimeout(t.timerId);this.longPressEntries.clear(),this.touchPointers.clear(),this.centerVec.destroy()}_cancelLongPress(t){const e=this.longPressEntries.get(t);e&&(clearTimeout(e.timerId),this.longPressEntries.delete(t))}_resetTwoTouchBaseline(){this.prevDistance=-1,this.prevAngle=0}_processTwoTouchGestures(){const t=this.touchPointers.values(),e=t.next().value,i=t.next().value,s=i.x-e.x,n=i.y-e.y,r=Math.sqrt(s*s+n*n),o=Math.atan2(n,s),a=(e.x+i.x)/2,h=(e.y+i.y)/2;if(this.centerVec.set(a,h),this.prevDistance>0){const t=r/this.prevDistance;Math.abs(t-1)>1e-4&&this.onPinch.dispatch(t,this.centerVec);const e=o-this.prevAngle;Math.abs(e)>1e-4&&this.onRotate.dispatch(e,this.centerVec)}this.prevDistance=r,this.prevAngle=o}}const ds=t=>Mi.Pointers+t,_s=(t,e)=>ds(16*t+e);var fs,ps;!function(t){t[t.None=0]="None",t[t.Over=1]="Over",t[t.Leave=2]="Leave",t[t.Down=4]="Down",t[t.Move=8]="Move",t[t.Up=16]="Up",t[t.Cancel=32]="Cancel"}(fs||(fs={})),function(t){t[t.Unknown=0]="Unknown",t[t.InsideCanvas=1]="InsideCanvas",t[t.OutsideCanvas=2]="OutsideCanvas",t[t.Pressed=3]="Pressed",t[t.Moving=4]="Moving",t[t.Released=5]="Released",t[t.Cancelled=6]="Cancelled"}(ps||(ps={}));class gs{id;type;position;startPos=new te(-1,-1);size;tilt;stateFlags=new Re;_app;_canvas;_channels;_slotIndex;_channelBase;_buttons;_pressure;_rotation;_isPrimary;_currentState=ps.Unknown;constructor(t,e,i,s,n){const{pointerId:r,pointerType:a,clientX:h,clientY:l,width:u,height:c,tiltX:d,tiltY:_,buttons:f,pressure:p,twist:g,isPrimary:m}=t;this._app=e,this._canvas=i,this._channels=s,this._slotIndex=n,this._channelBase=Mi.Pointers+16*n;const y=this._computeDesignGeometry(h,l,u,c);this.id=r,this.type=a,this.position=new te(y.x,y.y),this.size=new o(y.width,y.height),this.tilt=new te(d,_),this._buttons=f,this._pressure=p,this._rotation=g,this._isPrimary=m,this.stateFlags.push(fs.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=ps.InsideCanvas,this._writeChannels(!0)}handleLeave(t){this.handleEvent(t),this.stateFlags.push(fs.Leave),this._currentState=ps.OutsideCanvas,this._writeChannels(!1)}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(fs.Down),this._currentState=ps.Pressed,this._writeChannels(!0)}handleMove(t){this.handleEvent(t),this.stateFlags.push(fs.Move),this._currentState=ps.Moving,this._writeChannels(!0)}handleRelease(t){this.handleEvent(t),this.stateFlags.push(fs.Up),this._currentState=ps.Released,this._writeChannels(!0)}handleCancel(t){this.handleEvent(t),this.stateFlags.push(fs.Cancel),this._currentState=ps.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(t){const{clientX:e,clientY:i,width:s,height:n,tiltX:r,tiltY:o,buttons:a,pressure:h,twist:l,isPrimary:u}=t,c=this._computeDesignGeometry(e,i,s,n);return this.position.set(c.x,c.y),this.size.set(c.width,c.height),this.tilt.set(r,o),this._buttons=a,this._pressure=h,this._rotation=l,this._isPrimary=u,this}_computeDesignGeometry(t,e,i,s){const n=this._app,r=this._canvas;if(!n||!r)return{x:0,y:0,width:0,height:0};const o=r.getBoundingClientRect(),a=o.width>0?(t-o.left)/o.width:0,h=o.height>0?(e-o.top)/o.height:0,l=a*r.width,u=h*r.height,c=o.width>0?i/o.width*r.width:0,d=o.height>0?s/o.height*r.height:0,_=n._backingStoreToDesign(l,u),f=n._backingStoreToDesign(l+c,u+d);return{x:_.x,y:_.y,width:Math.abs(f.x-_.x),height:Math.abs(f.y-_.y)}}_writeChannels(t){const e=this._channels,i=this._canvas;if(!e||!i)return;const s=this._channelBase,n=this._app,r=(n?n.width:i.width)||1,o=(n?n.height:i.height)||1;if(!t){for(let t=0;t<16;t++)e[s+t]=0;return}const a=Math.min(1,Math.max(0,this.position.x/r)),h=Math.min(1,Math.max(0,this.position.y/o));e[s+0]=1,e[s+1]=a,e[s+2]=h,e[s+3]=this._pressure,e[s+4]=Math.min(1,this.size.width/r),e[s+5]=Math.min(1,this.size.height/o),e[s+6]=this._rotation/359,e[s+7]=(this.tilt.x+90)/180,e[s+8]=(this.tilt.y+90)/180,e[s+9]=1&this._buttons?1:0,e[s+10]=2&this._buttons?1:0,e[s+11]=4&this._buttons?1:0,e[s+12]="mouse"===this.type?1:0,e[s+13]="touch"===this.type?1:0,e[s+14]="pen"===this.type?1:0,e[s+15]=this._isPrimary?1:0}_clearChannels(){const t=this._channels;if(!t)return;const e=this._channelBase;for(let i=0;i<16;i++)t[e+i]=0}}!function(t){t.Active=ds(0),t.X=ds(1),t.Y=ds(2),t.Pressure=ds(3),t.Width=ds(4),t.Height=ds(5),t.Twist=ds(6),t.TiltX=ds(7),t.TiltY=ds(8),t.Left=ds(9),t.Right=ds(10),t.Middle=ds(11),t.IsMouse=ds(12),t.IsTouch=ds(13),t.IsPen=ds(14),t.IsPrimary=ds(15),t.Slot0Active=_s(0,0),t.Slot0X=_s(0,1),t.Slot0Y=_s(0,2),t.Slot1Active=_s(1,0),t.Slot1X=_s(1,1),t.Slot1Y=_s(1,2),t.Slot2Active=_s(2,0),t.Slot2X=_s(2,1),t.Slot2Y=_s(2,2),t.Slot3Active=_s(3,0),t.Slot3X=_s(3,1),t.Slot3Y=_s(3,2),t.Slot4Active=_s(4,0),t.Slot4X=_s(4,1),t.Slot4Y=_s(4,2),t.Slot5Active=_s(5,0),t.Slot5X=_s(5,1),t.Slot5Y=_s(5,2),t.Slot6Active=_s(6,0),t.Slot6X=_s(6,1),t.Slot6Y=_s(6,2),t.Slot7Active=_s(7,0),t.Slot7X=_s(7,1),t.Slot7Y=_s(7,2),t.Slot8Active=_s(8,0),t.Slot8X=_s(8,1),t.Slot8Y=_s(8,2),t.Slot9Active=_s(9,0),t.Slot9X=_s(9,1),t.Slot9Y=_s(9,2),t.Slot10Active=_s(10,0),t.Slot10X=_s(10,1),t.Slot10Y=_s(10,2),t.Slot11Active=_s(11,0),t.Slot11X=_s(11,1),t.Slot11Y=_s(11,2),t.Slot12Active=_s(12,0),t.Slot12X=_s(12,1),t.Slot12Y=_s(12,2),t.Slot13Active=_s(13,0),t.Slot13X=_s(13,1),t.Slot13Y=_s(13,2),t.Slot14Active=_s(14,0),t.Slot14X=_s(14,1),t.Slot14Y=_s(14,2),t.Slot15Active=_s(15,0),t.Slot15X=_s(15,1),t.Slot15Y=_s(15,2)}(gs||(gs={}));var ms,ys;!function(t){t[t.None=0]="None",t[t.KeyDown=1]="KeyDown",t[t.KeyUp=2]="KeyUp",t[t.MouseWheel=4]="MouseWheel",t[t.PointerUpdate=8]="PointerUpdate"}(ms||(ms={}));class ws{order=100;_app;canvas;channels=new Float32Array(Ti.Container);pointers=new Map;_gamepads;gamepadsByBrowserIndex=new Map;bindings=new Set;capturedKeyChannels=new Map;bindingDetacher={detach:t=>{this.bindings.delete(t);for(const e of t.channels)if(e<Ti.Category){const t=this.capturedKeyChannels.get(e);void 0!==t&&(t<=1?this.capturedKeyChannels.delete(e):this.capturedKeyChannels.set(e,t-1))}}};wheelOffset=new te;flags=new Re;channelsPressed=[];channelsReleased=[];gamepadDefinitions;slotStrategy;pointerSlots=new Map;freeSlots=Array.from({length:16},(t,e)=>e);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 m;onPointerEnter=new m;onPointerLeave=new m;onPointerDown=new m;onPointerMove=new m;onPointerUp=new m;onPointerTap=new m;onPointerSwipe=new m;onPointerCancel=new m;onMouseWheel=new m;onKeyDown=new m;onKeyUp=new m;onGamepadConnected=new m;onGamepadDisconnected=new m;onAnyGamepadReassigned=new m;onAnyGamepadButtonDown=new m;onAnyGamepadButtonUp=new m;onAnyGamepadAxisChange=new m;onPinch=new m;onRotate=new m;onLongPress=new m;constructor(t){const e=t.options.input??{},i=e.gamepadDefinitions??[],s=e.pointerDistanceThreshold??10,n=e.gamepadSlotStrategy??"sticky";this._app=t,this.canvas=t.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=s,this.gamepadDefinitions=[...i,...us],this.slotStrategy=n,this.canvas.style.touchAction="none",this.gestureRecognizer=new cs(s,this.onPinch,this.onRotate,this.onLongPress);const r=new Fi(0,this.channels),o=new Fi(1,this.channels),a=new Fi(2,this.channels),h=new Fi(3,this.channels);this._gamepads=[r,o,a,h];for(const t of this._gamepads)this.wireGamepadEvents(t);this.addEventListeners()}getPrimaryPointerPosition(){for(const t of this.pointers.values())if(t.isPrimary&&t.currentState!==ps.Cancelled)return{x:t.x,y:t.y};for(const t of this.pointers.values())if(t.currentState!==ps.Cancelled)return{x:t.x,y:t.y};return null}get pointersInCanvas(){for(const t of this.pointers.values())if(t.currentState!==ps.OutsideCanvas&&t.currentState!==ps.Cancelled)return!0;return!1}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this._gamepads}get gamepadSlotStrategy(){return this.slotStrategy}getGamepad(t){return this._gamepads[t]}get connectedGamepads(){const t=[];for(const e of this._gamepads)e.connected&&t.push(e);return t}get connectedGamepadCount(){let t=0;for(const e of this._gamepads)e.connected&&t++;return t}get firstConnectedGamepad(){for(const t of this._gamepads)if(t.connected)return t;return null}get hasGamepad(){for(const t of this._gamepads)if(t.connected)return!0;return!1}onStart(t,e,i){const s=this.createBinding(t,i);return s.onStart.add(e),s}onActive(t,e,i){const s=this.createBinding(t,i);return s.onActive.add(e),s}onStop(t,e,i){const s=this.createBinding(t,i);return s.onStop.add(e),s}onTrigger(t,e,i){const s=this.createBinding(t,i);return s.onTrigger.add(e),s}update(t){this.updateGamepads();for(const t of this.bindings)t.update(this.channels);this.flags.value!==ms.None&&this.updateEvents()}destroy(){this.removeEventListeners(),this.gestureRecognizer.destroy();for(const t of this.pointers.values())t.destroy();this.pointers.clear();for(const t of this._gamepads)t.destroy();for(const t of[...this.bindings])t.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,e={}){const i=Array.isArray(t)?t:[t],s=e.gamepadSlot??0,n=i.map(t=>this.resolveExternalChannel(t,s)),r=new Ui(n,e,this.bindingDetacher);this.bindings.add(r);for(const t of n)t<Ti.Category&&this.capturedKeyChannels.set(t,(this.capturedKeyChannels.get(t)??0)+1);return r}resolveExternalChannel(t,e){return t>=Mi.Gamepads&&t<Mi.Gamepads+Ti.Category?Mi.Gamepads+e*Ti.Gamepad+(t^Mi.Gamepads):t}wireGamepadEvents(t){t.onButtonDown.add((e,i)=>{this.onAnyGamepadButtonDown.dispatch(t,e,i)}),t.onButtonUp.add((e,i)=>{this.onAnyGamepadButtonUp.dispatch(t,e,i)}),t.onAxisChange.add((e,i)=>{this.onAnyGamepadAxisChange.dispatch(t,e,i)})}_assignSlot(t){if(this.pointerSlots.has(t))return this.pointerSlots.get(t);if(0===this.freeSlots.length)return null;const e=this.freeSlots.shift();return this.pointerSlots.set(t,e),e}_releaseSlot(t){const e=this.pointerSlots.get(t);void 0!==e&&(this.pointerSlots.delete(t),this.freeSlots.unshift(e))}handleKeyDown(t){if(!this.canvasFocusedValue)return;const e=Mi.Keyboard+t.keyCode;this.channels[e]=1,this.channelsPressed.push(e),this.flags.push(ms.KeyDown),this.capturedKeyChannels.has(e)&&u(t)}handleKeyUp(t){if(!this.canvasFocusedValue)return;const e=Mi.Keyboard+t.keyCode;this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(ms.KeyUp),this.capturedKeyChannels.has(e)&&u(t)}handlePointerOver(t){const e=this._assignSlot(t.pointerId);null!==e&&(this.pointers.set(t.pointerId,new gs(t,this._app,this.canvas,this.channels,e)),this.flags.push(ms.PointerUpdate))}handlePointerLeave(t){const e=this.pointers.get(t.pointerId);e&&(e.handleLeave(t),this.gestureRecognizer.onPointerLeave(e),this._releaseSlot(t.pointerId),this.flags.push(ms.PointerUpdate))}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0;const e=this.pointers.get(t.pointerId);e&&(e.handlePress(t),this.gestureRecognizer.onPointerDown(e),this.flags.push(ms.PointerUpdate),u(t))}handlePointerMove(t){const e=this.pointers.get(t.pointerId);e&&(e.handleMove(t),this.gestureRecognizer.onPointerMove(e,this.pointerDistanceThreshold),this.flags.push(ms.PointerUpdate))}handlePointerUp(t){const e=this.pointers.get(t.pointerId);e&&(e.handleRelease(t),this.gestureRecognizer.onPointerUp(e),this.flags.push(ms.PointerUpdate),u(t))}handlePointerCancel(t){const e=this.pointers.get(t.pointerId);e&&(e.handleCancel(t),this.gestureRecognizer.onPointerCancel(e),this._releaseSlot(t.pointerId),this.flags.push(ms.PointerUpdate))}handleMouseWheel(t){this.canvasFocusedValue&&(this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(ms.MouseWheel),u(t))}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<Ti.Category;t++){const e=Mi.Keyboard+t;0!==this.channels[e]&&(this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(ms.KeyUp))}}addEventListeners(){const t=window,e={capture:!0,passive:!1},i={capture:!0,passive:!0};t.addEventListener("keydown",this.keyDownHandler,!0),t.addEventListener("keyup",this.keyUpHandler,!0),t.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,e),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,e),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",u,e),this.canvas.addEventListener("selectstart",u,e)}removeEventListeners(){const t={capture:!0,passive:!1},e={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,t),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,e),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,e),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,e),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,t),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,e),this.canvas.removeEventListener("contextmenu",u,t),this.canvas.removeEventListener("selectstart",u,t)}updateGamepads(){const t=window.navigator.getGamepads(),e=new Set;for(const i of t){if(!i)continue;const t=i.index;if(t<0)continue;e.add(t);if(void 0===this.gamepadsByBrowserIndex.get(t)){const e=this.assignSlotForNewPad(i);if(null===e)continue;this.gamepadsByBrowserIndex.set(t,e),this.onGamepadConnected.dispatch(e)}}for(const[t,i]of[...this.gamepadsByBrowserIndex.entries()])e.has(t)||(this.gamepadsByBrowserIndex.delete(t),this.handleGamepadDisconnect(i));for(const t of this._gamepads)t.update();return this}assignSlotForNewPad(t){const e=((t,e=us)=>{const i="connected"in t?hs(t):t;for(const t of e){const e=ls(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new Wi}})(t,this.gamepadDefinitions);for(const i of this._gamepads)if(!i.connected)return i._bind(t,e),i;return null}handleGamepadDisconnect(t){if("compact"!==this.slotStrategy)return t._unbind(),void this.onGamepadDisconnected.dispatch(t);let e=-1;for(let t=3;t>=0;t--){const i=this._gamepads[t];if(void 0!==i&&i.connected){e=t;break}}t._silentUnbind();for(let t=0;t<4;t++){const e=this._gamepads[t];if(void 0!==e&&!e.connected)for(let i=t+1;i<4;i++){const t=this._gamepads[i];if(void 0===t||!t.connected)continue;const s=t.browserGamepad?.index,n=t.slot;e._rebindFrom(t),void 0!==s&&this.gamepadsByBrowserIndex.set(s,e),e.onPadReassigned.dispatch(n),this.onAnyGamepadReassigned.dispatch(e,n);break}}if(e>=0){const t=this._gamepads[e];void 0!==t&&(t._dispatchDisconnect(),this.onGamepadDisconnected.dispatch(t))}}updateEvents(){if(this.flags.pop(ms.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(ms.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(ms.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(ms.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of this.pointers.values()){const{stateFlags:e}=t;if(e.value!==fs.None){if(e.pop(fs.Over)&&this.onPointerEnter.dispatch(t),e.pop(fs.Down)&&this.onPointerDown.dispatch(t),e.pop(fs.Move)&&this.onPointerMove.dispatch(t),e.pop(fs.Up)){const{x:e,y:i}=t.startPos;this.onPointerUp.dispatch(t),e>=0&&i>=0&&(X(e,i,t.x,t.y)<this.pointerDistanceThreshold?this.onPointerTap.dispatch(t):this.onPointerSwipe.dispatch(t)),t.startPos.set(-1,-1)}e.pop(fs.Cancel)&&this.onPointerCancel.dispatch(t),e.pop(fs.Leave)&&(this.onPointerLeave.dispatch(t),this.pointers.delete(t.id))}}}}class xs{_bounds;_maxItems;_maxDepth;_depth;_items;_children;constructor(t,e=8,i=5,s=0){this._bounds=t,this._maxItems=e,this._maxDepth=i,this._depth=s,this._items=[],this._children=null}insert(t){if(null===this._children&&this._items.length<this._maxItems)this._items.push(t);else{if(null===this._children&&this._depth<this._maxDepth&&this._subdivide(),null!==this._children)for(const e of this._children)if(e._bounds.containsRect(t.bounds))return void e.insert(t);this._items.push(t)}}queryPoint(t,e,i=[]){if(!this._bounds.contains(t,e))return i;for(const s of this._items)s.bounds.contains(t,e)&&i.push(s);if(null!==this._children)for(const s of this._children)s.queryPoint(t,e,i);return i}queryRect(t,e=[]){if(t.right<this._bounds.left||t.left>this._bounds.right||t.bottom<this._bounds.top||t.top>this._bounds.bottom)return e;for(const i of this._items)i.bounds.right<t.left||i.bounds.left>t.right||i.bounds.bottom<t.top||i.bounds.top>t.bottom||e.push(i);if(null!==this._children)for(const i of this._children)i.queryRect(t,e);return e}remove(t){const e=this._items.indexOf(t);if(-1!==e)return this._items.splice(e,1),!0;if(null!==this._children)for(const e of this._children)if(e.remove(t))return!0;return!1}clear(){if(this._items.length=0,null!==this._children){for(const t of this._children)t.clear();this._children=null}}_walkBounds(t){if(t(this._bounds),null!==this._children)for(const e of this._children)e._walkBounds(t)}destroy(){if(this._items.length=0,this._bounds.destroy(),null!==this._children){for(const t of this._children)t.destroy();this._children=null}}_subdivide(){const{x:t,y:e,width:i,height:s}=this._bounds,n=i/2,r=s/2,o=this._depth+1,a=this._maxItems,h=this._maxDepth;this._children=[new xs(new Zt(t,e,n,r),a,h,o),new xs(new Zt(t+n,e,n,r),a,h,o),new xs(new Zt(t,e+r,n,r),a,h,o),new xs(new Zt(t+n,e+r,n,r),a,h,o)]}}class vs{type;target;currentTarget;pointer;worldX;worldY;_stopped=!1;constructor(t,e,i,s,n){this.type=t,this.target=e,this.currentTarget=e,this.pointer=i,this.worldX=s,this.worldY=n}get propagationStopped(){return this._stopped}stopPropagation(){this._stopped=!0}}!function(t){t[t.None=0]="None",t[t.Down=1]="Down",t[t.Move=2]="Move",t[t.Up=4]="Up",t[t.Tap=8]="Tap",t[t.Cancel=16]="Cancel",t[t.Leave=32]="Leave"}(ys||(ys={}));class bs{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(t){this._app=t,this._stage={interaction:this,focus:t.focus},this._uiStage={interaction:this._uiInteraction,focus:t.focus},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),t.input.onPointerDown.add(this._onPointerDownHandler),t.input.onPointerMove.add(this._onPointerMoveHandler),t.input.onPointerUp.add(this._onPointerUpHandler),t.input.onPointerTap.add(this._onPointerTapHandler),t.input.onPointerCancel.add(this._onPointerCancelHandler),t.input.onPointerLeave.add(this._onPointerLeaveHandler)}getHoveredNode(t){if(void 0!==t)return this._lastHit.get(t)??null;const e=this._lastHit.values().next();return e.done?null:e.value}getCapturedNodes(){return[...this._capturedPointers.values()]}pushInputCapture(t){this._captureStack.push(t)}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(t){if(this._dirty){this._dirty=!1,this._flushStaleEntries();for(const t of this._pending.values())this._processQueue(t);this._pending.clear(),this._updateCursor()}}attachRoot(t){t._setStage(this._stage),this._notifyNodeAdded(t)}detachRoot(t){this._app.focus.blur(),this._captureStack.length=0,this._notifyNodeRemoved(t),t._setStage(null)}attachUIRoot(t){t._setStage(this._uiStage)}detachUIRoot(t){t._setStage(null)}_notifyNodeAdded(t){for(const e of this._iterateSubtree(t))e.interactive&&this._registerNode(e)}_notifyNodeRemoved(t){for(const e of this._iterateSubtree(t))this._interactiveNodes.has(e)&&this._unregisterNode(e)}_notifyInteractiveChanged(t,e){e?this._registerNode(t):this._unregisterNode(t)}_notifyBoundsInvalidated(t){this._interactiveNodes.has(t)&&this._staleNodes.add(t)}_handlePointerDown(t){this._enqueue(t,ys.Down)}_handlePointerMove(t){this._enqueue(t,ys.Move)}_handlePointerUp(t){this._enqueue(t,ys.Up)}_handlePointerTap(t){this._enqueue(t,ys.Tap)}_handlePointerCancel(t){this._enqueue(t,ys.Cancel)}_handlePointerLeave(t){this._enqueue(t,ys.Leave)}_enqueue(t,e){let i=this._pending.get(t.id);i?i.pointer=t:(i={pointer:t,events:0},this._pending.set(t.id,i)),i.events|=e,this._dirty=!0}_processQueue(t){const{pointer:e,events:i}=t,{id:s}=e,n=this._capturedPointers.get(s)??null;let r,o,a;if(null!==n){const t=this._pointerCoords(e,this._isUINode(n));r=n,o=t.x,a=t.y}else{const t=this._resolveHit(e);r=t.node,o=t.x,a=t.y}const h=this._drags.get(s)??null,l=this._lastHit.get(s)??null,u=0!==(i&(ys.Cancel|ys.Leave));if(null!==n||r===l||u||(null!==l&&this._dispatchBubble(new vs("pointerout",l,e,o,a)),null!==r&&this._dispatchBubble(new vs("pointerover",r,e,o,a)),this._setLastHit(s,r)),0!==(i&ys.Down)&&null!==r&&(this._dispatchBubble(new vs("pointerdown",r,e,o,a)),r.draggable&&!this._drags.has(s))){const t=r.position.x-o,i=r.position.y-a;this._drags.set(s,{pointerId:s,node:r,offsetX:t,offsetY:i}),this._capturedPointers.set(s,r);try{this._app.canvas.setPointerCapture(s)}catch{}this._dispatchDirect(new vs("dragstart",r,e,o,a),r._peekInteractionSignal("dragstart"))}0!==(i&ys.Move)&&(null!==h&&(h.node.position.x=o+h.offsetX,h.node.position.y=a+h.offsetY),null!==r&&this._dispatchBubble(new vs("pointermove",r,e,o,a)),null!==h&&this._dispatchDirect(new vs("drag",h.node,e,o,a),h.node._peekInteractionSignal("drag"))),0!==(i&ys.Up)&&(null!==r&&this._dispatchBubble(new vs("pointerup",r,e,o,a)),null!==h&&(this._dispatchDirect(new vs("dragend",h.node,e,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(s))),0!==(i&ys.Tap)&&null!==r&&this._dispatchBubble(new vs("pointertap",r,e,o,a)),u&&(null!==h?(this._dispatchDirect(new vs("dragend",h.node,e,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(s)):null!==l&&this._dispatchBubble(new vs("pointerout",l,e,o,a)),this._lastHit.delete(s))}_endDrag(t){this._drags.delete(t),this._capturedPointers.delete(t);try{this._app.canvas.releasePointerCapture(t)}catch{}}_resolveHit(t){const e=this._captureStack.at(-1);if(void 0!==e){const i=this._pointerCoords(t,this._isUINode(e));return{node:this._hitTestNode(e,i.x,i.y),x:i.x,y:i.y}}const i=this._app.scene.currentScene?._peekUI()??null;if(null!==i){const e=this._app.rendering.screenView.screenToWorld(t.x,t.y),s=this._hitTestNode(i,e.x,e.y);if(null!==s)return{node:s,x:e.x,y:e.y}}const s=this._app.rendering.camera.screenToWorld(t.x,t.y);return{node:this._hitTest(s.x,s.y),x:s.x,y:s.y}}_pointerCoords(t,e){return(e?this._app.rendering.screenView:this._app.rendering.camera).screenToWorld(t.x,t.y)}_isUINode(t){const e=this._app.scene.currentScene?._peekUI()??null;if(null===e)return!1;let i=t;for(;null!==i;){if(i===e)return!0;i=i.parent}return!1}_hitTest(t,e){if(null!==this._quadtree)return this._hitTestIndexed(t,e);const i=this._app.scene.currentScene?.root;return i?this._hitTestNode(i,t,e):null}_hitTestIndexed(t,e){const i=this._quadtreeQueryBuffer;i.length=0,this._quadtree.queryPoint(t,e,i);let s=-1,n=null;for(const r of i){const i=r.payload;i.order>s&&i.node.contains(t,e)&&(s=i.order,n=i.node)}return n}_hitTestNode(t,e,i){if(!t.visible)return null;if(t instanceof Bi){const s=t.children;for(let t=s.length-1;t>=0;t--){const n=s[t];if(void 0===n)continue;const r=this._hitTestNode(n,e,i);if(r)return r}}return t.interactive&&t.contains(e,i)?t:null}_registerNode(t){this._interactiveNodes.has(t)||(this._interactiveNodes.add(t),null===this._quadtree&&(this._quadtree=this._createQuadtree()),this._insertNode(t))}_unregisterNode(t){if(!this._interactiveNodes.has(t))return;this._interactiveNodes.delete(t),this._staleNodes.delete(t);const e=this._quadtreeItems.get(t);void 0!==e&&null!==this._quadtree&&this._quadtree.remove(e),this._quadtreeItems.delete(t),0===this._interactiveNodes.size&&null!==this._quadtree&&(this._quadtree.destroy(),this._quadtree=null,this._quadtreeOrderCounter=0)}_insertNode(t){if(null===this._quadtree)return;const e=t.getBounds(),i={bounds:new Zt(e.x,e.y,e.width,e.height),payload:{node:t,order:this._quadtreeOrderCounter++}};this._quadtree.insert(i),this._quadtreeItems.set(t,i)}_flushStaleEntries(){if(null!==this._quadtree&&0!==this._staleNodes.size){for(const t of this._staleNodes){const e=this._quadtreeItems.get(t);void 0!==e&&(this._quadtree.remove(e),e.bounds.destroy()),this._quadtreeItems.delete(t);const i=t.getBounds(),s={bounds:new Zt(i.x,i.y,i.width,i.height),payload:{node:t,order:e?.payload.order??this._quadtreeOrderCounter++}};this._quadtree.insert(s),this._quadtreeItems.set(t,s)}this._staleNodes.clear()}}_createQuadtree(){const t=this._app.width||800,e=this._app.height||600,i=new Zt(0,0,t,e),s=this._app.scene.currentScene?.root;if(s){const t=s.getBounds(),e=Math.min(i.left,t.left),n=Math.min(i.top,t.top),r=Math.max(i.right,t.right),o=Math.max(i.bottom,t.bottom);i.set(e,n,r-e,o-n)}return new xs(i)}*_iterateSubtree(t){const e=[t];for(;e.length>0;){const t=e.pop();if(yield t,t instanceof Bi)for(let i=t.children.length-1;i>=0;i--){const s=t.children[i];void 0!==s&&e.push(s)}}}_dispatchBubble(t){let e=t.target;for(;null!==e&&!t.propagationStopped;){t.currentTarget=e;const i=this._signalFor(t.type,e);if(i?.dispatch(t),t.propagationStopped)break;const s=e.parent;e=null!==s&&s.interactive?s:null}}_dispatchDirect(t,e){t.currentTarget=t.target,e?.dispatch(t)}_signalFor(t,e){return e._peekInteractionSignal(t)}_setLastHit(t,e){null!==e?this._lastHit.set(t,e):this._lastHit.delete(t)}_updateCursor(){let t=null;for(const e of this._lastHit.values()){let i=e;for(;null!==i;){if(null!==i.cursor){t=i.cursor;break}i=i.parent}if(null!==t)break}this._app.canvas.style.cursor=t??""}}const Ss=(t,e)=>(t<<e|t>>>32-e)>>>0,Bs=1/2**32;class Cs{_state=new Uint32Array(4);_seed=0;_value=0;constructor(t=Date.now()){this.setSeed(t)}get seed(){return this._seed}get value(){return this._value}setSeed(t){return this._seed=t,this.reset(),this}reset(){let t=0|this._seed;for(let e=0;e<4;e++){t=t+2654435769|0;let i=t^t>>>16;i=Math.imul(i,569420461),i^=i>>>15,i=Math.imul(i,1935289751),i^=i>>>15,this._state[e]=i>>>0}return this._value=0,this}next(t=0,e=1){const i=this._state;let s=i[0],n=i[1],r=i[2],o=i[3];const a=Math.imul(Ss(Math.imul(n,5),7),9)>>>0,h=n<<9;return r^=s,o^=n,n^=r,s^=o,r^=h,o=Ss(o,11),i[0]=s,i[1]=n,i[2]=r,i[3]=o,this._value=a*Bs*(e-t)+t,this._value}destroy(){}}const Ts=new Set(["none","position","geometry"]);function Ms(t){return"string"==typeof t&&Ts.has(t)}const Ps=1e-6;function As(t,e,i,s){const n=t.x,r=t.y;if(!(i>0&&s>0))return Es(n,r);const o=e.worldToScreen(n,r,i,s);if(!Number.isFinite(o.x)||!Number.isFinite(o.y))return Es(n,r);const a=e.worldToScreen(n+1,r,i,s),h=e.worldToScreen(n,r+1,i,s),l=a.x-o.x,u=a.y-o.y,c=h.x-o.x,d=h.y-o.y,_=t.a*l+t.c*c,f=t.a*u+t.c*d,p=t.b*l+t.d*c,g=t.b*u+t.d*d,m=Math.abs(f)<Ps&&Math.abs(p)<Ps,y=Math.round(o.x),w=Math.round(o.y);let x=n,v=r;const b=l*d-c*u;if(Math.abs(b)>Ps){const t=y-o.x,e=w-o.y;x=n+(d*t-c*e)/b,v=r+(l*e-u*t)/b}return{originX:o.x,originY:o.y,snappedOriginX:y,snappedOriginY:w,worldX:x,worldY:v,scaleX:_,scaleY:g,axisAligned:m}}function Es(t,e){return{originX:t,originY:e,snappedOriginX:t,snappedOriginY:e,worldX:t,worldY:e,scaleX:0,scaleY:0,axisAligned:!1}}function Rs(t,e){return!Number.isFinite(t)||Math.abs(e)<Ps?t:Math.round(t*e)/e}function ks(t,e,i){const{scaleX:s,scaleY:n}=e;i.length=t.length;for(let e=0;e<t.length;e++){const r=t[e];let o=i[e];void 0===o&&(o=i[e]={x0:0,y0:0,x1:0,y1:0,u0:0,v0:0,u1:0,v1:0}),o.x0=Rs(r.x0,s),o.x1=Rs(r.x1,s),o.y0=Rs(r.y0,n),o.y1=Rs(r.y1,n),o.u0=r.u0,o.v0=r.v0,o.u1=r.u1,o.v1=r.v1}return i}function Ds(t,e,i,s,n){const r=t.getGlobalTransform();if("none"===t.pixelSnapMode)return r;return function(t,e,i){return t.copy(e),t.x=i.worldX,t.y=i.worldY,t}(n,r,As(r,e,i,s))}function Is(t,e,i){const s=Rs(t.left,e.scaleX),n=Rs(t.top,e.scaleY),r=Rs(t.right,e.scaleX),o=Rs(t.bottom,e.scaleY);return i.set(s,n,r-s,o-n)}class Ls extends Si{_tint=Ee.white.clone();_blendMode=ni.Normal;_pixelSnapMode="none";_materialKey=null;_materialKeyBackend=null;get tint(){return this._tint}set tint(t){this.setTint(t)}get blendMode(){return this._blendMode}set blendMode(t){this.setBlendMode(t)}get pixelSnapMode(){return this._pixelSnapMode}set pixelSnapMode(t){if(t!==this._pixelSnapMode){if(!Ms(t))throw new Error(`Drawable.pixelSnapMode must be 'none', 'position', or 'geometry' (got ${String(t)}).`);this._pixelSnapMode=t,this.invalidateCache()}}setTint(t){return t&&(this._tint.copy(t),this.invalidateCache()),this}setBlendMode(t){return this._blendMode!==t&&(this._blendMode=t,this.invalidateCache()),this}_collectContent(t){t.emitDraw(this)}_isDrawableForRenderPlan(){return!0}_renderPlanGetBlendMode(){return this._blendMode}_getOrComputeMaterialKey(t){const e=this._materialKey;if(null!==e)return null!==Xe(this)?je(e,this,t):this._materialKeyBackend===t?e:(this._materialKeyBackend=t,je(e,this,t));const i=je({rendererId:0,blendMode:this._blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},this,t);return this._materialKey=i,this._materialKeyBackend=t,i}invalidateCache(){return super.invalidateCache(),this._materialKeyBackend=null,this}destroy(){super.destroy(),this._tint.destroy()}}class Us extends Ls{_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(t){super();const{texture:e=null,material:i=null}=t;let s,n,r,o,a;if(void 0!==t.geometry){if(void 0!==t.vertices)throw new Error("Mesh accepts either `vertices` or `geometry`, not both.");a=t.geometry;const e=Vs(a);s=e.vertices,r=e.uvs,o=e.colors,n=e.indices}else{if(void 0===t.vertices)throw new Error("Mesh requires either `vertices` or `geometry`.");a=null,s=t.vertices,n=t.indices??null,r=t.uvs??null,o=t.colors??null}if(0===s.length||s.length%2!=0)throw new Error(`Mesh vertices must be a non-empty flat array of (x,y) pairs (got length ${s.length}).`);const h=s.length/2;if(h<3)throw new Error(`Mesh requires at least 3 vertices (got ${h}).`);if(null!==r&&r.length!==s.length)throw new Error(`Mesh uvs length ${r.length} must equal vertices length ${s.length}.`);if(null!==o&&o.length!==h)throw new Error(`Mesh colors length ${o.length} must equal vertex count ${h}.`);if(null!==n){if(0===n.length||n.length%3!=0)throw new Error(`Mesh indices must be a non-empty multiple of 3 (got length ${n.length}).`);for(let t=0;t<n.length;t++)if(n[t]>=h)throw new Error(`Mesh index ${n[t]} at position ${t} 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=s,this._indices=n,this._uvs=r,this._colors=o,this._material=i,this._geometry=a,this._texture=e,this.recomputeLocalBounds()}get vertexCount(){return this.vertices.length/2}get indexCount(){return this.indices?.length??this.vertexCount}get texture(){return this._texture}set texture(t){this._texture=t,this.invalidateCache()}recomputeLocalBounds(){let t=1/0,e=1/0,i=-1/0,s=-1/0;for(let n=0;n<this.vertices.length;n+=2){const r=this.vertices[n],o=this.vertices[n+1];r<t&&(t=r),r>i&&(i=r),o<e&&(e=o),o>s&&(s=o)}return this.getLocalBounds().set(t,e,i-t,s-e),this._invalidateBoundsCascade(),this}}const Fs=new Set(["a_position","position"]),Gs=new Set(["a_texcoord","texcoord","a_uv","uv"]),Ns=new Set(["a_color","color"]),Os=(t,e)=>t.find(t=>e.has(t.name));function Vs(t){if("triangle-list"!==t.topology)throw new Error(`Mesh only supports triangle-list geometry (got "${t.topology}").`);const e=Os(t.attributes,Fs);if(void 0===e)throw new Error("Mesh geometry requires a position attribute named `a_position` or `position`.");if("f32"!==e.type||e.size<2)throw new Error("Mesh geometry position attribute must be a float vector with at least 2 components.");const i=Os(t.attributes,Gs);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 s=Os(t.attributes,Ns),n=t.vertexCount,{stride:r}=t,o=t.vertexData,a=o instanceof Float32Array?new DataView(o.buffer,o.byteOffset,o.byteLength):new DataView(o),h=new Float32Array(2*n),l=void 0!==i?new Float32Array(2*n):null,u=void 0!==s?new Uint32Array(n):null;for(let t=0;t<n;t++){const n=t*r;h[2*t]=a.getFloat32(n+e.offset,!0),h[2*t+1]=a.getFloat32(n+e.offset+4,!0),null!==l&&void 0!==i&&(l[2*t]=a.getFloat32(n+i.offset,!0),l[2*t+1]=a.getFloat32(n+i.offset+4,!0)),null!==u&&void 0!==s&&(u[t]=zs(a,n+s.offset,s))}const c=function(t,e){if(null===t)return null;if(t instanceof Uint16Array)return t;if(e>65535)throw new Error(`Mesh geometry with ${e} vertices exceeds the 16-bit index limit.`);return Uint16Array.from(t)}(t.indices,n);return{vertices:h,uvs:l,colors:u,indices:c}}function zs(t,e,i){if("u32"===i.type&&1===i.size)return t.getUint32(e,!0)>>>0;if("u8"===i.type&&4===i.size){return(t.getUint8(e)|t.getUint8(e+1)<<8|t.getUint8(e+2)<<16|t.getUint8(e+3)<<24)>>>0}if("f32"===i.type&&4===i.size){return(Math.round(255*qs(t.getFloat32(e,!0)))|Math.round(255*qs(t.getFloat32(e+4,!0)))<<8|Math.round(255*qs(t.getFloat32(e+8,!0)))<<16|Math.round(255*qs(t.getFloat32(e+12,!0)))<<24)>>>0}throw new Error("Mesh geometry color attribute must be u8x4, u32x1, or f32x4.")}function qs(t){return t<0?0:t>1?1:t}function Ys(t){return"number"==typeof t&&Number.isFinite(t)}class Ws{texture;x;y;width;height;u0;v0;u1;v1;extrusion;constructor(t,e){if(!t)throw new Error("TextureRegion requires a non-null Texture.");const i=t.width,s=t.height;!function(t,e,i){const{x:s,y:n,width:r,height:o}=t;if(!(Ys(s)&&Ys(n)&&Ys(r)&&Ys(o)))throw new Error(`TextureRegion coordinates and dimensions must be finite numbers (got x=${s}, y=${n}, width=${r}, height=${o}).`);if(r<=0||o<=0)throw new Error(`TextureRegion dimensions must be positive (got width=${r}, height=${o}).`);if(e<=0||i<=0)throw new Error(`Texture must have positive dimensions (got ${e}x${i}).`);if(s<0||n<0)throw new Error(`TextureRegion origin must be non-negative (got x=${s}, y=${n}).`);if(s>=e||n>=i)throw new Error(`TextureRegion origin (${s}, ${n}) is outside texture bounds (${e}x${i}).`);if(s+r>e)throw new Error(`TextureRegion right edge (${s+r}) exceeds texture width (${e}).`);if(n+o>i)throw new Error(`TextureRegion bottom edge (${n+o}) exceeds texture height (${i}).`)}(e,i,s);const n=function(t){return void 0===t?Object.freeze({left:0,top:0,right:0,bottom:0}):"number"==typeof t?Object.freeze({left:t,top:t,right:t,bottom:t}):Object.freeze({left:t.left,top:t.top,right:t.right,bottom:t.bottom})}(e.extrusion);!function(t,e,i,s,n,r,o){const{left:a,top:h,right:l,bottom:u}=t;if(!(Ys(a)&&Ys(h)&&Ys(l)&&Ys(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>e||h>i||l>r-(e+s)||u>o-(i+n))throw new Error(`TextureRegion extrusion exceeds available source texture bounds: left=${a} (>${e}), top=${h} (>${i}), right=${l} (>${r-(e+s)}), bottom=${u} (>${o-(i+n)}).`)}(n,e.x,e.y,e.width,e.height,i,s),this.texture=t,this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this.u0=e.x/i,this.v0=e.y/s,this.u1=(e.x+e.width)/i,this.v1=(e.y+e.height)/s,this.extrusion=n}}function $s(t,e,i){if(0===t)return{destinationLength:0,sourceLength:e,segments:[]};const s=[];let n=0,r=0;for(;n<t;){const o=t-n,a=Math.min(e,o),h=a/e,l=i&&r%2==1,u={destinationStart:n,destinationLength:a,sourceStart:l?1:0,sourceEnd:l?1-h:h,mirrored:l};s.push(u),n+=a,r++}return{destinationLength:t,sourceLength:e,segments:s}}function Xs(t,e,i){if(0===t)return{destinationLength:0,sourceLength:e,segments:[]};const s=t/e,n=Math.max(1,Math.round(s)),r=t/n,o=[];for(let t=0;t<n;t++){const e=i&&t%2==1,s={destinationStart:t*r,destinationLength:r,sourceStart:e?1:0,sourceEnd:e?0:1,mirrored:e};o.push(s)}return{destinationLength:t,sourceLength:e,segments:o}}function js(t,e,i,s="round"){switch(function(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`RepeatPlanner: sourceLength and destinationLength must be finite numbers (got ${t}, ${e}).`);if(t<=0)throw new Error(`RepeatPlanner: sourceLength must be positive (got ${t}).`);if(e<0)throw new Error(`RepeatPlanner: destinationLength must be non-negative (got ${e}).`)}(t,e),i){case"stretch":return function(t,e){return 0===t?{destinationLength:0,sourceLength:e,segments:[]}:{destinationLength:t,sourceLength:e,segments:[{destinationStart:0,destinationLength:t,sourceStart:0,sourceEnd:1,mirrored:!1}]}}(e,t);case"repeat":return"round"===s?Xs(e,t,!1):$s(e,t,!1);case"mirror-repeat":return"round"===s?Xs(e,t,!0):$s(e,t,!0);default:throw new Error("RepeatPlanner: unknown RepeatMode.")}}const Hs=.5;function Ks(t){return"number"==typeof t&&Number.isFinite(t)}function Qs(t,e,i){const{left:s,top:n,right:r,bottom:o}=t;if(!(Ks(s)&&Ks(n)&&Ks(r)&&Ks(o)))throw new Error(`NineSliceSprite: slice values must be finite numbers (got left=${s}, top=${n}, right=${r}, bottom=${o}).`);if(s<0||n<0||r<0||o<0)throw new Error(`NineSliceSprite: slice values must be non-negative (got left=${s}, top=${n}, right=${r}, bottom=${o}).`);if(s+r>e)throw new Error(`NineSliceSprite: slices.left (${s}) + slices.right (${r}) exceeds region width (${e}).`);if(n+o>i)throw new Error(`NineSliceSprite: slices.top (${n}) + slices.bottom (${o}) exceeds region height (${i}).`)}function Zs(t){const{left:e,top:i,right:s,bottom:n}=t;if(!(Ks(e)&&Ks(i)&&Ks(s)&&Ks(n)))throw new Error(`NineSliceSprite: border values must be finite numbers (got left=${e}, top=${i}, right=${s}, bottom=${n}).`);if(e<0||i<0||s<0||n<0)throw new Error(`NineSliceSprite: border values must be non-negative (got left=${e}, top=${i}, right=${s}, bottom=${n}).`)}function Js(t,e){return"number"==typeof t?Object.freeze({left:t,top:t,right:t,bottom:t}):Object.freeze({left:t.left??e?.left??0,top:t.top??e?.top??0,right:t.right??e?.right??0,bottom:t.bottom??e?.bottom??0})}const tn=new Set(["stretch","repeat","mirror-repeat"]),en=new Set(["clip","round"]);function sn(t,e){if("string"!=typeof t||!tn.has(t))throw new Error(`NineSliceSprite: ${e} must be "stretch", "repeat", or "mirror-repeat".`)}function nn(t,e){if("string"!=typeof t||!en.has(t))throw new Error(`NineSliceSprite: ${e} must be "clip" or "round".`)}function rn(t){if(!t)return on;const e={};return void 0!==t.edges&&(sn(t.edges,"modes.edges"),e.edges=t.edges),void 0!==t.center&&(sn(t.center,"modes.center"),e.center=t.center),void 0!==t.top&&(sn(t.top,"modes.top"),e.top=t.top),void 0!==t.right&&(sn(t.right,"modes.right"),e.right=t.right),void 0!==t.bottom&&(sn(t.bottom,"modes.bottom"),e.bottom=t.bottom),void 0!==t.left&&(sn(t.left,"modes.left"),e.left=t.left),void 0!==t.edgeFit&&(nn(t.edgeFit,"modes.edgeFit"),e.edgeFit=t.edgeFit),void 0!==t.centerFit&&(nn(t.centerFit,"modes.centerFit"),e.centerFit=t.centerFit),Object.freeze(e)}const on=Object.freeze({});function an(t,e){return t.left===e.left&&t.top===e.top&&t.right===e.right&&t.bottom===e.bottom}function hn(t,e){return t?.[e]??t?.edges??"stretch"}function ln(t,e,i){return!Ks(t)||t<e?e:t>i?i:t}function un(t,e,i,s,n,r){const o=function(t,e){const i=t.texture.width,s=t.texture.height,n=t.x,r=t.y,o=t.width,a=t.height,h=t.extrusion,l=h.left>0||h.right>0?0:Hs/i,u=h.top>0||h.bottom>0?0:Hs/s,c=Hs/i,d=Hs/s,_=(n+e.left)/i,f=(n+o-e.right)/i,p=(r+e.top)/s,g=(r+a-e.bottom)/s,m=t.u0+l,y=t.u1-l,w=t.v0+u,x=t.v1-u,v=ln(_-c,m,y),b=ln(f+c,m,y),S=ln(p-d,w,x),B=ln(g+d,w,x);return{col0:{u0:m,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}}}(t,e),a=function(t,e,i){let s=t.left,n=t.right,r=t.top,o=t.bottom;if(s+n>e&&s+n>0){const t=e/(s+n);s*=t,n*=t}if(r+o>i&&r+o>0){const t=i/(r+o);r*=t,o*=t}return{bl:s,br:n,bt:r,bb:o}}(i,s,n),h=a.bl,l=a.br,u=a.bt,c=a.bb,d=Math.max(0,s-h-l),_=Math.max(0,n-u-c),f=h,p=h+d,g=s,m=u,y=u+_,w=n,x=Math.max(0,t.width-e.left-e.right),v=Math.max(0,t.height-e.top-e.bottom),b=x*(e.top>0?u/e.top:1),S=x*(e.bottom>0?c/e.bottom:1),B=v*(e.left>0?h/e.left:1),C=v*(e.right>0?l/e.right:1),T=b,M=B,P=hn(r,"top"),A=hn(r,"bottom"),E=hn(r,"left"),R=hn(r,"right"),k=function(t){return t?.center??"stretch"}(r),D=function(t){return t?.edgeFit??"round"}(r),I=function(t){return t?.centerFit??"round"}(r),L=[],{col0:U,col1:F,col2:G,row0:N,row1:O,row2:V}=o;h>0&&u>0&&L.push({x0:0,y0:0,x1:f,y1:m,u0:U.u0,v0:N.u0,u1:U.u1,v1:N.u1}),l>0&&u>0&&L.push({x0:p,y0:0,x1:g,y1:m,u0:G.u0,v0:N.u0,u1:G.u1,v1:N.u1}),h>0&&c>0&&L.push({x0:0,y0:y,x1:f,y1:w,u0:U.u0,v0:V.u0,u1:U.u1,v1:V.u1}),l>0&&c>0&&L.push({x0:p,y0:y,x1:g,y1:w,u0:G.u0,v0:V.u0,u1:G.u1,v1:V.u1});const z=F.u0,q=F.u1,Y=O.u0,W=O.u1;if(d>0&&u>0&&x>0&&b>0){const t=js(b,d,P,D);for(const e of t.segments){const t=f+e.destinationStart,i=f+e.destinationStart+e.destinationLength,s=z+e.sourceStart*(q-z),n=z+e.sourceEnd*(q-z);L.push({x0:t,y0:0,x1:i,y1:m,u0:s,v0:N.u0,u1:n,v1:N.u1})}}if(d>0&&c>0&&x>0&&S>0){const t=js(S,d,A,D);for(const e of t.segments){const t=f+e.destinationStart,i=f+e.destinationStart+e.destinationLength,s=z+e.sourceStart*(q-z),n=z+e.sourceEnd*(q-z);L.push({x0:t,y0:y,x1:i,y1:w,u0:s,v0:V.u0,u1:n,v1:V.u1})}}if(h>0&&_>0&&v>0&&B>0){const t=js(B,_,E,D);for(const e of t.segments){const t=m+e.destinationStart,i=m+e.destinationStart+e.destinationLength,s=Y+e.sourceStart*(W-Y),n=Y+e.sourceEnd*(W-Y);L.push({x0:0,y0:t,x1:f,y1:i,u0:U.u0,v0:s,u1:U.u1,v1:n})}}if(l>0&&_>0&&v>0&&C>0){const t=js(C,_,R,D);for(const e of t.segments){const t=m+e.destinationStart,i=m+e.destinationStart+e.destinationLength,s=Y+e.sourceStart*(W-Y),n=Y+e.sourceEnd*(W-Y);L.push({x0:p,y0:t,x1:g,y1:i,u0:G.u0,v0:s,u1:G.u1,v1:n})}}if(d>0&&_>0&&x>0&&v>0&&T>0&&M>0){const t=js(T,d,k,I),e=js(M,_,k,I);for(const i of e.segments){const e=m+i.destinationStart,s=m+i.destinationStart+i.destinationLength,n=Y+i.sourceStart*(W-Y),r=Y+i.sourceEnd*(W-Y);for(const i of t.segments){const t=f+i.destinationStart,o=f+i.destinationStart+i.destinationLength,a=z+i.sourceStart*(q-z),h=z+i.sourceEnd*(q-z);L.push({x0:t,y0:e,x1:o,y1:s,u0:a,v0:n,u1:h,v1:r})}}}return L}function cn(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`NineSliceSprite: width and height must be finite numbers (got ${t}, ${e}).`);if(t<0)throw new Error(`NineSliceSprite: width must be non-negative (got ${t}).`);if(e<0)throw new Error(`NineSliceSprite: height must be non-negative (got ${e}).`)}class dn extends Ls{_region;_slices;_border;_width;_height;_modes;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(t,e){super(),this._region=t instanceof Ws?t:new Ws(t,{x:0,y:0,width:t.width,height:t.height});const i=this._region,s=Js(e.slices);Qs(s,i.width,i.height),this._slices=s;const n=void 0!==e.border?Js(e.border):Js(e.slices);Zs(n),this._border=n;const r=e.width??i.width,o=e.height??i.height;cn(r,o),this._width=r,this._height=o,this._modes=rn(e.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(t){this.setSize(t,this._height)}get height(){return this._height}set height(t){this.setSize(this._width,t)}setSize(t,e){return cn(t,e),this._width===t&&this._height===e||(this._width=t,this._height=e,this._geometryDirty=!0,this.invalidateCache()),this}setSlices(t){const e=this._region,i=Js(t);return Qs(i,e.width,e.height),an(i,this._slices)||(this._slices=i,this._geometryDirty=!0,this.invalidateCache()),this}setBorder(t){const e=Js(t);return Zs(e),an(e,this._border)||(this._border=e,this._geometryDirty=!0,this.invalidateCache()),this}setModes(t){const e=rn(t);return i=e,s=this._modes,i.edges===s.edges&&i.center===s.center&&i.top===s.top&&i.right===s.right&&i.bottom===s.bottom&&i.left===s.left&&i.edgeFit===s.edgeFit&&i.centerFit===s.centerFit||(this._modes=e,this._geometryDirty=!0,this.invalidateCache()),this;var i,s}getLocalBounds(){const t=super.getLocalBounds();return t.set(0,0,this._width,this._height),t}get quads(){return this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(t,e,i){const s=this.quads;if(0===s.length)return s;const n=As(this.getGlobalTransform(),t,e,i);return n.axisAligned?ks(s,n,this._renderQuads):s}_rebuildGeometry(){this._quads=un(this._region,this._slices,this._border,this._width,this._height,this._modes),this._geometryDirty=!1}}const _n=new Set(["stretch","repeat","mirror-repeat"]),fn=new Set(["clip","round"]);function pn(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`RepeatingSprite: width and height must be finite numbers (got ${t}, ${e}).`);if(t<0)throw new Error(`RepeatingSprite: width must be non-negative (got ${t}).`);if(e<0)throw new Error(`RepeatingSprite: height must be non-negative (got ${e}).`)}function gn(t,e){if("string"!=typeof t||!_n.has(t))throw new Error(`RepeatingSprite: ${e} must be "stretch", "repeat", or "mirror-repeat" (got ${String(t)}).`)}function mn(t,e){if("string"!=typeof t||!fn.has(t))throw new Error(`RepeatingSprite: ${e} must be "clip" or "round" (got ${String(t)}).`)}function yn(t,e){if(!Number.isFinite(t))throw new Error(`RepeatingSprite: ${e} must be a finite number (got ${t}).`)}function wn(t,e,i,s){return"stretch"===i||t<=0||e<=0?1:"round"===s?Math.max(1,Math.round(e/t)):e/t}function xn(t,e,i,s,n){if(0===e||t<=0)return[];if("stretch"===i)return[...js(t,e,i,s).segments];const r=(n%t+t)%t;if(0===r)return[...js(t,e,i,s).segments];const o=js(t,e+r,i,s),a=[];for(const t of o.segments){const i=t.destinationStart-r,s=i+t.destinationLength;if(s<=0||i>=e)continue;const n=Math.max(0,i),o=Math.min(e,s),h=o-n;if(h<=0)continue;const l=(n-i)/t.destinationLength,u=(o-i)/t.destinationLength,c=t.sourceEnd-t.sourceStart;a.push({destinationStart:n,destinationLength:h,sourceStart:t.sourceStart+l*c,sourceEnd:t.sourceStart+u*c,mirrored:t.mirrored})}return a}class vn extends Ls{_source;_region;_width;_height;_modeX;_modeY;_fitX;_fitY;_offsetX;_offsetY;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(t,e){super(),this._source=t,this._region=t instanceof Ws?t:new Ws(t,{x:0,y:0,width:t.width,height:t.height});const i=this._region,s=e??{},n=s.modeX??"repeat",r=s.modeY??"repeat";gn(n,"modeX"),gn(r,"modeY"),this._modeX=n,this._modeY=r;const o=s.fitX??"round",a=s.fitY??"round";mn(o,"fitX"),mn(a,"fitY"),this._fitX=o,this._fitY=a;const h=s.offsetX??0,l=s.offsetY??0;yn(h,"offsetX"),yn(l,"offsetY"),this._offsetX=h,this._offsetY=l;const u=s.width??i.width,c=s.height??i.height;pn(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(t){this.setSize(t,this._height)}get height(){return this._height}set height(t){this.setSize(this._width,t)}get modeX(){return this._modeX}set modeX(t){gn(t,"modeX"),this._modeX!==t&&(this._modeX=t,this._geometryDirty=!0,this.invalidateCache())}get modeY(){return this._modeY}set modeY(t){gn(t,"modeY"),this._modeY!==t&&(this._modeY=t,this._geometryDirty=!0,this.invalidateCache())}get fitX(){return this._fitX}set fitX(t){mn(t,"fitX"),this._fitX!==t&&(this._fitX=t,this._geometryDirty=!0,this.invalidateCache())}get fitY(){return this._fitY}set fitY(t){mn(t,"fitY"),this._fitY!==t&&(this._fitY=t,this._geometryDirty=!0,this.invalidateCache())}get offsetX(){return this._offsetX}set offsetX(t){this.setOffset(t,this._offsetY)}get offsetY(){return this._offsetY}set offsetY(t){this.setOffset(this._offsetX,t)}setSize(t,e){return pn(t,e),this._width===t&&this._height===e||(this._width=t,this._height=e,this._geometryDirty=!0,this.invalidateCache()),this}setOffset(t,e){return yn(t,"offsetX"),yn(e,"offsetY"),this._offsetX===t&&this._offsetY===e||(this._offsetX=t,this._offsetY=e,"geometry"===this.resolvedStrategy&&(this._geometryDirty=!0),this.invalidateCache()),this}getLocalBounds(){const t=super.getLocalBounds();return t.set(0,0,this._width,this._height),t}get resolvedStrategy(){return this._source instanceof Ws?"geometry":"shader"}get quads(){return"geometry"===this.resolvedStrategy&&this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(t,e,i){const s=this.quads;if("geometry"!==this.pixelSnapMode||0===s.length)return s;const n=As(this.getGlobalTransform(),t,e,i);return n.axisAligned?ks(s,n,this._renderQuads):s}getRenderBounds(t,e,i,s){const n=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return n;const r=As(this.getGlobalTransform(),t,e,i);return r.axisAligned?Is(n,r,s):n}_rebuildGeometry(){this._quads=function(t,e,i,s,n,r,o,a,h){if(0===e||0===i||t.width<=0||t.height<=0)return[];const l=t.texture.width,u=t.texture.height,c=t.extrusion,d=c.left>0||c.right>0?0:.5/l,_=c.top>0||c.bottom>0?0:.5/u,f=t.u0+d,p=t.u1-d,g=t.v0+_,m=t.v1-_,y=t.width,w=t.height,x=p-f,v=m-g,b=xn(y,e,s,r,a),S=xn(w,i,n,o,h),B=[];for(const t of S){const e=t.destinationStart,i=t.destinationStart+t.destinationLength,s=g+t.sourceStart*v,n=g+t.sourceEnd*v;for(const t of b){const r=t.destinationStart,o=t.destinationStart+t.destinationLength,a=f+t.sourceStart*x,h=f+t.sourceEnd*x;B.push({x0:r,y0:e,x1:o,y1:i,u0:a,v0:s,u1:h,v1:n})}}return B}(this._region,this._width,this._height,this._modeX,this._modeY,this._fitX,this._fitY,this._offsetX,this._offsetY),this._geometryDirty=!1}}var bn;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint",t[t.Vertices=1024]="Vertices",t[t.Normals=2048]="Normals"}(bn||(bn={}));class Sn extends Ls{_texture=null;_textureFrame=new Zt;_material=null;_vertices=new Float32Array(8);_texCoords=new Uint32Array(4);_normals=[new te,new te,new te,new te];constructor(t){super(),this.flags.push(bn.Vertices|bn.Normals),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get material(){return this._material}set material(t){if(null!==t&&"sprite"!==t.target)throw new Error(`Sprite requires a SpriteMaterial (got a ${t.target} material).`);this._material=t,this.invalidateCache()}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(t){this.scale.x=t/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(t){this.scale.y=t/this._textureFrame.height}get vertices(){if(this.flags.has(bn.Vertices)){const{left:t,top:e,right:i,bottom:s}=this.getLocalBounds(),{a:n,b:r,x:o,c:a,d:h,y:l}=this.getGlobalTransform();this._vertices[0]=t*n+e*r+o,this._vertices[1]=t*a+e*h+l,this._vertices[2]=i*n+e*r+o,this._vertices[3]=i*a+e*h+l,this._vertices[4]=i*n+s*r+o,this._vertices[5]=i*a+s*h+l,this._vertices[6]=t*n+s*r+o,this._vertices[7]=t*a+s*h+l,this.flags.remove(bn.Vertices)}return this._vertices}getRenderBounds(t,e,i,s){const n=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return n;const r=As(this.getGlobalTransform(),t,e,i);return r.axisAligned?Is(n,r,s):n}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(bn.TextureCoords)){const{width:t,height:e}=this._texture,{left:i,top:s,right:n,bottom:r}=this._textureFrame,o=i/t*65535&65535,a=(s/e*65535&65535)<<16,h=n/t*65535&65535,l=(r/e*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(t){return this._texture!==t&&(this._texture=t,null!==t&&this.resetTextureFrame(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,e=!0){const i=this.width,s=this.height;return this._textureFrame.copy(t),this.flags.push(bn.TextureCoords),this.getLocalBounds().set(0,0,t.width,t.height),this._invalidateBoundsCascade(),e?(this.width=t.width,this.height=t.height):(this.width=i,this.height=s),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(Zt.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){if(this.flags.has(bn.Normals)){const t=this.vertices,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],o=t[5],a=t[6],h=t[7];this._normals[0].set(s-e,n-i).rperp().normalize(),this._normals[1].set(r-s,o-n).rperp().normalize(),this._normals[2].set(a-r,h-o).rperp().normalize(),this._normals[3].set(e-a,i-h).rperp().normalize(),this.flags.remove(bn.Normals)}return this._normals}project(t,e=new ft){const i=this.vertices,s=i[0],n=i[1],r=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=t.dot(s,n),d=t.dot(r,o),_=t.dot(a,h),f=t.dot(l,u);return e.set(Math.min(c,d,_,f),Math.max(c,d,_,f))}contains(t,e){if(this.isAlignedBox)return this.getBounds().contains(t,e);const i=this.vertices,s=i[0],n=i[1],r=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=(r-s)*(e-n)-(o-n)*(t-s),d=(a-r)*(e-o)-(h-o)*(t-r),_=(l-a)*(e-h)-(u-h)*(t-a),f=(s-l)*(e-u)-(n-u)*(t-l);return c>=0&&d>=0&&_>=0&&f>=0||c<=0&&d<=0&&_<=0&&f<=0}_invalidateSubtreeTransform(){super._invalidateSubtreeTransform(),this.flags.push(bn.Vertices|bn.Normals)}_invalidateBoundsCascade(){super._invalidateBoundsCascade(),this.flags.push(bn.Vertices|bn.Normals)}destroy(){super.destroy();for(const t of this._normals)t.destroy();this._textureFrame.destroy(),this._texture=null,this._material=null}}Si.setInternalSpriteFactory(()=>new Sn(null));class Bn extends Ls{_text;constructor(t){super(),this._text=t}get text(){return this._text}get textBounds(){return{width:0,height:0}}syncDirty(){}update(t){this.syncDirty()}}class Cn{fontData;textures;constructor(t,e){e.length,t.pages.length,e.length,t.pages.length,this.fontData=t,this.textures=e}}function Tn(t,e,i,s){if(0===t.length)return[];const{fontSize:n,lineHeight:r,leading:o,align:a}=e,h=n*r+o,l=i.letterSpacing??0,u=i.maxWidth,c=i.breakWords??!1,d=function(t,e){if("pre"===e)return t;if("normal"===e)return t.replaceAll("\n"," ").replaceAll(/[ \t]+/g," ");return t.split("\n").map(t=>t.replaceAll(/[ \t]+/g," ")).join("\n")}(t,i.whiteSpace??"pre-line"),_=d.split("\n"),f=[];for(const t of _)void 0===u?f.push(t):f.push(...Pn(t,n,s,u,l,c));const p=[];let g=0;for(let t=0;t<f.length;t++){const e=f[t],i=t*h;let r=0,o=0,a=!1;const u=[];let c=null;for(const t of e){null!==c&&void 0!==s.getKerning&&(r+=s.getKerning(c,t,n));const e=s.getGlyph(t,n);u.push({info:e,x:r,y:i,char:t}),r+=e.advance+l," "===t?a=!1:a||(a=!0,o++),c=t}const d=r-(u.length>0?l:0);d>g&&(g=d),p.push({placements:u,width:d,wordCount:o})}const m=[],y=p.length-1;for(let t=0;t<p.length;t++){const e=p[t];let i=0;if("right"===a)i=g-e.width;else if("center"===a)i=(g-e.width)/2;else if("justify"===a&&t!==y&&e.wordCount>1){const t=e.wordCount-1,r=(g-e.width)/t;let o=-1,a=!0;const h=s.getGlyph(" ",n).advance;for(const t of e.placements)a&&t.info.advance!==h?(o++,a=!1):a||t.info.advance!==h||(a=!0),m.push({x:t.x+i+o*r+(t.info.xBearing??0),y:t.y+(t.info.yBearing??0),width:t.info.width,height:t.info.height,page:t.info.page,uvLeft:t.info.uvLeft,uvTop:t.info.uvTop,uvRight:t.info.uvRight,uvBottom:t.info.uvBottom});continue}for(const{info:t,x:s,y:n}of e.placements)m.push({x:s+i+(t.xBearing??0),y:n+(t.yBearing??0),width:t.width,height:t.height,page:t.page,uvLeft:t.uvLeft,uvTop:t.uvTop,uvRight:t.uvRight,uvBottom:t.uvBottom})}return m}function Mn(t){const e=new Map;for(const i of t){if(i.width<=0||i.height<=0)continue;let t=e.get(i.page);void 0===t&&e.set(i.page,t=[]),t.push(i)}const i=[];for(const[t,s]of e){const e=s.length,n=new Float32Array(8*e),r=new Float32Array(8*e),o=new Uint16Array(6*e);for(let t=0;t<e;t++){const e=s[t],i=8*t,a=4*t,h=6*t;n[i+0]=e.x,n[i+1]=e.y,n[i+2]=e.x+e.width,n[i+3]=e.y,n[i+4]=e.x+e.width,n[i+5]=e.y+e.height,n[i+6]=e.x,n[i+7]=e.y+e.height,r[i+0]=e.uvLeft,r[i+1]=e.uvTop,r[i+2]=e.uvRight,r[i+3]=e.uvTop,r[i+4]=e.uvRight,r[i+5]=e.uvBottom,r[i+6]=e.uvLeft,r[i+7]=e.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:t,vertices:n,uvs:r,indices:o,quadCount:e})}return i}function Pn(t,e,i,s,n,r){if(0===t.length)return[""];const o=t.split(" "),a=[];let h="",l=0;const u=i.getGlyph(" ",e).advance+n;for(const t of o){let o=0;for(const s of t)o+=i.getGlyph(s,e).advance+n;if(o=Math.max(0,o-n),r&&o>s){h.length>0&&(a.push(h),h="",l=0);let r="",o=0;for(const h of t){const t=i.getGlyph(h,e).advance+n;r.length>0&&o+t>s?(a.push(r),r=h,o=t):(r+=h,o+=t)}r.length>0&&(h=r,l=o)}else if(0===h.length)h=t,l=o;else{const e=l+u+o;e<=s?(h+=` ${t}`,l=e):(a.push(h),h=t,l=o)}}return a.push(h),a}class An{_dirty=!1;_pendingHint="tint";onChange=new m;_fontFamily;_fontWeight;_fontStyle;_fontSize;_fillColor;_outlineColor;_outlineWidth;_align;_lineHeight;_leading;_shadowColor;_shadowOffsetX;_shadowOffsetY;_shadowAlpha;_shadowBlur;_gradientColors;_gradientAxis;constructor(t={}){const e="undefined"!=typeof FontFace&&t.font instanceof FontFace?t.font:null;this._fontFamily=e?e.family:t.fontFamily??"Arial",this._fontWeight=t.fontWeight??"normal",this._fontStyle=t.fontStyle??"normal",this._fontSize=t.fontSize??20,this._fillColor=t.fillColor?t.fillColor.clone():Ee.white.clone(),this._outlineColor=t.outlineColor?t.outlineColor.clone():Ee.black.clone(),this._outlineWidth=t.outlineWidth??0,this._align=t.align??"left",this._lineHeight=t.lineHeight??1.2,this._leading=t.leading??0,this._shadowColor=t.shadowColor?t.shadowColor.clone():Ee.black.clone(),this._shadowOffsetX=t.shadowOffsetX??0,this._shadowOffsetY=t.shadowOffsetY??0,this._shadowAlpha=t.shadowAlpha??0,this._shadowBlur=t.shadowBlur??0,this._gradientColors=t.gradientColors?[t.gradientColors[0].clone(),t.gradientColors[1].clone()]:null,this._gradientAxis=t.gradientAxis??"vertical",this._dirty=!0,this._pendingHint="font"}consumeDirty(){if(!this._dirty)return null;const t=this._pendingHint;return this._dirty=!1,this._pendingHint="tint",t}_markDirty(t){var e,i;this._pendingHint=(e=this._pendingHint,i=t,"font"===e||"font"===i?"font":"layout"===e||"layout"===i?"layout":"tint"),this._dirty||(this._dirty=!0,this.onChange.dispatch())}get fontFamily(){return this._fontFamily}set fontFamily(t){const e="undefined"!=typeof FontFace&&t instanceof FontFace?t.family:t;this._fontFamily!==e&&(this._fontFamily=e,this._markDirty("font"))}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this._markDirty("font"))}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this._markDirty("font"))}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this._markDirty("layout"))}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this._markDirty("layout"))}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this._markDirty("layout"))}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this._markDirty("layout"))}get fillColor(){return this._fillColor}set fillColor(t){this._fillColor=t.clone(),this._markDirty("tint")}get outlineColor(){return this._outlineColor}set outlineColor(t){this._outlineColor=t.clone(),this._markDirty("tint")}get outlineWidth(){return this._outlineWidth}set outlineWidth(t){this._outlineWidth!==t&&(this._outlineWidth=t,this._markDirty("tint"))}get shadowColor(){return this._shadowColor}set shadowColor(t){this._shadowColor=t.clone(),this._markDirty("tint")}get shadowOffsetX(){return this._shadowOffsetX}set shadowOffsetX(t){this._shadowOffsetX!==t&&(this._shadowOffsetX=t,this._markDirty("tint"))}get shadowOffsetY(){return this._shadowOffsetY}set shadowOffsetY(t){this._shadowOffsetY!==t&&(this._shadowOffsetY=t,this._markDirty("tint"))}get shadowAlpha(){return this._shadowAlpha}set shadowAlpha(t){this._shadowAlpha!==t&&(this._shadowAlpha=t,this._markDirty("tint"))}get shadowBlur(){return this._shadowBlur}set shadowBlur(t){this._shadowBlur!==t&&(this._shadowBlur=t,this._markDirty("tint"))}get gradientColors(){return this._gradientColors}set gradientColors(t){this._gradientColors=t?[t[0].clone(),t[1].clone()]:null,this._markDirty("tint")}get gradientAxis(){return this._gradientAxis}set gradientAxis(t){this._gradientAxis!==t&&(this._gradientAxis=t,this._markDirty("tint"))}get font(){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}copy(t){return t!==this&&(this._fontFamily=t._fontFamily,this._fontWeight=t._fontWeight,this._fontStyle=t._fontStyle,this._fontSize=t._fontSize,this._fillColor=t._fillColor.clone(),this._outlineColor=t._outlineColor.clone(),this._outlineWidth=t._outlineWidth,this._align=t._align,this._lineHeight=t._lineHeight,this._leading=t._leading,this._shadowColor=t._shadowColor.clone(),this._shadowOffsetX=t._shadowOffsetX,this._shadowOffsetY=t._shadowOffsetY,this._shadowAlpha=t._shadowAlpha,this._shadowBlur=t._shadowBlur,this._gradientColors=t._gradientColors?[t._gradientColors[0].clone(),t._gradientColors[1].clone()]:null,this._gradientAxis=t._gradientAxis,this._markDirty("font")),this}clone(){const t=new An;return t._fontFamily=this._fontFamily,t._fontWeight=this._fontWeight,t._fontStyle=this._fontStyle,t._fontSize=this._fontSize,t._fillColor=this._fillColor.clone(),t._outlineColor=this._outlineColor.clone(),t._outlineWidth=this._outlineWidth,t._align=this._align,t._lineHeight=this._lineHeight,t._leading=this._leading,t._shadowColor=this._shadowColor.clone(),t._shadowOffsetX=this._shadowOffsetX,t._shadowOffsetY=this._shadowOffsetY,t._shadowAlpha=this._shadowAlpha,t._shadowBlur=this._shadowBlur,t._gradientColors=this._gradientColors?[this._gradientColors[0].clone(),this._gradientColors[1].clone()]:null,t._gradientAxis=this._gradientAxis,t._dirty=!0,t._pendingHint="font",t}}class En{_fontData;_textures;_scale;_fallbackAdvance;_fontId;constructor(t,e,i){this._fontData=t,this._textures=e,this._scale=i,this._fallbackAdvance=t.lineHeight*i*.5,this._fontId=t.pages[0]??"unknown"}getGlyph(t,e){const i=t.codePointAt(0)??0,s=this._fontData.chars.get(i),n=this._scale,r=this._fontData.lineHeight,o=this._fontData.base;if(void 0===s)return{x:0,y:0,width:0,height:0,advance:this._fallbackAdvance,ascent:0,page:0,uvLeft:0,uvTop:0,uvRight:0,uvBottom:0};s.page,this._textures.length,s.page,this._fontId,this._textures.length;const a=this._textures[s.page]?.width??1,h=this._textures[s.page]?.height??1;return{x:s.x,y:s.y,width:s.width*n,height:s.height*n,advance:s.xAdvance*n,ascent:0,page:s.page,uvLeft:s.x/a,uvTop:s.y/h,uvRight:(s.x+s.width)/a,uvBottom:(s.y+s.height)/h,xBearing:s.xOffset*n,yBearing:(s.yOffset-o)*n+r*n}}getKerning(t,e,i){const s=t.codePointAt(0),n=e.codePointAt(0);return void 0===s||void 0===n?0:(this._fontData.kernings.get(`${s},${n}`)??0)*this._scale}}class Rn extends Bn{_font;_fontScale;_msdf;_style;_layout;_pageQuads=[];_textBounds={width:0,height:0};_adapter;constructor(t,e,i={}){super(t),this._font=e,this._fontScale=i.scale??1,this._msdf=i.msdf??!1,this._style=new An(i),this._layout=i.layout??{},this._adapter=new En(e.fontData,e.textures,this._fontScale),this._rebuild()}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this._rebuild())}get style(){return this._style}set style(t){this._style=t instanceof An?t:new An(t),this._rebuild()}get layout(){return this._layout}set layout(t){this._layout=t,this._rebuild()}get fontScale(){return this._fontScale}set fontScale(t){this._fontScale!==t&&(this._fontScale=t,this._adapter=new En(this._font.fontData,this._font.textures,t),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(t){this._font=t,this._adapter=new En(t.fontData,t.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 t={fontSize:this._font.fontData.lineHeight*this._fontScale,lineHeight:this._style.lineHeight,leading:this._style.leading,align:this._style.align},e=Tn(this._text,t,this._layout,this._adapter);let i=0,s=0;for(const t of e){const e=t.x+t.width,n=t.y+t.height;e>i&&(i=e),n>s&&(s=n)}this._textBounds={width:i,height:s},this._pageQuads=Mn(e)}}const kn={r8:1,r32f:1,rgba8:4,rgba32f:4},Dn={r8:1,r32f:4,rgba8:1,rgba32f:4};class In extends pi{static defaultSamplerOptions={scaleMode:ri.Nearest,wrapMode:oi.ClampToEdge,premultiplyAlpha:!1,generateMipMap:!1,flipY:!1};format;buffer;_dirty=null;constructor(t){super(null,{...In.defaultSamplerOptions,...t.samplerOptions});const{width:e,height:i,format:s,data:n}=t;if(!Number.isInteger(e)||e<=0)throw new Error(`DataTexture width must be a positive integer (got ${e}).`);if(!Number.isInteger(i)||i<=0)throw new Error(`DataTexture height must be a positive integer (got ${i}).`);const r=e*i*kn[s]*Dn[s];let o;if(void 0===n)o=Ln(s)?new Float32Array(r/4):new Uint8Array(r);else if(n instanceof ArrayBuffer){if(n.byteLength!==r)throw new Error(`DataTexture data byteLength ${n.byteLength} does not match ${e}x${i} ${s} (${r} bytes expected).`);o=Ln(s)?new Float32Array(n):new Uint8Array(n)}else if(n instanceof Uint8Array){if(Ln(s))throw new Error(`DataTexture format '${s}' requires a Float32Array, got Uint8Array.`);if(n.byteLength!==r)throw new Error(`DataTexture Uint8Array length ${n.length} does not match ${e}x${i} ${s} (${r} expected).`);o=n}else{if(!Ln(s))throw new Error(`DataTexture format '${s}' requires a Uint8Array, got Float32Array.`);if(n.byteLength!==r)throw new Error(`DataTexture Float32Array byteLength ${n.byteLength} does not match ${e}x${i} ${s} (${r} expected).`);o=n}this.format=s,this.buffer=o,this.setSize(e,i),this._dirty={full:!0,x:0,y:0,width:e,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(t,e,i,s){if(!(Number.isInteger(t)&&Number.isInteger(e)&&Number.isInteger(i)&&Number.isInteger(s)))throw new Error(`DataTexture commitRect requires integer coordinates (got ${t}, ${e}, ${i}, ${s}).`);if(i<=0||s<=0)throw new Error(`DataTexture commitRect requires positive width and height (got ${i}, ${s}).`);if(t<0||e<0||t+i>this.width||e+s>this.height)throw new Error(`DataTexture commitRect (${t}, ${e}, ${i}, ${s}) is out of bounds for ${this.width}x${this.height}.`);if(null===this._dirty)this._dirty={full:!1,x:t,y:e,width:i,height:s};else if(this._dirty.full);else{const n=Math.min(this._dirty.x,t),r=Math.min(this._dirty.y,e),o=Math.max(this._dirty.x+this._dirty.width,t+i),a=Math.max(this._dirty.y+this._dirty.height,e+s);this._dirty={full:!1,x:n,y:r,width:o-n,height:a-r}}return this._bumpVersion(),this}_consumeDirtyRegion(){const t=this._dirty;return this._dirty=null,t}}function Ln(t){return"r32f"===t||"rgba32f"===t}const Un=1e20;class Fn{_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(t){this._buffer=t.buffer??8,this._radius=t.radius??this._buffer,this._cutoff=t.cutoff??.5,this._fontSize=t.fontSize;const e=t.fontStyle&&"normal"!==t.fontStyle?`${t.fontStyle} `:"",i=t.fontWeight??"normal";if(this._font=`${e}${i} ${t.fontSize}px ${t.fontFamily}`,"undefined"!=typeof OffscreenCanvas){const t=new OffscreenCanvas(1,1);this._canvas=t,this._ctx=t.getContext("2d",{willReadFrequently:!0})}else{const t=document.createElement("canvas");this._canvas=t,this._ctx=t.getContext("2d",{willReadFrequently:!0})}}_ensureFontMetrics(){if(this._metricsReady)return;const t=this._ctx;t.font=this._font,t.textBaseline="alphabetic";const e=t.measureText("HgjpqyÉÅ");this._fontAscent=Math.max(1,Math.ceil(e.fontBoundingBoxAscent??e.actualBoundingBoxAscent??.8*this._fontSize)),this._fontDescent=Math.max(1,Math.ceil(e.fontBoundingBoxDescent??e.actualBoundingBoxDescent??.2*this._fontSize)),this._metricsReady=!0}draw(t){this._ensureFontMetrics();const e=this._ctx,i=this._buffer;e.font=this._font,e.textBaseline="alphabetic";const s=e.measureText(t),n=s.width,r=Math.max(0,Math.ceil(s.actualBoundingBoxLeft??0)),o=Math.max(0,Math.ceil(s.actualBoundingBoxRight??n)),a=Math.max(1,r+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),e.clearRect(0,0,l,u),e.font=this._font,e.textBaseline="alphabetic",e.fillStyle="#ffffff",e.fillText(t,i+r,i+this._fontAscent);const c=e.getImageData(0,0,l,u).data,d=l*u;if(d>this._gridOuter.length){const t=Math.max(l,u);this._gridOuter=new Float64Array(d),this._gridInner=new Float64Array(d),this._f=new Float64Array(t),this._d=new Float64Array(t),this._z=new Float64Array(t+1),this._v=new Int16Array(t)}d>this._out.length&&(this._out=new Uint8ClampedArray(d));for(let t=0;t<d;t++){const e=c[4*t+3]/255;1===e?(this._gridOuter[t]=0,this._gridInner[t]=Un):0===e?(this._gridOuter[t]=Un,this._gridInner[t]=0):(this._gridOuter[t]=Math.max(0,.5-e)**2,this._gridInner[t]=Math.max(0,e-.5)**2)}Gn(this._gridOuter,l,u,this._f,this._d,this._v,this._z),Gn(this._gridInner,l,u,this._f,this._d,this._v,this._z);for(let t=0;t<d;t++){const e=this._gridOuter[t]-this._gridInner[t];this._out[t]=Math.max(0,Math.min(255,Math.round(255-255*(e/this._radius+this._cutoff))))}return{data:this._out.slice(0,d),width:l,height:u,glyphWidth:a,glyphHeight:h,glyphTop:i,glyphLeft:i,glyphAdvance:n}}}function Gn(t,e,i,s,n,r,o){for(let a=0;a<e;a++){for(let n=0;n<i;n++)s[n]=t[n*e+a];Nn(s,n,r,o,i);for(let s=0;s<i;s++)t[s*e+a]=n[s]}for(let a=0;a<i;a++){for(let i=0;i<e;i++)s[i]=t[a*e+i];Nn(s,n,r,o,e);for(let i=0;i<e;i++)t[a*e+i]=Math.sqrt(n[i])}}function Nn(t,e,i,s,n){let r=0;i[0]=0,s[0]=-Un,s[1]=Un;for(let e=1;e<n;e++){let n;do{const o=i[r];if(n=(t[e]+e*e-t[o]-o*o)/(2*(e-o)),n>s[r])break;r--}while(r>=0);r++,i[r]=e,s[r]=n,s[r+1]=Un}r=0;for(let o=0;o<n;o++){for(;s[r+1]<o;)r++;const n=i[r];e[o]=(o-n)*(o-n)+t[n]}}class On{_shelves=[];_width;_height;constructor(t,e){this._width=t,this._height=e}insert(t,e){for(const i of this._shelves)if(i.height>=e&&i.cursorX+t<=this._width){const e=i.cursorX;return i.cursorX+=t,{x:e,y:i.y}}const i=this._shelves[this._shelves.length-1],s=void 0===i?0:i.y+i.height;return s+e>this._height?null:(this._shelves.push({y:s,height:e,cursorX:t}),{x:0,y:s})}reset(){this._shelves.length=0}}class Vn{texture;index;mode;_packer;_width;_height;_sdfBuffer=null;_sdfTexture=null;_ctx=null;_colorGlyphs;constructor(t,e,i,s){if(this.index=t,this.mode=s,this._width=e,this._height=i,this._colorGlyphs="color"===s,this._packer=new On(e,i),"sdf"===s)this._sdfBuffer=new Uint8Array(e*i),this._sdfTexture=new In({width:e,height:i,format:"r8",data:this._sdfBuffer}),this._sdfTexture.setSize(e,i),this.texture=this._sdfTexture;else{const{canvas:t,ctx:s}=function(t,e){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(t,e),s=i.getContext("2d");if(!s)throw new Error("GlyphAtlas: could not obtain OffscreenCanvas 2D context.");return{canvas:i,ctx:s}}const i=document.createElement("canvas");i.width=t,i.height=e;const s=i.getContext("2d");if(!s)throw new Error("GlyphAtlas: could not obtain canvas 2D context.");return{canvas:i,ctx:s}}(e,i);this._ctx=s,this.texture=new pi(t),this.texture.setSize(e,i)}}insert(t,e){return this._packer.insert(t,e)}writeSdf(t,e,i,s,n){const r=this._sdfBuffer,o=this._width;for(let a=0;a<n;a++){const n=a*s,h=(i+a)*o+e;r.set(t.subarray(n,n+s),h)}this._sdfTexture.commitRect(e,i,s,n)}measureGlyph(t,e){if(null!==this._ctx)return this._ctx.font=e,this._ctx.textBaseline="alphabetic",this._ctx.measureText(t);const i=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")).getContext("2d");return i.font=e,i.textBaseline="alphabetic",i.measureText(t)}rasterize(t,e,i,s,n,r){const o=this._ctx;o.font=r,o.textBaseline="alphabetic",this._colorGlyphs||(o.fillStyle="#ffffff"),o.fillText(t,e+2+n,i+2+s)}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 zn{_pages=[];_cache=new Map;_kerningCache=new Map;_pageSize;_family;_fontStyle;_fontWeight;_mode;_sdfRadius;onPageAdded=new m;_sdfInstances=new Map;constructor(t,e,i,s=1024,n="sdf",r=8){this._family=t,this._fontStyle=e,this._fontWeight=i,this._pageSize=s,this._mode=n,this._sdfRadius=r,this._addPage()}get pages(){return this._pages}get mode(){return this._mode}getGlyph(t,e){const i=`${t}:${e}`,s=this._cache.get(i);return void 0!==s?s:"sdf"===this._mode?this._rasterizeSdf(t,e,i):this._rasterizeCanvas(t,e,i)}getKerning(t,e,i){const s=`${t}${e}:${i}`,n=this._kerningCache.get(s);if(void 0!==n)return n;const r=this._cssFont(i),o=this._pages[0],a=o.measureGlyph(t+e,r).width-o.measureGlyph(t,r).width-o.measureGlyph(e,r).width;return this._kerningCache.set(s,a),a}clear(){this._cache.clear(),this._kerningCache.clear(),this._sdfInstances.clear();for(const t of this._pages)t.reset();this._pages=[],this._addPage()}_addPage(){const t=this._pages.length,e=new Vn(t,this._pageSize,this._pageSize,this._mode);return this._pages.push(e),t>0&&this.onPageAdded.dispatch(t),e}_cssFont(t){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${t}px ${this._family}`}_getSdf(t){let e=this._sdfInstances.get(t);return void 0===e&&(e=new Fn({fontSize:t,fontFamily:this._family,fontWeight:this._fontWeight,fontStyle:this._fontStyle,buffer:this._sdfRadius,radius:this._sdfRadius,cutoff:.5}),this._sdfInstances.set(t,e)),e}_rasterizeSdf(t,e,i){const s=this._getSdf(e).draw(t),{page:n,slot:r}=this._allocateSlot(s.width,s.height);n.writeSdf(s.data,r.x,r.y,s.width,s.height);const o=this._pageSize,a={x:r.x,y:r.y,width:s.width,height:s.height,advance:s.glyphAdvance,ascent:s.glyphTop+s.glyphHeight,page:n.index,uvLeft:r.x/o,uvTop:r.y/o,uvRight:(r.x+s.width)/o,uvBottom:(r.y+s.height)/o,xBearing:-s.glyphLeft,yBearing:-s.glyphTop};return this._cache.set(i,a),a}_rasterizeCanvas(t,e,i){const s=this._cssFont(e),n=this._pages[0].measureGlyph(t,s),r=Math.ceil(n.fontBoundingBoxAscent??n.actualBoundingBoxAscent??.8*e),o=Math.ceil(n.fontBoundingBoxDescent??n.actualBoundingBoxDescent??.2*e),a=n.width,h=n.actualBoundingBoxLeft??0,l=n.actualBoundingBoxRight??0,u=Math.max(1,Math.ceil(h+l)||Math.ceil(a)),c=Math.max(1,r+o),d=u+4,_=c+4,{page:f,slot:p}=this._allocateSlot(d,_);f.rasterize(t,p.x,p.y,r,h,s),f.uploadDirtyRegion();const g=this._pageSize,m={x:p.x,y:p.y,width:u,height:c,advance:a,ascent:r,page:f.index,uvLeft:p.x/g,uvTop:p.y/g,uvRight:(p.x+d)/g,uvBottom:(p.y+_)/g};return this._cache.set(i,m),m}_allocateSlot(t,e){for(const i of this._pages){const s=i.insert(t,e);if(null!==s)return{page:i,slot:s}}const i=this._addPage(),s=i.insert(t,e);if(null===s)throw new Error(`GlyphAtlas: glyph (${t}×${e}px) exceeds page size (${this._pageSize}px).`);return{page:i,slot:s}}}class qn{_atlases=new Map;_pageSize;constructor(t=1024){this._pageSize=t}getAtlas(t,e,i,s="sdf",n=8){const r=`${t}:${e}:${i}:${s}:${n}`;let o=this._atlases.get(r);return void 0===o&&(o=new zn(t,e,i,this._pageSize,s,n),this._atlases.set(r,o)),o}clearAll(){for(const t of this._atlases.values())t.clear()}}let Yn=null;function Wn(){return null===Yn&&(Yn=new qn),Yn}class $n extends Bn{_style;_layout;_colorGlyphs;_sdfRadius;_atlas=null;_destroyed=!1;_faceLoadVersion=0;_pageQuads=[];_textBounds={width:0,height:0};constructor(t,e={}){super(t),this._style=new An(e),this._layout=e,this._colorGlyphs=e.colorGlyphs??!1,this._sdfRadius=e.sdfRadius??8;const i=this._extractFace(e);null!==i&&this._loadFace(i),this._rebuild("font")}get style(){return this._style}set style(t){if(this._style=t instanceof An?t:new An(t),!(t instanceof An)){const e=this._extractFace(t);null!==e&&this._loadFace(e)}this._rebuild("font")}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this._rebuild("layout"))}get layout(){return this._layout}set layout(t){this._layout=t,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 t=this._style.consumeDirty();null!==t&&"tint"!==t&&this._rebuild(t)}destroy(){this._destroyed=!0,this._faceLoadVersion++,this._pageQuads=[],this._atlas=null,super.destroy()}_extractFace(t){return"undefined"==typeof FontFace?null:t.font instanceof FontFace?t.font:null}async _loadFace(t){if("undefined"==typeof document||!document.fonts)return;const e=++this._faceLoadVersion;document.fonts.has(t)||document.fonts.add(t);try{await t.load()}catch{return}if(this._destroyed||e!==this._faceLoadVersion)return;Wn().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius).clear(),this._rebuild("font")}_rebuild(t){if(this._pageQuads=[],this._textBounds={width:0,height:0},0===this._text.length)return void this._style.consumeDirty();const e=Wn().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius);this._atlas=e;const i=Tn(this._text,this._style,this._layout,e);if(0===i.length)return void this._style.consumeDirty();let s=0,n=0;for(const t of i){const e=t.x+t.width,i=t.y+t.height;e>s&&(s=e),i>n&&(n=i)}this._textBounds={width:s,height:n},this._pageQuads=Mn(i),this._style.consumeDirty()}}class Xn{attributes=new Map;uniforms=new Map;_vertexSource;_fragmentSource;_program=null;constructor(t,e){this._vertexSource=t,this._fragmentSource=e}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(t){return this._program=t,t.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(t){const e=this.attributes.get(t);if(!e)throw new Error(`Attribute "${t}" is not available.`);return e}getUniform(t){const e=this.uniforms.get(t);if(!e)throw new Error(`Uniform "${t}" is not available.`);return e}destroy(){this._program?.destroy(this),this._program=null,this.attributes.clear(),this.uniforms.clear()}}var jn;!function(t){t[t.WebGl2=0]="WebGl2",t[t.WebGpu=1]="WebGpu"}(jn||(jn={}));class Hn{backendType=jn.WebGl2;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==jn.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 Kn{_type;_usage;_runtime=null;_data=_;_version=0;_accountant=null;_accountedBytes=0;constructor(t,e,i){this._type=t,this._usage=i,e&&this.upload(e)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(t,e){return this._runtime=t,this._accountant=e??null,this._data.byteLength>0&&(t.upload(this,0),this._bookUpload()),this}disconnect(){return this._runtime=null,this}upload(t,e=0){this._data=t,this._version++,this._runtime?.upload(this,e),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 t=this._accountant;if(null===t||null===this._runtime)return;const e=this._data.byteLength;t.recordBufferUpload(e),e>this._accountedBytes&&(this._accountedBytes=t.reallocate(this._accountedBytes,e))}}const Qn={[ui.Float]:1,[ui.FloatVec2]:2,[ui.FloatVec3]:3,[ui.FloatVec4]:4,[ui.Int]:1,[ui.IntVec2]:2,[ui.IntVec3]:3,[ui.IntVec4]:4,[ui.UnsignedInt]:1,[ui.UnsignedIntVec2]:2,[ui.UnsignedIntVec3]:3,[ui.UnsignedIntVec4]:4,[ui.Bool]:1,[ui.BoolVec2]:2,[ui.BoolVec3]:3,[ui.BoolVec4]:4,[ui.FloatMat2]:4,[ui.FloatMat3]:9,[ui.FloatMat4]:16,[ui.Sampler2D]:1},Zn={[ui.Float]:Float32Array,[ui.FloatVec2]:Float32Array,[ui.FloatVec3]:Float32Array,[ui.FloatVec4]:Float32Array,[ui.Int]:Int32Array,[ui.IntVec2]:Int32Array,[ui.IntVec3]:Int32Array,[ui.IntVec4]:Int32Array,[ui.UnsignedInt]:Int32Array,[ui.UnsignedIntVec2]:Int32Array,[ui.UnsignedIntVec3]:Int32Array,[ui.UnsignedIntVec4]:Int32Array,[ui.Bool]:Uint8Array,[ui.BoolVec2]:Uint8Array,[ui.BoolVec3]:Uint8Array,[ui.BoolVec4]:Uint8Array,[ui.FloatMat2]:Float32Array,[ui.FloatMat3]:Float32Array,[ui.FloatMat4]:Float32Array,[ui.Sampler2D]:Uint8Array};ui.Float,ui.FloatVec2,ui.FloatVec3,ui.FloatVec4,ui.Int,ui.IntVec2,ui.IntVec3,ui.IntVec4,ui.UnsignedInt,ui.UnsignedIntVec2,ui.UnsignedIntVec3,ui.UnsignedIntVec4,ui.Bool,ui.BoolVec2,ui.BoolVec3,ui.BoolVec4,ui.FloatMat2,ui.FloatMat3,ui.FloatMat4,ui.Sampler2D;class Jn{index;name;type;size;location=-1;constructor(t,e,i){this.index=t,this.name=e,this.type=i,this.size=Qn[i]}destroy(){}}class tr{index;type;size;name;_value;_dirty=!0;constructor(t,e,i,s,n){this.name=s.replace(/\[.*?]/,""),this.index=t,this.type=e,this.size=i,this._value=n}get propName(){return this.name.substring(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(t){return this._value.set(t),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class er{index;name;binding;dataSize;_context;_program;_blockData;_uniformBuffer;_uniforms=new Map;constructor(t,e,i){this._context=t,this._program=e,this.index=i,this.name=t.getActiveUniformBlockName(e,i)||"",this.binding=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_BINDING),this.dataSize=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=t.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferData(t.UNIFORM_BUFFER,this._blockData,t.DYNAMIC_DRAW),t.bindBufferBase(t.UNIFORM_BUFFER,this.binding,this._uniformBuffer),t.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(t){if(!this._uniforms.has(t))throw new Error(`Uniform "${t}" is not available.`);return this._uniforms.get(t)}upload(){const t=this._context;t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferSubData(t.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const t of this._uniforms.values())t.destroy();this._uniforms.clear()}_extractUniforms(){const t=this._context,e=this._program,i=this._blockData,s=t.getActiveUniformBlockParameter(e,this.index,t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),n=t.getActiveUniforms(e,s,t.UNIFORM_OFFSET),r=s.length;for(let o=0;o<r;o++){const r=s[o],{type:a,size:h,name:l}=t.getActiveUniform(e,r),u=Zn[a],c=Qn[a];if(void 0===u||void 0===c)throw new Error(`Unsupported uniform type ${a} for uniform "${l}".`);const d=new u(i,n[o],c*h),_=new tr(r,a,h,l,d);this._uniforms.set(_.propName,_)}}}const ir={[ui.Float]:(t,e,i)=>{t.uniform1f(e,i[0])},[ui.FloatVec2]:(t,e,i)=>{t.uniform2fv(e,i)},[ui.FloatVec3]:(t,e,i)=>{t.uniform3fv(e,i)},[ui.FloatVec4]:(t,e,i)=>{t.uniform4fv(e,i)},[ui.Int]:(t,e,i)=>{t.uniform1i(e,i[0])},[ui.IntVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[ui.IntVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[ui.IntVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[ui.Bool]:(t,e,i)=>{t.uniform1i(e,i[0])},[ui.BoolVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[ui.BoolVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[ui.BoolVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[ui.FloatMat2]:(t,e,i)=>{t.uniformMatrix2fv(e,!1,i)},[ui.FloatMat3]:(t,e,i)=>{t.uniformMatrix3fv(e,!1,i)},[ui.FloatMat4]:(t,e,i)=>{t.uniformMatrix4fv(e,!1,i)},[ui.Sampler2D]:(t,e,i)=>{t.uniform1i(e,i[0])}};function sr(t){let e=null,i=null,s=null,n=null;const r=[],o=[],a=t.getExtension("KHR_parallel_shader_compile"),h=a?.COMPLETION_STATUS_KHR??37297;function l(r){e||(i=nr(t,t.VERTEX_SHADER,r.vertexSource),s=nr(t,t.FRAGMENT_SHADER,r.fragmentSource),e=function(t,e,i){const s=t.createProgram();if(!s)throw new Error("Could not create shader program.");return t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s),s}(t,i,s),n=r)}function u(){if(null!==n&&null!==e&&null!==i&&null!==s){if(null!==a&&t.getProgramParameter(e,h),!t.getShaderParameter(i,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(i);throw new Error(`Vertex shader compilation failed: ${e??"<no log>"}`)}if(!t.getShaderParameter(s,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(s);throw new Error(`Fragment shader compilation failed: ${e??"<no log>"}`)}if(!t.getProgramParameter(e,t.LINK_STATUS)){const i=t.getProgramInfoLog(e);throw new Error(`Shader program linking failed: ${i??"<no log>"}`)}!function(t,e,i){const s=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let n=0;n<s;n++){const s=t.getActiveAttrib(e,n);if(!s)continue;const r=new Jn(n,s.name,s.type);r.location=t.getAttribLocation(e,s.name),i.attributes.set(s.name,r)}}(t,e,n),function(t,e,i,s){const n=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),r=new Uint8Array(n).map((t,e)=>e),o=t.getActiveUniforms(e,r,t.UNIFORM_BLOCK_INDEX),a=r.filter(t=>-1===o[t]);for(const n of a){const r=t.getActiveUniform(e,n);if(!r)continue;const o=Zn[r.type],a=Qn[r.type],h=ir[r.type];if(void 0===o||void 0===a||void 0===h)throw new Error(`Unsupported uniform type ${r.type} for uniform "${r.name}".`);const l=new o(a*r.size),u=new tr(n,r.type,r.size,r.name,l),c=t.getUniformLocation(e,u.name);i.uniforms.set(u.name,u),c&&s.push({location:c,uploadFn:h,uniform:u})}}(t,e,n,r),function(t,e,i){const s=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let n=0;n<s;n++){const s=new er(t,e,n);i.push(s)}}(t,e,o),n=null}}function c(){for(const e of r)e.uniform.dirty&&(e.uploadFn(t,e.location,e.uniform.value),e.uniform.markClean());for(const t of o)t.upload()}return{initialize:l,bind:i=>{l(i),u(),t.useProgram(e),c()},unbind:()=>{t.useProgram(null)},sync:()=>{u(),t.useProgram(e),c()},destroy:a=>{t.deleteShader(i),t.deleteShader(s),t.deleteProgram(e);for(const t of o)t.destroy();i=null,s=null,e=null,n=null,r.length=0,o.length=0,a.disconnect()}}}function nr(t,e,i){const s=t.createShader(e);if(!s)throw new Error("Could not create shader.");return t.shaderSource(s,i),t.compileShader(s),s}class rr{_attributes=[];_indexBuffer=null;_drawMode;_runtime=null;_version=0;constructor(t=ai.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(t){return this._runtime=t,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(t,e,i=ui.Float,s=!1,n=0,r=0,o=!1,a=0){const{location:h,size:l}=e;return this._attributes.push({buffer:t,location:h,size:l,type:i,normalized:s,stride:n,start:r,integer:o,divisor:a}),this._version++,this}addIndex(t){return this._indexBuffer=t,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(t,e,i=this._drawMode){return this._runtime?.draw(this,t,e,i),this}drawInstanced(t,e,i,s=this._drawMode){return this._runtime?.drawInstanced?.(this,t,e,i,s),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}const or=20;class ar extends Hn{_defaultShader=new Xn("#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)},(t,e)=>new Int32Array([e]));_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 e=this._connection;if(!e)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(0===t.vertexCount)return;const i=this.getBackend(),s=t.material,n=null===s?this._defaultShader:this._getOrCreateCustomShader(s,e.gl),r=null!==s&&t.blendMode===ni.Normal?s.blendMode:t.blendMode,o=t.texture??pi.white,a=i.activeDrawCommand,h=null===s||this._isInstancingCompatible(n);let l=this._pendingDraws[this._pendingCount];void 0===l?(l={mesh:t,command:a,material:s,shader:n,blendMode:r,texture:o,supportsInstancing:h},this._pendingDraws.push(l)):(l.mesh=t,l.command=a,l.material=s,l.shader=n,l.blendMode=r,l.texture=o,l.supportsInstancing=h),this._pendingCount++}drawInstancedBatch(t,e,i){const s=this._connection;if(!s)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(i<=0||0===t.vertexCount)return;const n=t.geometry;if(null===n)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 r=this.getBackend(),o=this._defaultShader,a=t.blendMode,h=t.texture??pi.white,l=this._getOrCreateStaticGeometryEntry(n,t,s),u=this._getOrCreateStaticGeometryVao(l,o,s.gl,s.dynamicNodeIndexBuffer);this._setBlendMode(a,r),this._ensureNodeIndexCapacity(i);const c=e+i-1>>>0;for(let t=0;t<i;t++)this._nodeIndexData[t]=e+t>>>0;this._bindInstancedShaderState(o,h,null,r,c),r.bindVertexArrayObject(u),s.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,i)),u.drawInstanced(l.indexCount,0,i,ai.Triangles),r.stats.batches++,r.stats.drawCalls++}flush(){const t=this.getBackendOrNull(),e=this._connection,i=this._pendingCount;if(null!==t&&null!==e&&0!==i){for(let s=0;s<i;s++){const n=this._pendingDraws[s];if(this._canBatchStatic(n)){let n=s+1;for(;n<i&&this._isSameBatch(this._pendingDraws[n-1],this._pendingDraws[n]);)n++;if(n-s>=2){this._drawStaticBatch(s,n,t,e),s=n-1;continue}}this._drawSingle(s,t,e)}this._pendingCount=0}else this._pendingCount=0}destroy(){this.disconnect(),this._defaultShader.destroy();for(const t of this._customShaders.values())t.destroy();this._customShaders.clear(),this._compatibilityCache.clear()}onConnect(t){const e=t.context;this._defaultShader.connect(sr(e)),this._defaultShader.sync();for(const t of this._customShaders.values())t.connect(sr(e)),t.sync();const i=new Map,s=new Kn(hi.ElementArrayBuffer,this._indexData,li.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),n=new Kn(hi.ArrayBuffer,this._vertexData,li.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),r=new Kn(hi.ArrayBuffer,this._nodeIndexData,li.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),o=e.createVertexArray();if(null===o)throw new Error("Could not create vertex array object.");const a=(new rr).addIndex(s).addAttribute(n,this._defaultShader.getAttribute("a_position"),e.FLOAT,!1,or,0).addAttribute(n,this._defaultShader.getAttribute("a_texcoord"),e.FLOAT,!1,or,8).addAttribute(n,this._defaultShader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,or,16).addAttribute(r,this._defaultShader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(e,o));this._connection={gl:e,buffers:i,dynamicVao:a,dynamicVertexBuffer:n,dynamicIndexBuffer:s,dynamicNodeIndexBuffer:r}}onDisconnect(){const t=this._connection;if(t){this._defaultShader.disconnect();for(const t of this._customShaders.values())t.disconnect();for(const t of this._staticGeometryCache.values()){for(const e of t.vaos.values())e.destroy();t.vaos.clear(),t.indexBuffer.destroy(),t.vertexBuffer.destroy()}this._staticGeometryCache.clear(),t.dynamicNodeIndexBuffer.destroy(),t.dynamicIndexBuffer.destroy(),t.dynamicVertexBuffer.destroy(),t.dynamicVao.destroy(),this._connection=null,this._currentBlendMode=null,this._pendingDraws.length=0,this._pendingCount=0}}_drawSingle(t,e,i){const s=this._pendingDraws[t];this._canBatchStatic(s)?this._drawStaticBatch(t,t+1,e,i):s.supportsInstancing&&null===s.material?this._drawDynamicInstancedSingle(s,e,i):this._drawLegacyImmediate(s,e,i)}_drawDynamicInstancedSingle(t,e,i){const s=t.command?.nodeIndex??0;null===t.command&&e._writeTransformCommand(this._createSyntheticCommand(t.mesh,s)),this._setBlendMode(t.blendMode,e),this._bindInstancedShaderState(t.shader,t.texture,t.material,e,s),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]=s>>>0,e.bindVertexArrayObject(i.dynamicVao),i.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*t.mesh.vertexCount)),i.dynamicIndexBuffer.upload(this._indexData.subarray(0,t.mesh.indexCount)),i.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,1)),i.dynamicVao.drawInstanced(t.mesh.indexCount,0,1,ai.Triangles),e.stats.batches++,e.stats.drawCalls++}_drawStaticBatch(t,e,i,s){const n=this._pendingDraws[t],r=n.mesh.geometry,o=e-t,a=this._getOrCreateStaticGeometryEntry(r,n.mesh,s),h=this._getOrCreateStaticGeometryVao(a,n.shader,s.gl,s.dynamicNodeIndexBuffer);this._setBlendMode(n.blendMode,i);let l=0;this._ensureNodeIndexCapacity(o);for(let e=0;e<o;e++){const i=this._pendingDraws[t+e].command.nodeIndex>>>0;this._nodeIndexData[e]=i,i>l&&(l=i)}this._bindInstancedShaderState(n.shader,n.texture,n.material,i,l),i.bindVertexArrayObject(h),s.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,o)),h.drawInstanced(a.indexCount,0,o,ai.Triangles),i.stats.batches++,i.stats.drawCalls++}_drawLegacyImmediate(t,e,i){const s=t.mesh,n=t.shader;this._setBlendMode(t.blendMode,e),n.uniforms.has("u_projection")&&n.getUniform("u_projection").setValue(e.view.getTransform().toArray(!1)),n.uniforms.has("u_translation")&&n.getUniform("u_translation").setValue(s.getGlobalTransform().toArray(!1)),n.uniforms.has("u_tint")&&n.getUniform("u_tint").setValue(s.tint.toArray(!1)),n.uniforms.has("u_texture")&&(n.getUniform("u_texture").setValue(this._textureUnitScratch),e.bindTexture(t.texture,0)),null!==t.material&&this._bindCustomUniforms(n,t.material,e),this._ensureVertexCapacity(s.vertexCount),this._ensureIndexCapacity(s.indexCount),this._packVertices(s,0),this._packIndices(s,0),n.sync(),e.bindVertexArrayObject(i.dynamicVao),i.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*s.vertexCount)),i.dynamicIndexBuffer.upload(this._indexData.subarray(0,s.indexCount)),i.dynamicVao.draw(s.indexCount,0,ai.Triangles),e.stats.batches++,e.stats.drawCalls++}_bindInstancedShaderState(t,e,i,s,n){t.uniforms.has("u_projection")&&t.getUniform("u_projection").setValue(s.view.getTransform().toArray(!1)),t.uniforms.has("u_transforms")&&(s.bindTransformBufferTexture(8,n+1),t.getUniform("u_transforms").setValue(this._transformUnitScratch)),t.uniforms.has("u_texture")&&(t.getUniform("u_texture").setValue(this._textureUnitScratch),s.bindTexture(e,0)),null!==i&&this._bindCustomUniforms(t,i,s),t.sync()}_canBatchStatic(t){if(!t.supportsInstancing)return!1;if(void 0===t.command?.groupIndex)return!1;const e=t.mesh.geometry;return"static"===e?.usage}_isSameBatch(t,e){return!(!this._canBatchStatic(t)||!this._canBatchStatic(e))&&(t.command.groupIndex===e.command.groupIndex&&t.mesh.geometry===e.mesh.geometry&&t.shader===e.shader&&t.material===e.material&&t.blendMode===e.blendMode&&t.texture===e.texture&&t.command.material.pipelineKey===e.command.material.pipelineKey&&t.command.material.bindKey===e.command.material.bindKey)}_isInstancingCompatible(t){const e=this._compatibilityCache.get(t);if(void 0!==e)return e;const i=t.attributes.has("a_nodeIndex")&&t.uniforms.has("u_transforms")&&!t.uniforms.has("u_translation")&&!t.uniforms.has("u_tint");return this._compatibilityCache.set(t,i),i}_getOrCreateStaticGeometryEntry(t,e,i){const s=this._staticGeometryCache.get(t);if(void 0!==s)return s;const n=e.vertexCount,r=e.indexCount,o=new ArrayBuffer(n*or),a=new Float32Array(o),h=new Uint32Array(o);this._packVertices(e,0,a,h);const l=new Uint16Array(r);this._packIndices(e,0,l);const u=this.getBackend().accountant,c=new Kn(hi.ArrayBuffer,a,li.StaticDraw).connect(this._createBufferRuntime(i.gl,i.buffers),u),d=new Kn(hi.ElementArrayBuffer,l,li.StaticDraw).connect(this._createBufferRuntime(i.gl,i.buffers),u);c.upload(a),d.upload(l);const _=()=>{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(_);const f={geometry:t,vertexBuffer:c,indexBuffer:d,vaos:new Map,disposeListener:_,indexCount:r};return this._staticGeometryCache.set(t,f),f}_getOrCreateStaticGeometryVao(t,e,i,s){const n=t.vaos.get(e);if(void 0!==n)return n;const r=i.createVertexArray();if(null===r)throw new Error("Could not create vertex array object.");const o=e.getAttribute("a_nodeIndex"),a=(new rr).addIndex(t.indexBuffer).addAttribute(t.vertexBuffer,e.getAttribute("a_position"),i.FLOAT,!1,or,0).addAttribute(t.vertexBuffer,e.getAttribute("a_texcoord"),i.FLOAT,!1,or,8).addAttribute(t.vertexBuffer,e.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,or,16).addAttribute(s,o,i.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(i,r));return t.vaos.set(e,a),a}_setBlendMode(t,e){this._currentBlendMode!==t&&(this._currentBlendMode=t,e.setBlendMode(t))}_packVertices(t,e,i=this._float32View,s=this._uint32View){const n=t.vertices,r=t.uvs,o=t.colors,a=t.vertexCount;for(let t=0;t<a;t++){const a=5*(e+t),h=2*t;i[a]=n[h],i[a+1]=n[h+1],null!==r?(i[a+2]=r[h],i[a+3]=r[h+1]):(i[a+2]=0,i[a+3]=0),s[a+4]=null!==o?o[t]:4294967295}}_packIndices(t,e,i=this._indexData){const s=t.indexCount;if(null===t.indices)for(let t=0;t<s;t++)i[e+t]=t;else i.set(t.indices,e)}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*or),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeIndexCapacity(t){if(!(t<=this._nodeIndexCapacity)){for(;this._nodeIndexCapacity<t;)this._nodeIndexCapacity*=2;this._nodeIndexData=new Uint32Array(this._nodeIndexCapacity)}}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(s,n)=>{const r=e.get(s),o=s.data;t.bindBuffer(s.type,i),r&&r.dataByteLength>=o.byteLength?(t.bufferSubData(s.type,n,o),r.dataByteLength=o.byteLength):(t.bufferData(s.type,o,s.usage),e.set(s,{handle:i,dataByteLength:o.byteLength}))},destroy:s=>{t.deleteBuffer(i),e.delete(s),s.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:s=>{if(t.bindVertexArray(e),i!==s.version){let e=null;for(const i of s.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),i.integer?t.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location),t.vertexAttribDivisor(i.location,i.divisor);s.indexBuffer&&s.indexBuffer.bind(),i=s.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,n)=>{e.indexBuffer?t.drawElements(n,i,t.UNSIGNED_SHORT,s):t.drawArrays(n,s,i)},drawInstanced:(e,i,s,n,r)=>{e.indexBuffer?t.drawElementsInstanced(r,i,t.UNSIGNED_SHORT,s,n):t.drawArraysInstanced(r,s,i,n)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}_getOrCreateCustomShader(t,e){const i=this._customShaders.get(t);if(void 0!==i)return i;const s=t.shader.glsl;if(null===s)throw new Error("Mesh material shader has no `glsl` source; cannot render through the WebGL2 backend.");const n=new Xn(s.vertex,s.fragment);return n.connect(sr(e)),n.sync(),this._customShaders.set(t,n),t._onDispose(()=>{const e=this._customShaders.get(t);void 0!==e&&(e.destroy(),this._customShaders.delete(t))}),n}_bindCustomUniforms(t,e,i){let s=1;const n=e.uniforms;for(const e in n){if(!t.uniforms.has(e))continue;const r=n[e],o=t.getUniform(e);if(r instanceof pi||r instanceof _i){if(s>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(r,s),o.setValue(this._slotScratches[s]),s++}else o.setValue(this._marshalUniformValue(r))}const r=e.textures;for(const e in r)if(t.uniforms.has(e)){if(s>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(r[e],s),t.getUniform(e).setValue(this._slotScratches[s]),s++}}_marshalUniformValue(t){return t instanceof Float32Array||t instanceof Int32Array?t:"number"==typeof t?new Float32Array([t]):new Float32Array(t)}_createSyntheticCommand(t,e){return{kind:Fe.Draw,drawable:t,nodeIndex:e,seq:0,zIndex:t.zIndex,material:{rendererId:0,blendMode:t.blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},minX:0,minY:0,maxX:0,maxY:0,groupIndex:0}}}const hr=32,lr=hr/Uint32Array.BYTES_PER_ELEMENT;class ur extends Hn{_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(t){super(),this._batchSize=t,this._shader=new Xn("#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(t*hr),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(t){const e=this.getBackend();let i=t.quads;if("geometry"===t.pixelSnapMode){const s=e._getSnapPixelSize();i=t.getRenderQuads(e.view,s.width,s.height)}if(0===i.length)return;const s=t.texture,n=t.blendMode,r=t.tint.toRgba(),o=e.activeDrawCommand,a=null!==o?o.nodeIndex:e._pushTransform(t),h=null!==this._currentTexture&&s!==this._currentTexture,l=n!==this._currentBlendMode;this._quadIndex>0&&(l||h||this._quadIndex+i.length>this._batchSize)&&this.flush(),null!==this._currentBlendMode&&this._currentBlendMode===n||(this._currentBlendMode=n,e.setBlendMode(n)),this._currentTexture!==s&&(this._currentTexture=s,e.bindTexture(s,0));let u=0;for(;u<i.length;){const t=Math.min(u+this._batchSize,i.length);this._writeQuadChunk(i,u,t,s,r,a),u=t,u<i.length&&(this.flush(),this._currentBlendMode=n,e.setBlendMode(n),this._currentTexture=s,e.bindTexture(s,0))}}_writeQuadChunk(t,e,i,s,n,r){const o=this._instanceFloat32,a=this._instanceUint32,h=s.flipY;for(let s=e;s<i;s++){const e=t[s],i=this._quadIndex*lr;o[i+0]=e.x0,o[i+1]=e.y0,o[i+2]=e.x1,o[i+3]=e.y1;const l=65535*e.u0&65535,u=65535*e.u1&65535,c=65535*e.v0&65535,d=65535*e.v1&65535,_=h?d:c,f=h?c:d;a[i+4]=l|_<<16,a[i+5]=u|f<<16,a[i+6]=n,a[i+7]=r>>>0,this._quadIndex++,r>this._maxNodeIndex&&(this._maxNodeIndex=r)}}flush(){const t=this.getBackendOrNull(),e=this._instanceBuffer,i=this._vao;if(0===this._quadIndex||null===t||null===e||null===i)return this._quadIndex=0,void(this._maxNodeIndex=0);const s=t.view;this._currentView===s&&this._currentViewId===s.updateId||(this._currentView=s,this._currentViewId=s.updateId,this._shader.getUniform("u_projection").setValue(s.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(i),e.upload(this._instanceFloat32.subarray(0,this._quadIndex*lr)),i.drawInstanced(4,0,this._quadIndex,ai.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._quadIndex=0,this._maxNodeIndex=0}onConnect(t){const e=t.context;this._shader.connect(sr(e)),this._connection=this._createConnection(e),this._instanceBuffer=new Kn(hi.ArrayBuffer,this._instanceData,li.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new rr(ai.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_quadBounds"),e.FLOAT,!1,hr,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),e.UNSIGNED_SHORT,!0,hr,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,hr,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,hr,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(t){const e=t.createVertexArray();if(null===e)throw new Error("WebGl2NineSliceSpriteRenderer: could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}_createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("WebGl2NineSliceSpriteRenderer: could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,s)=>{const n=t.gl,r=i.data,o=t.buffers.get(i);n.bindBuffer(i.type,e),o&&o.dataByteLength>=r.byteLength?(n.bufferSubData(i.type,s,r),o.dataByteLength=r.byteLength):(n.bufferData(i.type,r,i.usage),t.buffers.set(i,{handle:e,dataByteLength:r.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(t){let e=-1;return{bind:i=>{const s=t.gl;if(s.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),e.integer?s.vertexAttribIPointer(e.location,e.size,e.type,e.stride,e.start):s.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),s.enableVertexAttribArray(e.location),s.vertexAttribDivisor(e.location,e.divisor);e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,s,n)=>{t.gl.drawArrays(n,s,i)},drawInstanced:(e,i,s,n,r)=>{t.gl.drawArraysInstanced(r,s,i,n)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}const cr="#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}",dr=40,_r=dr/Uint32Array.BYTES_PER_ELEMENT,fr=32,pr=fr/Uint32Array.BYTES_PER_ELEMENT;function gr(t){return"repeat"===t?oi.Repeat:"mirror-repeat"===t?oi.MirroredRepeat:oi.ClampToEdge}class mr extends Hn{_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 Zt;_currentView=null;_currentViewId=-1;constructor(t){super(),this._batchSize=t,this._shaderPathShader=new Xn("#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}",cr),this._geoPathShader=new Xn("#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}",cr),this._shaderData=new ArrayBuffer(t*dr),this._shaderF32=new Float32Array(this._shaderData),this._shaderU32=new Uint32Array(this._shaderData),this._geoData=new ArrayBuffer(t*fr),this._geoF32=new Float32Array(this._geoData),this._geoU32=new Uint32Array(this._geoData)}render(t){const e=t.resolvedStrategy,i=t.texture,s=t.blendMode,n=t.modeX,r=t.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const t=this._currentPath!==e,o=this._currentTexture!==i,a=this._currentBlendMode!==s,h="shader"===e&&(this._currentModeX!==n||this._currentModeY!==r);(t||o||a||h)&&this.flush()}const o=this.getBackend();this._currentTexture!==i&&(this._currentTexture=i,o.bindTexture(i,0)),this._currentBlendMode!==s&&(this._currentBlendMode=s,o.setBlendMode(s)),this._currentPath=e;const a=o.activeDrawCommand,h=null!==a?a.nodeIndex:o._pushTransform(t);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===e?(this._currentModeX=n,this._currentModeY=r,this._writeShaderInstance(t,h)):this._writeGeoQuads(t,h)}_writeShaderInstance(t,e){const i=t.texture,s=t.region.width,n=t.region.height;let r=t.width,o=t.height;const a=i instanceof pi&&i.flipY;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),i=e._getSnapPixelSize(),s=t.getRenderBounds(e.view,i.width,i.height,this._snapBounds);r=s.width,o=s.height}const h=wn(s,r,t.modeX,t.fitX),l=wn(n,o,t.modeY,t.fitY),u=t.offsetX/(s>0?s:1),c=t.offsetY/(n>0?n:1),d=a?-l:l,_=a?l+c:c;this._shaderQuadCount>=this._batchSize&&this.flush();const f=this._shaderQuadCount*_r,p=this._shaderF32,g=this._shaderU32;p[f+0]=0,p[f+1]=0,p[f+2]=r,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,g[f+8]=t.tint.toRgba(),g[f+9]=e>>>0,this._shaderQuadCount++}_writeGeoQuads(t,e){let i=t.quads;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),s=e._getSnapPixelSize();i=t.getRenderQuads(e.view,s.width,s.height)}const s=t.texture instanceof pi&&t.texture.flipY,n=t.tint.toRgba();let r=0;for(;r<i.length;){const o=i.length-r,a=Math.min(o,this._batchSize-this._geoQuadCount);if(a<=0){this.flush();const i=this.getBackend();i.bindTexture(t.texture,0),i.setBlendMode(t.blendMode),this._currentTexture=t.texture,this._currentBlendMode=t.blendMode,this._currentPath="geometry",e>this._maxNodeIndex&&(this._maxNodeIndex=e);continue}const h=this._geoF32,l=this._geoU32;for(let t=0;t<a;t++){const o=i[r+t],a=(this._geoQuadCount+t)*pr;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=s?_:d,p=s?d:_;l[a+4]=u|f<<16,l[a+5]=c|p<<16,l[a+6]=n,l[a+7]=e>>>0}this._geoQuadCount+=a,r+=a}}flush(){const t=this.getBackendOrNull();if(null===t)return void this._resetBatchState();const e=t.view;if(this._currentView!==e||this._currentViewId!==e.updateId){this._currentView=e,this._currentViewId=e.updateId;const t=e.getTransform().toArray(!1);this._shaderPathShader.getUniform("u_projection").setValue(t),this._geoPathShader.getUniform("u_projection").setValue(t)}this._shaderQuadCount>0&&this._flushShaderBatch(t),this._geoQuadCount>0&&this._flushGeoBatch(t),this._resetBatchState()}_flushShaderBatch(t){const e=this._connection,i=this._shaderBuf,s=this._shaderVao;if(!e||!i||!s||0===this._shaderQuadCount)return;const n=e.gl,r=this._currentTexture,o=r instanceof pi?r.scaleMode:ri.Linear,a=gr(this._currentModeX??"repeat"),h=gr(this._currentModeY??"repeat"),l=this._getOrCreateSampler(n,a,h,o);n.bindSampler(0,l),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(s),i.upload(this._shaderF32.subarray(0,this._shaderQuadCount*_r)),s.drawInstanced(4,0,this._shaderQuadCount,ai.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,n.bindSampler(0,null),this._shaderQuadCount=0}_flushGeoBatch(t){const e=this._connection,i=this._geoBuf,s=this._geoVao;e&&i&&s&&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(s),i.upload(this._geoF32.subarray(0,this._geoQuadCount*pr)),s.drawInstanced(4,0,this._geoQuadCount,ai.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(t,e,i,s){const n=`${e}:${i}:${s}`,r=this._samplers.get(n);if(void 0!==r)return r;const o=t.createSampler();if(null===o)throw new Error("WebGl2RepeatingSpriteRenderer: could not create sampler.");return t.samplerParameteri(o,t.TEXTURE_WRAP_S,e),t.samplerParameteri(o,t.TEXTURE_WRAP_T,i),t.samplerParameteri(o,t.TEXTURE_MAG_FILTER,s),t.samplerParameteri(o,t.TEXTURE_MIN_FILTER,s),this._samplers.set(n,o),o}onConnect(t){const e=t.context;this._shaderPathShader.connect(sr(e)),this._geoPathShader.connect(sr(e)),this._shaderPathShader.sync(),this._geoPathShader.sync();const i=this._createConnection(e);this._connection=i,this._shaderBuf=new Kn(hi.ArrayBuffer,this._shaderData,li.DynamicDraw).connect(this._createBufRuntime(i,"shader"),t.accountant),this._shaderVao=new rr(ai.TriangleStrip).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_quadBounds"),e.FLOAT,!1,dr,0,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_uvParams"),e.FLOAT,!1,dr,16,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,dr,32,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,dr,36,!0,1).connect(this._createVaoRuntime(i,"shader")),this._geoBuf=new Kn(hi.ArrayBuffer,this._geoData,li.DynamicDraw).connect(this._createBufRuntime(i,"geo"),t.accountant),this._geoVao=new rr(ai.TriangleStrip).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_quadBounds"),e.FLOAT,!1,fr,0,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_uvBounds"),e.UNSIGNED_SHORT,!0,fr,16,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,fr,24,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,fr,28,!0,1).connect(this._createVaoRuntime(i,"geo"))}onDisconnect(){const t=this._connection?.gl;if(void 0!==t)for(const e of this._samplers.values())t.deleteSampler(e);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(t){const e=t.createVertexArray(),i=t.createVertexArray();if(null===e||null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create vertex array object.");return{gl:t,buffers:new Map,shaderVaoHandle:e,geoVaoHandle:i}}_createBufRuntime(t,e){const i=t.gl.createBuffer();if(null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create render buffer.");return{bind:e=>{t.gl.bindBuffer(e.type,i)},upload:(e,s)=>{const n=t.gl,r=e.data,o=t.buffers.get(e);n.bindBuffer(e.type,i),o&&o.dataByteLength>=r.byteLength?(n.bufferSubData(e.type,s,r),o.dataByteLength=r.byteLength):(n.bufferData(e.type,r,e.usage),t.buffers.set(e,{handle:i,dataByteLength:r.byteLength}))},destroy:e=>{t.gl.deleteBuffer(i),t.buffers.delete(e),e.disconnect()}}}_createVaoRuntime(t,e){const i="shader"===e?t.shaderVaoHandle:t.geoVaoHandle;let s=-1;return{bind:e=>{const n=t.gl;if(n.bindVertexArray(i),s!==e.version){let t=null;for(const i of e.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),i.integer?n.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):n.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),n.enableVertexAttribArray(i.location),n.vertexAttribDivisor(i.location,i.divisor);s=e.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,s,n)=>{t.gl.drawArrays(n,s,i)},drawInstanced:(e,i,s,n,r)=>{t.gl.drawArraysInstanced(r,s,i,n)},destroy:e=>{t.gl.deleteVertexArray(i),e.disconnect()}}}}const yr=36,wr=yr/Uint32Array.BYTES_PER_ELEMENT;class xr extends Hn{_shader;_batchSize;_instanceData;_instanceFloat32;_instanceUint32;_activeTextures=new Array(8).fill(null);_textureSlots=new Map;_slotCount=0;_customShaders=new Map;_slotScratches=Array.from({length:8},(t,e)=>new Int32Array([e]));_transformUnitScratch=new Int32Array([8]);_currentMaterial=null;_currentBaseTexture=null;_snapBounds=new Zt;_activeBounds=null;_instanceCount=0;_maxNodeIndex=0;_currentBlendMode=null;_currentView=null;_currentViewId=-1;_instanceBuffer=null;_vao=null;_connection=null;constructor(t){super(),this._batchSize=t,this._shader=new Xn("#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(t*yr),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(t){const e=t.texture;if(null===e)return this;const i=this.getBackend(),s=t.material,n=i.activeDrawCommand,r=null!==n?n.nodeIndex:i._pushTransform(t);return this._activeBounds=this._resolveBounds(t,i),null===s?this._renderDefault(t,e,i,r):this._renderCustom(t,e,s,i,r),this}_resolveBounds(t,e){if("geometry"!==t.pixelSnapMode)return t.getLocalBounds();const i=e._getSnapPixelSize();return t.getRenderBounds(e.view,i.width,i.height,this._snapBounds)}flush(){const t=this.getBackendOrNull(),e=this._instanceBuffer,i=this._vao,s=this._connection;if(0===this._instanceCount||null===t||null===e||null===i||null===s)return this._maxNodeIndex=0,void this._resetSlots();const n=this._currentMaterial,r=null===n?this._shader:this._getOrCreateCustomShader(n,s.gl);if(null===n){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{r.uniforms.has("u_projection")&&r.getUniform("u_projection").setValue(t.view.getTransform().toArray(!1));const e=this._currentBaseTexture;null!==e&&r.uniforms.has("u_texture")&&(t.bindTexture(e,0),r.getUniform("u_texture").setValue(this._slotScratches[0])),this._bindCustomUniforms(r,n,t)}t.bindTransformBufferTexture(8,this._maxNodeIndex+1),r.uniforms.has("u_transforms")&&r.getUniform("u_transforms").setValue(this._transformUnitScratch),r.sync(),t.bindVertexArrayObject(i),e.upload(this._instanceFloat32.subarray(0,this._instanceCount*wr)),i.drawInstanced(4,0,this._instanceCount,ai.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots()}onConnect(t){const e=t.context;this._shader.connect(sr(e)),this._connection=this._createConnection(e),this._instanceBuffer=new Kn(hi.ArrayBuffer,this._instanceData,li.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new rr(ai.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_localBounds"),e.FLOAT,!1,yr,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),e.UNSIGNED_SHORT,!0,yr,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,yr,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_textureSlot"),e.UNSIGNED_INT,!1,yr,28,!0,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,yr,32,!0,1).connect(this._createVaoRuntime(this._connection));const i=new Int32Array(1);for(let t=0;t<8;t++)i[0]=t,this._shader.getUniform(`u_texture${t}`).setValue(i)}onDisconnect(){this._shader.disconnect();for(const t of this._customShaders.values())t.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(t,e,i,s){const n=t.blendMode,r=this._instanceCount>=this._batchSize,o=n!==this._currentBlendMode,a=!this._textureSlots.has(e)&&this._slotCount>=8,h=null!==this._currentMaterial&&this._instanceCount>0;(r||o||a||h)&&(this.flush(),o&&(this._currentBlendMode=n,i.setBlendMode(n))),this._currentMaterial=null;let l=this._textureSlots.get(e);void 0===l&&(l=this._slotCount++,this._textureSlots.set(e,l),this._activeTextures[l]=e,i.bindTexture(e,l)),this._packInstance(t,e,l,s),this._instanceCount++}_renderCustom(t,e,i,s,n){const r=t.blendMode===ni.Normal?i.blendMode:t.blendMode,o=this._instanceCount>=this._batchSize,a=r!==this._currentBlendMode,h=i!==this._currentMaterial,l=e!==this._currentBaseTexture;this._instanceCount>0&&(o||a||h||l)&&this.flush(),a&&(this._currentBlendMode=r,s.setBlendMode(r)),this._currentMaterial=i,this._currentBaseTexture=e,this._packInstance(t,e,0,n),this._instanceCount++}_packInstance(t,e,i,s){const n=this._instanceCount*wr,r=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??t.getLocalBounds();r[n+0]=a.left,r[n+1]=a.top,r[n+2]=a.right,r[n+3]=a.bottom;const h=t.textureFrame,l=e.width,u=e.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=e.flipY?f:_,g=e.flipY?_:f;o[n+4]=c|p<<16,o[n+5]=d|g<<16,o[n+6]=t.tint.toRgba(),o[n+7]=i;const m=s>>>0;o[n+8]=m,m>this._maxNodeIndex&&(this._maxNodeIndex=m)}_getOrCreateCustomShader(t,e){const i=this._customShaders.get(t);if(void 0!==i)return i;const s=t.shader.glsl;if(null===s)throw new Error("SpriteMaterial shader has no `glsl` source; cannot render through the WebGL2 backend.");const n=new Xn("#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",s.fragment);return n.connect(sr(e)),n.sync(),this._customShaders.set(t,n),t._onDispose(()=>{const e=this._customShaders.get(t);void 0!==e&&(e.destroy(),this._customShaders.delete(t))}),n}_bindCustomUniforms(t,e,i){let s=1;const n=e.uniforms;for(const e in n){if(!t.uniforms.has(e))continue;const r=n[e],o=t.getUniform(e);if(r instanceof pi||r instanceof _i){if(s>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(r,s),o.setValue(this._slotScratches[s]),s++}else o.setValue(this._marshalUniformValue(r))}const r=e.textures;for(const e in r)if(t.uniforms.has(e)){if(s>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(r[e],s),t.getUniform(e).setValue(this._slotScratches[s]),s++}}_marshalUniformValue(t){return t instanceof Float32Array||t instanceof Int32Array?t:"number"==typeof t?new Float32Array([t]):new Float32Array(t)}_resetSlots(){if(this._slotCount>0){for(let t=0;t<this._slotCount;t++)this._activeTextures[t]=null;this._textureSlots.clear(),this._slotCount=0}}_createConnection(t){const e=t.createVertexArray();if(null===e)throw new Error("WebGl2SpriteRenderer: could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}_createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("WebGl2SpriteRenderer: could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,s)=>{const n=t.gl,r=i.data,o=t.buffers.get(i);n.bindBuffer(i.type,e),o&&o.dataByteLength>=r.byteLength?(n.bufferSubData(i.type,s,r),o.dataByteLength=r.byteLength):(n.bufferData(i.type,r,i.usage),t.buffers.set(i,{handle:e,dataByteLength:r.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(t){let e=-1;return{bind:i=>{const s=t.gl;if(s.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),e.integer?s.vertexAttribIPointer(e.location,e.size,e.type,e.stride,e.start):s.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),s.enableVertexAttribArray(e.location),s.vertexAttribDivisor(e.location,e.divisor);e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,s,n)=>{t.gl.drawArrays(n,s,i)},drawInstanced:(e,i,s,n,r)=>{t.gl.drawArraysInstanced(r,s,i,n)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}var vr="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texcoord;\nlayout(location = 2) in float a_nodeIndex;\n\nuniform mat3 u_projection;\nuniform sampler2D u_nodeData;\n\nflat out int v_nodeIndex;\n out vec2 v_texcoord;\n out vec2 v_gradUV;\n\nvoid main(void) {\n int ni = int(a_nodeIndex);\n\n // texel 0: (a, c, 0, tx) texel 1: (b, d, 0, ty)\n vec4 t0 = texelFetch(u_nodeData, ivec2(0, ni), 0);\n vec4 t1 = texelFetch(u_nodeData, ivec2(1, ni), 0);\n\n // Reconstruct column-major mat3 from stored components\n mat3 xf = mat3(\n t0.x, t0.y, 0.0, // col 0: (a, c, 0)\n t1.x, t1.y, 0.0, // col 1: (b, d, 0)\n t0.w, t1.w, 1.0 // col 2: (tx, ty, 1)\n );\n\n gl_Position = vec4((u_projection * xf * vec3(a_position, 1.0)).xy, 0.0, 1.0);\n v_texcoord = a_texcoord;\n v_nodeIndex = ni;\n\n // texel 9: (minX, minY, width, height) — text block bounds in local space.\n // Normalise a_position into [0,1] so fragment shaders can interpolate\n // gradients across the whole block rather than individual atlas UVs.\n vec4 tBounds = texelFetch(u_nodeData, ivec2(9, ni), 0);\n vec2 bSize = tBounds.zw;\n v_gradUV = (bSize.x > 0.0 && bSize.y > 0.0)\n ? clamp((a_position - tBounds.xy) / bSize, 0.0, 1.0)\n : vec2(0.0);\n}\n";const br=20;class Sr extends Hn{_consumesSharedTransform=!1;_sdfShader=new Xn(vr,"#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 Xn(vr,"#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 Xn(vr,"#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(5120);_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(t){if(!this._connection)throw new Error("WebGl2TextRenderer is not connected to a backend.");t instanceof $n?this._collectText(t):this._collectBitmapText(t)}flush(){const t=this._connection;t&&0!==this._pendingQuads.length?(this._uploadNodeData(t),this._drawBatches(t),this._resetFrameState()):this._resetFrameState()}destroy(){this.disconnect(),this._sdfShader.destroy(),this._msdfShader.destroy(),this._colorShader.destroy()}onConnect(t){const e=t.context,i=new Map;this._sdfShader.connect(sr(e)),this._msdfShader.connect(sr(e)),this._colorShader.connect(sr(e)),this._sdfShader.sync(),this._msdfShader.sync(),this._colorShader.sync();const s=new Kn(hi.ElementArrayBuffer,this._indexData,li.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),n=new Kn(hi.ArrayBuffer,this._vertexData,li.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),r=e.createVertexArray();if(null===r)throw new Error("WebGl2TextRenderer: could not create VAO.");const o=(new rr).addIndex(s).addAttribute(n,this._sdfShader.getAttribute("a_position"),e.FLOAT,!1,br,0).addAttribute(n,this._sdfShader.getAttribute("a_texcoord"),e.FLOAT,!1,br,8).addAttribute(n,this._sdfShader.getAttribute("a_nodeIndex"),e.FLOAT,!1,br,16).connect(this._createVaoRuntime(e,r)),a=this._createNodeDataTexture(e,32);this._connection={gl:e,buffers:i,vertexBuffer:n,indexBuffer:s,vao:o,nodeDataTexture:a,nodeDataCapacity:32}}onDisconnect(){const t=this._connection;t&&(this._sdfShader.disconnect(),this._msdfShader.disconnect(),this._colorShader.disconnect(),t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),t.gl.deleteTexture(t.nodeDataTexture),this._connection=null)}_collectText(t){t.syncDirty();const{pageQuads:e,atlas:i}=t;if(0===e.length||null===i)return;const s=this._assignNodeIndex(t),n=t.colorGlyphs?"color":"sdf",r=i.pages;for(const t of e){const e=r[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:s,shaderType:n,atlasTexture:e.texture})}}_collectBitmapText(t){const{pageQuads:e,textures:i,msdf:s}=t;if(0===e.length)return;const n=this._assignNodeIndex(t),r=s?"msdf":"color";for(const t of e){const e=i[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:n,shaderType:r,atlasTexture:e})}}_assignNodeIndex(t){const e=this._nodeIndexMap.get(t);if(void 0!==e)return e;const i=this._nodeCount++;return this._nodeIndexMap.set(t,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,t),i}_packNodeData(t,e){const i=this._nodeDataArray,s=40*t,n=e.style,r=e.getGlobalTransform().toArray(!1);i[s+0]=r[0],i[s+1]=r[1],i[s+2]=r[2],i[s+3]=r[6],i[s+4]=r[3],i[s+5]=r[4],i[s+6]=r[5],i[s+7]=r[7];const o=n.fillColor;i[s+8]=o.r/255,i[s+9]=o.g/255,i[s+10]=o.b/255,i[s+11]=o.a;const a=n.outlineColor;i[s+12]=a.r/255,i[s+13]=a.g/255,i[s+14]=a.b/255,i[s+15]=a.a;const h=n.outlineWidth>0?Math.max(0,.5-n.outlineWidth):.5;i[s+16]=h,i[s+17]=n.shadowAlpha,i[s+18]=Math.max(.03,.1*n.shadowBlur),i[s+19]=null!==n.gradientColors?1:0;const l=n.shadowColor;i[s+20]=l.r/255,i[s+21]=l.g/255,i[s+22]=l.b/255,i[s+23]=l.a,i[s+24]=n.shadowOffsetX,i[s+25]=n.shadowOffsetY,i[s+26]="vertical"===n.gradientAxis?1:0,i[s+27]=0;const u=n.gradientColors;null!==u?(i[s+28]=u[0].r/255,i[s+29]=u[0].g/255,i[s+30]=u[0].b/255,i[s+31]=u[0].a,i[s+32]=u[1].r/255,i[s+33]=u[1].g/255,i[s+34]=u[1].b/255,i[s+35]=u[1].a):(i[s+28]=i[s+29]=i[s+30]=i[s+31]=0,i[s+32]=i[s+33]=i[s+34]=i[s+35]=0);const c=e.textBounds;i[s+36]=0,i[s+37]=0,i[s+38]=c.width,i[s+39]=c.height}_uploadNodeData(t){const e=t.gl,i=this._nodeCount;if(i>t.nodeDataCapacity){let s=t.nodeDataCapacity;for(;s<i;)s*=2;e.deleteTexture(t.nodeDataTexture),t.nodeDataTexture=this._createNodeDataTexture(e,s),t.nodeDataCapacity=s}e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,t.nodeDataTexture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,10,i,e.RGBA,e.FLOAT,this._nodeDataArray.subarray(0,40*i))}_drawBatches(t){const e=this.getBackend(),i=e.view;for(const t of this._pendingQuads)this._textureKeyMap.has(t.atlasTexture)||this._textureKeyMap.set(t.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((t,e)=>{const i=t.shaderType.localeCompare(e.shaderType);return 0!==i?i:(this._textureKeyMap.get(t.atlasTexture)??0)-(this._textureKeyMap.get(e.atlasTexture)??0)});const s=this._pendingQuads;let n=0;for(;n<s.length;){const r=s[n],o=this._textureKeyMap.get(r.atlasTexture);let a=n+1;for(;a<s.length;){const t=s[a];if(t.shaderType!==r.shaderType||this._textureKeyMap.get(t.atlasTexture)!==o)break;a++}const h=this._shaderFor(r.shaderType);let l=0,u=0;for(let t=n;t<a;t++)l+=4*s[t].quads.quadCount,u+=s[t].quads.indices.length;this._ensureVertexCapacity(l),this._ensureIndexCapacity(u);let c=0,d=0,_=0;for(let t=n;t<a;t++){const{quads:e,nodeIndex:i}=s[t],n=4*e.quadCount,{vertices:r,uvs:o,indices:a}=e;for(let t=0;t<n;t++){const e=5*(c+t),s=2*t;this._float32View[e+0]=r[s],this._float32View[e+1]=r[s+1],this._float32View[e+2]=o[s],this._float32View[e+3]=o[s+1],this._float32View[e+4]=i}for(let t=0;t<a.length;t++)this._indexData[d+t]=a[t]+_;c+=n,d+=a.length,_+=n}t.vertexBuffer.upload(this._float32View.subarray(0,5*l)),t.indexBuffer.upload(this._indexData.subarray(0,u)),h.sync(),e.bindVertexArrayObject(t.vao),e.bindTexture(r.atlasTexture,0),h.uniforms.has("u_projection")&&h.getUniform("u_projection").setValue(i.getTransform().toArray(!1)),h.uniforms.has("u_texture")&&h.getUniform("u_texture").setValue(this._textureUnitScratch),h.uniforms.has("u_nodeData")&&h.getUniform("u_nodeData").setValue(this._nodeDataUnitScratch),h.uniforms.has("u_pageSize")&&(this._floatScratch[0]=r.atlasTexture.width,h.getUniform("u_pageSize").setValue(this._floatScratch)),t.vao.draw(u,0,ai.Triangles),e.stats.batches++,e.stats.drawCalls++,n=a}}_shaderFor(t){return"sdf"===t?this._sdfShader:"msdf"===t?this._msdfShader:this._colorShader}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*br),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(t){if(t<=this._nodeCapacity)return;for(;this._nodeCapacity<t;)this._nodeCapacity*=2;const e=new Float32Array(40*this._nodeCapacity);e.set(this._nodeDataArray),this._nodeDataArray=e}_createNodeDataTexture(t,e){const i=t.createTexture();if(null===i)throw new Error("WebGl2TextRenderer: could not create node data texture.");return t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,10,e,0,t.RGBA,t.FLOAT,null),t.bindTexture(t.TEXTURE_2D,null),i}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("WebGl2TextRenderer: could not create buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(s,n)=>{const r=e.get(s),o=s.data;t.bindBuffer(s.type,i),r&&r.dataByteLength>=o.byteLength?(t.bufferSubData(s.type,n,o),r.dataByteLength=o.byteLength):(t.bufferData(s.type,o,s.usage),e.set(s,{handle:i,dataByteLength:o.byteLength}))},destroy:s=>{t.deleteBuffer(i),e.delete(s),s.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:s=>{if(t.bindVertexArray(e),i!==s.version){let e=null;for(const i of s.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);s.indexBuffer&&s.indexBuffer.bind(),i=s.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,n)=>{e.indexBuffer?t.drawElements(n,i,t.UNSIGNED_SHORT,s):t.drawArrays(n,s,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}class Br{backendType=jn.WebGpu;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==jn.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 Cr(t){switch(t){case ni.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case ni.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case ni.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case ni.Screen:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}};case ni.Darken:return{color:{operation:"min",srcFactor:"one",dstFactor:"one"},alpha:{operation:"min",srcFactor:"one",dstFactor:"one"}};case ni.Lighten:return{color:{operation:"max",srcFactor:"one",dstFactor:"one"},alpha:{operation:"max",srcFactor:"one",dstFactor:"one"}};default:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}}const Tr="depth24plus-stencil8",Mr=new Set(["a_position","position"]);class Pr{_matrix=new De;_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(t){null===this._device&&(this._device=t,this._shaderModule=t.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=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._pipelineLayout=t.createPipelineLayout({bindGroupLayouts:[this._bindGroupLayout]}),this._uniformBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._bindGroup=t.createBindGroup({layout:this._bindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}))}disconnect(){if(null!==this._device){this._uniformBuffer?.destroy(),this._vertexBuffer?.destroy();for(const t of this._stencilTextures.values())t.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(t,e,i){const s=this._device;if(null===s)throw new Error("WebGpuStencilClipper: not connected.");const n=Math.max(1,e),r=Math.max(1,i),o=this._stencilTextures.get(t);if(o?.width===n&&o.height===r)return o.view;o?.texture.destroy();const a=s.createTexture({size:{width:n,height:r},format:Tr,usage:GPUTextureUsage.RENDER_ATTACHMENT}),h={texture:a,view:a.createView(),width:n,height:r};return this._stencilTextures.set(t,h),h.view}releaseAttachment(t){const e=this._stencilTextures.get(t);void 0!==e&&(e.texture.destroy(),this._stencilTextures.delete(t))}draw(t,e,i,s,n,r){const o=this._device;if(null===o||null===this._bindGroup)throw new Error("WebGpuStencilClipper: not connected.");const a=this._extractPositions(s);0!==a&&(this._matrix.copy(n).combine(r.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),t.setPipeline(this._getPipeline(e,i,s.topology)),t.setBindGroup(0,this._bindGroup),t.setVertexBuffer(0,this._vertexBuffer),t.draw(a))}_getPipeline(t,e,i){const s=e?this._incrementPipelines:this._decrementPipelines,n=s.get(t);if(void 0!==n)return n;const r={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:e?"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:t,writeMask:0}]},primitive:{topology:"triangle-strip"===i?"triangle-strip":"triangle-list"},depthStencil:{format:Tr,depthWriteEnabled:!1,depthCompare:"always",stencilFront:r,stencilBack:r,stencilReadMask:255,stencilWriteMask:255}});return s.set(t,o),o}_packMatrix(t){const e=this._matrixData;e[0]=t.a,e[1]=t.c,e[2]=0,e[3]=0,e[4]=t.b,e[5]=t.d,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=t.x,e[13]=t.y,e[14]=0,e[15]=t.z}_extractPositions(t){const e=this._resolvePositionAttribute(t.attributes);if("f32"!==e.type)throw new Error(`Stencil clipShape position attribute "${e.name}" must be of type f32 (got "${e.type}").`);const{stride:i,vertexData:s,indices:n}=t,r=s instanceof Float32Array?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s),o=null!==n?n.length:t.vertexCount;this._ensurePositionCapacity(o);const a=this._positions;for(let t=0;t<o;t++){const s=(null!==n?n[t]:t)*i+e.offset;a[2*t]=r.getFloat32(s,!0),a[2*t+1]=r.getFloat32(s+4,!0)}return o}_resolvePositionAttribute(t){const e=t.find(t=>Mr.has(t.name));if(e)return e;const i=t.find(t=>t.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensurePositionCapacity(t){const e=2*t;this._positions.length<e&&(this._positions=new Float32Array(Math.max(e,2*this._positions.length)))}_ensureVertexCapacity(t){const e=2*t*Float32Array.BYTES_PER_ELEMENT;e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,2*this._vertexBufferCapacity||512),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}}const Ar={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:"keep"};function Er(){return{format:Tr,depthWriteEnabled:!1,depthCompare:"always",stencilFront:Ar,stencilBack:Ar,stencilReadMask:255,stencilWriteMask:0}}const Rr=20;function kr(t,e,i){return`${t}:${e}:${i?"s":"n"}`}const Dr=256;class Ir extends Br{_combinedTransform=new De;_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 e=this._backend;if(null===e)throw new Error("WebGpuMeshRenderer is not connected to a backend.");const i=t.material;if(null!==i&&null===i.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const s=t.vertexCount;if(0===s)return;const n=null!==i&&t.blendMode===ni.Normal?i.blendMode:t.blendMode;e.setBlendMode(n);const r=t.texture??pi.white,o=e.activeDrawCommand,a=e.shouldPremultiplyTextureSample(r),h=t.indexCount;let l=-1;if(null!==i){const t=this._getOrCreateCustomShaderResources(i);l=t.drawCount,t.drawCount++,t.totalVertices+=s,t.totalIndices+=h}const u={mesh:t,customShader:i,command:o,blendMode:n,texture:r,premultiplySample:a,vertexByteOffset:0,vertexCount:s,indexByteOffset:0,indexCount:h,customDrawIndex:l};this._drawCalls[this._drawCallCount++]=u}drawInstancedBatch(t,e,i){const s=this._backend,n=this._device;if(null===s||null===n||i<=0||0===t.vertexCount)return;if(null!==t.material)throw new Error("RenderBatch custom materials are not supported on the WebGPU backend yet (v1 renders with the default mesh material).");const r=t.geometry;if("static"!==r?.usage)throw new Error('drawInstancedBatch requires a mesh with usage="static" geometry.');const o=t.texture??pi.white,a=s.shouldPremultiplyTextureSample(o);this._ensureInstancedUniformCapacity(1);const h=this._uploadInstancedNodeIndexRange(e,i),l=s.getTransformStorageBuffer(h+1);this._writeInstancedUniformSlot(0,s,a);const u=this._getOrCreateStaticGeometryEntry(t),c=this._instancedNodeIndexBuffer;if(null===c)throw new Error("Instanced node-index buffer must be initialized before drawing.");const d=s.renderTargetFormat,_=s._passCoordinator.stencilActive,f=s._passCoordinator.acquirePass().pass;f.setPipeline(this._getInstancedPipeline({blendMode:t.blendMode,format:d,stencil:_})),f.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(l.buffer),[0]),f.setBindGroup(1,this._getTextureBindGroup(s,o)),f.setVertexBuffer(0,u.vertexBuffer),f.setVertexBuffer(1,c),f.setIndexBuffer(u.indexBuffer,"uint16"),f.drawIndexed(u.indexCount,i),s._passCoordinator.endPass(),s.stats.batches++,s.stats.drawCalls++}flush(){const t=this._backend,e=this._device;if(!t||!e)return;if(0===this._drawCallCount&&!t.clearRequested)return;const i=t.getScissorRect(),s=null!==i&&(i.width<=0||i.height<=0);if(0===this._drawCallCount||s)return t.clearRequested&&(t._passCoordinator.acquirePass(),t._passCoordinator.endPass()),void this._resetFrame();let n=0,r=0;const o=new Map,a=new Map;for(let t=0;t<this._drawCallCount;t++){const e=this._drawCalls[t];if(null===e.customShader)e.vertexByteOffset=n*Rr,e.indexByteOffset=r*Uint16Array.BYTES_PER_ELEMENT,n+=e.vertexCount,r+=e.indexCount;else{const t=o.get(e.customShader)??0,i=a.get(e.customShader)??0;e.vertexByteOffset=t*Rr,e.indexByteOffset=i*Uint16Array.BYTES_PER_ELEMENT,o.set(e.customShader,t+e.vertexCount),a.set(e.customShader,i+e.indexCount)}}this._ensureVertexCapacity(n),this._ensureIndexCapacity(r);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 e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e];if(null===i.customShader){if(this._writeMeshVertices(t,i.mesh,i.vertexByteOffset/Rr,!0),null!==i.mesh.indices)this._packedIndexData.set(i.mesh.indices,i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT);else{const t=i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT;for(let e=0;e<i.indexCount;e++)this._packedIndexData[t+e]=e}if(null!==c){const t=d*this._uniformAlignment/Float32Array.BYTES_PER_ELEMENT,e=i.mesh.tint;c[t+0]=e.r/255,c[t+1]=e.g/255,c[t+2]=e.b/255,c[t+3]=e.a,c[t+4]=i.premultiplySample?1:0,c[t+5]=0,c[t+6]=0,c[t+7]=0}d++}}for(const[i,s]of this._customShaders){if(0===s.drawCount)continue;this._ensureCustomCapacities(s);let n=0,r=0,o=0;for(let e=0;e<this._drawCallCount;e++){const a=this._drawCalls[e];if(a.customShader===i){if(this._writeMeshVerticesIntoBuffer(a.mesh,n,s.vertexFloatView,s.vertexUintView),null!==a.mesh.indices)s.indexData.set(a.mesh.indices,r);else for(let t=0;t<a.indexCount;t++)s.indexData[r+t]=t;this._writeCustomMeshUniform(i,s,o,a.mesh,t),n+=a.vertexCount,r+=a.indexCount,o++}}e.queue.writeBuffer(s.vertexBuffer,0,s.vertexData,0,s.totalVertices*Rr),e.queue.writeBuffer(s.indexBuffer,0,s.indexData.buffer,s.indexData.byteOffset,s.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4),this._uploadUserUniforms(i,s)}n>0&&(e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,n*Rr),e.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,r*Uint16Array.BYTES_PER_ELEMENT+3&-4)),null!==u&&e.queue.writeBuffer(this._uniformBuffer,0,u,0,l);const _=t._passCoordinator.acquirePass().pass,f=t.renderTargetFormat,p=t._passCoordinator.stencilActive;let g=null,m=null,y=null,w=null,x=0,v=0;const b=new Map;for(let e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e];if(null===i.customShader){const s=this._getStaticBatchLength(e);if(s>=2){("instanced"!==g||i.blendMode!==m||f!==y)&&(_.setPipeline(this._getInstancedPipeline({blendMode:i.blendMode,format:f,stencil:p})),g="instanced",m=i.blendMode,y=f,w=null);const n=this._uploadInstancedNodeIndices(e,s),r=t.getTransformStorageBuffer(n+1);this._writeInstancedUniformSlot(v,t,i.premultiplySample),_.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(r.buffer),[v*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(t,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,s),t.stats.batches++,t.stats.drawCalls++,x+=s,v++,e+=s-1;continue}("default"!==g||i.blendMode!==m||f!==y)&&(_.setPipeline(this._getPipeline({blendMode:i.blendMode,format:f,stencil:p})),g="default",m=i.blendMode,y=f,w=null),_.setBindGroup(0,this._uniformBindGroup,[x*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(t,i.texture))),_.setVertexBuffer(0,this._vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(this._indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),x++}else{const e=this._customShaders.get(i.customShader),s=g!==i.customShader||i.blendMode!==m||f!==y;_.pushDebugGroup("MeshMaterial (custom)"),s&&(_.setPipeline(this._getOrCreateCustomPipeline(e,i.blendMode,f,p)),g=i.customShader,m=i.blendMode,y=f,w=null,_.setBindGroup(2,this._buildUserBindGroup(t,i.customShader,e)));const n=b.get(i.customShader)??0;_.setBindGroup(0,e.meshUniformBindGroup,[n*Dr]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getOrCreateMeshTextureBindGroup(e,t,i.texture))),_.setVertexBuffer(0,e.vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(e.indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),_.popDebugGroup(),b.set(i.customShader,n+1)}t.stats.batches++,t.stats.drawCalls++}t._passCoordinator.endPass(),this._resetFrame()}destroy(){this.disconnect(),this._combinedTransform.destroy()}async prewarmPipelines(t){const e=this._device;if(!e||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof e.createRenderPipelineAsync)return;const i=[ni.Normal,ni.Additive,ni.Subtract,ni.Multiply,ni.Screen,ni.Darken,ni.Lighten],s=[];for(const n of i)for(const i of t){const t=kr(n,i,!1);this._pipelines.has(t)||(s.push(e.createRenderPipelineAsync(this._buildPipelineDescriptor(n,i)).then(e=>{this._pipelines.set(t,e)})),this._instancedPipelines.has(t)||s.push(e.createRenderPipelineAsync(this._buildInstancedPipelineDescriptor(n,i)).then(e=>{this._instancedPipelines.set(t,e)})))}await Promise.all(s)}onConnect(t){this._device||(this._device=t.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 t of this._staticGeometryCache.values())t.vertexBuffer.destroy(),t.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 t of this._customShaders.values())this._releaseCustomShaderResources(t);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(t,e,i,s){const n=e.vertices,r=e.uvs,o=e.colors,a=e.vertexCount;if(s){const s=this._combinedTransform.copy(e.getGlobalTransform()).combine(t.view.getTransform()),h=s.a,l=s.b,u=s.c,c=s.d,d=s.x,_=s.y;for(let t=0;t<a;t++){const e=2*t,s=5*(i+t),a=n[e],f=n[e+1];this._float32View[s+0]=h*a+l*f+d,this._float32View[s+1]=u*a+c*f+_,this._float32View[s+2]=null!==r?r[e]:0,this._float32View[s+3]=null!==r?r[e+1]:0,this._uint32View[s+4]=null!==o?o[t]:4294967295}}else for(let t=0;t<a;t++){const e=2*t,s=5*(i+t);this._float32View[s+0]=n[e],this._float32View[s+1]=n[e+1],this._float32View[s+2]=null!==r?r[e]:0,this._float32View[s+3]=null!==r?r[e+1]:0,this._uint32View[s+4]=null!==o?o[t]:4294967295}}_getPipeline(t){const e=kr(t.blendMode,t.format,t.stencil);let i=this._pipelines.get(e);return i||(i=this._device.createRenderPipeline(this._buildPipelineDescriptor(t.blendMode,t.format,t.stencil)),this._pipelines.set(e,i)),i}_buildPipelineDescriptor(t,e,i=!1){const s={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Rr,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:e,blend:Cr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(s.depthStencil=Er()),s}_getTextureBindGroup(t,e){const i=t.getTextureBinding(e),s=this._textureBindGroups.get(e);if(s?.view===i.view)return s.group;const n=this._device.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:i.view},{binding:1,resource:i.sampler}]});return this._textureBindGroups.set(e,{group:n,view:i.view}),n}_getStaticBatchLength(t){const e=this._drawCalls[t];if(!this._isStaticBatchCandidate(e))return 1;let i=1;for(let s=t+1;s<this._drawCallCount;s++){const t=this._drawCalls[s];if(!this._isSameStaticBatch(e,t))break;i++}return i}_isStaticBatchCandidate(t){const e=t.command;return null===t.customShader&&void 0!==e?.groupIndex&&"static"===t.mesh.geometry?.usage}_isSameStaticBatch(t,e){return!(!this._isStaticBatchCandidate(t)||!this._isStaticBatchCandidate(e))&&(t.command.groupIndex===e.command.groupIndex&&t.mesh.geometry===e.mesh.geometry&&t.texture===e.texture&&t.blendMode===e.blendMode&&t.command.material.pipelineKey===e.command.material.pipelineKey&&t.command.material.bindKey===e.command.material.bindKey)}_uploadInstancedNodeIndices(t,e){this._ensureInstancedNodeIndexCapacity(e);let i=0;for(let s=0;s<e;s++){const e=this._drawCalls[t+s].command.nodeIndex>>>0;this._instancedNodeIndexData[s]=e,e>i&&(i=e)}return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,e*Uint32Array.BYTES_PER_ELEMENT),i}_uploadInstancedNodeIndexRange(t,e){this._ensureInstancedNodeIndexCapacity(e);for(let i=0;i<e;i++)this._instancedNodeIndexData[i]=t+i>>>0;return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,e*Uint32Array.BYTES_PER_ELEMENT),t+e-1>>>0}_ensureInstancedNodeIndexCapacity(t){const e=t*Uint32Array.BYTES_PER_ELEMENT;this._instancedNodeIndexData.length<t&&(this._instancedNodeIndexData=new Uint32Array(Math.max(t,2*this._instancedNodeIndexData.length||1))),e>this._instancedNodeIndexBufferCapacity&&(this._instancedNodeIndexBuffer?.destroy(),this._instancedNodeIndexBufferCapacity=Math.max(e,2*this._instancedNodeIndexBufferCapacity||Uint32Array.BYTES_PER_ELEMENT),this._instancedNodeIndexBuffer=this._device.createBuffer({size:this._instancedNodeIndexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureInstancedUniformCapacity(t){if(0===t)return;const e=t*this._uniformAlignment;e>this._instancedUniformBufferCapacity&&(this._instancedUniformBuffer?.destroy(),this._instancedUniformBufferCapacity=Math.max(e,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(t,e,i){const s=this._instancedUniformScratch,n=e.view.getTransform();s.fill(0),s[0]=n.a,s[1]=n.b,s[4]=n.c,s[5]=n.d,s[8]=n.x,s[9]=n.y,s[10]=1,s[12]=i?1:0,this._device.queue.writeBuffer(this._instancedUniformBuffer,t*this._uniformAlignment,s.buffer,s.byteOffset,64)}_getOrCreateInstancedTransformBindGroup(t){return null!==this._instancedTransformBindGroup&&this._instancedTransformStorageBuffer===t||(this._instancedTransformStorageBuffer=t,this._instancedTransformBindGroup=this._device.createBindGroup({layout:this._instancedTransformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._instancedUniformBuffer,size:64}},{binding:1,resource:{buffer:t}}]})),this._instancedTransformBindGroup}_getInstancedPipeline(t){const e=kr(t.blendMode,t.format,t.stencil);let i=this._instancedPipelines.get(e);return i||(i=this._device.createRenderPipeline(this._buildInstancedPipelineDescriptor(t.blendMode,t.format,t.stencil)),this._instancedPipelines.set(e,i)),i}_buildInstancedPipelineDescriptor(t,e,i=!1){const s={layout:this._instancedPipelineLayout,vertex:{module:this._instancedShaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Rr,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:e,blend:Cr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(s.depthStencil=Er()),s}_getOrCreateStaticGeometryEntry(t){const e=t.geometry;if("static"!==e?.usage)throw new Error('Static mesh batching requires Geometry with usage="static".');const i=this._staticGeometryCache.get(e);if(void 0!==i)return i;const s=new ArrayBuffer(t.vertexCount*Rr),n=new Float32Array(s),r=new Uint32Array(s);this._writeMeshVerticesIntoBuffer(t,0,n,r);const o=new Uint16Array(t.indexCount+(1&t.indexCount));if(null!==t.indices)o.set(t.indices,0);else for(let e=0;e<t.indexCount;e++)o[e]=e;const a=t.indexCount*Uint16Array.BYTES_PER_ELEMENT+3&-4,h=this._device.createBuffer({size:s.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,s,0,s.byteLength),this._device.queue.writeBuffer(l,0,o.buffer,o.byteOffset,a);const u=()=>{const t=this._staticGeometryCache.get(e);void 0!==t&&(t.vertexBuffer.destroy(),t.indexBuffer.destroy(),this._staticGeometryCache.delete(e))};e._onDispose(u);const c={geometry:e,vertexBuffer:h,indexBuffer:l,indexCount:t.indexCount,disposeListener:u};return this._staticGeometryCache.set(e,c),c}_ensureVertexCapacity(t){const e=t*Rr;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?Rr:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(t),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,0===this._vertexBufferCapacity?Rr:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(t){const e=t*Uint16Array.BYTES_PER_ELEMENT+3&-4;this._packedIndexData.length*Uint16Array.BYTES_PER_ELEMENT<e&&(this._packedIndexData=new Uint16Array(Math.max(e/Uint16Array.BYTES_PER_ELEMENT,0===this._packedIndexData.length?2:2*this._packedIndexData.length))),e>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(e,0===this._indexBufferCapacity?4:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_ensureUniformCapacity(t){if(0===t)return;const e=t*this._uniformAlignment;e>this._uniformBufferCapacity&&(this._uniformBuffer?.destroy(),this._uniformBufferCapacity=Math.max(e,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 t=0;for(const e of this._customShaders.values())t+=e.drawCount;return t}_resetFrame(){this._drawCallCount=0;for(const t of this._customShaders.values())t.drawCount=0,t.totalVertices=0,t.totalIndices=0}_getOrCreateCustomShaderResources(t){let e=this._customShaders.get(t);if(void 0!==e)return e;if(null===this._device)throw new Error("WebGpuMeshRenderer is not connected to a backend.");if(null===t.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const i=this._device,s=i.createShaderModule({code:t.shader.wgsl}),n=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}}]}),r=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),o=this._buildUserBindGroupLayout(i,t),a=i.createPipelineLayout({bindGroupLayouts:[n,r,o]}),h=i.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),l=new ArrayBuffer(1280);return e={shaderModule:s,meshUniformLayout:n,meshTextureLayout:r,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(t,e),t._onDispose(()=>{const e=this._customShaders.get(t);void 0!==e&&(this._releaseCustomShaderResources(e),this._customShaders.delete(t))}),e}_ensureCustomCapacities(t){const e=this._device,i=t.totalVertices*Rr;if(i>t.vertexData.byteLength){const e=Math.max(i,2*t.vertexData.byteLength);t.vertexData=new ArrayBuffer(e),t.vertexFloatView=new Float32Array(t.vertexData),t.vertexUintView=new Uint32Array(t.vertexData)}i>t.vertexBufferCapacity&&(t.vertexBuffer?.destroy(),t.vertexBufferCapacity=Math.max(i,2*t.vertexBufferCapacity||Rr),t.vertexBuffer=e.createBuffer({size:t.vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}));const s=t.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4;t.indexData.length*Uint16Array.BYTES_PER_ELEMENT<s&&(t.indexData=new Uint16Array(Math.max(s/Uint16Array.BYTES_PER_ELEMENT,2*t.indexData.length))),s>t.indexBufferCapacity&&(t.indexBuffer?.destroy(),t.indexBufferCapacity=Math.max(s,2*t.indexBufferCapacity||4),t.indexBuffer=e.createBuffer({size:t.indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}));const n=t.drawCount*Dr;n>t.meshUniformBufferCapacity&&(t.meshUniformBuffer?.destroy(),t.meshUniformBufferCapacity=Math.max(n,2*t.meshUniformBufferCapacity||Dr),t.meshUniformBuffer=e.createBuffer({size:t.meshUniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.meshUniformBindGroup=e.createBindGroup({layout:t.meshUniformLayout,entries:[{binding:0,resource:{buffer:t.meshUniformBuffer,size:112}}]}))}_writeMeshVerticesIntoBuffer(t,e,i,s){const n=t.vertices,r=t.uvs,o=t.colors,a=t.vertexCount;for(let t=0;t<a;t++){const a=2*t,h=5*(e+t);i[h+0]=n[a],i[h+1]=n[a+1],i[h+2]=null!==r?r[a]:0,i[h+3]=null!==r?r[a+1]:0,s[h+4]=null!==o?o[t]:4294967295}}_writeCustomMeshUniform(t,e,i,s,n){const r=256/Float32Array.BYTES_PER_ELEMENT,o=new Float32Array(r),a=n.view.getTransform(),h=s.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=s.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(e.meshUniformBuffer,256*i,o)}_getOrCreateCustomPipeline(t,e,i,s){const n=`${e}:${i}:${s?"s":"n"}`;let r=t.pipelines.get(n);if(void 0===r){const o={layout:t.pipelineLayout,vertex:{module:t.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Rr,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]}]},fragment:{module:t.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:Cr(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};s&&(o.depthStencil=Er()),r=this._device.createRenderPipeline(o),t.pipelines.set(n,r)}return r}_getOrCreateMeshTextureBindGroup(t,e,i){const s=e.getTextureBinding(i),n=t.meshTextureBindGroups.get(i);if(n?.view===s.view)return n.group;const r=this._device.createBindGroup({layout:t.meshTextureLayout,entries:[{binding:0,resource:s.view},{binding:1,resource:s.sampler}]});return t.meshTextureBindGroups.set(i,{group:r,view:s.view}),r}_buildUserBindGroupLayout(t,e){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const s=Ur(e);if(s.length>7)throw new Error("Mesh material requested more than 7 user texture bindings.");let n=1;for(let t=0;t<s.length;t++)i.push({binding:n,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),n++,i.push({binding:n,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),n++;return t.createBindGroupLayout({entries:i})}_uploadUserUniforms(t,e){const i=this._device,s=function(t){const e=[];for(const i of Object.values(t.uniforms))Lr(i)||e.push(i);return e}(t),n=16*Math.max(s.length,1);(null===e.userUniformBuffer||e.userUniformBufferCapacity<n)&&(e.userUniformBuffer?.destroy(),e.userUniformBufferCapacity=n,e.userUniformBuffer=i.createBuffer({size:n,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const r=new Float32Array(n/4);let o=0;for(const t of s){const e=4*o;if("number"==typeof t)r[e]=t;else if(t instanceof Float32Array)r.set(t,e);else if(t instanceof Int32Array)for(let i=0;i<t.length;i++)r[e+i]=t[i];else{const i=t;for(let t=0;t<i.length;t++)r[e+t]=i[t]}o++}i.queue.writeBuffer(e.userUniformBuffer,0,r)}_buildUserBindGroup(t,e,i){const s=this._device,n=[];n.push({binding:0,resource:{buffer:i.userUniformBuffer}});let r=1;for(const i of Ur(e)){const e=t.getTextureBinding(i);n.push({binding:r,resource:e.view}),r++,n.push({binding:r,resource:e.sampler}),r++}return s.createBindGroup({layout:i.userLayout,entries:n})}_releaseCustomShaderResources(t){t.vertexBuffer?.destroy(),t.indexBuffer?.destroy(),t.meshUniformBuffer?.destroy(),t.userUniformBuffer?.destroy(),t.pipelines.clear(),t.meshTextureBindGroups=new WeakMap,t.vertexBuffer=null,t.indexBuffer=null,t.meshUniformBuffer=null,t.userUniformBuffer=null,t.meshUniformBindGroup=null,t.vertexBufferCapacity=0,t.indexBufferCapacity=0,t.meshUniformBufferCapacity=0,t.userUniformBufferCapacity=0}}function Lr(t){return!("object"!=typeof t||null===t||!("width"in t)||!("height"in t)||t instanceof Float32Array||t instanceof Int32Array||Array.isArray(t))}function Ur(t){const e=[];for(const i of Object.values(t.uniforms))Lr(i)&&e.push(i);for(const i of Object.values(t.textures))e.push(i);return e}const Fr=32/Uint32Array.BYTES_PER_ELEMENT,Gr=new Uint16Array([0,1,2,0,2,3]);class Nr extends Br{_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(t){this._device||(this._device=t.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:Gr.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Gr.buffer,Gr.byteOffset,Gr.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(t){const e=this._backend;if(null===e)return;let i=t.quads;if("geometry"===t.pixelSnapMode){const s=e._getSnapPixelSize();i=t.getRenderQuads(e.view,s.width,s.height)}if(0===i.length)return;const s=t.texture;if(0===s.width||0===s.height)return;if(s instanceof pi&&null===s.source)return;const n=t.blendMode,r=e.activeDrawCommand,o=null!==r?r.nodeIndex:e._pushTransform(t),a=null!==this._currentBlendMode&&n!==this._currentBlendMode,h=null!==this._currentTexture&&s!==this._currentTexture,l=this._quadIndex+i.length>this._instanceCapacity&&this._instanceCapacity>0;(a||h||l)&&this._quadIndex>0&&this.flush(),this._currentBlendMode=n,this._currentTexture=s,e.setBlendMode(n),this._ensureInstanceCapacity(this._quadIndex+i.length);const u=this._instanceFloat32,c=this._instanceUint32,d=s instanceof pi&&s.flipY;for(const e of i){const i=this._quadIndex*Fr;u[i+0]=e.x0,u[i+1]=e.y0,u[i+2]=e.x1,u[i+3]=e.y1;const s=65535*e.u0&65535,n=65535*e.u1&65535,r=65535*e.v0&65535,a=65535*e.v1&65535,h=d?a:r,l=d?r:a;c[i+4]=s|h<<16,c[i+5]=n|l<<16,c[i+6]=t.tint.toRgba(),c[i+7]=o>>>0,this._quadIndex++,o>this._maxNodeIndex&&(this._maxNodeIndex=o)}}flush(){const t=this._backend,e=this._device,i=this._uniformBuffer;if(!t||!e||!i)return;if(0===this._quadIndex&&!t.clearRequested)return;const s=t.view.getTransform();this._projectionData.set([s.a,s.c,0,0,s.b,s.d,0,0,0,0,1,0,s.x,s.y,0,s.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const n=t.getScissorRect(),r=null!==n&&(n.width<=0||n.height<=0),o=t._passCoordinator.acquirePass().pass;if(this._quadIndex>0&&!r&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode&&null!==this._currentTexture){e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,32*this._quadIndex);const s=t.getTransformStorageBuffer(this._maxNodeIndex+1),n=this._getOrCreateTransformBindGroup(e,i,s.buffer),r=this._createTextureBindGroup(e,t,this._currentTexture),a=t._passCoordinator.stencilActive,h=this._getPipeline(this._currentBlendMode,t.renderTargetFormat,a);o.setPipeline(h),o.setBindGroup(0,n),o.setBindGroup(1,r),o.setVertexBuffer(0,this._instanceBuffer),o.setIndexBuffer(this._indexBuffer,"uint16"),o.drawIndexed(6,this._quadIndex,0,0,0),t.stats.batches++,t.stats.drawCalls++}t._passCoordinator.endPass(),this._quadIndex=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentTexture=null}destroy(){this.disconnect()}_getOrCreateTransformBindGroup(t,e,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=t.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_createTextureBindGroup(t,e,i){const s=e.getTextureBinding(i);return t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:s.view},{binding:1,resource:s.sampler}]})}_getPipeline(t,e,i){const s=`${t}:${e}:${i?"s":"n"}`,n=this._pipelines.get(s);if(n)return n;if(!this._device||!this._shaderModule||!this._pipelineLayout)throw new Error("WebGpuNineSliceSpriteRenderer: renderer must be connected first.");const r={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:e,blend:Cr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};i&&(r.depthStencil=Er());const o=this._device.createRenderPipeline(r);return this._pipelines.set(s,o),o}_ensureInstanceCapacity(t){if(!this._device||t<=this._instanceCapacity)return;let e=Math.max(this._instanceCapacity,32);for(;e<t;)e*=2;const i=this._instanceData,s=Math.min(32*this._quadIndex,i.byteLength),n=new ArrayBuffer(32*e);s>0&&new Uint8Array(n).set(new Uint8Array(i,0,s));const r=this._device.createBuffer({size:n.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=e,this._instanceData=n,this._instanceFloat32=new Float32Array(n),this._instanceUint32=new Uint32Array(n),this._instanceBuffer=r}}const Or=new Uint16Array([0,1,2,0,2,3]);function Vr(t){return"repeat"===t?"repeat":"mirror-repeat"===t?"mirror-repeat":"clamp-to-edge"}class zr extends Br{_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 Zt;onConnect(t){if(this._device)return;const e=t.device;this._device=e,this._shaderModule=e.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=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._uniformBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=e.createBuffer({size:Or.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._indexBuffer,0,Or.buffer,Or.byteOffset,Or.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(t){const e=this._backend;if(!e)return;const i=t.texture;if(i instanceof pi&&null===i.source)return;if(0===i.width||0===i.height)return;const s=t.resolvedStrategy,n=t.blendMode,r=t.modeX,o=t.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const t=this._currentPath!==s,e=this._currentTexture!==i,a=this._currentBlendMode!==n,h="shader"===s&&(this._currentModeX!==r||this._currentModeY!==o);(t||e||a||h)&&this.flush()}this._currentTexture=i,this._currentBlendMode=n,this._currentPath=s,e.setBlendMode(n);const a=e.activeDrawCommand,h=null!==a?a.nodeIndex:e._pushTransform(t);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===s?(this._currentModeX=r,this._currentModeY=o,this._writeShaderInstance(t,h)):this._writeGeoQuads(t,h)}_writeShaderInstance(t,e){const i=t.texture,s=t.region.width,n=t.region.height;let r=t.width,o=t.height;const a=i instanceof pi&&i.flipY;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),i=e._getSnapPixelSize(),s=t.getRenderBounds(e.view,i.width,i.height,this._snapBounds);r=s.width,o=s.height}const h=wn(s,r,t.modeX,t.fitX),l=wn(n,o,t.modeY,t.fitY),u=t.offsetX/(s>0?s:1),c=t.offsetY/(n>0?n:1),d=a?-l:l,_=a?l+c:c;this._ensureShaderCapacity(this._shaderQuadCount+1);const f=10*this._shaderQuadCount,p=this._shaderInstF32,g=this._shaderInstU32;p[f+0]=0,p[f+1]=0,p[f+2]=r,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,g[f+8]=t.tint.toRgba(),g[f+9]=e>>>0,this._shaderQuadCount++}_writeGeoQuads(t,e){let i=t.quads;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),s=e._getSnapPixelSize();i=t.getRenderQuads(e.view,s.width,s.height)}if(0===i.length)return;const s=t.texture instanceof pi&&t.texture.flipY,n=t.tint.toRgba();this._ensureGeoCapacity(this._geoQuadCount+i.length);const r=this._geoInstF32,o=this._geoInstU32;for(let t=0;t<i.length;t++){const a=i[t],h=8*(this._geoQuadCount+t);r[h+0]=a.x0,r[h+1]=a.y0,r[h+2]=a.x1,r[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,_=s?d:c,f=s?c:d;o[h+4]=l|_<<16,o[h+5]=u|f<<16,o[h+6]=n,o[h+7]=e>>>0}this._geoQuadCount+=i.length}flush(){const t=this._backend,e=this._device,i=this._uniformBuffer;if(!t||!e||!i)return;if(0===this._shaderQuadCount&&0===this._geoQuadCount&&!t.clearRequested)return;const s=t.view.getTransform();this._projData.set([s.a,s.c,0,0,s.b,s.d,0,0,0,0,1,0,s.x,s.y,0,s.z]),e.queue.writeBuffer(i,0,this._projData.buffer,this._projData.byteOffset,this._projData.byteLength);const n=t.getScissorRect(),r=null!==n&&(n.width<=0||n.height<=0),o=t._passCoordinator.acquirePass().pass,a=t._passCoordinator.stencilActive;this._shaderQuadCount>0&&!r&&this._drawShaderBatch(e,t,o,a),this._geoQuadCount>0&&!r&&this._drawGeoBatch(e,t,o,a),t._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(t,e,i,s){if(!this._shaderInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;t.queue.writeBuffer(this._shaderInstBuf,0,this._shaderInstData,0,40*this._shaderQuadCount);const n=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,this._uniformBuffer,n.buffer),o=this._currentModeX??"repeat",a=this._currentModeY??"repeat",h=this._getOrCreateSampler(t,o,a),l=e.getTextureBinding(this._currentTexture).view,u=t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:l},{binding:1,resource:h}]}),c=this._getPipeline("shader",this._currentBlendMode,e.renderTargetFormat,s);i.setPipeline(c),i.setBindGroup(0,r),i.setBindGroup(1,u),i.setVertexBuffer(0,this._shaderInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._shaderQuadCount,0,0,0),e.stats.batches++,e.stats.drawCalls++}_drawGeoBatch(t,e,i,s){if(!this._geoInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;t.queue.writeBuffer(this._geoInstBuf,0,this._geoInstData,0,32*this._geoQuadCount);const n=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,this._uniformBuffer,n.buffer),o=e.getTextureBinding(this._currentTexture),a=t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:o.view},{binding:1,resource:o.sampler}]}),h=this._getPipeline("geo",this._currentBlendMode,e.renderTargetFormat,s);i.setPipeline(h),i.setBindGroup(0,r),i.setBindGroup(1,a),i.setVertexBuffer(0,this._geoInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._geoQuadCount,0,0,0),e.stats.batches++,e.stats.drawCalls++}destroy(){this.disconnect()}_getOrCreateSampler(t,e,i){const s=`${e}:${i}`,n=this._samplers.get(s);if(n)return n;const r=t.createSampler({addressModeU:Vr(e),addressModeV:Vr(i),magFilter:"linear",minFilter:"linear"});return this._samplers.set(s,r),r}_getOrCreateTransformBindGroup(t,e,i){return null!==this._transformBindGroup&&this._transformStorageBuf===i||(this._transformStorageBuf=i,this._transformBindGroup=t.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_getPipeline(t,e,i,s){const n=`${t}:${e}:${i}:${s?"s":"n"}`,r=this._pipelines.get(n);if(r)return r;if(!(this._device&&this._shaderModule&&this._uniformBindGroupLayout&&this._textureBindGroupLayout))throw new Error("WebGpuRepeatingSpriteRenderer: not connected.");const o="shader"===t,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:Cr(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};s&&(l.depthStencil=Er());const u=this._device.createRenderPipeline(l);return this._pipelines.set(n,u),u}_ensureShaderCapacity(t){if(!this._device||t<=this._shaderInstCapacity)return;this._shaderInstCapacity=this._growCapacity(this._shaderInstCapacity,t);const e=this._shaderInstData,i=40*this._shaderQuadCount;this._shaderInstData=new ArrayBuffer(40*this._shaderInstCapacity),i>0&&new Uint8Array(this._shaderInstData).set(new Uint8Array(e,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(t){if(!this._device||t<=this._geoInstCapacity)return;this._geoInstCapacity=this._growCapacity(this._geoInstCapacity,t);const e=this._geoInstData,i=32*this._geoQuadCount;this._geoInstData=new ArrayBuffer(32*this._geoInstCapacity),i>0&&new Uint8Array(this._geoInstData).set(new Uint8Array(e,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(t,e){let i=Math.max(t,32);for(;i<e;)i*=2;return i}}const qr=36,Yr=qr/Uint32Array.BYTES_PER_ELEMENT,Wr=new Uint16Array([0,1,2,0,2,3]);class $r extends Br{_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 Zt;_activeBounds=null;onConnect(t){this._device||(this._device=t.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},(t,e)=>({binding:e,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(t,e)=>({binding:8+e,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:Wr.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Wr.buffer,Wr.byteOffset,Wr.byteLength))}onDisconnect(){this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy();for(const t of this._customMaterials.values())this._releaseCustomResources(t);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(t){const e=this._backend,i=t.texture;if(null===e||!(i instanceof pi)&&!(i instanceof _i)||0===i.width||0===i.height||i instanceof pi&&null===i.source)return;const s=t.material,n=e.activeDrawCommand,r=null!==n?n.nodeIndex:e._pushTransform(t);this._activeBounds=this._resolveBounds(t,e),null===s?this._renderDefault(t,i,e,r):this._renderCustom(t,i,s,e,r)}_resolveBounds(t,e){if("geometry"!==t.pixelSnapMode)return t.getLocalBounds();const i=e._getSnapPixelSize();return t.getRenderBounds(e.view,i.width,i.height,this._snapBounds)}_renderDefault(t,e,i,s){const n=t.blendMode,r=null!==this._currentBlendMode&&n!==this._currentBlendMode,o=!this._textureSlots.has(e)&&this._slotCount>=8,a=null!==this._currentMaterial&&this._instanceCount>0;(r||o||a)&&this.flush(),this._currentBlendMode=n,this._currentMaterial=null,i.setBlendMode(n);let h=this._textureSlots.get(e);void 0===h&&(h=this._slotCount++,this._textureSlots.set(e,h),this._activeTextures[h]=e);const l=h|(i.shouldPremultiplyTextureSample(e)?1:0)<<8;this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(t,e,l,s),this._instanceCount++}_renderCustom(t,e,i,s,n){if(null===i.shader.wgsl)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const r=t.blendMode===ni.Normal?i.blendMode:t.blendMode,o=null!==this._currentBlendMode&&r!==this._currentBlendMode,a=null!==this._currentMaterial&&i!==this._currentMaterial,h=null!==this._currentBaseTexture&&e!==this._currentBaseTexture,l=null===this._currentMaterial&&this._instanceCount>0;(o||a||h||l)&&this.flush(),this._currentBlendMode=r,this._currentMaterial=i,this._currentBaseTexture=e,s.setBlendMode(r),this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(t,e,0,n),this._instanceCount++}flush(){const t=this._backend,e=this._device,i=this._uniformBuffer;if(!t||!e||!i)return;if(0===this._instanceCount&&!t.clearRequested)return;const s=t.view.getTransform();this._projectionData.set([s.a,s.c,0,0,s.b,s.d,0,0,0,0,1,0,s.x,s.y,0,s.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const n=t.getScissorRect(),r=null!==n&&(n.width<=0||n.height<=0),o=t._passCoordinator.acquirePass().pass;if(this._instanceCount>0&&!r&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode){e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,this._instanceCount*qr);const s=t.getTransformStorageBuffer(this._maxNodeIndex+1),n=this._getOrCreateTransformBindGroup(e,i,s.buffer),r=this._currentMaterial,a=t._passCoordinator.stencilActive;if(null===r){const i=this._getPipeline(this._currentBlendMode,t.renderTargetFormat,a),s=this._createTextureBindGroup(e,t);o.setPipeline(i),o.setBindGroup(0,n),o.setBindGroup(1,s),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,e,t,r,n,a),o.popDebugGroup();t.stats.batches++,t.stats.drawCalls++}t._passCoordinator.endPass(),this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots(),this._currentBlendMode=null,this._currentMaterial=null,this._currentBaseTexture=null}_getOrCreateTransformBindGroup(t,e,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=t.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}destroy(){this.disconnect()}async prewarmPipelines(t){const e=this._device;if(!e||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof e.createRenderPipelineAsync)return;const i=[ni.Normal,ni.Additive,ni.Subtract,ni.Multiply,ni.Screen,ni.Darken,ni.Lighten],s=[];for(const n of i)for(const i of t){const t=`${n}:${i}`;if(this._pipelines.has(t))continue;const r=e.createRenderPipelineAsync(this._buildPipelineDescriptor(n,i)).then(e=>{this._pipelines.set(t,e)});s.push(r)}await Promise.all(s)}_packInstance(t,e,i,s){const n=this._instanceCount*Yr,r=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??t.getLocalBounds();r[n+0]=a.left,r[n+1]=a.top,r[n+2]=a.right,r[n+3]=a.bottom;const h=t.textureFrame,l=e.width,u=e.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=e instanceof pi&&e.flipY,g=p?f:_,m=p?_:f;o[n+4]=c|g<<16,o[n+5]=d|m<<16,o[n+6]=t.tint.toRgba(),o[n+7]=i;const y=s>>>0;o[n+8]=y,y>this._maxNodeIndex&&(this._maxNodeIndex=y)}_ensureInstanceCapacity(t){if(!this._device||t<=this._instanceCapacity)return;let e=Math.max(this._instanceCapacity,32);for(;e<t;)e*=2;const i=this._instanceData,s=Math.min(this._instanceCount*qr,i.byteLength),n=new ArrayBuffer(e*qr);s>0&&new Uint8Array(n).set(new Uint8Array(i,0,s));const r=this._device.createBuffer({size:n.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=e,this._instanceData=n,this._instanceFloat32=new Float32Array(n),this._instanceUint32=new Uint32Array(n),this._instanceBuffer=r}_resetSlots(){if(this._slotCount>0){for(let t=0;t<this._slotCount;t++)this._activeTextures[t]=null;this._textureSlots.clear(),this._slotCount=0}}_createTextureBindGroup(t,e){const i=this._activeTextures[0]??pi.empty,s=e.getTextureBinding(i),n=new Array(8);for(let t=0;t<8;t++){const r=this._activeTextures[t]??i;n[t]=r===i?s:e.getTextureBinding(r)}const r=[];for(let t=0;t<8;t++)r.push({binding:t,resource:n[t].view});for(let t=0;t<8;t++)r.push({binding:8+t,resource:n[t].sampler});return t.createBindGroup({layout:this._textureBindGroupLayout,entries:r})}_getPipeline(t,e,i){const s=`${t}:${e}:${i?"s":"n"}`,n=this._pipelines.get(s);if(n)return n;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._backend))throw new Error("Renderer has to be connected first!");const r=this._device.createRenderPipeline(this._buildPipelineDescriptor(t,e,i));return this._pipelines.set(s,r),r}_buildPipelineDescriptor(t,e,i=!1){if(!this._shaderModule||!this._pipelineLayout)throw new Error("Renderer has to be connected first!");const s={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:qr,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:e,blend:Cr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return i&&(s.depthStencil=Er()),s}_drawCustomBatch(t,e,i,s,n,r){const o=this._getOrCreateCustomResources(s,e),a=this._currentBaseTexture??pi.empty;this._uploadUserUniforms(s,o,e);const h=this._getOrCreateCustomPipeline(o,this._currentBlendMode,i.renderTargetFormat,r,e);t.setPipeline(h),t.setBindGroup(0,n),t.setBindGroup(1,this._getCustomBaseTextureBindGroup(o,i,a,e)),t.setBindGroup(2,this._buildUserBindGroup(s,o,i,e)),t.setVertexBuffer(0,this._instanceBuffer),t.setIndexBuffer(this._indexBuffer,"uint16"),t.drawIndexed(6,this._instanceCount,0,0,0)}_getOrCreateCustomResources(t,e){const i=this._customMaterials.get(t);if(void 0!==i)return i;const s=t.shader.wgsl;if(null===s)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const n=e.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${s}`}),r=this._buildUserBindGroupLayout(e,t),o={shaderModule:n,userLayout:r,pipelineLayout:e.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._customBaseTextureLayout,r]}),pipelines:new Map,userUniformBuffer:null,userUniformBufferCapacity:0,baseTextureBindGroups:new WeakMap};return this._customMaterials.set(t,o),t._onDispose(()=>{const e=this._customMaterials.get(t);void 0!==e&&(this._releaseCustomResources(e),this._customMaterials.delete(t))}),o}_getOrCreateCustomPipeline(t,e,i,s,n){const r=`${e}:${i}:${s?"s":"n"}`,o=t.pipelines.get(r);if(void 0!==o)return o;const a={layout:t.pipelineLayout,vertex:{module:t.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:qr,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:t.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:Cr(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};s&&(a.depthStencil=Er());const h=n.createRenderPipeline(a);return t.pipelines.set(r,h),h}_getCustomBaseTextureBindGroup(t,e,i,s){const n=e.getTextureBinding(i),r=t.baseTextureBindGroups.get(i);if(r?.view===n.view)return r.group;const o=s.createBindGroup({layout:this._customBaseTextureLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]});return t.baseTextureBindGroups.set(i,{group:o,view:n.view}),o}_buildUserBindGroupLayout(t,e){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const s=jr(e);if(s.length>7)throw new Error("SpriteMaterial requested more than 7 user texture bindings.");let n=1;for(let t=0;t<s.length;t++)i.push({binding:n,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),n++,i.push({binding:n,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),n++;return t.createBindGroupLayout({entries:i})}_uploadUserUniforms(t,e,i){const s=function(t){const e=[];for(const i of Object.values(t.uniforms))Xr(i)||e.push(i);return e}(t),n=16*Math.max(s.length,1);(null===e.userUniformBuffer||e.userUniformBufferCapacity<n)&&(e.userUniformBuffer?.destroy(),e.userUniformBufferCapacity=n,e.userUniformBuffer=i.createBuffer({size:n,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const r=new Float32Array(n/4);let o=0;for(const t of s){const e=4*o;if("number"==typeof t)r[e]=t;else if(t instanceof Float32Array)r.set(t,e);else if(t instanceof Int32Array)for(let i=0;i<t.length;i++)r[e+i]=t[i];else{const i=t;for(let t=0;t<i.length;t++)r[e+t]=i[t]}o++}i.queue.writeBuffer(e.userUniformBuffer,0,r)}_buildUserBindGroup(t,e,i,s){const n=[];n.push({binding:0,resource:{buffer:e.userUniformBuffer}});let r=1;for(const e of jr(t)){const t=i.getTextureBinding(e);n.push({binding:r,resource:t.view}),r++,n.push({binding:r,resource:t.sampler}),r++}return s.createBindGroup({layout:e.userLayout,entries:n})}_releaseCustomResources(t){t.userUniformBuffer?.destroy(),t.pipelines.clear(),t.userUniformBuffer=null,t.userUniformBufferCapacity=0,t.baseTextureBindGroups=new WeakMap}}function Xr(t){return!("object"!=typeof t||null===t||!("width"in t)||!("height"in t)||t instanceof Float32Array||t instanceof Int32Array||Array.isArray(t))}function jr(t){const e=[];for(const i of Object.values(t.uniforms))Xr(i)&&e.push(i);for(const i of Object.values(t.textures))e.push(i);return e}const Hr=20;class Kr extends Br{_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(t){if(!this._device)throw new Error("WebGpuTextRenderer is not connected to a backend.");t instanceof $n?this._collectText(t):this._collectBitmapText(t)}flush(){if(0===this._pendingQuads.length)return void this._resetFrameState();const t=this.getBackend(),e=this._device;for(const t of this._pendingQuads)this._textureKeyMap.has(t.atlasTexture)||this._textureKeyMap.set(t.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((t,e)=>{const i=t.shaderType.localeCompare(e.shaderType);return 0!==i?i:(this._textureKeyMap.get(t.atlasTexture)??0)-(this._textureKeyMap.get(e.atlasTexture)??0)});const i=t.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,e.queue.writeBuffer(this._projBuffer,0,this._projData.buffer,0,48),this._uploadNodeBuffer(e);const s=this._pendingQuads,n=[];let r=0,o=0;for(const t of s)r+=4*t.quads.quadCount,o+=t.quads.indices.length;this._ensureVertexCapacity(r),this._ensureIndexCapacity(o);let a=0,h=0,l=0;for(;l<s.length;){const t=s[l],e=this._textureKeyMap.get(t.atlasTexture);let i=l+1;for(;i<s.length;){const n=s[i];if(n.shaderType!==t.shaderType||this._textureKeyMap.get(n.atlasTexture)!==e)break;i++}const r=h;let o=0;for(let t=l;t<i;t++){const{quads:e,nodeIndex:i}=s[t],n=4*e.quadCount,{vertices:r,uvs:l,indices:u}=e;for(let t=0;t<n;t++){const e=5*(a+t),s=2*t;this._float32View[e+0]=r[s],this._float32View[e+1]=r[s+1],this._float32View[e+2]=l[s],this._float32View[e+3]=l[s+1],this._float32View[e+4]=i}for(let t=0;t<u.length;t++)this._indexData[h+t]=u[t]+a;a+=n,h+=u.length,o+=u.length}n.push({shaderType:t.shaderType,atlasTexture:t.atlasTexture,firstIndex:r,indexCount:o}),l=i}this._ensureGpuVertexBuffer(e,a),this._ensureGpuIndexBuffer(e,h),e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,a*Hr),e.queue.writeBuffer(this._indexBuffer,0,this._indexData.buffer,0,2*h);const u=t.renderTargetFormat,c=t._passCoordinator.stencilActive,d=this._getFrameBindGroup(e),_=t._passCoordinator.acquirePass().pass;_.setVertexBuffer(0,this._vertexBuffer),_.setIndexBuffer(this._indexBuffer,"uint16");let f=null,p=null;for(const i of n)i.shaderType!==f&&(_.setPipeline(this._getPipeline(i.shaderType,u,c)),_.setBindGroup(0,d),f=i.shaderType),i.atlasTexture!==p&&(_.setBindGroup(1,this._getTexBindGroup(e,t,i.atlasTexture)),p=i.atlasTexture),_.drawIndexed(i.indexCount,1,i.firstIndex,0,0),t.stats.batches++,t.stats.drawCalls++;t._passCoordinator.endPass(),this._resetFrameState()}destroy(){this.disconnect()}async prewarmPipelines(t){const e=this._device;if(!e||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof e.createRenderPipelineAsync)return;const i=["sdf","msdf","color"],s=[];for(const n of i)for(const i of t){const t=`${n}:${i}:n`;this._pipelines.has(t)||s.push(e.createRenderPipelineAsync(this._buildPipelineDescriptor(n,i)).then(e=>{this._pipelines.set(t,e)}))}await Promise.all(s)}onConnect(t){const e=t.device;this._device=e,this._shaderModule=e.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=e.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=e.createBindGroupLayout({label:"WebGpuTextRenderer/texture",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=e.createPipelineLayout({label:"WebGpuTextRenderer",bindGroupLayouts:[this._frameBindGroupLayout,this._textureBindGroupLayout]}),this._projBuffer=e.createBuffer({label:"WebGpuTextRenderer/proj",size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this._nodeBuffer=e.createBuffer({label:"WebGpuTextRenderer/nodes",size:5120,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=5120;this._vertexBuffer=e.createBuffer({label:"WebGpuTextRenderer/vertices",size:5120,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=5120;this._indexBuffer=e.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(t){t.syncDirty();const{pageQuads:e,atlas:i}=t;if(0===e.length||null===i)return;const s=this._assignNodeIndex(t),n=t.colorGlyphs?"color":"sdf",r=i.pages;for(const t of e){const e=r[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:s,shaderType:n,atlasTexture:e.texture})}}_collectBitmapText(t){const{pageQuads:e,textures:i,msdf:s}=t;if(0===e.length)return;const n=this._assignNodeIndex(t),r=s?"msdf":"color";for(const t of e){const e=i[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:n,shaderType:r,atlasTexture:e})}}_assignNodeIndex(t){const e=this._nodeIndexMap.get(t);if(void 0!==e)return e;const i=this._nodeCount++;return this._nodeIndexMap.set(t,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,t),i}_packNodeData(t,e){const i=this._nodeDataArray,s=40*t,n=e.style,r=e.getGlobalTransform().toArray(!1);i[s+0]=r[0],i[s+1]=r[1],i[s+2]=r[2],i[s+3]=r[6],i[s+4]=r[3],i[s+5]=r[4],i[s+6]=r[5],i[s+7]=r[7];const o=n.fillColor;i[s+8]=o.r/255,i[s+9]=o.g/255,i[s+10]=o.b/255,i[s+11]=o.a;const a=n.outlineColor;i[s+12]=a.r/255,i[s+13]=a.g/255,i[s+14]=a.b/255,i[s+15]=a.a;const h=n.outlineWidth>0?Math.max(0,.5-n.outlineWidth):.5;i[s+16]=h,i[s+17]=n.shadowAlpha,i[s+18]=Math.max(.03,.1*n.shadowBlur),i[s+19]=null!==n.gradientColors?1:0;const l=n.shadowColor;i[s+20]=l.r/255,i[s+21]=l.g/255,i[s+22]=l.b/255,i[s+23]=l.a,i[s+24]=n.shadowOffsetX,i[s+25]=n.shadowOffsetY,i[s+26]="vertical"===n.gradientAxis?1:0,i[s+27]=0;const u=n.gradientColors;null!==u?(i[s+28]=u[0].r/255,i[s+29]=u[0].g/255,i[s+30]=u[0].b/255,i[s+31]=u[0].a,i[s+32]=u[1].r/255,i[s+33]=u[1].g/255,i[s+34]=u[1].b/255,i[s+35]=u[1].a):(i[s+28]=i[s+29]=i[s+30]=i[s+31]=0,i[s+32]=i[s+33]=i[s+34]=i[s+35]=0);const c=e.textBounds;i[s+36]=0,i[s+37]=0,i[s+38]=c.width,i[s+39]=c.height}_uploadNodeBuffer(t){const e=40*this._nodeCount*4;if(e>this._nodeBufferCapacity){let i=this._nodeBufferCapacity;for(;i<e;)i*=2;this._nodeBuffer?.destroy(),this._nodeBuffer=t.createBuffer({label:"WebGpuTextRenderer/nodes",size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=i,this._frameBindGroupDirty=!0}t.queue.writeBuffer(this._nodeBuffer,0,this._nodeDataArray.buffer,0,e)}_ensureGpuVertexBuffer(t,e){const i=e*Hr;if(i<=this._vertexBufferCapacity)return;let s=this._vertexBufferCapacity;for(;s<i;)s*=2;this._vertexBuffer?.destroy(),this._vertexBuffer=t.createBuffer({label:"WebGpuTextRenderer/vertices",size:s,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=s}_ensureGpuIndexBuffer(t,e){const i=2*e;if(i<=this._indexBufferCapacity)return;let s=this._indexBufferCapacity;for(;s<i;)s*=2;this._indexBuffer?.destroy(),this._indexBuffer=t.createBuffer({label:"WebGpuTextRenderer/indices",size:s,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._indexBufferCapacity=s}_getFrameBindGroup(t){return this._frameBindGroupDirty||null===this._frameBindGroup?(this._frameBindGroup=t.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(t,e,i){const{view:s,sampler:n}=e.getTextureBinding(i),r=this._texBindGroups.get(i);if(r?.view===s)return r.group;const o=t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:s},{binding:1,resource:n}]});return this._texBindGroups.set(i,{group:o,view:s}),o}_getPipeline(t,e,i){const s=`${t}:${e}:${i?"s":"n"}`,n=this._pipelines.get(s);if(n)return n;const r=this._device.createRenderPipeline(this._buildPipelineDescriptor(t,e,i));return this._pipelines.set(s,r),r}_buildPipelineDescriptor(t,e,i=!1){let s;s="sdf"===t?"fragmentSdf":"msdf"===t?"fragmentMsdf":"fragmentColor";const n={label:`WebGpuTextRenderer/${t}`,layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Hr,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:s,targets:[{format:e,blend:Cr(ni.Normal),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return i&&(n.depthStencil=Er()),n}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*Hr),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(t){if(t<=this._nodeCapacity)return;for(;this._nodeCapacity<t;)this._nodeCapacity*=2;const e=new Float32Array(40*this._nodeCapacity);e.set(this._nodeDataArray),this._nodeDataArray=e}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}}class Qr extends Us{_rawTransform=null;_sourceGeometry=null;_sourceVersion=-1;constructor(){super({vertices:new Float32Array([0,0,1,0,0,1])})}getGlobalTransform(){return this._rawTransform??super.getGlobalTransform()}configure(t,e,i,s){this._flattenGeometry(t),this._geometry=null,this._material=i,this._rawTransform=e,this.setTint(s??Ee.white)}configureBatchSource(t,e){this._flattenGeometry(t),this._geometry=t,this._material=e,this._rawTransform=null,this.setTint(Ee.white)}_flattenGeometry(t){if(t===this._sourceGeometry&&t.version===this._sourceVersion)return;const e=Vs(t);this._vertices=e.vertices,this._uvs=e.uvs,this._colors=e.colors,this._indices=e.indices,this._sourceGeometry=t,this._sourceVersion=t.version}}class Zr extends ci{constructor(t={}){super(t.center?.x??0,t.center?.y??0,t.size?.width??0,t.size?.height??0),t.viewport&&(this.viewport=t.viewport),t.rotation&&0!==t.rotation&&(this.rotation=t.rotation),void 0!==t.zoom&&1!==t.zoom&&this.setZoom(t.zoom)}}class Jr{geometry;material;_transforms=[];_tints=[];_count=0;constructor(t,e=null){if("static"!==t.usage)throw new Error(`RenderBatch requires geometry with usage='static' (got '${t.usage}').`);if(null!==e&&"mesh"!==e.target)throw new Error(`RenderBatch material must target 'mesh' (got '${String(e.target)}').`);this.geometry=t,this.material=e}get count(){return this._count}add(t,e=null){let i=this._transforms[this._count];void 0===i&&(i=new De,this._transforms[this._count]=i),i.copy(t);let s=this._tints[this._count];return void 0===s&&(s=new Ee,this._tints[this._count]=s),s.copy(e??Ee.white),this._count++,this}clear(){return this._count=0,this}destroy(){for(const t of this._transforms)t.destroy();for(const t of this._tints)t.destroy();this._transforms.length=0,this._tints.length=0,this._count=0}get _instanceTransforms(){return this._transforms}get _instanceTints(){return this._tints}}const to=()=>({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}),eo=t=>(t.frame++,t.submittedNodes=0,t.culledNodes=0,t.drawCalls=0,t.batches=0,t.renderPasses=0,t.renderTargetChanges=0,t.frameTimeMs=0,t.rawFrameDeltaMs=0,t.textureUploadBytes=0,t.bufferUploadBytes=0,t.downloadBytes=0,t.downloadCount=0,t);class io{order=500;_backend;_camera;_screenView;_immediateMesh=null;_batchMesh=null;constructor(t){this._backend=t;const e=t.view?.width??0,i=t.view?.height??0,s=t.view?.center?.x??e/2,n=t.view?.center?.y??i/2;this._camera=new Zr({center:{x:s,y:n},size:{width:e,height:i}}),this._screenView=new ci(s,n,e,i)}get camera(){return this._camera}set camera(t){const e=this._camera;this._camera=t,e!==t&&e.destroy()}get screenView(){return this._screenView}get view(){return this._camera}update(t){this._camera.update(t.milliseconds)}destroy(){this._camera.destroy(),this._screenView.destroy(),this._immediateMesh?.destroy(),this._immediateMesh=null,this._batchMesh?.destroy(),this._batchMesh=null}resize(t,e){this._camera.resize(t,e),this._screenView.resize(t,e),this._screenView.setCenter(t/2,e/2)}render(t,e={}){const i=e.view??this._camera;this._backend.setView(i),wi(t,this._backend)}renderTo(t,e){const i=new _i(e.width,e.height),s=new ci(e.width/2,e.height/2,e.width,e.height),n=this._backend._passCoordinator;if(n)return n.withChildPass({target:i,view:s,load:void 0!==e.clearColor?"clear":"load",clearColor:e.clearColor??null,stencil:xi.None},()=>{wi(t,this._backend)}),i;const r=this._backend.renderTarget,o=this._backend.view;this._backend.setRenderTarget(i),this._backend.setView(s),void 0!==e.clearColor&&this._backend.clear(e.clearColor);try{wi(t,this._backend)}finally{this._backend.setRenderTarget(r),this._backend.setView(o)}return i}drawGeometry(t,e,i={}){const s=i.material??null;if(null!==s&&"mesh"!==s.target)throw new Error(`drawGeometry material must target 'mesh' (got '${String(s.target)}').`);const n=i.view??this._camera,r=this._immediateMesh??=new Qr;this._backend.setView(n),r.configure(t,e,s,i.tint??null),this._backend.draw(r),this._backend.flush()}drawBatch(t,e={}){if(null!==t.material)throw new Error("drawBatch custom materials are not supported yet — v1 renders batches with the default mesh material.");if(0===t.count)return;const i=e.view??this._camera,s=this._batchMesh??=new Qr;this._backend.setView(i),s.configureBatchSource(t.geometry,t.material),this._backend.drawInstanced(s,t._instanceTransforms,t._instanceTints,t.count),this._backend.flush()}get stats(){return this._backend.stats}get backend(){return this._backend}}class so{_stats;_liveBytes=0;constructor(t){this._stats=t,this._stats.gpuMemoryBytes=0}get liveBytes(){return this._liveBytes}allocate(t){t<=0||(this._liveBytes+=t,this._stats.gpuMemoryBytes=this._liveBytes)}free(t){t<=0||(this._liveBytes=Math.max(0,this._liveBytes-t),this._stats.gpuMemoryBytes=this._liveBytes)}reallocate(t,e){return this.free(t),this.allocate(e),e}recordTextureUpload(t){t<=0||(this._stats.textureUploadBytes+=t)}recordBufferUpload(t){t<=0||(this._stats.bufferUploadBytes+=t)}recordDownload(t){t<=0||(this._stats.downloadBytes+=t,this._stats.downloadCount++)}}const no=(t,e,i,s=1)=>{const n=Math.max(1,Math.floor(t)),r=Math.max(1,Math.floor(e)),o=Math.max(1,Math.floor(s));let a=0,h=n,l=r;for(let t=0;t<o&&(a+=h*l*i,1!==h||1!==l);t++)h=Math.max(1,h>>1),l=Math.max(1,l>>1);return a},ro=t=>{switch(t){case"r8":return 1;case"r32f":case"rgba8":return 4;case"rgba32f":return 16}};class oo{_entries=new Map;_walk;_dispose;constructor(t={}){this._walk=t.walk??null,this._dispose=t.dispose??null}set(t,e){this._entries.set(t,e)}hasOwn(t){return this._entries.has(t)}has(t){return void 0!==this._find(t)}resolve(t){return this._find(t)}values(){return this._entries.values()}destroy(){if(null!==this._dispose){const t=new Set;for(const e of this._entries.values())t.has(e)||(t.add(e),this._dispose(e))}this._entries.clear()}_find(t){let e,i=t;for(;null!==i&&void 0===e;)e=this._entries.get(i),void 0===e&&(i=null!==this._walk?this._walk(i):null);return e}}const ao=t=>{const e=Object.getPrototypeOf(t.prototype);return e?.constructor??null};class ho{_renderers=new oo({walk:ao,dispose:t=>{t.disconnect(),"destroy"in t&&"function"==typeof t.destroy&&t.destroy()}});_resolved=new Map;_backend=null;registerRenderer(t,e){if(this._renderers.hasOwn(t))throw new Error(`A renderer is already registered for ${t.name}.`);this._renderers.set(t,e),this._resolved.clear(),null!==this._backend&&e.connect(this._backend)}bindRenderer(t,e){if(0===t.length)throw new Error("A RendererBinding must declare at least one target.");const i=new Set;for(const e of t){if(i.has(e))throw new Error(`A RendererBinding declares the same target ${e.name} more than once.`);i.add(e)}for(const e of t)if(this._renderers.hasOwn(e))throw new Error(`A renderer is already registered for ${e.name}.`);for(const i of t)this._renderers.set(i,e);this._resolved.clear(),null!==this._backend&&e.connect(this._backend)}renderers(){return this._renderers.values()}resolve(t){const e=t.constructor,i=this._resolved.get(e);if(void 0!==i)return i;const s=this._renderers.resolve(e);if(!s)throw new Error(`No renderer registered for ${t.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(e,s),s}connect(t){this._backend=t;for(const e of this._renderers.values())e.connect(t)}disconnect(){for(const t of this._renderers.values())t.disconnect();this._backend=null}destroy(){this._renderers.destroy(),this._resolved.clear(),this._backend=null}}const lo=new Float32Array(1),uo=new Uint32Array(lo.buffer);class co{_data=new Float32Array(192);_count=0;_version=0;_frameHash=2166136261;_lastCommittedHash=0;_lastCommittedCount=-1;_writeCount=0;_skippedWriteCount=0;_uploadCount=0;_uploadedRecordCount=0;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}begin(t=0){return t>0&&this._ensureCapacity(t),this._count=0,this._frameHash=2166136261,this._writeCount=0,this._skippedWriteCount=0,this._uploadCount=0,this._uploadedRecordCount=0,this}push(t,e){const i=this._count;return this.write(i,t,e),i}write(t,e,i){if(!Number.isInteger(t)||t<0)throw new Error(`TransformBuffer slot must be a non-negative integer (got ${t}).`);this._ensureCapacity(t+1);const s=12*t,n=this._data;n[s+0]=e.a,n[s+1]=e.b,n[s+2]=e.c,n[s+3]=e.d,n[s+4]=e.x,n[s+5]=e.y,n[s+6]=0,n[s+7]=0,n[s+8]=i.r/255,n[s+9]=i.g/255,n[s+10]=i.b/255,n[s+11]=i.a,t>=this._count&&(this._count=t+1),this._frameHash=this._mix(this._frameHash,t);for(let t=0;t<12;t++)this._frameHash=this._mix(this._frameHash,this._hashFloat(n[s+t]));return this._writeCount++,this}recordSkippedWrite(){return this._skippedWriteCount++,this}recordUpload(t){return this._uploadCount++,this._uploadedRecordCount+=t,this}commitSnapshot(t=0){const e=Math.max(this._count,t),i=this._mix(this._frameHash,e),s=i!==this._lastCommittedHash||e!==this._lastCommittedCount;return s&&(this._version++,this._lastCommittedHash=i,this._lastCommittedCount=e),{count:e,hash:i,changed:s,version:this._version}}_ensureCapacity(t){const e=this.capacity;if(t<=e)return;let i=Math.max(e,16);for(;i<t;)i*=2;const s=new Float32Array(12*i);s.set(this._data),this._data=s}_hashFloat(t){return lo[0]=t,uo[0]>>>0}_mix(t,e){return Math.imul((t^e)>>>0,16777619)>>>0}}const _o=new Uint16Array([0,1,2,0,2,3]);class fo{_shader=new Xn("#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 e=t.context,i=e.createVertexArray();if(null===i)throw new Error("WebGl2MaskCompositor: could not create vertex array object.");this._shader.connect(sr(e));const s=new Map,n=new Kn(hi.ElementArrayBuffer,_o,li.StaticDraw).connect(this._createBufferRuntime(e,s),t.accountant),r=new Kn(hi.ArrayBuffer,this._vertexData,li.DynamicDraw).connect(this._createBufferRuntime(e,s),t.accountant);this._shader.sync();const o=(new rr).addIndex(n).addAttribute(r,this._shader.getAttribute("a_position"),e.FLOAT,!1,16,0).addAttribute(r,this._shader.getAttribute("a_texcoord"),e.FLOAT,!1,16,8).connect(this._createVaoRuntime(e,i));this._connection={gl:e,vaoHandle:i,vao:o,indexBuffer:n,vertexBuffer:r,bufferHandles:s}}disconnect(){const t=this._connection;null!==t&&(t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(t,e,i,s,n,r,o,a){const h=this._connection;if(null===h)throw new Error("WebGl2MaskCompositor: not connected.");this._writeQuadVertices(s,n,s+r,n+o),t.bindShader(this._shader);const l=t.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(),t.bindTexture(e,0),t.bindTexture(i,1),t.setBlendMode(a),t.bindVertexArrayObject(h.vao),h.vertexBuffer.upload(this._float32View),h.vao.draw(6,0),t.stats.batches++,t.stats.drawCalls++,t.bindTexture(null,1)}_writeQuadVertices(t,e,i,s){const n=this._float32View;n[0]=t,n[1]=e,n[2]=0,n[3]=0,n[4]=i,n[5]=e,n[6]=1,n[7]=0,n[8]=i,n[9]=s,n[10]=1,n[11]=1,n[12]=t,n[13]=s,n[14]=0,n[15]=1}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("WebGl2MaskCompositor: could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:s=>{const n=s.data;t.bindBuffer(s.type,i),t.bufferData(s.type,n,s.usage),e.set(s,i)},destroy:s=>{t.deleteBuffer(i),e.delete(s),s.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:s=>{if(t.bindVertexArray(e),i!==s.version){let e=null;for(const i of s.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);s.indexBuffer&&s.indexBuffer.bind(),i=s.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,n)=>{e.indexBuffer?t.drawElements(n,i,t.UNSIGNED_SHORT,s):t.drawArrays(n,s,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}class po{_backend;_stencilEnabled=!1;constructor(t){this._backend=t}get activeTarget(){return this._backend.renderTarget}get activeView(){return this._backend.view}hasActivePass=!0;beginPass(t){this._backend.setRenderTarget(t.target),this._backend.setView(t.view),this._stencilEnabled=t.stencil===xi.Enabled,"clear"===t.load&&this._backend.clear(t.clearColor??void 0)}endPass(){this._backend.flush()}withChildPass(t,e){const i=this._backend.renderTarget,s=this._backend.view,n=this._stencilEnabled;this.beginPass(t);try{e()}finally{this._backend.setRenderTarget(i),this._backend.setView(s),this._stencilEnabled=n}}pushScissorRect(t){this._backend.pushScissorRect(t)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(t,e){this._backend.pushStencilClip(t,e)}popStencilClip(){this._backend.popStencilClip()}resolveLoad(t,e){return e?"clear":"load"}}const go=new Set(["a_position","position"]);class mo{_shader=new Xn("#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 De;_positions=new Float32Array(64);_connection=null;connect(t){if(null!==this._connection)return;const e=t.context,i=e.createVertexArray();if(null===i)throw new Error("WebGl2StencilClipper: could not create vertex array object.");this._shader.connect(sr(e)),this._shader.sync();const s=new Kn(hi.ArrayBuffer,this._positions,li.DynamicDraw).connect(this._createBufferRuntime(e),t.accountant),n=new rr(ai.Triangles).addAttribute(s,this._shader.getAttribute("a_position"),e.FLOAT,!1,8,0).connect(this._createVaoRuntime(e,i));this._connection={gl:e,vao:n,vertexBuffer:s}}disconnect(){const t=this._connection;null!==t&&(t.vertexBuffer.destroy(),t.vao.destroy(),this._shader.disconnect(),this._connection=null)}draw(t,e,i){const s=this._connection;if(null===s)throw new Error("WebGl2StencilClipper: not connected.");const n=this._extractPositions(e);if(0===n)return;this._matrix.copy(i).combine(t.view.getTransform()),t.bindShader(this._shader),this._shader.getUniform("u_matrix").setValue(this._matrix.toArray(!1)),this._shader.sync(),t.bindVertexArrayObject(s.vao),s.vertexBuffer.upload(this._positions.subarray(0,2*n));const r="triangle-strip"===e.topology?ai.TriangleStrip:ai.Triangles;s.vao.draw(n,0,r),t.stats.drawCalls++}_extractPositions(t){const e=this._resolvePositionAttribute(t.attributes);if("f32"!==e.type)throw new Error(`Stencil clipShape position attribute "${e.name}" must be of type f32 (got "${e.type}").`);const{stride:i,vertexData:s,indices:n}=t,r=s instanceof Float32Array?new DataView(s.buffer,s.byteOffset,s.byteLength):new DataView(s),o=null!==n?n.length:t.vertexCount;this._ensureCapacity(o);const a=this._positions;for(let t=0;t<o;t++){const s=(null!==n?n[t]:t)*i+e.offset;a[2*t]=r.getFloat32(s,!0),a[2*t+1]=r.getFloat32(s+4,!0)}return o}_resolvePositionAttribute(t){const e=t.find(t=>go.has(t.name));if(e)return e;const i=t.find(t=>t.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensureCapacity(t){const e=2*t;this._positions.length<e&&(this._positions=new Float32Array(Math.max(e,2*this._positions.length)))}_createBufferRuntime(t){const e=t.createBuffer();if(null===e)throw new Error("WebGl2StencilClipper: could not create render buffer.");return{bind:i=>{t.bindBuffer(i.type,e)},upload:i=>{t.bindBuffer(i.type,e),t.bufferData(i.type,i.data,i.usage)},destroy:i=>{t.deleteBuffer(e),i.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:s=>{if(t.bindVertexArray(e),i!==s.version){let e=null;for(const i of s.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);i=s.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,n)=>{t.drawArrays(n,s,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}const yo=(t,e)=>{const i=t.constructor;for(const t of Object.getOwnPropertyNames(i))if(i[t]===e)return t;return`0x${e.toString(16).padStart(4,"0").toUpperCase()}`},wo=(t,e)=>e.map(e=>"number"==typeof e?yo(t,e):String(e)).join(", ");class xo{backendType=jn.WebGl2;rendererRegistry=new ho;onContextLost=new m;onContextRestored=new m;_context;_rootRenderTarget;_onContextLostHandler;_onContextRestoredHandler;_textureStates=new Map;_renderTargetStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_clipBoundsStack=[];_clipPixelStack=[];_clipPointA=new te;_clipPointB=new te;_maskCompositor=new fo;_maskCompositorConnected=!1;_stencilClipper=new mo;_stencilStates=new Map;_stencilClipperConnected=!1;_passCoordinatorInstance=null;_canvas;_contextLost;_renderTarget;_snapTransform=new De;_renderer=null;_shader=null;_blendMode=null;_texture=null;_textureUnit=0;_vao=null;_clearColor=new Ee;_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 so(this._stats);_transformBuffer=new co;_transformTexture=null;_transformTextureHash=0;_transformTextureCount=-1;_activeDrawCommand=null;_drawPlanDepth=0;constructor(t){const e=t.options.canvas??{},i=t.options.rendering??{},s=e.width??800,n=e.height??600,r=t.options.clearColor,o=i.webglAttributes,a=i.debug??!1;this._canvas=t.canvas;const h=this._createContext(o);if(!h)throw new Error("This browser or hardware does not support WebGL.");this._context=a?(t=>new Proxy(t,{get(t,e,i){const s=Reflect.get(t,e,i);if("function"!=typeof s)return s;const n=String(e);return(...e)=>{console.log(`gl.${n}(${wo(t,e)})`);for(const i of e)void 0===i&&console.error(`undefined passed to gl.${n}(${wo(t,e)})`);const i=Reflect.apply(s,t,e);if("getError"!==n){const e=t.getError();if(e!==t.NO_ERROR)throw new Error(`${yo(t,e)} was caused by call to: ${n}`)}return i}}}))(h):h,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),r&&this.clearColor.copy(r),this._rootRenderTarget=new di(s,n,!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(ni.Normal),this.resize(s,n)}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 po(this)}async initialize(){return this}resetStats(){return eo(this._stats),this}_beginDrawPlan(t){this._transformBuffer.begin(t),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(t,e,i){const s=e+i;for(let i=e;i<s;i++){const e=t[i];if(e.kind!==Fe.Draw)continue;const s=e.command;He(s,this)?this._writeTransformCommand(s):this._transformBuffer.recordSkippedWrite()}}_prepareDrawCommand(t){this._activeDrawCommand=t}_writeTransformCommand(t){const e=t.drawable;this._transformBuffer.write(t.nodeIndex,this._resolveSnapTransform(e),e.tint)}_resolveSnapTransform(t){const e=this._renderTarget,i=e.root?this._canvas.width:e.width,s=e.root?this._canvas.height:e.height;return Ds(t,e.view,i,s,this._snapTransform)}_getSnapPixelSize(){const t=this._renderTarget;return{width:t.root?this._canvas.width:t.width,height:t.root?this._canvas.height:t.height}}_pushTransform(t){return this._transformBuffer.push(this._resolveSnapTransform(t),t.tint)}_endDrawPlan(){this._activeDrawCommand=null,this._drawPlanDepth>0&&this._drawPlanDepth--,0===this._drawPlanDepth&&this._assertBalancedStencil()}_assertBalancedStencil(){let t=0;for(const e of this._stencilStates.values())t+=e.stack.length;if(0===t)return;for(const t of this._stencilStates.values())t.depth=0,t.stack.length=0;const e=this._context;throw e.stencilFunc(e.ALWAYS,0,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.disable(e.STENCIL_TEST),new Error(`Unbalanced stencil clip stack at end of frame (${t} unpopped clip(s)).`)}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(t,e,i,s){if(s<=0||0===t.vertexCount)return this;if(e.length<s||i.length<s)throw new Error(`drawInstanced requires ${s} transforms and tints (got ${e.length}/${i.length}).`);const n=this.rendererRegistry.resolve(t);if(!(n instanceof ar))throw new Error("drawInstanced requires a mesh handled by the WebGL2 mesh renderer.");this._setActiveRenderer(n);const r=this._transformBuffer.push(e[0],i[0]);for(let t=1;t<s;t++)this._transformBuffer.push(e[t],i[t]);return n.drawInstancedBatch(t,r,s),this._activeDrawCommand=null,this._stats.submittedNodes+=s,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setRenderTarget(t){const e=t||this._rootRenderTarget,i=this._renderTarget!==e;return i&&(this._flushActiveRenderer(),this._renderTarget=e,this._stats.renderTargetChanges++),this._bindRenderTarget(e),i&&this._applyStencilState(e),this}pushScissorRect(t){this._flushActiveRenderer(),this._clipBoundsStack.push(t.clone());const e=this._toClipPixels(t),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,s=i?this._intersectClips(i,e):e;return this._clipPixelStack.push(s),this._applyClipState(),this}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const t=this._clipBoundsStack.pop();return t&&t.destroy(),this._clipPixelStack.pop(),this._applyClipState(),this}pushStencilClip(t,e){const i=this._renderTarget,s=this._getStencilState(i);if(s.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 n=this._context,r=s.depth;return 0===r&&(this._ensureTargetStencil(),n.enable(n.STENCIL_TEST),n.disable(n.SCISSOR_TEST),n.clearStencil(0),n.clear(n.STENCIL_BUFFER_BIT),this._applyClipState()),n.colorMask(!1,!1,!1,!1),n.stencilFunc(n.EQUAL,r,255),n.stencilOp(n.KEEP,n.KEEP,n.INCR),this._stencilClipper.draw(this,t,e),n.colorMask(!0,!0,!0,!0),s.depth=r+1,s.stack.push({shape:t,transform:(new De).copy(e)}),n.stencilFunc(n.EQUAL,s.depth,255),n.stencilOp(n.KEEP,n.KEEP,n.KEEP),this}popStencilClip(){const t=this._renderTarget,e=this._getStencilState(t),i=e.stack.pop();if(void 0===i)return this;this._flushActiveRenderer(),this._setActiveRenderer(null);const s=this._context,n=e.depth;return s.colorMask(!1,!1,!1,!1),s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR),this._stencilClipper.draw(this,i.shape,i.transform),s.colorMask(!0,!0,!0,!0),e.depth=n-1,this._applyStencilState(t),this}composeWithAlphaMask(t,e,i,s,n,r,o){return n<=0||r<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._maskCompositorConnected||(this._maskCompositor.connect(this),this._maskCompositorConnected=!0),this._maskCompositor.compose(this,t,e,i,s,n,r,o)),this}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const s=this._temporaryRenderTextures[i];if(s.width===t&&s.height===e)return this._temporaryRenderTextures.splice(i,1),s}return new _i(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(t){return this._vao!==t&&(t?t.bind():this._vao?.unbind(),this._vao=t),this}bindShader(t){return this._shader!==t&&(this._shader&&(this._shader.unbind(),this._shader=null),t&&t.bind(),this._shader=t),this}bindTexture(t,e){if(void 0!==e&&this._setTextureUnit(e),null===t)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(t);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=t,this}bindTransformBufferTexture(t,e){const i=Math.max(1,e),s=this._transformTexture;s?.height===this._transformBuffer.capacity&&s.buffer===this._transformBuffer.data||(s?.destroy(),this._transformTexture=new In({width:3,height:this._transformBuffer.capacity,format:"rgba32f",data:this._transformBuffer.data}),this._transformTextureHash=0,this._transformTextureCount=-1);const n=this._transformBuffer.commitSnapshot(i),r=this._transformTexture;if(null===r)throw new Error("Transform texture must be initialized before binding.");return(n.changed||n.count!==this._transformTextureCount||n.hash!==this._transformTextureHash)&&(r.commitRect(0,0,3,n.count),this._transformBuffer.recordUpload(n.count),this._transformTextureHash=n.hash,this._transformTextureCount=n.count),this.bindTexture(r,t)}setBlendMode(t){if(t!==this._blendMode){const e=this._context;switch(this._blendMode=t,t){case ni.Additive:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE);break;case ni.Subtract:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ZERO,e.ONE_MINUS_SRC_COLOR);break;case ni.Multiply:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA);break;case ni.Screen:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_COLOR);break;case ni.Darken:e.blendEquation(e.MIN),e.blendFunc(e.ONE,e.ONE);break;case ni.Lighten:e.blendEquation(e.MAX),e.blendFunc(e.ONE,e.ONE);break;default:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(t){if(this._textureUnit!==t){const e=this._context;this._textureUnit=t,e.activeTexture(e.TEXTURE0+t)}}setClearColor(t){if(!this._clearColor.equals(t)){const e=this._context;this._clearColor.copy(t),e.clearColor(t.r/255,t.g/255,t.b/255,t.a)}return this}clear(t){const e=this._context;return t&&this.setClearColor(t),this._bindRenderTarget(this._renderTarget),e.clear(e.COLOR_BUFFER_BIT),this}resize(t,e){return this._rootRenderTarget.resize(t,e),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 t of this._clipBoundsStack)t.destroy();this._clipBoundsStack.length=0,this._clipPixelStack.length=0,this._clipPointA.destroy(),this._clipPointB.destroy(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!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(t){try{return this._canvas.getContext("webgl2",{...t,stencil:!0})}catch(t){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const t=this._context,{r:e,g:i,b:s,a:n}=this._clearColor;t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.clearColor(e/255,i/255,s/255,n)}_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 t=this._context.createFramebuffer();if(null===t)throw new Error("Could not create framebuffer.");return t}_createTextureHandle(){const t=this._context.createTexture();if(null===t)throw new Error("Could not create texture.");return t}_bookTextureStorage(t,e,i){const s=no(e.width,e.height,i,this._textureMipLevelCount(e));t.accountedBytes=this._accountant.reallocate(t.accountedBytes,s)}_textureMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_destroyManagedResources(){for(const t of[...this._renderTargetStates.keys()])this._evictRenderTarget(t,!1);for(const t of[...this._textureStates.keys()])this._evictTexture(t,!1)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(t){let e=this._renderTargetStates.get(t);return e||(this._subscribeToDestroy(t,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(t,!0)}),e={framebuffer:t.root?null:this._createFramebuffer(),version:-1,attachedTexture:null,stencilRenderbuffer:null,stencilWidth:0,stencilHeight:0},this._renderTargetStates.set(t,e)),e}_getTextureState(t){let e=this._textureStates.get(t);return e||(this._subscribeToDestroy(t,this._textureDestroyHandlers,()=>{this._evictTexture(t,!0)}),e={handle:this._createTextureHandle(),version:-1,width:0,height:0,accountedBytes:0},this._textureStates.set(t,e)),e}_subscribeToDestroy(t,e,i){e.has(t)||(t.addDestroyListener(i),e.set(t,i))}_unsubscribeFromDestroy(t,e){const i=e.get(t);i&&(t.removeDestroyListener(i),e.delete(t))}_evictRenderTarget(t,e){const i=this._renderTargetStates.get(t);this._unsubscribeFromDestroy(t,this._renderTargetDestroyHandlers),t instanceof _i&&this._evictTexture(t,!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(t)),this._stencilStates.delete(t),this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget,e&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(t,e){const i=this._textureStates.get(t);this._unsubscribeFromDestroy(t,this._textureDestroyHandlers),i&&(this._texture===t&&(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(t)),this._texture===t&&(this._texture=null),e&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(t){const e=this._prepareRenderTarget(t);if(this._boundFramebuffer!==e.framebuffer||e.version!==t.version){const i=this._context,s=t.getViewport(),n=t.root&&t.width>0?this._canvas.width/t.width:1,r=t.root&&t.height>0?this._canvas.height/t.height:1,o=Math.floor(s.x*n),a=Math.floor(s.y*r),h=Math.max(0,Math.round(s.width*n)),l=Math.max(0,Math.round(s.height*r));i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.viewport(o,a,h,l),this._boundFramebuffer=e.framebuffer,e.version=t.version}this._clipPixelStack.length>0&&this._applyClipState()}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(t){const e=this._getRenderTargetState(t);if(t instanceof _i&&e.framebuffer){const i=this._boundFramebuffer,s=this._textureUnit;this._setTextureUnit(15);const n=this._syncTexture(t);if(this._setTextureUnit(s),e.attachedTexture!==n.handle){const t=this._context;t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n.handle,0),t.bindFramebuffer(t.FRAMEBUFFER,i),e.attachedTexture=n.handle}this._stencilStates.has(t)||(t.needsStencil=!1),(t.needsStencil||null!==e.stencilRenderbuffer)&&this._syncStencilAttachment(t,e)}return e}_ensureTargetStencil(){const t=this._renderTarget;t.root||(t.needsStencil=!0,this._syncStencilAttachment(t,this._getRenderTargetState(t)))}_syncStencilAttachment(t,e){if(null===e.framebuffer)return;const i=this._context,s=Math.max(1,t.width),n=Math.max(1,t.height);if(null!==e.stencilRenderbuffer&&e.stencilWidth===s&&e.stencilHeight===n)return;null===e.stencilRenderbuffer&&(e.stencilRenderbuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,e.stencilRenderbuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH24_STENCIL8,s,n),i.bindRenderbuffer(i.RENDERBUFFER,null);const r=this._boundFramebuffer;i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e.stencilRenderbuffer),i.bindFramebuffer(i.FRAMEBUFFER,r),e.stencilWidth=s,e.stencilHeight=n}_getStencilState(t){let e=this._stencilStates.get(t);return void 0===e&&(e={depth:0,stack:[]},this._stencilStates.set(t,e)),e}_applyStencilState(t){const e=this._context,i=this._getStencilState(t).depth;if(0===i)return e.stencilFunc(e.ALWAYS,0,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),void e.disable(e.STENCIL_TEST);e.enable(e.STENCIL_TEST),e.stencilFunc(e.EQUAL,i,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP)}_syncTexture(t){const e=this._context,i=this._getTextureState(t),s=t instanceof _i?t.textureVersion:t.version;if(e.bindTexture(e.TEXTURE_2D,i.handle),i.version!==s){if(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t.wrapMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t.wrapMode),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),t instanceof In){const s=t.format,n=function(t){const e=WebGL2RenderingContext;switch(t){case"r8":return{internalFormat:e.R8,format:e.RED,type:e.UNSIGNED_BYTE,channels:1};case"r32f":return{internalFormat:e.R32F,format:e.RED,type:e.FLOAT,channels:1};case"rgba8":return{internalFormat:e.RGBA8,format:e.RGBA,type:e.UNSIGNED_BYTE,channels:4};case"rgba32f":return{internalFormat:e.RGBA32F,format:e.RGBA,type:e.FLOAT,channels:4}}}(s),r=t._consumeDirtyRegion(),o=-1===i.version||i.width!==t.width||i.height!==t.height;e.pixelStorei(e.UNPACK_ALIGNMENT,1);const a=ro(s);if(o||null===r||r.full)e.texImage2D(e.TEXTURE_2D,0,n.internalFormat,t.width,t.height,0,n.format,n.type,t.buffer),this._bookTextureStorage(i,t,a),this._accountant.recordTextureUpload(t.width*t.height*a);else{const i=n.channels,s=t.width*i,o=r.width*i,h=t.buffer instanceof Float32Array?new Float32Array(r.width*r.height*i):new Uint8Array(r.width*r.height*i);for(let e=0;e<r.height;e++){const n=(r.y+e)*s+r.x*i,a=e*o;h.set(t.buffer.subarray(n,n+o),a)}e.texSubImage2D(e.TEXTURE_2D,0,r.x,r.y,r.width,r.height,n.format,n.type,h),this._accountant.recordTextureUpload(r.width*r.height*a)}e.pixelStorei(e.UNPACK_ALIGNMENT,4)}else t instanceof _i?-1===i.version||i.width!==t.width||i.height!==t.height||null===t.source?(e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.width,t.height,0,e.RGBA,e.UNSIGNED_BYTE,t.source),this._bookTextureStorage(i,t,vo),this._accountant.recordTextureUpload(t.width*t.height*vo)):(e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,t.source),this._accountant.recordTextureUpload(t.width*t.height*vo)):t.source&&(-1===i.version||i.width!==t.width||i.height!==t.height?(e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source),this._bookTextureStorage(i,t,vo)):e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,t.source),this._accountant.recordTextureUpload(t.width*t.height*vo));t.generateMipMap&&(t instanceof _i||null!==t.source)&&e.generateMipmap(e.TEXTURE_2D),i.version=s,i.width=t.width,i.height=t.height}return i}_toClipPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(t.right,t.bottom)),s=Math.min(e.x,i.x),n=Math.max(e.x,i.x),r=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(s))),u=Math.max(0,Math.min(a,Math.ceil(n))),c=Math.max(0,Math.min(h,Math.floor(r))),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(t,e){const i=Math.max(t.x,e.x),s=Math.max(t.y,e.y),n=Math.min(t.x+t.width,e.x+e.width),r=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:s,width:Math.max(0,n-i),height:Math.max(0,r-s)}}_applyClipState(){const t=this._context;if(0===this._clipPixelStack.length)return void t.disable(t.SCISSOR_TEST);const e=this._clipPixelStack[this._clipPixelStack.length-1],i=this._renderTarget.root&&this._renderTarget.width>0?this._canvas.width/this._renderTarget.width:1,s=this._renderTarget.root&&this._renderTarget.height>0?this._canvas.height/this._renderTarget.height:1,n=Math.floor(e.x*i),r=Math.floor(e.y*s),o=Math.max(0,Math.round(e.width*i)),a=Math.max(0,Math.round(e.height*s));t.enable(t.SCISSOR_TEST),t.scissor(n,r,o,a)}}const vo=4;class bo{_projectionData=new Float32Array(16);_vertexData=new Float32Array(16);_indexData=new Uint16Array([0,1,2,0,2,3]);_projectionMatrix=new De;_pipelines=new Map;_device=null;_shaderModule=null;_projectionBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_projectionBuffer=null;_projectionBindGroup=null;connect(t){null===this._device&&(this._device=t,this._shaderModule=t.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=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=t.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=t.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout]}),this._vertexBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=t.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._projectionBindGroup=t.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(t,e,i,s,n,r,o,a){if(null===this._device)throw new Error("WebGpuMaskCompositor: not connected.");if(r<=0||o<=0)return;const h=this._device;this._writeQuadVertices(s,n,s+r,n+o),h.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(t.view.getTransform()),h.queue.writeBuffer(this._projectionBuffer,0,this._projectionData);const l=t.getTextureBinding(e),u=t.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=t.renderTargetFormat,_=t._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,a,_),p=t._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),t.stats.batches++,t.stats.drawCalls++,t._passCoordinator.endPass()}_getOrCreatePipeline(t,e,i){const s=`${t}|${e}|${i?"s":"n"}`,n=this._pipelines.get(s);if(void 0!==n)return n;const r=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:Cr(e)}]},primitive:{topology:"triangle-list"}};i&&(o.depthStencil=Er());const a=r.createRenderPipeline(o);return this._pipelines.set(s,a),a}_writeQuadVertices(t,e,i,s){const n=this._vertexData;n[0]=t,n[1]=e,n[2]=0,n[3]=0,n[4]=i,n[5]=e,n[6]=1,n[7]=0,n[8]=i,n[9]=s,n[10]=1,n[11]=1,n[12]=t,n[13]=s,n[14]=0,n[15]=1}_writeProjectionMatrix(t){const e=this._projectionMatrix.copy(t),i=this._projectionData;i[0]=e.a,i[1]=e.c,i[2]=0,i[3]=0,i[4]=e.b,i[5]=e.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=0,i[15]=1}}class So{_backend;_stencil=new Pr;_stencilDepths=new Map;_stencilStacks=new Map;_stencilConnected=!1;_stencilWriteInProgress=!1;_stencilLoadOp="load";_stencilRef=0;_active=null;constructor(t){this._backend=t}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 t=this._backend,e=this.stencilActive,i={colorAttachments:[t.createColorAttachment()]};e&&(i.depthStencilAttachment=this._createStencilAttachment(t.renderTarget));const s=t.device.createCommandEncoder(),n=s.beginRenderPass(i);t.stats.renderPasses++;const r=t.getScissorRect();return null!==r&&r.width>0&&r.height>0&&n.setScissorRect(r.x,r.y,r.width,r.height),e&&n.setStencilReference(this._stencilRef),this._active={encoder:s,pass:n,targetFormat:t.renderTargetFormat,view:t.view,stencilEnabled:e,stencilRef:this._stencilRef},this._active}endPass(){const t=this._active;null!==t&&(this._active=null,t.pass.end(),this._backend.submit(t.encoder.finish()))}beginPass(t){this._backend.setRenderTarget(t.target),this._backend.setView(t.view),"clear"===t.load&&this._backend.clear(t.clearColor??void 0)}withChildPass(t,e){const i=this._backend.renderTarget,s=this._backend.view;this.beginPass(t);try{e()}finally{this._backend.setRenderTarget(i),this._backend.setView(s)}}pushScissorRect(t){this._backend.pushScissorRect(t)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(t,e){const i=this._backend.renderTarget,s=this._stencilDepths.get(i)??0;if(s>=255)throw new Error("Stencil clip nesting exceeds the 255-level limit.");this._connectStencil(),this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=s,this._stencilLoadOp=0===s?"clear":"load";const n=this.acquirePass();this._stencil.draw(n.pass,n.targetFormat,!0,t,e,n.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(i,s+1),this._stencilRef=s+1,this._getStencilStack(i).push({shape:t,transform:(new De).copy(e)})}popStencilClip(){const t=this._backend.renderTarget,e=this._stencilStacks.get(t),i=e?.pop();if(void 0===i)return;const s=this._stencilDepths.get(t)??0;this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=s,this._stencilLoadOp="load";const n=this.acquirePass();this._stencil.draw(n.pass,n.targetFormat,!1,i.shape,i.transform,n.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(t,s-1),this._stencilRef=s-1}resolveLoad(t,e){return e||!this._backend._targetHasContent(t)?"clear":"load"}releaseStencilTarget(t){this._stencilConnected&&this._stencil.releaseAttachment(t),this._stencilDepths.delete(t),this._stencilStacks.delete(t)}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 t=0;for(const e of this._stencilStacks.values())t+=e.length;return t}_activeTargetDepth(){return this._stencilDepths.get(this._backend.renderTarget)??0}_connectStencil(){this._stencilConnected||(this._stencil.connect(this._backend.device),this._stencilConnected=!0)}_getStencilStack(t){let e=this._stencilStacks.get(t);return void 0===e&&(e=[],this._stencilStacks.set(t,e)),e}_createStencilAttachment(t){const{width:e,height:i}=this._backend._getAttachmentPixelSize(t),s=this._stencil.getAttachmentView(t,e,i),n=this._stencilLoadOp;return this._stencilLoadOp="load",{view:s,depthReadOnly:!0,stencilLoadOp:n,stencilStoreOp:"store",stencilClearValue:0}}}class Bo{_buffer=new co;_storageBuffer=null;_storageCapacity=0;_storageHash=0;_storageCount=-1;_accountant=null;_accountedBytes=0;get buffer(){return this._buffer}begin(t){this._buffer.begin(t)}writeCommand(t,e){const i=t.drawable;this._buffer.write(t.nodeIndex,e??i.getGlobalTransform(),i.tint)}recordSkippedWrite(){this._buffer.recordSkippedWrite()}push(t,e){return this._buffer.push(e??t.getGlobalTransform(),t.tint)}pushValues(t,e){return this._buffer.push(t,e)}reserve(t,e,i){this._accountant=i??this._accountant;const s=12*Math.max(1,e)*Float32Array.BYTES_PER_ELEMENT;null!==this._storageBuffer&&s<=this._storageCapacity||this._growBuffer(t,s)}getBuffer(t,e,i){this._accountant=i??this._accountant;const s=Math.max(1,e),n=12*s*Float32Array.BYTES_PER_ELEMENT,r=this._buffer.commitSnapshot(s);if((null===this._storageBuffer||n>this._storageCapacity)&&this._growBuffer(t,n),r.changed||r.hash!==this._storageHash||r.count!==this._storageCount){const e=12*r.count*Float32Array.BYTES_PER_ELEMENT;t.queue.writeBuffer(this._storageBuffer,0,this._buffer.data.buffer,this._buffer.data.byteOffset,e),this._buffer.recordUpload(r.count),this._accountant?.recordBufferUpload(e),this._storageHash=r.hash,this._storageCount=r.count}return{buffer:this._storageBuffer,count:r.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(t,e){let i=Math.max(this._storageCapacity,12*Float32Array.BYTES_PER_ELEMENT);for(;i<e;)i*=2;this._storageBuffer?.destroy(),this._storageBuffer=t.createBuffer({size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._storageCapacity=i,this._storageHash=0,this._storageCount=-1,this._accountedBytes=this._accountant?.reallocate(this._accountedBytes,i)??this._accountedBytes}}const Co="rgba8unorm";class To{backendType=jn.WebGpu;rendererRegistry=new ho;onDeviceLost=new m;onDeviceRestored=new m;_canvas;_rootRenderTarget;_clearColor=new Ee;_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 te;_clipPointB=new te;_maskCompositor=new bo;_maskCompositorConnected=!1;_mipmapShaderModule=null;_mipmapBindGroupLayout=null;_mipmapPipelineLayout=null;_mipmapPipeline=null;_mipmapSampler=null;_context=null;_device=null;_format=null;_initializePromise=null;_renderTarget;_snapTransform=new De;_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 so(this._stats);_transformStorage=new Bo;_activeDrawCommand=null;_passCoordinatorInstance=null;_drawPlanDepth=0;constructor(t){const e=t.options.canvas??{},i=e.width??800,s=e.height??600,n=t.options.clearColor;this._canvas=t.canvas,this._rootRenderTarget=new di(i,s,!0),this._renderTarget=this._rootRenderTarget,n&&this._clearColor.copy(n),this.resize(i,s)}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:Co}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 So(this)}get clearColor(){return this._clearColor}get deviceLost(){return this._deviceLost}setClearColor(t){return this._clearColor.copy(t),this}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(t=>{throw this._initializePromise=null,t})),this._initializePromise}resetStats(){return eo(this._stats),this}_beginDrawPlan(t){const e=this._getTransformStorage();e.begin(t),t>0&&null!==this._device&&!this._deviceLost&&e.reserve(this._device,t,this._accountant),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(t,e,i){const s=this._getTransformStorage(),n=e+i;for(let i=e;i<n;i++){const e=t[i];if(e.kind!==Fe.Draw)continue;const n=e.command;He(n,this)?s.writeCommand(n,this._resolveSnapTransform(n.drawable)):s.recordSkippedWrite()}}_prepareDrawCommand(t){this._activeDrawCommand=t}_endDrawPlan(){if(this._activeDrawCommand=null,this._drawPlanDepth>0&&this._drawPlanDepth--,0===this._drawPlanDepth&&null!==this._passCoordinatorInstance){const t=this._passCoordinatorInstance.unbalancedStencilClips();if(t>0)throw this._passCoordinatorInstance.resetStencil(),new Error(`Unbalanced stencil clip stack at end of frame (${t} unpopped clip(s)).`)}}draw(t){if(this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(t,e,i,s){if(s<=0||0===t.vertexCount||this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const n=this.rendererRegistry.resolve(t);if(!(n instanceof Ir))throw new Error("drawInstanced requires a mesh handled by the WebGPU mesh renderer.");this._setActiveRenderer(n);const r=this._getTransformStorage(),o=r.pushValues(e[0],i[0]);for(let t=1;t<s;t++)r.pushValues(e[t],i[t]);return n.drawInstancedBatch(t,o,s),this._activeDrawCommand=null,this._stats.submittedNodes+=s,this}execute(t){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this)),this}setBlendMode(t){return this}setRenderTarget(t){const e=t??this._rootRenderTarget;return this._renderTarget!==e&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=e,this._stats.renderTargetChanges++,e!==this._rootRenderTarget&&this._subscribeRenderTarget(e)),this}pushScissorRect(t){this._flushActiveRenderer(),this._clipBoundsStack.push(t.clone());const e=this._toClipPixels(t),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,s=i?this._intersectClips(i,e):e;return this._clipPixelStack.push(s),this}composeWithAlphaMask(t,e,i,s,n,r,o){return n<=0||r<=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,t,e,i,s,n,r,o)),this}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const t=this._clipBoundsStack.pop();return t&&t.destroy(),this._clipPixelStack.pop(),this}pushStencilClip(t,e){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._passCoordinator.pushStencilClip(t,e)),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 t=this._clipPixelStack[this._clipPixelStack.length-1],e=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(t.x*e),y:Math.floor(t.y*i),width:Math.max(0,Math.round(t.width*e)),height:Math.max(0,Math.round(t.height*i))}}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const s=this._temporaryRenderTextures[i];if(s.width===t&&s.height===e)return this._temporaryRenderTextures.splice(i,1),s}return new _i(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this}clear(t){return t&&this.setClearColor(t),this._clearRequested=!0,this}resize(t,e){return this._rootRenderTarget.resize(t,e),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 t of this._clipBoundsStack)t.destroy();this._clipBoundsStack.length=0,this._clipPixelStack.length=0,this._clipPointA.destroy(),this._clipPointB.destroy(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!1),this._transformStorage?.destroy(),this._transformStorage=null,this._activeDrawCommand=null,this._passCoordinatorInstance?.destroyStencil(),this._drawPlanDepth=0;for(const t of[...this._renderTargetDestroyHandlers.keys()])this._unsubscribeRenderTarget(t);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 t=this._renderTarget;let e;if(t===this._rootRenderTarget)e=this.context.getCurrentTexture().createView();else{if(!(t instanceof _i))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");e=this._syncTexture(t).view}const i=this._passCoordinator.resolveLoad(t,this._clearRequested);return this._clearRequested=!1,{view:e,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(t){if(this.device.queue.submit([t]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof _i){const t=this._syncTexture(this._renderTarget);t.hasContent=!0,t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}}_targetHasContent(t){return t===this._rootRenderTarget?this._hasPresentedFrame:t instanceof _i&&this._getTextureState(t).hasContent}_getAttachmentPixelSize(t){return t===this._rootRenderTarget?{width:this._canvas.width,height:this._canvas.height}:{width:t.width,height:t.height}}getTextureBinding(t){const e=this._syncTexture(t);return{view:e.view,sampler:e.sampler}}shouldPremultiplyTextureSample(t){return!(t instanceof _i)&&t.premultiplyAlpha}getTransformStorageBuffer(t){return this._getTransformStorage().getBuffer(this.device,t,this._accountant)}_pushTransform(t){return this._getTransformStorage().push(t,this._resolveSnapTransform(t))}_resolveSnapTransform(t){const e=this._renderTarget,i=e===this._rootRenderTarget,s=i?this._canvas.width:e.width,n=i?this._canvas.height:e.height;return Ds(t,e.view,s,n,this._snapTransform)}_getSnapPixelSize(){return this._getAttachmentPixelSize(this._renderTarget)}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer?.flush()}_getTransformStorage(){return null!==this._transformStorage&&void 0!==this._transformStorage||(this._transformStorage=new Bo),this._transformStorage}async _initialize(){const t=this._getGpuNavigator();if(null===t)throw new Error("This browser does not support WebGPU.");if("function"!=typeof t.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof t.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");let e;try{e=await t.gpu.requestAdapter()}catch(t){throw this._createInitializationError("Failed to request a WebGPU adapter.",t)}if(null===e)throw new Error("Could not acquire a WebGPU adapter.");const i=this._canvas.getContext("webgpu");if(null===i)throw new Error("Could not create WebGPU canvas context.");if("function"!=typeof e.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");let s;try{s=await e.requestDevice()}catch(t){throw this._createInitializationError("Failed to request a WebGPU device.",t)}if(null===s)throw new Error("Could not acquire a WebGPU device.");const n=t.gpu.getPreferredCanvasFormat();try{i.configure({device:s,format:n,alphaMode:"opaque"})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}this._context=i,this._device=s,this._format=n,this._hasPresentedFrame=!1,this._subscribeToDeviceLoss(),this.rendererRegistry.connect(this),this.resize(this._rootRenderTarget.width,this._rootRenderTarget.height);const r=[n,Co];return await this._prewarmRendererPipelines(r),this}_subscribeToDeviceLoss(){if(!this._device)return;const t=this._device;t.lost.then(e=>{this._destroyed||this._device!==t||this._handleDeviceLoss(e)})}_handleDeviceLoss(t){this._deviceLost=!0,this.onDeviceLost.dispatch(t),"destroyed"!==t.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 t=this._recoveryBackoffMs*Math.pow(2,this._recoveryAttempt-1);await new Promise(e=>{setTimeout(e,t)})}}}finally{this._isRecovering=!1}}}_teardownDeviceState(){for(const[t,e]of this._textureDestroyHandlers)t.removeDestroyListener(e);this._textureDestroyHandlers.clear(),this._textureStates.clear(),this._temporaryRenderTextures.length=0,this.rendererRegistry.disconnect(),this._maskCompositorConnected&&(this._maskCompositor.disconnect(),this._maskCompositorConnected=!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(t){const e=[];for(const i of this.rendererRegistry.renderers()){const s=i;"function"==typeof s.prewarmPipelines&&e.push(s.prewarmPipelines(t))}await Promise.all(e)}_getGpuNavigator(){const t=navigator;return t.gpu?t:null}_createInitializationError(t,e){return e instanceof Error&&e.message.length>0?new Error(`${t} ${e.message}`):new Error(t)}_destroyManagedTextures(){for(const t of[...this._textureStates.keys()])this._evictTexture(t)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getTextureState(t){let e=this._textureStates.get(t);if(!e){const i=this.device.createTexture({size:{width:Math.max(t.width,1),height:Math.max(t.height,1)},format:this._getGpuTextureFormat(t),mipLevelCount:this._getMipLevelCount(t),usage:this._getTextureUsage(t)}),s=this._getMipLevelCount(t);e={texture:i,view:i.createView(),sampler:this._createSampler(t),version:-1,width:t.width,height:t.height,mipLevelCount:s,hasContent:!1,accountedBytes:0},e.accountedBytes=this._accountant.reallocate(0,this._estimateTextureBytes(t,s));const n=()=>{this._evictTexture(t)};t.addDestroyListener(n),this._textureDestroyHandlers.set(t,n),this._textureStates.set(t,e)}return e}_syncTexture(t){if(!(t instanceof _i||t instanceof In||null!==t.source&&0!==t.width&&0!==t.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const e=this._getTextureState(t),i=t instanceof _i?t.textureVersion:t.version,s=this._getMipLevelCount(t);if(e.version!==i){if(e.width!==t.width||e.height!==t.height||e.mipLevelCount!==s){e.texture.destroy();const i=this.device.createTexture({size:{width:t.width,height:t.height},format:this._getGpuTextureFormat(t),mipLevelCount:s,usage:this._getTextureUsage(t)});e.texture=i,e.view=i.createView(),e.width=t.width,e.height=t.height,e.mipLevelCount=s,e.hasContent=!1,e.accountedBytes=this._accountant.reallocate(e.accountedBytes,this._estimateTextureBytes(t,s))}if(e.sampler=this._createSampler(t),t instanceof In){const i=Mo(t.format),s=t._consumeDirtyRegion();if(null===s||s.full||!e.hasContent)this.device.queue.writeTexture({texture:e.texture},t.buffer,{bytesPerRow:t.width*i.bytesPerPixel,rowsPerImage:t.height},{width:t.width,height:t.height}),this._accountant.recordTextureUpload(t.width*t.height*i.bytesPerPixel);else{const n=i.channels,r=i.bytesPerPixel,o=s.width*s.height*r,a=t.buffer instanceof Float32Array?new Float32Array(o/4):new Uint8Array(o),h=t.width*n,l=s.width*n;for(let e=0;e<s.height;e++){const i=(s.y+e)*h+s.x*n,r=e*l;a.set(t.buffer.subarray(i,i+l),r)}this.device.queue.writeTexture({texture:e.texture,origin:{x:s.x,y:s.y}},a,{bytesPerRow:s.width*r,rowsPerImage:s.height},{width:s.width,height:s.height}),this._accountant.recordTextureUpload(s.width*s.height*r)}e.hasContent=!0}else if(!(t instanceof _i)){const i=t.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:e.texture},{width:t.width,height:t.height}),this._accountant.recordTextureUpload(t.width*t.height*4),e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}e.version=i}return e}_evictTexture(t){const e=this._textureStates.get(t),i=this._textureDestroyHandlers.get(t);i&&(t.removeDestroyListener(i),this._textureDestroyHandlers.delete(t)),e&&(e.texture.destroy(),this._accountant.free(e.accountedBytes),e.accountedBytes=0,this._textureStates.delete(t)),this._texture===t&&(this._texture=null)}_subscribeRenderTarget(t){if(!this._renderTargetDestroyHandlers.has(t)){const e=()=>{this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget),this._passCoordinatorInstance?.releaseStencilTarget(t),this._renderTargetDestroyHandlers.delete(t)};t.addDestroyListener(e),this._renderTargetDestroyHandlers.set(t,e)}}_unsubscribeRenderTarget(t){const e=this._renderTargetDestroyHandlers.get(t);e&&(t.removeDestroyListener(e),this._renderTargetDestroyHandlers.delete(t))}_toClipPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(t.right,t.bottom)),s=Math.min(e.x,i.x),n=Math.max(e.x,i.x),r=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(s))),u=Math.max(0,Math.min(a,Math.ceil(n))),c=Math.max(0,Math.min(h,Math.floor(r))),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(t,e){const i=Math.max(t.x,e.x),s=Math.max(t.y,e.y),n=Math.min(t.x+t.width,e.x+e.width),r=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:s,width:Math.max(0,n-i),height:Math.max(0,r-s)}}_createSampler(t){const e=t instanceof In&&("r32f"===t.format||"rgba32f"===t.format),i=e?"nearest":this._getFilterMode(t.scaleMode);return this.device.createSampler({addressModeU:this._getAddressMode(t.wrapMode),addressModeV:this._getAddressMode(t.wrapMode),magFilter:i,minFilter:i,mipmapFilter:e?"nearest":this._getMipmapFilterMode(t.scaleMode)})}_getGpuTextureFormat(t){if(t instanceof In){return Mo(t.format).gpuFormat}return Co}_getTextureUsage(t){const e=this._getMipLevelCount(t)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return t instanceof _i?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|e:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|e}_getAddressMode(t){switch(t){case oi.Repeat:return"repeat";case oi.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case ri.Nearest:case ri.NearestMipmapNearest:case ri.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case ri.NearestMipmapLinear:case ri.LinearMipmapLinear:return"linear";default:return"nearest"}}_textureBytesPerPixel(t){if(t instanceof In){const e=t.format;return ro(e)}return 4}_estimateTextureBytes(t,e){return no(t.width,t.height,this._textureBytesPerPixel(t),e)}_getMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_generateMipmaps(t,e){if(e<=1)return;const i=this._getMipmapResources(),s=this.device.createCommandEncoder();for(let n=1;n<e;n++){const e=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:t.createView({baseMipLevel:n-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),r=s.beginRenderPass({colorAttachments:[{view:t.createView({baseMipLevel:n,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});r.setPipeline(i.pipeline),r.setBindGroup(0,e),r.draw(3),r.end()}this.device.queue.submit([s.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:Co,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 Mo(t){switch(t){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 Po extends Sn{onStart=new m;onStop=new m;_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=t=>{k.remove(this._onAudioContextReady),this.setupWithAudioContext(t)};constructor(t,e,i){super(new pi(t,i));const{duration:s,volume:n,playbackRate:r,loop:o,muted:a}=t;this._videoElement=t,this._duration=s,this._volume=n,this._playbackRate=r,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)),e&&this.applyOptions(e),I()?this.setupWithAudioContext(D()):k.add(this._onAudioContextReady),this.updateTexture(),this._requestVideoFrameCallback()}get videoElement(){return this._videoElement}get duration(){return this._duration}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get paused(){return this._videoElement.paused}set paused(t){t?this.pause():this.play()}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}get bus(){return this._bus}set bus(t){if(this._bus!==t&&(this._audioSetup&&this._audioSetup.gainNode.disconnect(),this._bus=t,this._audioSetup)){const e=t._getInputNode();e?this._audioSetup.gainNode.connect(e):this._audioSetup.gainNode.connect(this._audioSetup.audioContext.destination)}}play(t){return t&&this.applyOptions(t),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:s,time:n,muted:r}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==s&&(this.playbackRate=s),void 0!==n&&(this.currentTime=n),void 0!==r&&(this.muted=r),this}setVolume(t){const e=q(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,.01)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._videoElement.loop=t),this}setPlaybackRate(t){const e=q(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._videoElement.playbackRate=e),this}getTime(){return this._videoElement.currentTime}setTime(t){return this._videoElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,.01)}return this}_collect(t,e){this.visible&&(this._markTextureDirtyOnPlaybackAdvance(),this.updateTexture()),super._collect(t,e)}updateTexture(){const t=this.texture;if(!t||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const e=this.textureFrame.width>0&&this.textureFrame.height>0;return t.updateSource(),t.width>0&&t.height>0&&this.setTextureFrame(Zt.temp.set(0,0,t.width,t.height),!e),this._textureDirty=!1,this}destroy(){super.destroy(),this.stop(),this._videoElement.removeEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.removeEventListener("resize",this._onResizeHandler),this._cancelVideoFrameCallback(),k.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(t,e){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyOnPlaybackAdvance(){const t=this._videoElement.currentTime;this._lastVideoTime!==t&&(this._lastVideoTime=t,this._textureDirty=!0)}_requestVideoFrameCallback(){const t=this._videoElement;t.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=t.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const t=this._videoElement;t.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(t.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext=t=>{const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,.01);const i=this.bus?._getInputNode()??null;i?e.connect(i):e.connect(t.destination);const s=t.createMediaElementSource(this._videoElement);s.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:s}}}class Ao{_objectUrls=[];createObjectUrl(t){const e=URL.createObjectURL(t);return this._objectUrls.push(e),e}revokeObjectUrl(t){URL.revokeObjectURL(t);const e=this._objectUrls.indexOf(t);-1!==e&&this._objectUrls.splice(e,1)}destroy(){for(const t of this._objectUrls)URL.revokeObjectURL(t);this._objectUrls.length=0}}class Eo extends Ao{storageName="binary";async process(t){return t.arrayBuffer()}async create(t){return t}}function Ro(t,e){const i=t.match(new RegExp(`\\b${e}=(-?\\d+)`));return void 0!==i?.[1]?parseInt(i[1],10):0}function ko(t,e){const i=t.match(new RegExp(`\\b${e}="([^"]*)"`));if(void 0!==i?.[1])return i[1];const s=t.match(new RegExp(`\\b${e}=(\\S+)`));return s?.[1]??""}function Do(t){const e=t.split(/\r?\n/),i=[],s=new Map,n=new Map;let r=0,o=0;for(const t of e){const e=t.trim();if(0===e.length)continue;switch(e.split(/\s/)[0]??""){case"common":r=Ro(e,"lineHeight"),o=Ro(e,"base");break;case"page":{const t=Ro(e,"id"),s=ko(e,"file");i[t]=s;break}case"char":{const t=Ro(e,"id");s.set(t,{x:Ro(e,"x"),y:Ro(e,"y"),width:Ro(e,"width"),height:Ro(e,"height"),xOffset:Ro(e,"xoffset"),yOffset:Ro(e,"yoffset"),xAdvance:Ro(e,"xadvance"),page:Ro(e,"page")});break}case"kerning":{const t=Ro(e,"first"),i=Ro(e,"second"),s=Ro(e,"amount");n.set(`${t},${i}`,s);break}}}return{pages:i,chars:s,kernings:n,lineHeight:r,base:o}}class Io extends Ao{storageName="bmfont";_loader;constructor(t){super(),this._loader=t}async process(t){return{text:await t.text(),url:t.url}}async create(t){const{text:e,url:i}=t,s=Do(e),n=await Promise.all(s.pages.map(t=>this._loader.load(pi,new URL(t,i).href)));return new Cn(s,n)}}class Lo extends Ao{storageName="csv";async process(t){return t.text()}async create(t,e={}){const i=e.delimiter??",",s=[],n=t.replaceAll("\r\n","\n").replaceAll("\r","\n");let r=[],o="",a=!1,h=0;for(;h<n.length;){const t=n[h];a?'"'===t?'"'===n[h+1]?(o+='"',h+=2):(a=!1,h++):(o+=t,h++):'"'===t?(a=!0,h++):t===i?(r.push(o),o="",h++):"\n"===t?(r.push(o),o="",s.push(r),r=[],h++):(o+=t,h++)}return r.push(o),r.some(t=>""!==t)&&s.push(r),s}}class Uo extends Ao{storageName="font";_addedFontFaces=[];async process(t){return t.arrayBuffer()}async create(t,e){if(!e?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:s,addToDocument:n}=e;if(t.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${t.byteLength}.`);const r=await new FontFace(i,t,s).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${t.byteLength} bytes).`)});return!1!==n&&(document.fonts.add(r),this._addedFontFaces.push(r)),r}destroy(){for(const t of this._addedFontFaces)document.fonts.delete(t);this._addedFontFaces.length=0,super.destroy()}}const Fo=[{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]}],Go=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of Fo)if(!(e.length<t.pattern.length)&&t.pattern.every((i,s)=>((e[s]??0)&(t.mask[s]??0))===i))return t.mimeType;return(t=>{const e=new Uint8Array(t),i=new DataView(t).getUint32(0,!1);return!(e.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...e.subarray(4,11))})(t)?"video/mp4":(t=>{const e=new Uint8Array(t),i=[26,69,223,163].every((t,i)=>t===e[i]),s=e.subarray(4,4100),n=s.findIndex((t,e,i)=>66===i[e]&&130===i[e+1]);return!(!i||-1===n)&&"webm"===String.fromCharCode(...s.subarray(n+3,n+7))})(t)?"video/webm":(t=>{if(t.byteLength<12)return!1;const e=new Uint8Array(t);if("ftyp"!==String.fromCharCode(e[4]??0,e[5]??0,e[6]??0,e[7]??0))return!1;const i=String.fromCharCode(e[8]??0,e[9]??0,e[10]??0,e[11]??0);return"avif"===i||"avis"===i})(t)?"image/avif":"text/plain"};class No extends Ao{storageName="image";async process(t){return t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??Go(t)});if("function"==typeof createImageBitmap)return createImageBitmap(i);const s=this.createObjectUrl(i);return new Promise((t,e)=>{const i=new Image,n=()=>{this.revokeObjectUrl(s)};i.addEventListener("load",()=>{n(),t(i)},{once:!0}),i.addEventListener("error",()=>{n(),e(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{n(),e(new Error("Image loading was canceled."))},{once:!0}),i.src=s})}}const Oo={once:!0};class Vo extends Ao{storageName="music";_audioElements=[];async process(t){return t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:s,playbackOptions:n,stallTimeout:r}=e,o=new Blob([t],{type:i??Go(t)}),a=this.createObjectUrl(o);return new Promise((t,e)=>{const i=document.createElement("audio");let o;this._audioElements.push(i);let h=!1;const l=t=>{h||(h=!0,void 0!==o&&(clearTimeout(o),o=void 0),this.revokeObjectUrl(a),t())};i.addEventListener("error",()=>l(()=>e(new Error("Error loading audio source."))),Oo),i.addEventListener("abort",()=>l(()=>e(new Error("Audio loading was canceled."))),Oo),i.addEventListener("emptied",()=>l(()=>e(new Error("Audio loading was emptied."))),Oo),i.addEventListener(s??"canplaythrough",()=>l(()=>t(new fe(i,n))),Oo),void 0!==r&&i.addEventListener("stalled",()=>{h||(void 0!==o&&clearTimeout(o),o=setTimeout(()=>l(()=>e(new Error("Audio loading stalled."))),r))}),i.preload="auto",i.src=a})}destroy(){for(const t of this._audioElements)t.pause(),t.src="",t.load();this._audioElements.length=0,super.destroy()}}class zo extends Ao{storageName="sound";async process(t){return t.arrayBuffer()}async create(t,e={}){const i=await U(t);return new ae(i,{...e.playbackOptions,...void 0!==e.poolSize&&{poolSize:e.poolSize},...void 0!==e.sprites&&{sprites:e.sprites}})}}const qo=t=>{const e=t.split(":");let i;return i=3===e.length?3600*Number(e[0])+60*Number(e[1])+Number(e[2]):2===e.length?60*Number(e[0])+Number(e[1]):Number(e[0]),i},Yo=new Set(["start","center","end","left","right"]),Wo=new Set(["start","center","end"]),$o=new Set(["auto","line-left","center","line-right"]),Xo=(t,e)=>{if(e)for(const i of e.split(/\s+/)){const e=i.indexOf(":");if(-1===e)continue;const s=i.slice(0,e),n=i.slice(e+1);switch(s){case"vertical":"rl"!==n&&"lr"!==n&&""!==n||(t.vertical=n);break;case"line":if("auto"===n)t.line="auto";else{const[e="",i]=n.split(","),s=parseFloat(e);Number.isNaN(s)||(t.line=s),void 0!==i&&Wo.has(i)&&(t.lineAlign=i)}break;case"position":{const[e="",i]=n.split(","),s=parseFloat(e);Number.isNaN(s)||(t.position=s),void 0!==i&&$o.has(i)&&(t.positionAlign=i);break}case"size":{const e=parseFloat(n);Number.isNaN(e)||(t.size=e);break}case"align":Yo.has(n)&&(t.align=n)}}},jo=t=>{const e=t.trim().replace(",",".").split(":");return 3600*Number(e[0])+60*Number(e[1])+Number(e[2])};class Ho extends Ao{storageName="subtitle";async process(t){const e=await t.text();return{fmt:(t.url.split("?")[0]??t.url).toLowerCase().endsWith(".srt")?"srt":"vtt",text:e}}async create(t){return"srt"===t.fmt?(t=>{const e=[],i=t.replaceAll("\r\n","\n").replaceAll("\r","\n").split(/\n[ \t]*\n/);for(const t of i){const i=t.trim().split("\n");if(i.length<2)continue;let s=0;/^\d+$/.test((i[0]??"").trim())&&(s=1);const n=i[s];if(!n?.includes("--\x3e"))continue;const r=n.indexOf("--\x3e"),o=jo(n.slice(0,r)),a=jo(n.slice(r+3)),h=i.slice(s+1).join("\n");e.push(new VTTCue(o,a,h))}return e})(t.text):(t=>{const e=[],i=t.replaceAll("\r\n","\n").replaceAll("\r","\n").split("\n");let s=0;for(;s<i.length&&!(i[s]??"").includes("--\x3e");)s++;for(;s<i.length;){const t=(i[s]??"").trim();if(t.includes("--\x3e")){const n=t.indexOf("--\x3e"),r=t.slice(0,n).trim(),o=t.slice(n+3).trim().split(/\s+/),a=o[0]??"",h=o.slice(1).join(" "),l=qo(r),u=qo(a);s++;const c=[];for(;s<i.length;){const t=i[s];if(void 0===t||""===t.trim())break;c.push(t),s++}const d=new VTTCue(l,u,c.join("\n"));Xo(d,h),e.push(d)}else s++}return e})(t.text)}}class Ko extends Ao{storageName="svg";async process(t){return t.text()}async create(t,e={}){const{width:i,height:s}=e;let n=t;if(void 0!==i||void 0!==s){const t=n.indexOf("<svg"),e=n.indexOf(">",t);if(-1!==t&&-1!==e){const r=n.slice(0,t),o=n.slice(t+4,e),a=n.slice(e+1);n=`${r}<svg${String(o).replaceAll(/\s+width=(?:"[^"]*"|'[^']*')/g,"").replaceAll(/\s+height=(?:"[^"]*"|'[^']*')/g,"")}${(void 0!==i?` width="${i}"`:"")+(void 0!==s?` height="${s}"`:"")}>${a}`}}const r=new Blob([n],{type:"image/svg+xml"}),o=this.createObjectUrl(r);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(o)};i.addEventListener("load",()=>{s(),t(i)},{once:!0}),i.addEventListener("error",()=>{s(),e(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(new Error("Image loading was canceled."))},{once:!0}),i.src=o})}}class Qo extends Ao{storageName="texture";async process(t){return t.arrayBuffer()}async create(t,e={}){const{mimeType:i,samplerOptions:s}=e,n=new Blob([t],{type:i??Go(t)});if("function"==typeof createImageBitmap){const t=await createImageBitmap(n);return new pi(t,s)}const r=this.createObjectUrl(n);return new Promise((t,e)=>{const i=new Image,n=()=>{this.revokeObjectUrl(r)};i.addEventListener("load",()=>{n(),t(new pi(i,s))},{once:!0}),i.addEventListener("error",()=>{n(),e(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{n(),e(new Error("Image loading was canceled."))},{once:!0}),i.src=r})}}const Zo={once:!0};class Jo extends Ao{storageName="video";_videoElements=[];async process(t){return t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:s,playbackOptions:n,samplerOptions:r,stallTimeout:o}=e,a=new Blob([t],{type:i??Go(t)}),h=this.createObjectUrl(a);return new Promise((t,e)=>{const i=document.createElement("video");let a;this._videoElements.push(i);let l=!1;const u=t=>{l||(l=!0,void 0!==a&&(clearTimeout(a),a=void 0),this.revokeObjectUrl(h),t())};i.addEventListener("error",()=>u(()=>e(new Error("Video loading error."))),Zo),i.addEventListener("abort",()=>u(()=>e(new Error("Video loading error: cancelled."))),Zo),i.addEventListener("emptied",()=>u(()=>e(new Error("Video loading error: emptied."))),Zo),i.addEventListener(s??"canplaythrough",()=>u(()=>t(new Po(i,n,r))),Zo),void 0!==o&&i.addEventListener("stalled",()=>{l||(void 0!==a&&clearTimeout(a),a=setTimeout(()=>u(()=>e(new Error("Video loading stalled."))),o))}),i.preload="auto",i.src=h})}destroy(){for(const t of this._videoElements)t.pause(),t.src="",t.load();this._videoElements.length=0,super.destroy()}}class ta extends Ao{storageName="wasm";async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}class ea extends Ao{storageName="xml";async process(t){return t.text()}async create(t){const e=(new DOMParser).parseFromString(t,"text/xml"),i=e.querySelector("parsererror");if(i)throw new Error(`XML parse error: ${i.textContent.trim()||"unknown error"}`);return e}}class ia{}class sa{}class na{}class ra{}class oa{}class aa{}class ha{}class la{}class ua{}class ca{}function da(t){return()=>{const e=t();return{async load({source:t,options:i},s){const n=await s.fetchArrayBuffer(t);return e.create(n,i)},createFromBytes:(t,i)=>e.create(t,i),destroy(){e.destroy()}}}}function _a(t){return()=>{const e=t();return{async load({source:t,options:i},s){const n=await s.fetchText(t);return e.create(n,i)},createFromBytes:(t,i)=>e.create((new TextDecoder).decode(t),i),destroy(){e.destroy()}}}}function fa(t,e,i){return{type:t,...e,create:i}}const pa=fa(pi,{typeNames:["texture"]},da(()=>new Qo)),ga=fa(ae,{typeNames:["sound"]},da(()=>new zo)),ma=fa(fe,{typeNames:["music"]},da(()=>new Vo)),ya=fa(Po,{typeNames:["video"]},da(()=>new Jo)),wa=fa(ia,{typeNames:["json"]},()=>({load:async({source:t},e)=>e.fetchJson(t),createFromBytes:t=>Promise.resolve(JSON.parse((new TextDecoder).decode(t)))})),xa=fa(sa,{typeNames:["text"]},()=>({load:async({source:t},e)=>e.fetchText(t),createFromBytes:t=>Promise.resolve((new TextDecoder).decode(t))})),va=fa(na,{typeNames:["svg"]},_a(()=>new Ko)),ba=fa(ra,{typeNames:["vtt","srt"]},()=>{const t=new Ho;return{async load({source:e},i){const s=await i.fetchText(e),n=(e.split("?")[0]??e).toLowerCase().endsWith(".srt")?"srt":"vtt",r=await t.process({text:()=>Promise.resolve(s),url:e});return t.create({...r,fmt:n})},destroy(){t.destroy()}}}),Sa=fa(oa,{typeNames:["xml"]},_a(()=>new ea)),Ba=fa(aa,{typeNames:["csv"]},_a(()=>new Lo)),Ca=fa(ua,{typeNames:["binary"]},da(()=>new Eo)),Ta=fa(Cn,{typeNames:["bmFont"],extensions:["fnt"]},t=>({async load({source:e},i){const s=Do(await i.fetchText(e)),n=await Promise.all(s.pages.map(i=>t.load(pi,function(t,e){try{return new URL(t,e).href}catch{const i="https://exojs.invalid/";return new URL(t,i+e.replace(/^\/+/,"")).href.slice(i.length)}}(i,e))));return new Cn(s,n)}})),Ma=[];"undefined"!=typeof FontFace&&Ma.push(fa(la,{typeNames:["font"],extensions:["woff","woff2","ttf","otf"]},da(()=>new Uo))),"undefined"!=typeof HTMLImageElement&&Ma.push(fa(ha,{typeNames:["image"]},da(()=>new No))),"undefined"!=typeof WebAssembly&&Ma.push(fa(ca,{typeNames:["wasm"]},da(()=>new ta)));const Pa=Object.freeze([pa,ga,ma,ya,wa,xa,va,ba,Sa,Ba,Ca,Ta,...Ma]);class Aa{_config;constructor(t){this._config=t}get type(){return this._config.type}get source(){return this._config.source}}const Ea=Aa,Ra="EXOA";function ka(t){throw new Error(`Invalid asset container: ${t}.`)}function Da(t){t.byteLength<12&&ka(`buffer too small for a 12-byte header (got ${t.byteLength})`);const e=new Uint8Array(t),i=new DataView(t);for(let t=0;t<4;t++)e[t]!==Ra.charCodeAt(t)&&ka(`bad magic (expected "${Ra}")`);const s=i.getUint32(4,!0);s>1&&ka(`unsupported version ${s} (this build reads up to 1)`);const n=i.getUint32(8,!0),r=12+n;let o;r>t.byteLength&&ka(`index length ${n} runs past the buffer (size ${t.byteLength})`);try{o=JSON.parse((new TextDecoder).decode(e.subarray(12,r)))}catch{ka("index is not valid JSON")}Array.isArray(o)||ka("index is not an array");const a=t.byteLength-r,h=o.map((t,e)=>function(t,e,i){"object"==typeof t&&null!==t||ka(`index entry ${e} is not an object`);const s=t,{alias:n,type:r,offset:o,length:a,mime:h}=s;return"string"!=typeof n&&ka(`index entry ${e} has a non-string "alias"`),"string"!=typeof r&&ka(`index entry ${e} ("${n}") has a non-string "type"`),("number"!=typeof o||!Number.isFinite(o)||o<0)&&ka(`index entry "${n}" has an invalid "offset"`),("number"!=typeof a||!Number.isFinite(a)||a<0)&&ka(`index entry "${n}" has an invalid "length"`),o+a>i&&ka(`index entry "${n}" runs past the data section (offset ${o} + length ${a} > ${i})`),void 0!==h&&"string"!=typeof h&&ka(`index entry "${n}" has a non-string "mime"`),{alias:n,type:r,offset:o,length:a,..."string"==typeof h&&{mime:h},...void 0!==s.options&&{options:s.options}}}(t,e,a));return{version:s,entries:h,dataStart:r}}class Ia extends Error{bundle;failures;constructor(t,e){super(`Failed to load bundle "${t}" (${e.length} failure${1===e.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=t,this.failures=e}}function La(t){return function(t){if(!Ua(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!Ua(t.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[e,i]of Object.entries(t.bundles)){if(0===e.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 "${e}" must be an array of entries.`);const t=new Map;for(const[s,n]of i.entries()){const i=`bundle "${e}" entry[${s}]`;if(!Ua(n))throw new Error(`Invalid asset manifest: ${i} must be an object.`);if("function"!=typeof n.type)throw new Error(`Invalid asset manifest: ${i} has an invalid "type" token.`);Fa(n.alias,`${i} has an invalid "alias".`),Fa(n.path,`${i} has an invalid "path".`);const r=n.type,o=n.alias;t.has(r)||t.set(r,new Set);const a=t.get(r);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${Ga(r)}, "${o}") in bundle "${e}".`);a.add(o)}}}(t),t}function Ua(t){return"object"==typeof t&&null!==t}function Fa(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function Ga(t){return t.name.length>0?t.name:"(anonymous type)"}class Na{entries;constructor(t){if(Object.hasOwn(t,"entries"))throw new Error('An Assets container may not define an asset named "entries": that name is reserved for the spread-composition helper.');const e={};for(const i of Object.keys(t)){const s=t[i],n=s instanceof Aa?s:new Aa(s);e[i]=n,Object.defineProperty(this,i,{value:n,enumerable:!0,configurable:!1,writable:!1})}this.entries=e}}const Oa=Na;class Va{async resolve(t,e){const{storageName:i,key:s,url:n,requestOptions:r,factory:o,options:a}=t;for(const t of e){const e=await t.load(i,s);if(null!=e)try{return await o.create(e,a)}catch{await t.delete(i,s)}}const h=await fetch(n,r);if(!h.ok)throw new Error(`Failed to fetch "${n}" (${h.status} ${h.statusText}).`);const l=await o.process(h),u=await o.create(l,a);for(const t of e)try{await t.save(i,s,l)}catch{}return u}}const za=t=>{const e=Object.getPrototypeOf(t.prototype);return e?.constructor??null};class qa{_factories=new oo({walk:za,dispose:t=>t.destroy()});register(t,e){this._factories.set(t,e)}resolve(t){const e=this._factories.resolve(t);if(!e)throw new Error(`No factory registered for ${t.name}. Register one with loader.register() before loading.`);return e}has(t){return this._factories.has(t)}destroy(){this._factories.destroy()}}class Ya{onProgress;_progress;_promise;constructor(t,e){this.onProgress=new m,this._progress={total:e,loaded:0,pending:e,failed:0},this._promise=t}get progress(){return this._progress}_notifyItem(t){const e=this._progress,i=e.loaded+(t?1:0),s=e.failed+(t?0:1),n=i+s;this._progress={total:e.total,loaded:i,pending:Math.max(0,e.total-n),failed:s},this.onProgress.dispatch(this._progress)}then(t,e){return this._promise.then(t,e)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}}class Wa{_registry=new qa;_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;_backgroundQueue=[];_backgroundActive=0;_backgroundTotal=0;_backgroundLoaded=0;_backgroundResolve=null;onProgress=new m;onBundleProgress=new m;onLoaded=new m;onError=new m;constructor(t={}){this._basePath=t.basePath??"",this._fetchOptions=t.fetchOptions??{},this._concurrency=t.concurrency??6,this._stores=t.cache?Array.isArray(t.cache)?t.cache:[t.cache]:[],this._cacheStrategy=t.cacheStrategy??new Va}register(t,e){return this._registry.register(t,e),this}registerAssetType(t,e,i){if("function"==typeof e)this._assetTypeMap.set(t,e),i&&this._registry.register(e,i);else{const i=class{};Object.defineProperty(i,"name",{value:t}),this._assetTypeMap.set(t,i);const s=e.getIdentityKey?.bind(e);this._handlerFunctions.set(i,{load:(t,i)=>e.load(t,i),...void 0!==s&&{getIdentityKey:s}})}return this}registerExtension(t,e){return this._extensionMap.set(t.replace(/^\./,"").toLowerCase(),e),this}add(t,e){const i=t;if("string"==typeof e)this._addManifestEntry(i,e,e);else if(Array.isArray(e)){const t=e;for(const e of t)this._addManifestEntry(i,e,e)}else for(const[t,s]of Object.entries(e))this._addManifestEntry(i,t,s);return this}registerManifest(t){const e=La(t),i=new Map,s=new Array;for(const[t,n]of Object.entries(e.bundles)){if(this._bundles.has(t))throw new Error(`Bundle "${t}" is already registered.`);const e=new Array;for(const s of n){const n=s.type,r=this._key(n,s.alias),o=i.get(r)??this._getManifestEntry(n,s.alias);if(o&&!this._isManifestDefinitionEquivalent(o,s.path,s.options))throw new Error(`Conflicting asset definition for (${this._describeType(n)}, "${s.alias}") while registering bundle "${t}".`);i.set(r,{path:s.path,options:s.options}),e.push({type:n,alias:s.alias,path:s.path,options:s.options})}s.push([t,e])}for(const[t,e]of s){for(const t of e)this._addManifestEntry(t.type,t.alias,t.path,t.options);this._bundles.set(t,e)}return this}async loadBundle(t,e={}){const i=this._bundles.get(t);if(!i)throw new Error(`Unknown bundle "${t}".`);const s=i.length;let n=0;const r=new Array;if(0!==s){if(await Promise.all(i.map(async i=>{try{await(e.background?this._loadSingleBackground(i.type,i.alias,i.path,i.options):this._loadSingle(i.type,i.alias,i.options,i.path))}catch(t){r.push({type:i.type,alias:i.alias,error:this._normalizeError(t)})}finally{n++,this._emitBundleProgress(t,n,s,e.onProgress)}})),r.length>0)throw new Ia(t,r)}else this._emitBundleProgress(t,0,0,e.onProgress)}async loadContainer(t){const e=await this._contextFetch(t,"__ctx_binary",t=>t.arrayBuffer()),{entries:i,dataStart:s}=Da(e),n=i.map(e=>{const i=this._assetTypeMap.get(e.type);if(!i)throw new Error(`Container "${t}" references unknown asset type "${e.type}".`);return{entry:e,type:i}});await Promise.all(n.map(({entry:t,type:i})=>{const n=s+t.offset,r=e.slice(n,n+t.length);return this._injectSource(i,t.alias,r,t.options)}))}hasBundle(t){const e=this._bundles.get(t);return!!e&&e.every(t=>this._hasResource(t.type,t.alias))}load(t,e,i){if(t instanceof Aa){const e=t,i=e._config.source;return this._createLoadingQueue([{alias:i,asset:e}],t=>t.get(i))}if(t instanceof Na){const e=t,i=Object.entries(e.entries).map(([t,e])=>({alias:t,asset:e}));return this._createLoadingQueue(i,t=>{const e={};for(const{alias:s}of i)e[s]=t.get(s);return e})}if("string"==typeof t&&void 0===e){const e=t,i=e.match(/\.([^./?#]+)(?:[?#]|$)/)?.[1]?.toLowerCase(),s=i?this._extensionMap.get(i):void 0;if(void 0===s)throw new Error(`Loader: no type registered for extension ".${i??"?"}" in "${e}". Register one via loader.registerExtension().`);const n=s===la?{family:(e.split("/").pop()?.split(/[?#]/)[0]??"").replace(/\.[^.]+$/,"")}:void 0;let r=null;const o=this._loadSingle(s,e,n).then(t=>(r?.(!0),t),t=>{throw r?.(!1),t}),a=new Ya(o,1);return r=a._notifyItem.bind(a),a}if("function"==typeof t){const s=t,n=e,r=i;if("string"==typeof n){let t=null;const e=this._loadSingle(s,n,r).then(e=>(t?.(!0),e),e=>{throw t?.(!1),e}),i=new Ya(e,1);return t=i._notifyItem.bind(i),i}if(Array.isArray(n)){const t=n;let e=null;const i=new Array(t.length),o=t.map((t,n)=>this._loadSingle(s,t,r).then(t=>{i[n]=t,e?.(!0)},t=>{throw e?.(!1),t})),a=Promise.all(o).then(()=>i),h=new Ya(a,t.length);return e=h._notifyItem.bind(h),h}const o=Object.entries(n),a={};let h=null;const l=o.map(([t,e])=>{const i="string"==typeof e?e:e.source,n="string"==typeof e?r:{...e,..."object"==typeof r&&null!==r?r:{}};return this._loadSingle(s,t,n,i).then(e=>{a[t]=e,h?.(!0)},t=>{throw h?.(!1),t})}),u=Promise.all(l).then(()=>a),c=new Ya(u,o.length);return h=c._notifyItem.bind(c),c}const s=t,n=Object.entries(s).map(([t,e])=>({alias:t,asset:e instanceof Aa?e:new Ea(e)}));return this._createLoadingQueue(n,t=>{const e={};for(const{alias:i}of n)e[i]=t.get(i);return e})}backgroundLoad(){for(const[t,e]of this._manifest)for(const[i,s]of e){if(this._hasResource(t,i))continue;const e=this._key(t,i);this._inFlight.has(e)||this._backgroundQueue.push({type:t,alias:i,path:s.path,options:s.options})}this._backgroundTotal=this._backgroundQueue.length,this._backgroundLoaded=0,this._drainBackground()}loadAll(){return new Promise(t=>{this._backgroundResolve=t,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,t())})}setConcurrency(t){return this._concurrency=t,this}get(t,e){const i=t,s=this._resources.get(i);if(!s?.has(e))throw new Error(`Missing resource "${e}" for type ${i.name}.`);return s.get(e)}peek(t,e){const i=t;return this._resources.get(i)?.get(e)??null}has(t,e){const i=t;return this._resources.get(i)?.has(e)??!1}keyFor(t){return this._resourceKeys.get(t)??null}unload(t,e){if(t instanceof Aa){const e=t,i=this._assetTypeMap.get(e.type);if(!i)return this;const s=this._resolveAssetIdentityKey(i,e),n=this._identityKeyToAliases.get(s);if(n&&n.size>0)for(const t of[...n])this._unloadOne(i,t);else this._unloadOne(i,e._config.source);return this}if(t instanceof Na){const e=t;for(const[t,i]of Object.entries(e.entries)){const e=i,s=this._assetTypeMap.get(e.type);if(!s)continue;const n=this._resolveAssetIdentityKey(s,e),r=this._identityKeyToAliases.get(n);if(r?.has(t))for(const t of[...r])this._unloadOne(s,t);else this._unloadOne(s,t)}return this}return this._unloadOne(t,e)}_unloadOne(t,e){const i=t,s=this._key(i,e);this._resources.get(i)?.delete(e);const n=this._aliasKeyToIdentityKey.get(s);if((this._inFlight.has(s)||void 0!==n&&this._inFlightByIdentity.has(n))&&this._preventStoreKeys.add(s),void 0!==n){this._aliasKeyToIdentityKey.delete(s);const t=this._identityKeyToAliases.get(n);t&&(t.delete(e),0===t.size&&this._identityKeyToAliases.delete(n))}return this}unloadAll(t){if(t)this._resources.get(t)?.clear();else for(const t of this._resources.values())t.clear();return this}get basePath(){return this._basePath}set basePath(t){this._basePath=t}get fetchOptions(){return this._fetchOptions}set fetchOptions(t){this._fetchOptions=t}bindAsset(t,e){const i=[],s=void 0!==t.typeNames?[...t.typeNames]:[];for(const e of t.extensions??[])i.push(e.replace(/^\./,"").toLowerCase());const n=new Set;for(const t of i){if(n.has(t))throw new Error(`Duplicate extension key ".${t}" within a single asset binding.`);n.add(t)}if(this._handlerFunctions.has(t.type))throw new Error(`An asset handler is already registered for ${t.type.name}.`);for(const t of s)if(this._assetTypeMap.has(t))throw new Error(`Asset type name "${t}" is already registered.`);for(const t of i)if(this._extensionMap.has(t))throw new Error(`File extension ".${t}" is already mapped to an asset type.`);const r=t=>{const{source:e,...i}=t;return 0===Object.keys(i).length?{source:e}:{source:e,options:i}},o=e.getIdentityKey?.bind(e),a=e.createFromBytes?.bind(e);this._handlerFunctions.set(t.type,{load:(t,i)=>e.load(r(t),i),...o&&{getIdentityKey:t=>o(r(t))},...a&&{createFromBytes:(t,e)=>a(t,e)}});for(const e of s)this._assetTypeMap.set(e,t.type);for(const e of i)this._extensionMap.set(e,t.type);this._boundHandlers.push(e)}hasLoadable(t){return this._handlerFunctions.has(t)||this._registry.has(t)}hasAssetType(t){return this._assetTypeMap.has(t)}hasExtension(t){return this._extensionMap.has(t.replace(/^\./,"").toLowerCase())}destroy(){this._registry.destroy();for(const t of this._stores)t.destroy();const t=new Set;for(const e of this._boundHandlers)t.has(e)||(t.add(e),e.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()}async _loadSingle(t,e,i,s){if(this._hasResource(t,e)){const i=this._resources.get(t);if(!0===i?.has(e))return i.get(e)}const n=this._key(t,e);if(this._inFlight.has(n))return this._inFlight.get(n);if(this._boostFromQueue(t,e),this._inFlight.has(n))return this._inFlight.get(n);const r=this._getManifestEntry(t,e),o=s??r?.path??e,a=i??r?.options,h=this._handlerFunctions.get(t);if(h){const i=this._identityKey(t,o),s={source:o};null!=a&&"object"==typeof a&&Object.assign(s,a);const r=this._buildHandlerContext(i);return this._trackInFlight(n,this._fetchWithHandler(t,e,o,s,h.load,r))}return this._trackInFlight(n,this._fetch(t,e,o,a))}_loadSingleBackground(t,e,i,s){if(this._hasResource(t,e)){const i=this._resources.get(t);if(!0===i?.has(e))return Promise.resolve(i.get(e))}const n=this._key(t,e),r=this._inFlight.get(n);if(r)return r;this._isQueuedInBackground(t,e)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:t,alias:e,path:i,options:s}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(n);return o||this._waitForBackgroundEntry(t,e)}_createLoadingQueue(t,e){const i=new Map;let s=null;const n=t.map(({alias:t,asset:e})=>{const n=this._assetTypeMap.get(e.type);return n?this._loadSingleAsset(n,t,e).then(e=>{i.set(t,e),s?.(!0)},t=>{throw s?.(!1),t}):Promise.reject(new Error(`No constructor registered for asset type "${e.type}". Call registerAssetType() first.`)).then(()=>{s?.(!0)},t=>{throw s?.(!1),t})}),r=Promise.all(n).then(()=>e(i)),o=new Ya(r,t.length);return s=o._notifyItem.bind(o),o}async _loadSingleAsset(t,e,i){if(this._hasResource(t,e))return this._resources.get(t)?.get(e);const s=i.source,n=i._config,{type:r,source:o,...a}=n,h=this._handlerFunctions.get(t),l=h?.getIdentityKey?.(n)??s,u=`id:${this._getTypeId(t)}:${l}`,c=this._key(t,e);this._aliasKeyToIdentityKey.set(c,u);let d=this._identityKeyToAliases.get(u);d||(d=new Set,this._identityKeyToAliases.set(u,d)),d.add(e);const _=this._inFlightByIdentity.get(u);if(_)return _.then(i=>(this._storeResource(t,e,i),i));let f;if(h){const i={source:s,...a},n=this._buildHandlerContext(u);f=this._fetchWithHandler(t,e,s,i,h.load,n)}else{const i=Object.keys(a).length>0?a:void 0;f=this._fetch(t,e,s,i)}const p=f.finally(()=>{this._inFlightByIdentity.delete(u)}).then(t=>t,e=>{const i=this._identityKeyToAliases.get(u);if(i){for(const e of i){const i=this._key(t,e);this._aliasKeyToIdentityKey.delete(i),this._preventStoreKeys.delete(i)}this._identityKeyToAliases.delete(u)}throw e});return this._inFlightByIdentity.set(u,p),p}async _fetchWithHandler(t,e,i,s,n,r){const o=this._resolveUrl(i);try{const i=await n(s,r);return this._storeResource(t,e,i),i}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load "${e}" from "${o}": ${i}`,{cause:t})}}_buildHandlerContext(t){return{loader:this,identityKey:t,fetchText:t=>this._contextFetch(t,"__ctx_text",t=>t.text()),fetchArrayBuffer:t=>this._contextFetch(t,"__ctx_binary",t=>t.arrayBuffer()),fetchJson:t=>this._contextFetch(t,"__ctx_json",t=>t.json())}}_contextFetch(t,e,i){const s=this._resolveUrl(t),n={storageName:e,process:i,create:t=>Promise.resolve(t),destroy(){}};return this._cacheStrategy.resolve({storageName:e,key:t,url:s,requestOptions:this._fetchOptions,factory:n,options:void 0},this._stores)}async _injectSource(t,e,i,s){const n=this._handlerFunctions.get(t);let r;if(n?.createFromBytes)r=await n.createFromBytes(i,s);else{if(!this._registry.has(t))throw new Error(`Asset type "${t.name}" cannot be built from container bytes (no createFromBytes handler).`);r=await this._registry.resolve(t).create(i,s)}this._storeResource(t,e,r)}async _fetch(t,e,i,s){const n=this._registry.resolve(t),r=this._resolveUrl(i);try{const o=await this._cacheStrategy.resolve({storageName:n.storageName,key:i,url:r,requestOptions:this._fetchOptions,factory:n,options:s},this._stores);return this._storeResource(t,e,o),o}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load "${e}" from "${r}": ${i}`,{cause:t})}}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const t=this._backgroundQueue.shift();if(!t)continue;const e=this._key(t.type,t.alias);this._hasResource(t.type,t.alias)||this._inFlight.has(e)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(t)}}_boostFromQueue(t,e){const i=this._backgroundQueue.findIndex(i=>i.type===t&&i.alias===e);if(-1===i)return;const[s]=this._backgroundQueue.splice(i,1);void 0!==s&&this._startBackgroundEntry(s)}_isQueuedInBackground(t,e){return this._backgroundQueue.some(i=>i.type===t&&i.alias===e)}_waitForBackgroundEntry(t,e){if(this._hasResource(t,e)){const i=this._resources.get(t);if(!0===i?.has(e))return Promise.resolve(i.get(e))}const i=this._key(t,e),s=this._inFlight.get(i);return s||new Promise((s,n)=>{const r=(i,n,r)=>{i===t&&n===e&&(a(),s(r))},o=(i,s,r)=>{i===t&&s===e&&(a(),n(r))},a=()=>{this.onLoaded.remove(r),this.onError.remove(o)};this.onLoaded.add(r),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(s,n);if(this._hasResource(t,e)){a();const i=this._resources.get(t);s(i?.get(e))}})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const t=this._backgroundResolve;this._backgroundResolve=null,t()}}_startBackgroundEntry(t){const e=this._key(t.type,t.alias);this._backgroundActive++,this._trackInFlight(e,this._fetch(t.type,t.alias,t.path,t.options)).catch(e=>{const i=e instanceof Error?e:new Error(String(e));this.onError.dispatch(t.type,t.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(t,e){const i=e.finally(()=>{this._inFlight.delete(t),this._preventStoreKeys.delete(t)});return this._inFlight.set(t,i),i}_emitBundleProgress(t,e,i,s){this.onBundleProgress.dispatch(t,e,i),s&&s(e,i)}_addManifestEntry(t,e,i,s){this._manifest.has(t)||this._manifest.set(t,new Map);const n=this._manifest.get(t);n&&n.set(e,{path:i,options:s})}_getManifestEntry(t,e){return this._manifest.get(t)?.get(e)}_isManifestDefinitionEquivalent(t,e,i){return t.path===e&&this._areOptionsEquivalent(t.options,i)}_areOptionsEquivalent(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this._areOptionsEquivalent(t[i],e[i]))return!1;return!0}const i=Object.getPrototypeOf(t);if(i!==Object.getPrototypeOf(e))return!1;if(i!==Object.prototype&&null!==i)return!1;const s=t,n=e,r=Object.keys(s),o=Object.keys(n);if(r.length!==o.length)return!1;for(const t of r){if(!Object.hasOwn(n,t))return!1;if(!this._areOptionsEquivalent(s[t],n[t]))return!1}return!0}_normalizeError(t){return t instanceof Error?t:new Error(String(t))}_describeType(t){return t.name.length>0?t.name:"(anonymous type)"}_hasResource(t,e){return this._resources.get(t)?.has(e)??!1}_storeResource(t,e,i){const s=this._key(t,e);if(this._preventStoreKeys.delete(s))return;let n=this._resources.get(t);n||(n=new Map,this._resources.set(t,n)),n.set(e,i),"object"!=typeof i||null===i||this._resourceKeys.has(i)||this._resourceKeys.set(i,{type:t,source:e}),this.onLoaded.dispatch(t,e,i)}_getTypeId(t){let e=this._typeIds.get(t);return void 0===e&&(e=this._nextTypeId++,this._typeIds.set(t,e)),e}_key(t,e){return`${this._getTypeId(t)}:${e}`}_identityKey(t,e){return`id:${this._getTypeId(t)}:${e}`}_resolveAssetIdentityKey(t,e){const i=e._config,s=this._handlerFunctions.get(t),n=s?.getIdentityKey?.(i)??e.source;return`id:${this._getTypeId(t)}:${n}`}_resolveUrl(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("/")?t:`${this._basePath}${t}`}}const $a="undefined"!=typeof window,Xa="undefined"!=typeof document,ja="undefined"!=typeof navigator;class Ha{static _readyPromise=null;static get ready(){return null===Ha._readyPromise&&(Ha._readyPromise=Ha._detect()),Ha._readyPromise}webgl2;webgpu;webgpuAdapter;webgpuVendor;webgpuArchitecture;pointer;keyboard;gamepad;touch;maxTouchPoints;audio;fullscreen;vibration;imageBitmap;deviceMemory;offscreenCanvas;webWorkers;devicePixelRatio;constructor(t){this.webgl2=t.webgl2,this.webgpu=t.webgpu,this.webgpuAdapter=t.webgpuAdapter,this.webgpuVendor=t.webgpuVendor,this.webgpuArchitecture=t.webgpuArchitecture,this.pointer=t.pointer,this.keyboard=t.keyboard,this.gamepad=t.gamepad,this.touch=t.touch,this.maxTouchPoints=t.maxTouchPoints,this.audio=t.audio,this.fullscreen=t.fullscreen,this.vibration=t.vibration,this.imageBitmap=t.imageBitmap,this.deviceMemory=t.deviceMemory,this.offscreenCanvas=t.offscreenCanvas,this.webWorkers=t.webWorkers,this.devicePixelRatio=t.devicePixelRatio,Object.freeze(this)}static async _detect(){const[t,e]=await async function(){if(!Qa())return[null,null];const t=navigator.gpu;if(!t||"function"!=typeof t.requestAdapter)return[null,null];try{const e=await t.requestAdapter();if(!e)return[null,null];const i=e;if(i.info)return[e,i.info];if("function"==typeof i.requestAdapterInfo)try{return[e,await i.requestAdapterInfo()]}catch{return[e,null]}return[e,null]}catch{return[null,null]}}();return new Ha({webgl2:Ka(),webgpu:Qa(),webgpuAdapter:t,webgpuVendor:e?.vendor??null,webgpuArchitecture:e?.architecture??null,pointer:$a&&"PointerEvent"in window,keyboard:$a&&"KeyboardEvent"in window,gamepad:ja&&"function"==typeof navigator.getGamepads,touch:Za(),maxTouchPoints:Ja(),audio:th(),fullscreen:eh(),vibration:ja&&"function"==typeof navigator.vibrate,imageBitmap:"function"==typeof createImageBitmap,deviceMemory:ih(),offscreenCanvas:$a&&void 0!==window.OffscreenCanvas,webWorkers:$a&&"function"==typeof window.Worker,devicePixelRatio:$a?window.devicePixelRatio:1})}}function Ka(){if(!Xa)return!1;try{const t=document.createElement("canvas");return null!==t.getContext("webgl2")}catch{return!1}}function Qa(){return ja&&"gpu"in navigator}function Za(){return!!$a&&("ontouchstart"in window||Ja()>0)}function Ja(){if(!ja)return 0;const t=navigator.maxTouchPoints;return"number"==typeof t?t:0}function th(){if(!$a)return!1;const t=window;return void 0!==t.AudioContext||void 0!==t.webkitAudioContext}function eh(){if(!Xa)return!1;const t=document.documentElement;return"function"==typeof t.requestFullscreen||"function"==typeof t.webkitRequestFullscreen}function ih(){if(!ja)return 0;const t=navigator.deviceMemory;return"number"==typeof t?t:0}class sh extends Bi{onResize=new m;_screenWidth=0;_screenHeight=0;get screenWidth(){return this._screenWidth}get screenHeight(){return this._screenHeight}_render(t){const e=t.screenView;this._screenWidth===e.width&&this._screenHeight===e.height||(this._screenWidth=e.width,this._screenHeight=e.height,this.onResize.dispatch(e.width,e.height)),t.render(this,{view:e})}destroy(){this.onResize.destroy(),super.destroy()}}class nh{_items=new Set;_order=[];_disposed=!1;get disposed(){return this._disposed}get size(){return this._items.size}track(t){return this._disposed||this._items.has(t)||(this._items.add(t),this._order.push(t)),t}has(t){return this._items.has(t)}untrack(t){if(this._disposed||!this._items.delete(t))return!1;const e=this._order.indexOf(t);return-1!==e&&this._order.splice(e,1),!0}destroy(){if(!this._disposed){this._disposed=!0;for(let t=this._order.length-1;t>=0;t--)try{this._order[t].destroy()}catch(t){}this._items.clear(),this._order.length=0}}}function rh(t,e){if("number"==typeof e.x&&(t.x=e.x),"number"==typeof e.y&&(t.y=e.y),"number"==typeof e.rotation&&(t.rotation=e.rotation),"number"==typeof e.scaleX&&(t.scale.x=e.scaleX),"number"==typeof e.scaleY&&(t.scale.y=e.scaleY),"number"==typeof e.skewX&&(t.skewX=e.skewX),"number"==typeof e.skewY&&(t.skewY=e.skewY),"number"==typeof e.originX&&(t.origin.x=e.originX),"number"==typeof e.originY&&(t.origin.y=e.originY),!1===e.visible&&(t.visible=!1),"number"==typeof e.zIndex&&(t.zIndex=e.zIndex),!1===e.cullable&&(t.cullable=!1),"string"==typeof e.name&&(t.name=e.name),t instanceof Si){!0===e.interactive&&(t.interactive=!0),!0===e.draggable&&(t.draggable=!0),!0===e.focusable&&(t.focusable=!0),"number"==typeof e.tabIndex&&(t.tabIndex=e.tabIndex),"string"==typeof e.cursor&&(t.cursor=e.cursor),!0===e.clip&&(t.clip=!0),!0===e.preserveDrawOrder&&(t.preserveDrawOrder=!0),!0===e.cacheAsBitmap&&(t.cacheAsBitmap=!0);const i=e.clipShape;Array.isArray(i)&&4===i.length&&(t.clipShape=new Zt(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3])))}if(t instanceof Ls){const i=e.tint;Array.isArray(i)&&4===i.length&&(t.tint=new Ee(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"number"==typeof e.blendMode&&(t.blendMode=e.blendMode),"string"==typeof e.pixelSnapMode&&Ms(e.pixelSnapMode)&&(t.pixelSnapMode=e.pixelSnapMode)}}function oh(t,e,i){const s=t[e];return"number"==typeof s&&Number.isFinite(s)?s:i}function ah(t,e,i){const s=t[e];return"boolean"==typeof s?s:i}function hh(t,e,i,s){const n=t[e];return"string"==typeof n&&i.includes(n)?n:s}function lh(t){return"object"!=typeof t||null===t||Array.isArray(t)?null:t}function uh(t){return"object"==typeof t&&null!==t&&"string"==typeof t.type?t: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(t,e,i,s,n,r){return(i-t)*(r-e)-(s-e)*(n-t)>0}function gh(t,e,i,s,n,r,o,a){const h=(t-n)*(s-r)-(i-n)*(e-r),l=(t-o)*(r-a)-(n-o)*(e-a),u=(t-i)*(a-s)-(o-i)*(e-s);return!((h<0||l<0||u<0)&&(h>0||l>0||u>0))&&0!==h&&0!==l&&0!==u}function mh(t,e,i,s,n,r){const o=t[2*s],a=t[2*s+1],h=t[2*n],l=t[2*n+1],u=t[2*r],c=t[2*r+1];let d=i[r];for(;d!==s;){if(d!==n){if(gh(t[2*d],t[2*d+1],o,a,h,l,u,c))return!1}d=i[d]}return!0}const yh=(t,e,i,s,n)=>{const r=[t,e,i,s],o=n/2,a=new te(t-i,e-s).perp().normalize().multiply(o),h=new te(i-t,s-e).perp().normalize().multiply(o),l=new Float32Array([t-a.x,e-a.y,t+a.x,e+a.y,i-h.x,s-h.y,i+h.x,s+h.y]);a.destroy(),h.destroy();return{vertices:l,indices:new Uint16Array([0,1,3,0,3,2]),points:r}},wh=(t,e)=>{if(t.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const i=e/2,s=new te(t[0],t[1]),n=new te(t[t.length-2],t[t.length-1]),r=t;if(s.x===n.x&&s.y===n.y){(t=[...t]).pop(),t.pop();const[e=0,i=0]=[t[t.length-2],t[t.length-1]];n.set(e,i);const r=n.x+.5*(s.x-n.x),o=n.y+.5*(s.y-n.y);t.unshift(r,o),t.push(r,o)}s.destroy(),n.destroy();const o=t.length/2,a=[];let h,l,u,c,d,_,f=t[0],p=t[1],g=t[2],m=t[3],y=-(p-m),w=f-g,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 e=1;e<o-1;e++){f=t[2*(e-1)],p=t[2*(e-1)+1],g=t[2*e],m=t[2*e+1],h=t[2*(e+1)],l=t[2*(e+1)+1],y=-(p-m),w=f-g,x=Math.sqrt(y*y+w*w),y/=x,w/=x,y*=i,w*=i,u=-(m-l),c=g-h,x=Math.sqrt(u*u+c*c),u/=x,c/=x,u*=i,c*=i;const s=-w+p-(-w+m),n=-y+g-(-y+f),r=(-y+f)*(-w+m)-(-y+g)*(-w+p),o=-c+l-(-c+m),v=-u+g-(-u+h),b=(-u+h)*(-c+m)-(-u+g)*(-c+l),S=s*v-o*n;if(Math.abs(S)<.1){a.push(g-y,m-w),a.push(g+y,m+w);continue}const B=(n*b-v*r)/S,C=(o*r-s*b)/S;(B-g)*(B-g)+(C-m)*(C-m)>196*i*i?(d=y-u,_=w-c,x=Math.sqrt(d*d+_*_),d/=x,_/=x,d*=i,_*=i,a.push(g-d,m-_),a.push(g+d,m+_),a.push(g-d,m-_)):(a.push(B,C),a.push(g-(B-g),m-(C-m)))}f=t[2*(o-2)],p=t[2*(o-2)+1],g=t[2*(o-1)],m=t[2*(o-1)+1],y=-(p-m),w=f-g,x=Math.sqrt(y*y+w*w),y/=x,w/=x,y*=i,w*=i,a.push(g-y,m-w),a.push(g+y,m+w);const v=a.length/2,b=new Float32Array(a),S=v>=3?v-2:0,B=new Uint16Array(3*S);for(let t=0;t<S;t++){const e=3*t;1&t?(B[e]=t+1,B[e+1]=t,B[e+2]=t+2):(B[e]=t,B[e+1]=t+1,B[e+2]=t+2)}return{vertices:b,indices:B,points:r}},xh=(t,e,i)=>{const s=Math.floor(15*Math.sqrt(i+i)),n=2*Math.PI/s,r=[],o=new Float32Array(2*(s+1));o[0]=t,o[1]=e;for(let a=0;a<s;a++){const s=t+Math.sin(n*a)*i,h=e+Math.cos(n*a)*i;r.push(s,h);const l=2*(a+1);o[l]=s,o[l+1]=h}const a=new Uint16Array(3*s);for(let t=0;t<s;t++){const e=3*t;a[e]=0,a[e+1]=t+1,a[e+2]=t+2>s?1:t+2}return{vertices:o,indices:a,points:r}},vh=(t,e,i,s)=>{const n=Math.floor(15*Math.sqrt(i+s)),r=2*Math.PI/n,o=[],a=new Float32Array(2*(n+1));a[0]=t,a[1]=e;for(let h=0;h<n;h++){const n=t+Math.sin(r*h)*i,l=e+Math.cos(r*h)*s;o.push(n,l);const u=2*(h+1);a[u]=n,a[u+1]=l}const h=new Uint16Array(3*n);for(let t=0;t<n;t++){const e=3*t;h[e]=0,h[e+1]=t+1,h[e+2]=t+2>n?1:t+2}return{vertices:a,indices:h,points:o}},bh=t=>{if(t.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const e=t.length/2,i=function(t){const e=t.length>>1;if(e<3)return new Uint32Array(0);if(3===e)return ph(t[0],t[1],t[2],t[3],t[4],t[5])?new Uint32Array([0,1,2]):new Uint32Array([2,1,0]);const i=new Uint32Array(e),s=new Uint32Array(e);for(let t=0;t<e;t++)i[t]=(t+e-1)%e,s[t]=(t+1)%e;if(function(t){const e=t.length>>1;let i=0;for(let s=0;s<e;s++){const n=(s+1)%e,r=t[2*s],o=t[2*s+1],a=t[2*n];i+=r*t[2*n+1]-a*o}return i}(t)<0)for(let t=0;t<e;t++){const e=i[t];i[t]=s[t],s[t]=e}const n=new Uint32Array(3*(e-2));let r=0,o=e,a=0;for(;o>3;){let e=!1;const h=a;do{const h=i[a],l=s[a],u=a;if(ph(t[2*h],t[2*h+1],t[2*u],t[2*u+1],t[2*l],t[2*l+1])&&mh(t,0,s,h,u,l)){n[r++]=h,n[r++]=u,n[r++]=l,s[h]=l,i[l]=h,o--,e=!0,a=l;break}a=s[a]}while(a!==h);if(!e)break}if(3===o){const e=i[a],o=s[a];ph(t[2*e],t[2*e+1],t[2*a],t[2*a+1],t[2*o],t[2*o+1])?(n[r++]=e,n[r++]=a,n[r++]=o):(n[r++]=o,n[r++]=a,n[r++]=e)}return n.subarray(0,r)}(t),s=new Float32Array(t.length);for(let i=0;i<e;i++)s[2*i]=t[2*i],s[2*i+1]=t[2*i+1];return{vertices:s,indices:new Uint16Array(i),points:t}},Sh=(t,e,i,s)=>({vertices:new Float32Array([t,e,t+i,e,t,e+s,t+i,e+s]),indices:new Uint16Array([0,1,2,1,3,2]),points:[t,e,t+i,e,t+i,e+s,t,e+s]}),Bh=(t,e,i,s,n)=>{const r=Math.min(Math.abs(n),i/2,s/2);if(r<=0)return Sh(t,e,i,s);const o=Math.max(1,Math.floor(15*Math.sqrt(r+r)/4)),a=Math.PI/2/o,h=[[t+r,e+r,Math.PI],[t+i-r,e+r,1.5*Math.PI],[t+i-r,e+s-r,0],[t+r,e+s-r,.5*Math.PI]],l=[];for(const[t=0,e=0,i=0]of h)for(let s=0;s<=o;s++){const n=i+a*s,o=t+Math.cos(n)*r,h=e+Math.sin(n)*r,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]=t+i/2,c[1]=e+s/2;for(let t=0;t<u;t++){const e=2*(t+1);c[e]=l[2*t],c[e+1]=l[2*t+1]}const d=new Uint16Array(3*u);for(let t=0;t<u;t++){const e=3*t;d[e]=0,d[e+1]=t+1,d[e+2]=t+2>u?1:t+2}return{vertices:c,indices:d,points:[...l,l[0],l[1]]}},Ch=(t,e,i,s,n=s/2,r=0)=>{const o=Math.PI/-2+r,a=2*i,h=F/a,l=[];for(let i=0;i<a;i++){const r=o+i*h,a=i%2?n:s;l.push(t+a*Math.cos(r),e+a*Math.sin(r))}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 Ee;_lineColor=new Ee;_fillStyle=this._fillColor;_strokeStyle=this._lineColor;_fillStyleTexture=null;_strokeStyleTexture=null;_ownedTextures=new Set;_currentPoint=new te(0,0);get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t}get lineColor(){return this._lineColor}set lineColor(t){this.strokeStyle=t}get fillColor(){return this._fillColor}set fillColor(t){this.fillStyle=t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=this._resolveStyle(t,this._fillColor),this._fillStyleTexture=null}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=this._resolveStyle(t,this._lineColor),this._strokeStyleTexture=null}get currentPoint(){return this._currentPoint}getChildAt(t){return super.getChildAt(t)}addChild(t){if(!(t instanceof Us))throw new Error("Graphics can only contain Mesh children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof Us))throw new Error("Graphics can only contain Mesh children.");return super.addChildAt(t,e)}moveTo(t,e){return this._currentPoint.set(t,e),this}lineTo(t,e){const{x:i,y:s}=this._currentPoint;return this.drawPath([i,s,t,e]),this.moveTo(t,e),this}quadraticCurveTo(t,e,i,s){const{x:n,y:r}=this._currentPoint;return this.drawPath(H(n,r,t,e,i,s)),this.moveTo(i,s),this}bezierCurveTo(t,e,i,s,n,r){const{x:o,y:a}=this._currentPoint;return this.drawPath(j(o,a,t,e,i,s,n,r)),this.moveTo(n,r),this}arcTo(t,e,i,s,n){const{x:r,y:o}=this._currentPoint,a=Math.abs(n);if(0===a||r===t&&o===e||t===i&&e===s)return this.lineTo(t,e);const h=t-r,l=e-o,u=i-t,c=s-e,d=Math.hypot(h,l),_=Math.hypot(u,c);if(0===d||0===_)return this.lineTo(t,e);const f=h/d,p=l/d,g=u/_,m=c/_,y=q(f*g+p*m,-1,1),w=Math.acos(y);if(0===w||w===Math.PI)return this.lineTo(t,e);const x=a/Math.tan(w/2);if(!Number.isFinite(x)||x>d||x>_)return this.lineTo(t,e);const v=t-f*x,b=e-p*x,S=t+g*x,B=e+m*x,C=f*m-p*g>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(t,e,i,s,n,r=!1){const o=Math.abs(i);if(0===o)return this;let a=n-s;if(!r&&a<0?a+=F:r&&a>0&&(a-=F),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 n=s+a*(i/h);l.push(t+Math.cos(n)*o,e+Math.sin(n)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(t,e,i,s){const n=yh(t,e,i,s,this._lineWidth);return this.addChild(this._createStrokeMesh(n)),this}drawPath(t){const e=wh(t,this._lineWidth);return this.addChild(this._createStrokeMesh(e)),this}drawPolygon(t){const e=bh(t);return this.addChild(this._createFillMesh(e)),this._lineWidth>0&&this.drawPath(e.points),this}drawCircle(t,e,i){const s=xh(t,e,i);return this.addChild(this._createFillMesh(s)),this._lineWidth>0&&this.drawPath(s.points),this}drawEllipse(t,e,i,s){const n=vh(t,e,i,s);return this.addChild(this._createFillMesh(n)),this._lineWidth>0&&this.drawPath(n.points),this}drawRectangle(t,e,i,s){const n=Sh(t,e,i,s);return this.addChild(this._createFillMesh(n)),this._lineWidth>0&&this.drawPath(n.points),this}drawRoundedRectangle(t,e,i,s,n){const r=Bh(t,e,i,s,n);return this.addChild(this._createFillMesh(r)),this._lineWidth>0&&this.drawPath(r.points),this}drawStar(t,e,i,s,n=s/2,r=0){const o=Ch(t,e,i,s,n,r);return this.addChild(this._createFillMesh(o)),this._lineWidth>0&&this.drawPath(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._fillColor.copy(Ee.black),this._lineColor.copy(Ee.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(t,e){return null===t?e:t instanceof Ee?(e.copy(t),e):t.clone()}_createFillMesh(t){return this._fillStyle instanceof Ee?this._createSolidMesh(t,this._fillStyle):(this._fillStyleTexture??=this._rasterizeGradient(this._fillStyle),this._createGradientMesh(t,this._fillStyleTexture))}_createStrokeMesh(t){return this._strokeStyle instanceof Ee?this._createSolidMesh(t,this._strokeStyle):(this._strokeStyleTexture??=this._rasterizeGradient(this._strokeStyle),this._createGradientMesh(t,this._strokeStyleTexture))}_createSolidMesh(t,e){const i=new Us({vertices:t.vertices,indices:t.indices});return i.tint=e,i}_createGradientMesh(t,e){return new Us({vertices:t.vertices,indices:t.indices,uvs:Ph(t.vertices),texture:e})}_rasterizeGradient(t){const e=t.toTexture(256,256,{samplerOptions:{scaleMode:ri.Linear}});return this._ownedTextures.add(e),e}_destroyOwnedTextures(){for(const t of this._ownedTextures)t.destroy();this._ownedTextures.clear()}}const Ph=t=>{let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let r=0;r<t.length;r+=2){const o=t[r],a=t[r+1];o<e&&(e=o),o>s&&(s=o),a<i&&(i=a),a>n&&(n=a)}const r=s-e,o=n-i,a=r>0?1/r:0,h=o>0?1/o:0,l=new Float32Array(t.length);for(let s=0;s<t.length;s+=2)l[s]=(t[s]-e)*a,l[s+1]=(t[s+1]-i)*h;return l};class Ah extends Sn{_clips=new Map;_currentClipName=null;_currentFrameIndex=0;_playing=!1;_loopOverride=null;_elapsedFrameTimeMs=0;onComplete=new m;onFrame=new m;constructor(t,e){super(t),e&&this.setClips(e)}get currentClip(){return this._currentClipName}get currentFrame(){return this._currentFrameIndex}get playing(){return this._playing}get loop(){return null!==this._loopOverride?this._loopOverride:!!this._currentClipName&&(this._clips.get(this._currentClipName)?.loop??!1)}set loop(t){this._loopOverride=t}setClips(t){this._clips.clear();for(const[e,i]of Object.entries(t))this.defineClip(e,i);return this}defineClip(t,e){if(0===t.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");const i=e.frames;if(!Array.isArray(e.frames)||0===i.length)throw new Error(`AnimatedSprite clip "${t}" must define at least one frame.`);const s=e.fps??12;if(!Number.isFinite(s)||s<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid fps value (${s}).`);return this._clips.set(t,{frames:i.map(t=>t.clone()),frameDurationMs:1e3/s,loop:e.loop??!0}),this}_getClipDefinitions(){const t={};for(const[e,i]of this._clips)t[e]={frames:i.frames.map(t=>t.clone()),fps:1e3/i.frameDurationMs,loop:i.loop};return t}removeClip(t){return this._currentClipName===t&&this.stop(),this._clips.delete(t),this}play(t,e={}){const i=this._clips.get(t);if(!i)throw new Error(`AnimatedSprite clip "${t}" is not defined.`);const s=this._currentClipName===t,n=e.restart??!0;return s&&!n||(this._currentClipName=t,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._applyFrame(i.frames[0]),this.onFrame.dispatch(t,0)),this._loopOverride=e.loop??this._loopOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const t=this._clips.get(this._currentClipName);return t&&t.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(t.frames[0]),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(t){if(!this._playing||null===this._currentClipName)return this;const e=this._clips.get(this._currentClipName);if(!e||e.frames.length<=1)return this;const i="number"==typeof t?t:t.milliseconds;if(i<=0)return this;for(this._elapsedFrameTimeMs+=i;this._elapsedFrameTimeMs>=e.frameDurationMs;){this._elapsedFrameTimeMs-=e.frameDurationMs;const t=this._currentFrameIndex+1;if(t>=e.frames.length){if(this.loop){this._currentFrameIndex=0,this._applyFrame(e.frames[0]),this.onFrame.dispatch(this._currentClipName,0);continue}this._currentFrameIndex=e.frames.length-1,this._applyFrame(e.frames[this._currentFrameIndex]),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=t,this._applyFrame(e.frames[this._currentFrameIndex]),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex)}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const t of this._clips.values())for(const e of t.frames)e.destroy();this._clips.clear()}static fromSpritesheet(t){const e={};for(const[i,s]of t.animations)e[i]={frames:s.map(e=>t.getFrame(e)),loop:!0};return new Ah(t.texture,e)}_applyFrame(t){this.setTextureFrame(t,!1)}}function Eh(t){const e={};for(const[i,s]of Object.entries(t))void 0!==s&&(e[i]=s);return e}const Rh=t=>[t.r,t.g,t.b,t.a],kh=t=>Array.isArray(t)&&4===t.length?new Ee(Number(t[0]),Number(t[1]),Number(t[2]),Number(t[3])):void 0,Dh=(t,e,i,s,n)=>t.r===e&&t.g===i&&t.b===s&&t.a===n;function Ih(t){const e={};return"Arial"!==t.fontFamily&&(e.fontFamily=t.fontFamily),"normal"!==t.fontWeight&&(e.fontWeight=t.fontWeight),"normal"!==t.fontStyle&&(e.fontStyle=t.fontStyle),20!==t.fontSize&&(e.fontSize=t.fontSize),Dh(t.fillColor,255,255,255,1)||(e.fillColor=Rh(t.fillColor)),Dh(t.outlineColor,0,0,0,1)||(e.outlineColor=Rh(t.outlineColor)),0!==t.outlineWidth&&(e.outlineWidth=t.outlineWidth),"left"!==t.align&&(e.align=t.align),1.2!==t.lineHeight&&(e.lineHeight=t.lineHeight),0!==t.leading&&(e.leading=t.leading),Dh(t.shadowColor,0,0,0,1)||(e.shadowColor=Rh(t.shadowColor)),0!==t.shadowOffsetX&&(e.shadowOffsetX=t.shadowOffsetX),0!==t.shadowOffsetY&&(e.shadowOffsetY=t.shadowOffsetY),0!==t.shadowAlpha&&(e.shadowAlpha=t.shadowAlpha),0!==t.shadowBlur&&(e.shadowBlur=t.shadowBlur),null!==t.gradientColors&&(e.gradientColors=[Rh(t.gradientColors[0]),Rh(t.gradientColors[1])]),"vertical"!==t.gradientAxis&&(e.gradientAxis=t.gradientAxis),Object.keys(e).length>0?e:void 0}function Lh(t){if("object"!=typeof t||null===t)return;const e=t,i={};"string"==typeof e.fontFamily&&(i.fontFamily=e.fontFamily);const s=hh(e,"fontWeight",ch);void 0!==s&&(i.fontWeight=s),"italic"!==e.fontStyle&&"normal"!==e.fontStyle||(i.fontStyle=e.fontStyle),"number"==typeof e.fontSize&&(i.fontSize=e.fontSize);const n=kh(e.fillColor);void 0!==n&&(i.fillColor=n);const r=kh(e.outlineColor);void 0!==r&&(i.outlineColor=r),"number"==typeof e.outlineWidth&&(i.outlineWidth=e.outlineWidth);const o=hh(e,"align",dh);void 0!==o&&(i.align=o),"number"==typeof e.lineHeight&&(i.lineHeight=e.lineHeight),"number"==typeof e.leading&&(i.leading=e.leading);const a=kh(e.shadowColor);if(void 0!==a&&(i.shadowColor=a),"number"==typeof e.shadowOffsetX&&(i.shadowOffsetX=e.shadowOffsetX),"number"==typeof e.shadowOffsetY&&(i.shadowOffsetY=e.shadowOffsetY),"number"==typeof e.shadowAlpha&&(i.shadowAlpha=e.shadowAlpha),"number"==typeof e.shadowBlur&&(i.shadowBlur=e.shadowBlur),Array.isArray(e.gradientColors)&&2===e.gradientColors.length){const t=kh(e.gradientColors[0]),s=kh(e.gradientColors[1]);void 0!==t&&void 0!==s&&(i.gradientColors=[t,s])}return"horizontal"!==e.gradientAxis&&"vertical"!==e.gradientAxis||(i.gradientAxis=e.gradientAxis),i}const Uh=["visible","clip","ellipsis"],Fh=["ltr","rtl"],Gh=["normal","pre","pre-line"];function Nh(t){if("object"!=typeof t||null===t)return;const e=t,i={},s=oh(e,"maxWidth");void 0!==s&&(i.maxWidth=s);const n=oh(e,"maxHeight");void 0!==n&&(i.maxHeight=n);const r=hh(e,"overflow",Uh);void 0!==r&&(i.overflow=r);const o=oh(e,"letterSpacing");void 0!==o&&(i.letterSpacing=o);const a=hh(e,"direction",Fh);void 0!==a&&(i.direction=a);const h=ah(e,"breakWords");void 0!==h&&(i.breakWords=h);const l=hh(e,"whiteSpace",Gh);return void 0!==l&&(i.whiteSpace=l),Object.keys(i).length>0?i:void 0}const Oh=t=>Array.isArray(t)?new Float32Array(t.map(Number)):new Float32Array,Vh=t=>Array.isArray(t)?new Uint32Array(t.map(Number)):new Uint32Array,zh=t=>"number"==typeof t&&Number.isFinite(t)?t:void 0,qh=t=>{const e=lh(t);return{left:zh(e?.left)??0,top:zh(e?.top)??0,right:zh(e?.right)??0,bottom:zh(e?.bottom)??0}},Yh=t=>{const e=lh(t);if(null===e)return;const i={},s=hh(e,"edges",_h);void 0!==s&&(i.edges=s);const n=hh(e,"center",_h);void 0!==n&&(i.center=n);const r=hh(e,"top",_h);void 0!==r&&(i.top=r);const o=hh(e,"right",_h);void 0!==o&&(i.right=o);const a=hh(e,"bottom",_h);void 0!==a&&(i.bottom=a);const h=hh(e,"left",_h);void 0!==h&&(i.left=h);const l=hh(e,"edgeFit",fh);void 0!==l&&(i.edgeFit=l);const u=hh(e,"centerFit",fh);return void 0!==u&&(i.centerFit=u),i},Wh={write(t,e){const i={vertices:[...t.vertices]};null!==t.indices&&(i.indices=[...t.indices]),null!==t.uvs&&(i.uvs=[...t.uvs]),null!==t.colors&&(i.colors=[...t.colors]);const s=e.keyFor(t.texture);return null!==s&&(i.texture=s),t.material,i},read(t,e){return new Us(Eh({vertices:Oh(t.vertices),indices:void 0!==t.indices?(i=t.indices,Array.isArray(i)?new Uint16Array(i.map(Number)):new Uint16Array):void 0,uvs:void 0!==t.uvs?Oh(t.uvs):void 0,colors:void 0!==t.colors?Vh(t.colors):void 0,texture:e.resolveAsset("string"==typeof t.texture?t.texture:null,pi)}));var i}},$h={write:(t,e)=>0===t.children.length?{}:{children:t.children.map(t=>e.writeNode(t))},read(t,e){const i=new Mh,s=t.children;if(Array.isArray(s))for(const t of s){const s=uh(t);null!==s&&i.addChild(e.readNode(s))}return i}},Xh={write(t,e){const i={slices:{...t.slices},border:{...t.border},modes:{...t.modes},width:t.width,height:t.height},s=e.keyFor(t.texture);return null!==s&&(i.texture=s),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,pi);if(null===i)throw new Error("NineSliceSprite deserialize requires its texture to be pre-loaded into the Loader.");return new dn(i,Eh({slices:qh(t.slices),border:null!==lh(t.border)?qh(t.border):void 0,modes:Yh(t.modes),width:zh(t.width),height:zh(t.height)}))}},jh={write(t,e){const i={width:t.width,height:t.height,modeX:t.modeX,modeY:t.modeY,fitX:t.fitX,fitY:t.fitY,offsetX:t.offsetX,offsetY:t.offsetY},s=e.keyFor(t.texture);return null!==s&&(i.texture=s),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,pi);if(null===i)throw new Error("RepeatingSprite deserialize requires its texture to be pre-loaded into the Loader.");return new vn(i,Eh({width:zh(t.width),height:zh(t.height),modeX:hh(t,"modeX",_h),modeY:hh(t,"modeY",_h),fitX:hh(t,"fitX",fh),fitY:hh(t,"fitY",fh),offsetX:zh(t.offsetX),offsetY:zh(t.offsetY)}))}},Hh={write(t,e){const i={},s=e.keyFor(t.texture);null!==s&&(i.texture=s);const n={};for(const[e,i]of Object.entries(t._getClipDefinitions()))n[e]={frames:i.frames.map(t=>[t.x,t.y,t.width,t.height]),fps:i.fps,loop:i.loop};return i.clips=n,null!==t.currentClip&&(i.currentClip=t.currentClip),t.playing&&(i.playing=!0),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,pi),s={},n=lh(t.clips);if(null!==n)for(const[t,e]of Object.entries(n)){const i=lh(e);if(null===i)continue;const n=Array.isArray(i.frames)?i.frames.map(t=>{const e=(i=t,(Array.isArray(i)?i.map(t=>"number"==typeof t&&Number.isFinite(t)?t:0):null)??[]);var i;return new Zt(e[0]??0,e[1]??0,e[2]??0,e[3]??0)}):[];s[t]=Eh({frames:n,fps:zh(i.fps),loop:ah(i,"loop")})}const r=new Ah(i,s);return"string"==typeof t.currentClip&&t.currentClip in s&&(r.play(t.currentClip),!0!==t.playing&&r.pause()),r}},Kh={write(t,e){const i={text:t.text},s=e.keyFor(t.font);null!==s&&(i.font=s),t.msdf&&(i.msdf=!0),1!==t.fontScale&&(i.scale=t.fontScale);const n=Ih(t.style);return void 0!==n&&(i.style=n),Object.keys(t.layout).length>0&&(i.layout={...t.layout}),i},read(t,e){const i=e.resolveAsset("string"==typeof t.font?t.font:null,Cn);if(null===i)throw new Error("BitmapText deserialize requires its BmFont to be pre-loaded into the Loader.");const s=Nh(t.layout);return new Rn("string"==typeof t.text?t.text:"",i,Eh({...Lh(t.style),msdf:!0===t.msdf,scale:zh(t.scale),layout:s}))}},Qh={write(t){const e={src:t.videoElement.src};return 1!==t.volume&&(e.volume=t.volume),t.loop&&(e.loop=!0),1!==t.playbackRate&&(e.playbackRate=t.playbackRate),t.muted&&(e.muted=!0),t.currentTime>0&&(e.time=t.currentTime),e},read(t){const e=document.createElement("video");return"string"==typeof t.src&&(e.src=t.src),new Po(e,Eh({volume:zh(t.volume),loop:!0===t.loop||void 0,playbackRate:zh(t.playbackRate),muted:!0===t.muted||void 0,time:zh(t.time)}))}};class Zh extends Bi{_uiWidth=0;_uiHeight=0;_enabled=!0;_uiAnchor=null;_uiAnchorOffsetX=0;_uiAnchorOffsetY=0;_uiAnchorRoot=null;_onAnchorResize=(t,e)=>{this._applyAnchor(t,e)};get uiWidth(){return this._uiWidth}get uiHeight(){return this._uiHeight}setSize(t,e){const i=Math.max(0,t),s=Math.max(0,e);return this._uiWidth===i&&this._uiHeight===s||(this._uiWidth=i,this._uiHeight=s,this._relayout(),null!==this._uiAnchorRoot&&this._applyAnchor(this._uiAnchorRoot.screenWidth,this._uiAnchorRoot.screenHeight)),this}get enabled(){return this._enabled}set enabled(t){this._enabled!==t&&(this._enabled=t,this._onEnabledChanged(t))}anchorIn(t,e,i=0,s=0){return this._uiAnchor=e,this._uiAnchorOffsetX=i,this._uiAnchorOffsetY=s,this._uiAnchorRoot!==t&&(this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=t,t.onResize.add(this._onAnchorResize)),this._applyAnchor(t.screenWidth,t.screenHeight),this}_applyAnchor(t,e){if(null===this._uiAnchor)return;const[i,s]=(t=>{let e=.5,i=.5;return t.endsWith("left")?e=0:t.endsWith("right")&&(e=1),t.startsWith("top")?i=0:t.startsWith("bottom")&&(i=1),[e,i]})(this._uiAnchor);this.setPosition(i*(t-this._uiWidth)+this._uiAnchorOffsetX,s*(e-this._uiHeight)+this._uiAnchorOffsetY)}_relayout(){}_onEnabledChanged(t){}destroy(){this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=null,super.destroy()}}class Jh extends Zh{onClick=new m;_background=new Mh;_label;_colors;_cornerRadius;_state="normal";_pointerInside=!1;constructor(t={}){super(),this._colors={normal:(t.color??new Ee(54,120,220,1)).clone(),hover:(t.hoverColor??new Ee(74,140,240,1)).clone(),pressed:(t.pressedColor??new Ee(40,96,180,1)).clone(),disabled:(t.disabledColor??new Ee(70,76,90,1)).clone()},this._cornerRadius=t.cornerRadius??8,this._label=new $n(t.label??"",{fillColor:t.textColor??Ee.white,fontSize:t.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(t.width??120,t.height??40)}get label(){return this._label.text}set label(t){this._label.text=t,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 e=t.channel;!this.enabled||e!==Ei.Enter&&e!==Ei.Space||(t.preventDefault(),this.onClick.dispatch(this))};_refreshState(){let t="normal";this.enabled?this._pointerInside&&(t="hover"):t="disabled",this._state=t,this._draw()}_onEnabledChanged(t){this.interactive=t,this._refreshState()}_relayout(){this._draw(),this._positionLabel()}_draw(){const t=this._background;t.clear(),this._uiWidth<=0||this._uiHeight<=0||(t.fillColor=this._colors[this._state],t.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_positionLabel(){const t=this._label.getLocalBounds();this._label.setPosition((this._uiWidth-t.width)/2,(this._uiHeight-t.height)/2)}}class tl extends Zh{_text;constructor(t="",e={}){super(),this._text=new $n(t,{fillColor:Ee.white,fontSize:16,...e}),this.addChild(this._text),this._syncSize()}get text(){return this._text.text}set text(t){this._text.text!==t&&(this._text.text=t,this._syncSize())}get textNode(){return this._text}_syncSize(){const t=this._text.getLocalBounds();this.setSize(t.width,t.height)}}class el extends Zh{_background=new Mh;_color;_borderColor;_borderWidth;_cornerRadius;constructor(t={}){super(),this._color=(t.color??new Ee(30,34,45,.92)).clone(),this._borderColor=(t.borderColor??new Ee(255,255,255,.12)).clone(),this._borderWidth=t.borderWidth??0,this._cornerRadius=t.cornerRadius??8,this.addChild(this._background),this.setSize(t.width??0,t.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 t=this._background;t.clear(),this._uiWidth<=0||this._uiHeight<=0||(this._borderWidth>0&&(t.lineWidth=this._borderWidth,t.lineColor=this._borderColor),t.fillColor=this._color,t.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}}class il extends Zh{_track=new Mh;_fill=new Mh;_trackColor;_fillColor;_cornerRadius;_value;constructor(t={}){super(),this._value=q(t.value??0,0,1),this._trackColor=(t.trackColor??new Ee(255,255,255,.16)).clone(),this._fillColor=(t.fillColor??new Ee(80,220,120,1)).clone(),this._cornerRadius=t.cornerRadius??4,this.addChild(this._track),this.addChild(this._fill),this.setSize(t.width??200,t.height??12)}get value(){return this._value}set value(t){const e=q(t,0,1);this._value!==e&&(this._value=e,this._drawFill())}get trackColor(){return this._trackColor}get fillColor(){return this._fillColor}get cornerRadius(){return this._cornerRadius}_relayout(){this._drawTrack(),this._drawFill()}_drawTrack(){const t=this._track;t.clear(),this._uiWidth<=0||this._uiHeight<=0||(t.fillColor=this._trackColor,t.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_drawFill(){const t=this._fill;t.clear();const e=this._uiWidth*this._value;e<=0||this._uiHeight<=0||(t.fillColor=this._fillColor,t.drawRoundedRectangle(0,0,e,this._uiHeight,Math.min(this._cornerRadius,e/2)))}}class sl extends Zh{_direction;_spacing;_padding;constructor(t={}){super(),this._direction=t.direction??"column",this._spacing=t.spacing??8,this._padding=t.padding??0}get direction(){return this._direction}get spacing(){return this._spacing}get padding(){return this._padding}addItem(t){return this.addChild(t),this.layout()}layout(){const t="row"===this._direction;let e=this._padding,i=0,s=!0;for(const n of this.children){const r=n instanceof Zh?n.uiWidth:n.getLocalBounds().width,o=n instanceof Zh?n.uiHeight:n.getLocalBounds().height;s||(e+=this._spacing),s=!1,t?(n.setPosition(e,this._padding),e+=r,i=Math.max(i,o)):(n.setPosition(this._padding,e),e+=o,i=Math.max(i,r))}const n=e+this._padding,r=i+2*this._padding;return this.setSize(t?n:r,t?r:n),this}}const nl=t=>"number"==typeof t&&Number.isFinite(t)?t:void 0,rl={write(t){const e={text:t.text},i=Ih(t.textNode.style);return void 0!==i&&(e.style=i),t.enabled||(e.enabled=!1),e},read(t){const e=new tl("string"==typeof t.text?t.text:"",Lh(t.style));return!1===t.enabled&&(e.enabled=!1),e}},ol={write(t,e){const i={width:t.uiWidth,height:t.uiHeight,color:Rh(t.color),borderColor:Rh(t.borderColor),borderWidth:t.borderWidth,cornerRadius:t.cornerRadius};t.enabled||(i.enabled=!1);const s=t.children.filter(e=>e!==t.background);return s.length>0&&(i.children=s.map(t=>e.writeNode(t))),i},read(t,e){const i=new el(Eh({width:nl(t.width),height:nl(t.height),color:kh(t.color),borderColor:kh(t.borderColor),borderWidth:nl(t.borderWidth),cornerRadius:nl(t.cornerRadius)}));!1===t.enabled&&(i.enabled=!1);const s=t.children;if(Array.isArray(s))for(const t of s){const s=uh(t);null!==s&&i.addChild(e.readNode(s))}return i}},al={write(t){const e={width:t.uiWidth,height:t.uiHeight,label:t.label,cornerRadius:t.cornerRadius,color:Rh(t.colors.normal),hoverColor:Rh(t.colors.hover),pressedColor:Rh(t.colors.pressed),disabledColor:Rh(t.colors.disabled),textColor:Rh(t.textColor),fontSize:t.fontSize};return t.enabled||(e.enabled=!1),e},read(t){const e=new Jh(Eh({width:nl(t.width),height:nl(t.height),label:"string"==typeof t.label?t.label:void 0,cornerRadius:nl(t.cornerRadius),color:kh(t.color),hoverColor:kh(t.hoverColor),pressedColor:kh(t.pressedColor),disabledColor:kh(t.disabledColor),textColor:kh(t.textColor),fontSize:nl(t.fontSize)}));return!1===t.enabled&&(e.enabled=!1),e}},hl={write(t){const e={width:t.uiWidth,height:t.uiHeight,value:t.value,trackColor:Rh(t.trackColor),fillColor:Rh(t.fillColor),cornerRadius:t.cornerRadius};return t.enabled||(e.enabled=!1),e},read(t){const e=new il(Eh({width:nl(t.width),height:nl(t.height),value:nl(t.value),trackColor:kh(t.trackColor),fillColor:kh(t.fillColor),cornerRadius:nl(t.cornerRadius)}));return!1===t.enabled&&(e.enabled=!1),e}},ll={write(t,e){const i={direction:t.direction,spacing:t.spacing,padding:t.padding};return t.enabled||(i.enabled=!1),t.children.length>0&&(i.children=t.children.map(t=>e.writeNode(t))),i},read(t,e){const i=new sl(Eh({direction:"row"===t.direction||"column"===t.direction?t.direction:void 0,spacing:nl(t.spacing),padding:nl(t.padding)}));!1===t.enabled&&(i.enabled=!1);const s=t.children;if(Array.isArray(s)){for(const t of s){const s=uh(t);null!==s&&i.addChild(e.readNode(s))}i.layout()}return i}},ul={write:(t,e)=>t.children.length>0?{children:t.children.map(t=>e.writeNode(t))}:{},read(t,e){const i=new sh,s=t.children;if(Array.isArray(s))for(const t of s){const s=uh(t);null!==s&&i.addChild(e.readNode(s))}return i}};const cl={write:(t,e)=>0===t.children.length?{}:{children:t.children.map(t=>e.writeNode(t))},read(t,e){const i=new Bi,s=t.children;if(Array.isArray(s))for(const t of s){const s=uh(t);null!==s&&i.addChild(e.readNode(s))}return i}},dl={write(t,e){const i={},s=e.keyFor(t.texture);null!==s&&(i.texture=s),t.material;const n=t.texture,r=t.textureFrame;return null===n||0===r.x&&0===r.y&&r.width===n.width&&r.height===n.height||(i.frame=[r.x,r.y,r.width,r.height]),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,pi),s=new Sn(i),n=t.frame;return null!==i&&Array.isArray(n)&&4===n.length&&s.setTextureFrame(Zt.temp.set(Number(n[0]),Number(n[1]),Number(n[2]),Number(n[3]))),s}},_l={write(t){const e={text:t.text},i=Ih(t.style);return void 0!==i&&(e.style=i),Object.keys(t.layout).length>0&&(e.layout={...t.layout}),t.colorGlyphs&&(e.colorGlyphs=!0),8!==t.sdfRadius&&(e.sdfRadius=t.sdfRadius),e},read(t){const e=Nh(t.layout);return new $n("string"==typeof t.text?t.text:"",Eh({...Lh(t.style),...e,colorGlyphs:!0===t.colorGlyphs,sdfRadius:"number"==typeof t.sdfRadius?t.sdfRadius:void 0}))}};function fl(t){t.register("Container",Bi,cl),t.register("Sprite",Sn,dl),t.register("Text",$n,_l),function(t){t.register("Mesh",Us,Wh),t.register("Graphics",Mh,$h),t.register("NineSliceSprite",dn,Xh),t.register("RepeatingSprite",vn,jh),t.register("AnimatedSprite",Ah,Hh),t.register("BitmapText",Rn,Kh),t.register("Video",Po,Qh)}(t),function(t){t.register("Label",tl,rl),t.register("Panel",el,ol),t.register("Button",Jh,al),t.register("ProgressBar",il,hl),t.register("Stack",sl,ll),t.register("UIRoot",sh,ul)}(t)}const pl=t=>{const e=Object.getPrototypeOf(t);return"function"==typeof e&&e!==Function.prototype?e:null};class gl{_fallback;_byCtor=new oo({walk:pl});_byName=new Map;constructor(t=null){this._fallback=t}register(t,e,i){const s=this._byName.get(t);if(void 0!==s&&s.ctor!==e)throw new Error(`A serializer for type name "${t}" is already registered for a different constructor.`);const n={typeName:t,ctor:e,serializer:i};this._byCtor.set(e,n),this._byName.set(t,n)}resolveByNode(t){return this._byCtor.resolve(t.constructor)??this._fallback?.resolveByNode(t)}resolveByName(t){return this._byName.get(t)??this._fallback?.resolveByName(t)}hasType(t){return this._byName.has(t)||(this._fallback?.hasType(t)??!1)}clear(){this._byName.clear(),this._byCtor.destroy()}}const ml=new gl;function yl(t,e,i,s=ml){s.register(t,e,i)}const wl=1;let xl=!1;function vl(){xl||(xl=!0,fl(ml))}function bl(t,e,i){const s={version:e,loader:t,readNode:t=>Bl(t,s,i),resolveAsset:(e,i)=>{if(null==e||null===t)return null;return t.peek(i,e)}};return s}function Sl(t,e,i){const s=i.resolveByNode(t);if(void 0===s)throw new Error(`No serializer registered for node type "${t.constructor.name}". Register one via registerSerializer().`);const n={type:s.typeName};return function(t,e){if(0!==t.x&&(e.x=t.x),0!==t.y&&(e.y=t.y),0!==t.rotation&&(e.rotation=t.rotation),1!==t.scale.x&&(e.scaleX=t.scale.x),1!==t.scale.y&&(e.scaleY=t.scale.y),0!==t.skewX&&(e.skewX=t.skewX),0!==t.skewY&&(e.skewY=t.skewY),0!==t.origin.x&&(e.originX=t.origin.x),0!==t.origin.y&&(e.originY=t.origin.y),t.visible||(e.visible=!1),0!==t.zIndex&&(e.zIndex=t.zIndex),t.cullable||(e.cullable=!1),null!==t.name&&(e.name=t.name),t instanceof Si){t.interactive&&(e.interactive=!0),t.draggable&&(e.draggable=!0),t.focusable&&(e.focusable=!0),0!==t.tabIndex&&(e.tabIndex=t.tabIndex),null!==t.cursor&&(e.cursor=t.cursor),t.clip&&(e.clip=!0),t.preserveDrawOrder&&(e.preserveDrawOrder=!0),t.cacheAsBitmap&&(e.cacheAsBitmap=!0);const i=t.clipShape;i instanceof Zt&&(e.clipShape=[i.x,i.y,i.width,i.height])}if(t instanceof Ls){const i=t.tint;255===i.r&&255===i.g&&255===i.b&&1===i.a||(e.tint=[i.r,i.g,i.b,i.a]),t.blendMode!==ni.Normal&&(e.blendMode=t.blendMode),"none"!==t.pixelSnapMode&&(e.pixelSnapMode=t.pixelSnapMode)}}(t,n),Object.assign(n,s.serializer.write(t,e)),n}function Bl(t,e,i){const s=i.resolveByName(t.type);if(void 0===s)throw new Error(`No serializer registered for type "${t.type}". Register one via registerSerializer().`);const n=s.serializer.read(t,e);return rh(n,t),n}function Cl(t,e=null,i=ml){return vl(),Sl(t,function(t,e){const i={version:1,loader:t,writeNode:t=>Sl(t,i,e),keyFor:e=>{if(null==e||"object"!=typeof e||null===t)return null;const i=t.keyFor(e);return null===i?null:i.source}};return i}(e,i),i)}function Tl(t,e,i=null,s=ml){vl();const n=bl(i,1,s);t.removeChildren(),rh(t,e);const r=e.children;if(Array.isArray(r))for(const e of r){const i=uh(e);null!==i&&t.addChild(n.readNode(i))}}class Ml{_systems=[];_set=new Set;_pending=[];_ticking=!1;_sorted=!0;add(t){return this._ticking?this._pending.push({add:!0,system:t}):this._insert(t),t}remove(t){return this._ticking?!!this._set.has(t)&&(this._pending.push({add:!1,system:t}),!0):this._delete(t)}has(t){return this._set.has(t)}get size(){return this._set.size}_tick(t){if(0!==this._systems.length){this._sorted||(this._systems.sort((t,e)=>(t.order??0)-(e.order??0)),this._sorted=!0),this._ticking=!0;for(const e of this._systems)e.update(t);this._ticking=!1,this._drainPending()}}destroy(){for(let t=this._systems.length-1;t>=0;t--)this._systems[t].destroy();this._systems.length=0,this._set.clear(),this._pending.length=0}_insert(t){this._set.has(t)||(this._set.add(t),this._systems.push(t),this._sorted=!1)}_delete(t){if(!this._set.delete(t))return!1;const e=this._systems.indexOf(t);return-1!==e&&this._systems.splice(e,1),!0}_drainPending(){if(0!==this._pending.length){for(const{add:t,system:e}of this._pending)t?this._insert(e):this._delete(e);this._pending.length=0}}}class Pl{_scene;_bindings=new Set;constructor(t){this._scene=t}onStart(t,e,i){return this._track(this._scene.app.input.onStart(t,e,i))}onActive(t,e,i){return this._track(this._scene.app.input.onActive(t,e,i))}onStop(t,e,i){return this._track(this._scene.app.input.onStop(t,e,i))}onTrigger(t,e,i){return this._track(this._scene.app.input.onTrigger(t,e,i))}destroy(){for(const t of this._bindings)t.unbind();this._bindings.clear()}_track(t){return this._bindings.add(t),t}}class Al{_scene;_tweens=new Set;constructor(t){this._scene=t}create(t){const e=this._scene.app.tweens.create(t);return this._tweens.add(e),e}add(t){return this._scene.app.tweens.add(t),this._tweens.add(t),this}destroy(){for(const t of this._tweens)t.stop();this._tweens.clear()}}class El{_app=null;_root=new Bi;paused=!1;_inputs=null;_tweens=null;_systems=null;_disposal=new nh;get app(){return this._app}set app(t){this._app=t}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(t){return this._disposal.track(t)}get systems(){return null===this._systems&&(this._systems=this._disposal.track(new Ml)),this._systems}_tickSystems(t){this._systems?._tick(t)}_ui=null;get ui(){return null===this._ui&&(this._ui=this._disposal.track(new sh),null!==this._root._getStage()&&this._app?.interaction.attachUIRoot(this._ui)),this._ui}_peekUI(){return this._ui}addChild(t){return this._root.addChild(t),this}removeChild(t){return this._root.removeChild(t),this}serialize(){const t=this._app?.loader??null,e=this._app?.serializers,i={version:1,root:Cl(this._root,t,e)},s=this._peekUI();return null!==s&&(i.ui=Cl(s,t,e)),i}deserialize(t){const e=function(t){const e=lh(t);if(null===e)throw new Error("Cannot deserialize scene: the document is not an object.");const i="number"==typeof e.version?e.version:0;if(i>1)throw new Error(`Cannot deserialize scene: data version ${i} is newer than the supported version 1.`);const s=uh(e.root);if(null===s)throw new Error("Cannot deserialize scene: the document has no valid root node.");const n=uh(e.ui);return null!==n?{version:i,root:s,ui:n}:{version:i,root:s}}(t),i=this._app?.loader??null,s=this._app?.serializers;return Tl(this._root,e.root,i,s),void 0!==e.ui&&Tl(this.ui,e.ui,i,s),this}load(t){}init(t){}update(t){}draw(t){}unload(t){}destroy(){this._disposal.destroy(),this._inputs=null,this._tweens=null,this._systems=null,this._root.destroy(),this._app=null}}class Rl extends Us{render(t){return this.visible&&t.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 m;onStartScene=new m;onUpdateScene=new m;onStopScene=new m;_asyncUpdateWarned=new WeakSet;_asyncDrawWarned=new WeakSet;constructor(t){this._app=t}get currentScene(){return this._activeScene}set currentScene(t){this.setScene(t)}async setScene(t,e={}){return await this._runWithTransition(async()=>{if(t===this._activeScene)return;null!==t&&await this._prepareScene(t);const e=this._activeScene;this._activeScene=t,null!==e&&await this._disposeScene(e),this.onChangeScene.dispatch(t),null!==t&&this.onStartScene.dispatch(t)},e.transition),this}update(t){this._advanceTransition(t.milliseconds);const e=this._activeScene;if(null!==e){if(!e.paused){const i=e.update(t);!this._asyncUpdateWarned.has(e)&&i instanceof Promise&&(this._asyncUpdateWarned.add(e),console.warn("[ExoJS] 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.")),e._tickSystems(t)}const i=e.draw(this._app.rendering);!this._asyncDrawWarned.has(e)&&i instanceof Promise&&(this._asyncDrawWarned.add(e),console.warn("[ExoJS] Scene.draw() returned a Promise. draw() must be synchronous — an async draw() produces incomplete frames and silently drops errors.")),e._peekUI()?._render(this._app.rendering)}const i=this._getTransitionAlpha();return i>0&&this._renderTransitionOverlay(i),null!==e&&this.onUpdateScene.dispatch(e),this}destroy(){if(this._transition){const t=this._transition;this._transition=null,t.color.destroy(),t.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(t){t.app=this._app;try{await t.load(this._app.loader),await t.init(this._app.loader),t.root.children.length>0&&t.draw===El.prototype.draw&&console.warn(`[ExoJS] Scene.root has ${t.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(t.root);const e=t._peekUI();null!==e&&this._app.interaction.attachUIRoot(e)}catch(e){let i=null;try{await t.unload(this._app.loader)}catch(t){i=t}if(t.destroy(),t.app=null,i){const t=e instanceof Error?e.message:String(e);let s="unknown cleanup error";throw i instanceof Error?s=i.message:"string"==typeof i&&(s=i),new Error(`Failed to initialize scene: ${t}. Cleanup also failed: ${s}.`,{cause:e})}throw e}}async _disposeScene(t){this.onStopScene.dispatch(t),await t.unload(this._app.loader);const e=t._peekUI();null!==e&&this._app.interaction.detachUIRoot(e),this._app.interaction.detachRoot(t.root),t.destroy(),t.app=null}async _unloadActiveSceneOnDestroy(){const t=this._activeScene;if(null!==t){this._activeScene=null;try{await this._disposeScene(t)}catch(t){console.error("SceneManager.destroy() failed to unload the active scene.",t)}}}async _runWithTransition(t,e){if("fade"!==e?.type)return void await t();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,e.duration??220);0!==i?await new Promise((s,n)=>{this._transition={type:"fade",durationMs:i,action:t,resolve:s,reject:n,color:(e.color??Ee.black).clone(),elapsedMs:0,phase:"out"}}):await t()}_advanceTransition(t){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),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,t)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const t=this._transition;if("switching"===t?.phase){try{await t.action()}catch(e){return void(this._transition===t&&(this._transition=null,t.color.destroy(),t.reject(e)))}this._transition===t&&(t.phase="in",t.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const t=this._transition;this._transition=null,t.color.destroy(),t.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const t=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?t:1-t}_renderTransitionOverlay(t){const e=this._transition,i=e?e.color:Ee.black,s=this._app.backend,n=s.view.getBounds(),r=this._transitionOverlay,o=r.vertices;o[0]=n.left,o[1]=n.top,o[2]=n.right,o[3]=n.top,o[4]=n.left,o[5]=n.bottom,o[6]=n.right,o[7]=n.bottom,r.tint.set(i.r,i.g,i.b,Math.max(0,Math.min(1,t))),r.render(s)}}var Dl;!function(t){t[t.Loading=1]="Loading",t[t.Running=2]="Running",t[t.Halting=3]="Halting",t[t.Stopped=4]="Stopped"}(Dl||(Dl={}));const Il={type:"auto"},Ll=800,Ul=600,Fl=1,Gl=-1,Nl={method:"GET",mode:"cors",cache:"default"},Ol={debug:!1,spriteRendererBatchSize:4096,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1}},Vl={gamepadDefinitions:[],gamepadSlotStrategy:"sticky",pointerDistanceThreshold:10};class zl{options;canvas;loader;input;focus;interaction;scene;random;tweens=new n;systems=new Ml;serializers=new gl(ml);onResize=new m;onFrame=new m;onCanvasFocusChange=new m;onVisibilityChange=new m;onBackendLost=new m;onBackendRestored=new m;pauseOnHidden=!1;_updateHandler;_startupClock=new Ii;_activeClock=new Ii;_frameClock=new Ii;_status=Dl.Stopped;_pixelRatio=Fl;_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;_audio=new de;constructor(t={}){const e=t.canvas??{},i=t.loader??{},s=t.rendering??{},n=t.input??{},r=e.element??document.createElement("canvas"),o=e.width??Ll,a=e.height??Ul;this._pixelRatio=e.pixelRatio??(()=>{const t=globalThis.devicePixelRatio;return"number"==typeof t&&t>0?Math.min(t,2):1})(),this._designWidth=o,this._designHeight=a,this.canvas=r,this._applyCanvasSize(o,a),void 0!==e.tabIndex?this.canvas.tabIndex=e.tabIndex:this.canvas.hasAttribute("tabindex")||(this.canvas.tabIndex=Gl),void 0!==e.imageRendering&&(this.canvas.style.imageRendering=e.imageRendering),this._mountCanvas(e.mount),this._applySizingMode(e.sizingMode??"fixed"),this.options={clearColor:t.clearColor??Ee.cornflowerBlue,backend:t.backend??Il,canvas:{element:this.canvas,width:o,height:a,pixelRatio:this._pixelRatio,tabIndex:this.canvas.tabIndex,...void 0!==e.imageRendering&&{imageRendering:e.imageRendering}},loader:{basePath:i.basePath??"",fetchOptions:i.fetchOptions??{...Nl},...void 0!==i.cache&&{cache:i.cache},...void 0!==i.cacheStrategy&&{cacheStrategy:i.cacheStrategy},...void 0!==i.concurrency&&{concurrency:i.concurrency}},rendering:{debug:s.debug??Ol.debug,webglAttributes:s.webglAttributes??Ol.webglAttributes,spriteRendererBatchSize:s.spriteRendererBatchSize??Ol.spriteRendererBatchSize},input:{gamepadDefinitions:n.gamepadDefinitions??[...Vl.gamepadDefinitions],gamepadSlotStrategy:n.gamepadSlotStrategy??Vl.gamepadSlotStrategy,pointerDistanceThreshold:n.pointerDistanceThreshold??Vl.pointerDistanceThreshold}},this._snapshot=void 0===t.extensions?function(){if(0===Te?.revision)return Te.snapshot;const t=Ce([...Me.values()]);return Te={revision:0,snapshot:t},t}():Ce([...t.extensions??[]]),this.loader=new Wa(this.options.loader);try{!function(t,e){const i=new Set,s=new Set,n=new Set;for(const r of e){if(i.has(r.type)||t.hasLoadable(r.type))throw new Error(`An asset handler is already registered for ${r.type.name}.`);for(const e of r.typeNames??[]){if(s.has(e)||t.hasAssetType(e))throw new Error(`Asset type name "${e}" is already registered. Remove the conflicting binding.`);s.add(e)}for(const e of r.extensions??[]){const i=e.replace(/^\./,"").toLowerCase();if(n.has(i)||t.hasExtension(i))throw new Error(`File extension ".${i}" is already mapped to an asset type. Remove the conflicting binding.`);n.add(i)}i.add(r.type)}for(const i of e){const e=i.create(t);t.bindAsset({type:i.type,...void 0!==i.typeNames&&{typeNames:i.typeNames},...void 0!==i.extensions&&{extensions:i.extensions}},e)}}(this.loader,[...Pa,...this._snapshot.assets]),function(t,e){for(const i of e)t.register(i.typeName,i.target,i.serializer)}(this.serializers,this._snapshot.serializers)}catch(t){try{this.loader.destroy()}catch{}throw t}this._backendType=this.resolveInitialBackendType(),this._backend=this.createBackend(this._backendType,this._snapshot),this._rendering=new io(this._backend),this.input=new ws(this),this.focus=new Ri(this),this.interaction=new bs(this),this.scene=new kl(this),this.random=new Cs(this.options.seed),this._updateHandler=this.update.bind(this),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(t=>{this.onCanvasFocusChange.dispatch(t)}),this.onVisibilityChange.add(t=>{this._audio._applyVisibility(t)})}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 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(t){this.setCursor(t)}get audio(){return this._audio}get width(){return this._designWidth}get height(){return this._designHeight}get pixelRatio(){return this._pixelRatio}screenToWorld(t,e){return this._rendering.camera.screenToWorld(t,e)}_backingStoreToDesign(t,e){const i=this.canvas.width||1,s=this.canvas.height||1;return{x:t/i*this._designWidth,y:e/s*this._designHeight}}async start(t){if(this._status===Dl.Stopped){this._status=Dl.Loading;const e=Ha.ready;try{await this.initializeBackend(),this._capabilities=await e,await this.scene.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._activeClock.start(),this._status=Dl.Running}catch(t){throw this._status=Dl.Stopped,t}}return this}update(){if(this._status===Dl.Running){if(this.pauseOnHidden&&!this._documentVisible)return this._frameClock.restart(),this._frameRequest=requestAnimationFrame(this._updateHandler),this;const t=this._frameClock.elapsedTime.milliseconds,e=Math.min(t,100),i=Di.temp.set(e),s=performance.now();this.backend.resetStats(),this.backend.stats.rawFrameDeltaMs=t,this.systems._tick(i),this.scene.update(i),this.onFrame.dispatch(i),this.backend.flush(),this.backend.stats.frameTimeMs=performance.now()-s,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===Dl.Running&&(this._status=Dl.Halting,cancelAnimationFrame(this._frameRequest),this.scene.setScene(null).catch(t=>{console.error("Application.stop() failed to unload the active scene.",t)}),this._activeClock.stop(),this._frameClock.stop(),this._status=Dl.Stopped),this}resize(t,e){return this._designWidth=t,this._designHeight=e,this._applyCanvasSize(t,e),this.options.canvas={...this.options.canvas??{},width:t,height:e,pixelRatio:this._pixelRatio},this.backend.resize(t,e),this._rendering.resize(t,e),this.onResize.dispatch(t,e,this),this}_mountCanvas(t){if(void 0===t||"undefined"==typeof document)return;const e="string"==typeof t?document.querySelector(t):t;e?.append(this.canvas)}_applySizingMode(t){const e=this.canvas.style;switch(t){case"fill":{const t=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!t)break;this._resizeObserver=new ResizeObserver(()=>{const e=t.clientWidth,i=t.clientHeight;e>0&&i>0&&this.resize(e,i)}),this._resizeObserver.observe(t);break}case"letterbox":{const t=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!t)break;const e=t.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.overflow="hidden",e.background="#000",this._resizeObserver=new ResizeObserver(()=>{const e=t.clientWidth,i=t.clientHeight;e>0&&i>0&&this._applyLetterboxLayout(e,i)}),this._resizeObserver.observe(t);break}case"fit":e.width="100%",e.height="100%",e.objectFit="contain";break;case"shrink":e.maxWidth="100%",e.maxHeight="100%",e.objectFit="contain"}}_applyLetterboxLayout(t,e){const i=((t,e,i,s,n)=>{const r=Math.min(t/i,e/s),o=i*r,a=s*r;return{contentWidthCss:o,contentHeightCss:a,backingWidth:Math.max(1,Math.round(o*n)),backingHeight:Math.max(1,Math.round(a*n))}})(t,e,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(t){const e=t instanceof pi?t.source:t;if(null===e)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof e?e:`url(${g(e)}), auto`,this.canvas.style.cursor=this._cursor,this}renderTo(t,e){return this._rendering.renderTo(t,e)}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.onCanvasFocusChange.destroy(),this.onVisibilityChange.destroy(),this.onBackendLost.destroy(),this.onBackendRestored.destroy()}_onDocumentVisibilityChange(){const t="visible"===document.visibilityState;t!==this._documentVisible&&(this._documentVisible=t,this.onVisibilityChange.dispatch(t))}resolveInitialBackendType(){const t=this.options.backend?.type;return"webgl2"===t?"webgl2":"webgpu"===t||this.canUseWebGpu()?"webgpu":"webgl2"}createBackend(t,e){const i=function(t){const e=t.spriteRendererBatchSize??4096,i={[jn.WebGl2]:()=>new xr(e),[jn.WebGpu]:()=>new $r},s={[jn.WebGl2]:()=>new ar,[jn.WebGpu]:()=>new Ir},n={[jn.WebGl2]:()=>new Sr,[jn.WebGpu]:()=>new Kr},r={[jn.WebGl2]:()=>new ur(e),[jn.WebGpu]:()=>new Nr},o={[jn.WebGl2]:()=>new mr(e),[jn.WebGpu]:()=>new zr};return[{targets:[Sn],create:t=>i[t.backendType]?.()},{targets:[Us],create:t=>s[t.backendType]?.()},{targets:[$n,Rn],create:t=>n[t.backendType]?.()},{targets:[dn],create:t=>r[t.backendType]?.()},{targets:[vn],create:t=>o[t.backendType]?.()}]}(this.options.rendering??{}),s=[...i,...e.renderers];if("webgpu"===t){const t=new To(this);t.onDeviceLost.add(()=>{this.onBackendLost.dispatch()}),t.onDeviceRestored.add(()=>{this.onBackendRestored.dispatch()});try{Pe(t,s)}catch(e){try{t.destroy()}catch{}throw e}return t}const n=new xo(this);n.onContextLost.add(()=>{this.onBackendLost.dispatch()}),n.onContextRestored.add(()=>{this.onBackendRestored.dispatch()});try{Pe(n,s)}catch(t){try{n.destroy()}catch{}throw t}return n}async initializeBackend(){try{await this._backend.initialize()}catch(t){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw t;this._backend.destroy(),this._backendType="webgl2",this._backend=this.createBackend(this._backendType,this._snapshot);const e=this._rendering;this.systems.remove(e),e.destroy(),this._rendering=new io(this._backend),this.systems.add(this._rendering),await this._backend.initialize()}}canUseWebGpu(){return!!navigator.gpu}_applyCanvasSize(t,e){const i=Math.round(t*this._pixelRatio),s=Math.round(e*this._pixelRatio);this.canvas.width=i,this.canvas.height=s,this.canvas.style.width=`${t}px`,this.canvas.style.height=`${e}px`}}const ql=Object.freeze({version:"0.14.0",revision:"e4d9d55",development:!1}),Yl="undefined"!=typeof performance,Wl={mark:t=>{Yl&&"function"==typeof performance.mark&&performance.mark(t)},measure:(t,e,i)=>{if(Yl&&"function"==typeof performance.measure)try{return performance.measure(t,e,i)}catch{return}},clearMarks:t=>{Yl&&"function"==typeof performance.clearMarks&&performance.clearMarks(t)},clearMeasures:t=>{Yl&&"function"==typeof performance.clearMeasures&&performance.clearMeasures(t)}};class $l{_descriptor;constructor(t){this._descriptor=t}static from(t,e=null,i){return new $l(Cl(t,e,i))}static fromJSON(t){return new $l(t)}instantiate(t=null,e){return function(t,e=null,i=ml){return vl(),Bl(t,bl(e,1,i),i)}(this._descriptor,t,e)}toJSON(){return this._descriptor}}const Xl=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",Gi.North],["ButtonWest",Gi.West],["ButtonEast",Gi.East],["ButtonSouth",Gi.South],["LeftShoulder",Gi.LeftShoulder],["RightShoulder",Gi.RightShoulder],["LeftTrigger",Gi.LeftTrigger],["RightTrigger",Gi.RightTrigger],["Select",Gi.Select],["Start",Gi.Start],["LeftStick",Gi.LeftStick],["RightStick",Gi.RightStick],["DPadUp",Gi.DPadUp],["DPadDown",Gi.DPadDown],["DPadLeft",Gi.DPadLeft],["DPadRight",Gi.DPadRight]]),Hl=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"]]),Kl=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"]]),Ql=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"]]),Zl=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"]]),Jl=new Map([[Oi.GenericDualAnalog,Hl],[Oi.Xbox,Kl],[Oi.PlayStation,Ql],[Oi.SwitchPro,Zl],[Oi.JoyConLeft,Zl],[Oi.JoyConRight,Zl],[Oi.GameCube,Hl],[Oi.SteamController,Hl],[Oi.SteamDeck,Hl],[Oi.ArcadeStick,Hl]]);class tu{static controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];static getControlPosition(t){return Xl.get(t)??[.5,.5]}static getControlLabels(t){return Jl.get(t)??Hl}static getControlChannelMap(){return jl}}let eu=null;class iu{static collisionSegments=32;collisionType=tt.Circle;_position;_collisionVertices=null;_verticesDirty=!0;_normals=null;_normalsDirty=!0;_radius;constructor(t=0,e=0,i=0){this._position=new te(t,e),this._radius=i}get position(){return this._position}set position(t){this._position.copy(t),this._verticesDirty=!0,this._normalsDirty=!0}get x(){return this._position.x}set x(t){this._position.x!==t&&(this._position.x=t,this._verticesDirty=!0,this._normalsDirty=!0)}get y(){return this._position.y}set y(t){this._position.y!==t&&(this._position.y=t,this._verticesDirty=!0,this._normalsDirty=!0)}get radius(){return this._radius}set radius(t){this._radius!==t&&(this._radius=t,this._verticesDirty=!0,this._normalsDirty=!0)}setPosition(t,e){return this._position.set(t,e),this._verticesDirty=!0,this._normalsDirty=!0,this}setRadius(t){return this._radius!==t&&(this._radius=t,this._verticesDirty=!0,this._normalsDirty=!0),this}set(t,e,i){return this._position.set(t,e),this._radius=i,this._verticesDirty=!0,this._normalsDirty=!0,this}copy(t){return this._position.copy(t.position),this._radius=t.radius,this._verticesDirty=!0,this._normalsDirty=!0,this}clone(){return new iu(this.x,this.y,this.radius)}equals({x:t,y:e,radius:i}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.radius!==i)}getBounds(){return new Zt(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){if(this._normalsDirty){const t=this.getCollisionVertices();null===this._normals&&(this._normals=t.map(()=>new te));for(let e=0;e<t.length;e++){const i=t[e],s=t[(e+1)%t.length];this._normals[e].set(s.x-i.x,s.y-i.y).rperp().normalize()}this._normalsDirty=!1}return this._normals}project(t,e=new ft){const i=t.dot(this.x,this.y),s=this.radius*t.length;return e.set(i-s,i+s)}contains(t,e){return wt(te.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case tt.SceneNode:return Pt(t.getBounds(),this);case tt.Rectangle:return Pt(t,this);case tt.Polygon:return Ut(this,t);case tt.Circle:return Rt(this,t);case tt.Ellipse:return kt(this,t);case tt.Line:return Bt(t,this);case tt.Point:return wt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case tt.SceneNode:return zt(this,t.getBounds());case tt.Rectangle:return zt(this,t);case tt.Polygon:return Wt(t,this,!0);case tt.Circle:return Vt(this,t);case tt.Ellipse:return Yt(t,this,!0);default:return null}}destroy(){if(this._position.destroy(),null!==this._collisionVertices){for(const t of this._collisionVertices)t.destroy();this._collisionVertices=null}if(null!==this._normals){for(const t of this._normals)t.destroy();this._normals=null}}getCollisionVertices(){if(this._verticesDirty){const t=iu.collisionSegments;if(null===this._collisionVertices){this._collisionVertices=new Array(t);for(let e=0;e<t;e++)this._collisionVertices[e]=new te}for(let e=0;e<t;e++){const i=2*e*Math.PI/t-Math.PI/2,s=Math.cos(i)*this._radius,n=Math.sin(i)*this._radius;this._collisionVertices[e].set(this._radius+s,this._radius+n)}this._verticesDirty=!1}return this._collisionVertices}static get temp(){return null===eu&&(eu=new iu),eu}}class su{collisionType=tt.Ellipse;_position;_radius;constructor(t=0,e=0,i=0,s=i){this._position=new te(t,e),this._radius=new te(i,s)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius.copy(t)}get rx(){return this._radius.x}set rx(t){this._radius.x=t}get ry(){return this._radius.y}set ry(t){this._radius.y=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t,e=t){return this._radius.set(t,e),this}set(t,e,i,s){return this._position.set(t,e),this._radius.set(i,s),this}copy(t){return this._position.copy(t.position),this._radius.copy(t.radius),this}clone(){return new su(this.x,this.y,this.rx,this.ry)}getBounds(){return new Zt(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new ft){const i=this.x*t.x+this.y*t.y,s=Math.sqrt((this.rx*t.x)**2+(this.ry*t.y)**2);return e.set(i-s,i+s)}intersectsWith(t){switch(t.collisionType){case tt.SceneNode:return At(t.getBounds(),this);case tt.Rectangle:return At(t,this);case tt.Polygon:return Gt(this,t);case tt.Circle:return kt(t,this);case tt.Ellipse:return Ft(this,t);case tt.Line:return Ct(t,this);case tt.Point:return xt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case tt.SceneNode:return qt(this,t.getBounds());case tt.Rectangle:return qt(this,t);case tt.Circle:return Yt(this,t);case tt.Polygon:return Xt(this,t);case tt.Ellipse:return $t(this,t);default:return null}}contains(t,e){return xt(te.temp.set(t,e),this)}equals({x:t,y:e,rx:i,ry:s}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.rx!==i||void 0!==s&&this.ry!==s)}destroy(){this._position.destroy(),this._radius.destroy()}}let nu=null;class ru{collisionType=tt.Line;_fromPosition;_toPosition;constructor(t=0,e=0,i=0,s=0){this._fromPosition=new te(t,e),this._toPosition=new te(i,s)}get fromPosition(){return this._fromPosition}set fromPosition(t){this._fromPosition.copy(t)}get fromX(){return this._fromPosition.x}set fromX(t){this._fromPosition.x=t}get fromY(){return this._fromPosition.y}set fromY(t){this._fromPosition.y=t}get toPosition(){return this._toPosition}set toPosition(t){this._toPosition.copy(t)}get toX(){return this._toPosition.x}set toX(t){this._toPosition.x=t}get toY(){return this._toPosition.y}set toY(t){this._toPosition.y=t}set(t,e,i,s){return this._fromPosition.set(t,e),this._toPosition.set(i,s),this}copy(t){return this._fromPosition.copy(t.fromPosition),this.toPosition.copy(t.toPosition),this}clone(){return new ru(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:t,fromY:e,toX:i,toY:s}=this,n=Math.min(t,i),r=Math.min(e,s);return new Zt(n,r,Math.max(t,i)-n,Math.max(e,s)-r)}getNormals(){return[]}project(t,e=new ft){return e}intersectsWith(t){switch(t.collisionType){case tt.SceneNode:return St(this,t.getBounds());case tt.Rectangle:return St(this,t);case tt.Polygon:return Tt(this,t);case tt.Circle:return Bt(this,t);case tt.Ellipse:return Ct(this,t);case tt.Line:return bt(this,t);case tt.Point:return mt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return mt(te.temp.set(t,e),this,i)}equals({fromX:t,fromY:e,toX:i,toY:s}={}){return!(void 0!==t&&this.fromX!==t||void 0!==e&&this.fromY!==e||void 0!==i&&this.toX!==i||void 0!==s&&this.toY!==s)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===nu&&(nu=new ru),nu}}class ou{radius;phi;constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new ou(t.length,t.angle)}toVector(){return te.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}let au=null;class hu{collisionType=tt.Polygon;_position;_points=[];_edges=[];_cachedNormals=null;_normalsDirty=!0;constructor(t=[],e=0,i=0){this._position=new te(e,i),this.setPoints(t)}get position(){return this._position}set position(t){this._position.copy(t),this._normalsDirty=!0}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get points(){return this._points}set points(t){this.setPoints(t)}get edges(){return this._edges}setPosition(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setPoints(t){const e=this._points.length,i=t.length,s=e-i,n=Math.min(e,i);for(let e=0;e<n;e++)this._points[e].copy(t[e]);if(s>0){for(const t of this._points.splice(i))t.destroy();for(const t of this._edges.splice(i))t.destroy();if(null!==this._cachedNormals&&this._cachedNormals.length>i){const t=this._cachedNormals.splice(i);for(const e of t)e.destroy()}}else if(s<0)for(let s=e;s<i;s++)this._points.push(t[s].clone()),this._edges.push(t[s].clone());for(let t=0;t<i;t++){const e=this._points[t],s=this._points[(t+1)%i];this._edges[t].set(s.x-e.x,s.y-e.y)}return this._normalsDirty=!0,this}set(t,e,i){return this._position.set(t,e),this.setPoints(i),this._normalsDirty=!0,this}copy(t){return this._position.copy(t.position),this.setPoints(t.points),this._normalsDirty=!0,this}clone(){return new hu(this.points,this.x,this.y)}equals({x:t,y:e,points:i}={}){return(void 0===t||this.x===t)&&(void 0===e||this.y===e)&&(void 0===i||this.points.length===i.length&&this.points.every((t,e)=>t.equals(i[e])))}getBounds(){let t=1/0,e=1/0,i=-1/0,s=-1/0;for(const n of this._points)t=Math.min(n.x,t),e=Math.min(n.y,e),i=Math.max(n.x,i),s=Math.max(n.y,s);return new Zt(this.x+t,this.y+e,i-t,s-e)}getNormals(){if(this._normalsDirty){const t=this._points.length;for(null===this._cachedNormals&&(this._cachedNormals=[]);this._cachedNormals.length<t;)this._cachedNormals.push(new te);for(let e=0;e<t;e++)this._cachedNormals[e].copy(this._edges[e]).rperp().normalize();this._normalsDirty=!1}return this._cachedNormals}project(t,e=new ft){const i=Math.sqrt(t.x*t.x+t.y*t.y)||1,s=t.x/i,n=t.y/i,r=this._points;let o=1/0,a=-1/0;for(let t=0;t<r.length;t++){const e=r[t],i=s*e.x+n*e.y;i<o&&(o=i),i>a&&(a=i)}return e.set(o,a)}contains(t,e){return vt(te.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case tt.SceneNode:return Et(t.getBounds(),this);case tt.Rectangle:return Et(t,this);case tt.Polygon:return Nt(this,t);case tt.Circle:return Ut(t,this);case tt.Ellipse:return Gt(t,this);case tt.Line:return Tt(t,this);case tt.Point:return vt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case tt.SceneNode:case tt.Rectangle:case tt.Polygon:case tt.Ellipse:return Xt(this,t);case tt.Circle:return Wt(this,t);default:return null}}destroy(){for(const t of this._points)t.destroy();for(const t of this._edges)t.destroy();if(null!==this._cachedNormals){for(const t of this._cachedNormals)t.destroy();this._cachedNormals=null}this._position.destroy(),this._points.length=0,this._edges.length=0}static get temp(){return null===au&&(au=new hu),au}}let lu=null;class uu{_startPoint;_endPoint;constructor(t=0,e=0,i=0,s=0){this._startPoint=new te(t,e),this._endPoint=new te(i,s)}get startPoint(){return this._startPoint}set startPoint(t){this._startPoint.copy(t)}get startX(){return this._startPoint.x}set startX(t){this._startPoint.x=t}get startY(){return this._startPoint.y}set startY(t){this._startPoint.y=t}get endPoint(){return this._endPoint}set endPoint(t){this._endPoint.copy(t)}get endX(){return this._endPoint.x}set endX(t){this._endPoint.x=t}get endY(){return this._endPoint.y}set endY(t){this._endPoint.y=t}set(t,e,i,s){return this._startPoint.set(t,e),this._endPoint.set(i,s),this}copy(t){return this._startPoint.copy(t.startPoint),this._endPoint.copy(t.endPoint),this}clone(){return new uu(this.startX,this.startY,this.endX,this.endY)}equals({startX:t,startY:e,endX:i,endY:s}={}){return!(void 0!==t&&this.startX!==t||void 0!==e&&this.startY!==e||void 0!==i&&this.endX!==i||void 0!==s&&this.endY!==s)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===lu&&(lu=new uu),lu}}function cu(t,e,i,s){const n=t.x,r=t.x+t.width,o=t.y,a=t.y+t.height,h=s.x,l=s.x+s.width,u=s.y,c=s.y+s.height;let d=-1/0,_=1/0;if(e>0)d=(h-r)/e,_=(l-n)/e;else if(e<0)d=(l-n)/e,_=(h-r)/e;else if(r<=h||n>=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 g=Math.max(d,f),m=Math.min(_,p);if(g>m||m<0||g>1)return null;const y=Math.max(0,g),w=t.x+e*y,x=t.y+i*y;let v=0,b=0;if(g<=0){Math.min(r-h,l-n)<Math.min(a-u,c-o)?v=n<h?-1:1:b=o<u?-1:1}else d>f?v=e>0?-1:1:b=i>0?-1:1;return{t:y,x:w,y:x,normalX:v,normalY:b}}function du(t,e,i,s){const n=t.x-s.x,r=t.y-s.y,o=t.radius+s.radius,a=e*e+i*i,h=2*(n*e+r*i),l=n*n+r*r-o*o;if(l<=0){const e=Math.sqrt(n*n+r*r),i=e>0?n/e:1,s=e>0?r/e:0;return{t:0,x:t.x,y:t.y,normalX:i,normalY:s}}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=t.x+e*c,_=t.y+i*c;return{t:c,x:d,y:_,normalX:(d-s.x)/o,normalY:(_-s.y)/o}}const _u={rectangle:cu,circleVsRectangle:function(t,e,i,s){const n=t.radius,r=t.x,o=t.y,a=s.x,h=s.x+s.width,l=s.y,u=s.y+s.height,c=r-Math.max(a,Math.min(r,h)),d=o-Math.max(l,Math.min(o,u));if(c*c+d*d<=n*n){const t=Math.sqrt(c*c+d*d);if(t>0)return{t:0,x:r,y:o,normalX:c/t,normalY:d/t};const e=r-a,i=h-r,s=o-l,n=u-o;return Math.min(e,i)<=Math.min(s,n)?{t:0,x:r,y:o,normalX:e<i?-1:1,normalY:0}:{t:0,x:r,y:o,normalX:0,normalY:s<n?-1:1}}if(0===e&&0===i)return null;let _=1/0,f=0,p=0;const g=(t,e,i)=>{t>=0&&t<=1&&t<_&&(_=t,f=e,p=i)};if(0!==e){const t=(a-n-r)/e;if(t>=0&&t<=1){const e=o+i*t;e>=l&&e<=u&&g(t,-1,0)}const s=(h+n-r)/e;if(s>=0&&s<=1){const t=o+i*s;t>=l&&t<=u&&g(s,1,0)}}if(0!==i){const t=(l-n-o)/i;if(t>=0&&t<=1){const i=r+e*t;i>=a&&i<=h&&g(t,0,-1)}const s=(u+n-o)/i;if(s>=0&&s<=1){const t=r+e*s;t>=a&&t<=h&&g(s,0,1)}}const m=e*e+i*i,y=[a,h,a,h],w=[l,l,u,u];for(let t=0;t<4;t++){const s=y[t],a=w[t],h=r-s,l=o-a,u=2*(h*e+l*i),c=u*u-4*m*(h*h+l*l-n*n);if(c<0)continue;const d=(-u-Math.sqrt(c))/(2*m);if(d<0||d>1)continue;g(d,(r+e*d-s)/n,(o+i*d-a)/n)}return _>1?null:{t:_,x:r+e*_,y:o+i*_,normalX:f,normalY:p}},circleVsCircle:du,rectangleAgainst:function(t,e,i,s){if(0===s.length)return null;const n=Math.min(t.x,t.x+e),r=Math.max(t.x+t.width,t.x+t.width+e),o=Math.min(t.y,t.y+i),a=Math.max(t.y+t.height,t.y+t.height+i);let h=null;for(const l of s){if(r<=l.x||n>=l.x+l.width||a<=l.y||o>=l.y+l.height)continue;const s=cu(t,e,i,l);null!==s&&(null===h||s.t<h.t)&&(h=s)}return h},circleAgainst:function(t,e,i,s){if(0===s.length)return null;const n=Math.min(t.x,t.x+e)-t.radius,r=Math.max(t.x,t.x+e)+t.radius,o=Math.min(t.y,t.y+i)-t.radius,a=Math.max(t.y,t.y+i)+t.radius;let h=null;for(const l of s){if(r<=l.x-l.radius||n>=l.x+l.radius||a<=l.y-l.radius||o>=l.y+l.radius)continue;const s=du(t,e,i,l);null!==s&&(null===h||s.t<h.t)&&(h=s)}return h},substep:function*(t,e,i,s,n){const r=Math.hypot(i,s),o=Math.max(1,Math.ceil(r/n));for(let n=0;n<=o;n++){const r=n/o;yield{x:t+i*r,y:e+s*r,t:r}}}};class fu{enabled;label;_pipelineOwner=null;constructor(t){this.enabled=t?.enabled??!0,this.label=t?.label??new.target.name}resize(t,e){}destroy(){}}class pu extends fu{_callback;_clear;_redirect;_activeContext=null;_executing=!1;constructor(t,e){super(e),this._callback=t,this._clear=e?.clear??null;const i=e?.target??null;this._redirect=null!==i?new vi(()=>this._runCallback(),{target:i,view:e?.view??i.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(t){if(this._executing)throw new Error("CallbackRenderPass.execute is not re-entrant.");this._executing=!0;try{if(null!==this._redirect){this._activeContext=t;try{t.backend.execute(this._redirect)}finally{this._activeContext=null}return}null!==this._clear&&t.backend.clear(this._clear),this._callback(t)}finally{this._executing=!1}}_runCallback(){null!==this._activeContext&&this._callback(this._activeContext)}}class gu extends fu{_node;_target;_clear;_renderOptions;_redirect;constructor(t,e){super(e),this._node=t,this._target=e?.target??null,this._clear=e?.clear??null,this._renderOptions=void 0!==e?.view?{view:e.view}:{},this._redirect=null!==this._target?new vi(t=>wi(this._node,t),{target:this._target,view:e?.view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(t){null===this._redirect?(null!==this._clear&&t.backend.clear(this._clear),t.render(this._node,this._renderOptions)):t.backend.execute(this._redirect)}}class mu extends fu{_passes=[];_executing=!1;_destroyed=!1;constructor(t){super(t)}get size(){return this._passes.length}addPass(t){return this._admit(t),this._passes.push(t),t._pipelineOwner=this,this}insertPass(t,e){this._admit(t);const i=Math.max(0,Math.min(e,this._passes.length));return this._passes.splice(i,0,t),t._pipelineOwner=this,this}removePass(t){this._assertLive(),this._assertNotExecuting();const e=this._passes.indexOf(t);return-1!==e&&(this._passes.splice(e,1),t._pipelineOwner=null,!0)}clear(){this._assertLive(),this._assertNotExecuting();for(const t of this._passes)t._pipelineOwner=null;return this._passes.length=0,this}hasPass(t){return t._pipelineOwner===this}indexOf(t){return this._passes.indexOf(t)}at(t){return this._passes[t]}[Symbol.iterator](){return this._passes[Symbol.iterator]()}execute(t){if(this.enabled){if(this._assertLive(),this._executing)throw new Error("RenderPipeline.execute is not re-entrant.");this._executing=!0;try{for(const e of this._passes)e.enabled&&e.execute(t)}finally{this._executing=!1}}}resize(t,e){for(const i of this._passes)i.resize(t,e)}destroy(){if(this._destroyed)return;this._assertNotExecuting(),this._destroyed=!0;const t=this._passes.splice(0,this._passes.length),e=[];for(const i of t){i._pipelineOwner=null;try{i.destroy()}catch(t){e.push(t)}}if(e.length>0)throw e[0]}_admit(t){if(this._assertLive(),this._assertNotExecuting(),null!==t._pipelineOwner)throw new Error("RenderPass already belongs to a RenderPipeline; remove it from its current pipeline first.");if(t instanceof mu&&t._reaches(this))throw new Error("RenderPipeline cannot contain itself, directly or indirectly (cycle).")}_reaches(t){if(this===t)return!0;for(const e of this._passes)if(e instanceof mu&&e._reaches(t))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 yu{destroy(){}}class wu extends yu{_sprite=new Sn(null);_sampleTint=Ee.white.clone();_radius=2;_quality=1;constructor(t={}){super(),this._radius=Math.max(0,t.radius??2),this._quality=Math.max(1,Math.floor(t.quality??1))}get radius(){return this._radius}set radius(t){this._radius=Math.max(0,t)}get quality(){return this._quality}set quality(t){this._quality=Math.max(1,Math.floor(t))}apply(t,e,i){const s=this._radius,n=this._quality,r=Math.max(1,2*n+1),o=1/(s<=0?1:2*r);this._sampleTint.set(255,255,255,o),this._sprite.setTexture(e).setBlendMode(ni.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new vi(()=>{if(s<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<r;e++){const i=(2*(1===r?0:e/(r-1))-1)*s;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:i,view:i.view,clearColor:Ee.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}}class xu extends yu{_color;_sprite=new Sn(null);constructor(t=Ee.white){super(),this._color=t.clone()}get color(){return this._color}apply(t,e,i){this._sprite.setTexture(e).setBlendMode(ni.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new vi(()=>{this._sprite.render(t)},{target:i,view:i.view,clearColor:Ee.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}}const vu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);class bu extends yu{uniforms;_fragmentSource;_vertexSource;_shader=null;_connection=null;constructor(t){if(super(),!t.fragmentSource)throw new Error("WebGl2ShaderFilter requires fragmentSource for the WebGL2 backend.");const e=!1!==t.autoUpgrade;var i;this._fragmentSource=e?(i=t.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")):t.fragmentSource,this._vertexSource=t.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={...t.uniforms??{}}}apply(t,e,i){if(t.backendType===jn.WebGpu)throw new Error("WebGl2ShaderFilter requires the WebGL2 backend. Use WebGpuShaderFilter on WebGPU.");const s=t;this._ensureConnected(s);const n=this._shader;t.execute(new vi(t=>{const s=t;s.bindShader(n),s.bindTexture(e,0),n.uniforms.has("uTexture")&&n.getUniform("uTexture").setValue(new Int32Array([0])),n.uniforms.has("uResolution")&&n.getUniform("uResolution").setValue(new Float32Array([i.width,i.height]));let r=1;for(const[t,e]of Object.entries(this.uniforms)){if(!n.uniforms.has(t))continue;const i=n.getUniform(t);e instanceof pi?(s.bindTexture(e,r),i.setValue(new Int32Array([r])),r++):i.setValue(this._marshalValue(e))}n.sync();const o=this._connection;s.bindVertexArrayObject(o.vao),o.vao.draw(4,0,ai.TriangleStrip)},{target:i,view:i.view,clearColor:Ee.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 t of Object.keys(this.uniforms))delete this.uniforms[t]}_ensureConnected(t){if(null!==this._shader)return;const e=t.context,i=new Xn(this._vertexSource,this._fragmentSource);i.connect(sr(e)),i.sync();const s=e.createVertexArray();if(null===s)throw new Error("WebGl2ShaderFilter: could not create vertex array object.");const n=this._createVertexBuffer(e),r=this._createVao(e,s,i,n);this._shader=i,this._connection={gl:e,vertexBuffer:n,vao:r}}_createVertexBuffer(t){const e=t.createBuffer();if(null===e)throw new Error("WebGl2ShaderFilter: could not create vertex buffer.");const i=new Kn(hi.ArrayBuffer,vu,li.StaticDraw);return i.connect({bind:()=>{t.bindBuffer(t.ARRAY_BUFFER,e)},upload:(i,s)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,i.data,i.usage)},destroy:i=>{t.deleteBuffer(e),i.disconnect()}}),i}_createVao(t,e,i,s){let n=-1;const r=new rr(ai.TriangleStrip);return i.attributes.has("aPosition")&&r.addAttribute(s,i.getAttribute("aPosition"),t.FLOAT,!1,16,0),i.attributes.has("aUv")&&r.addAttribute(s,i.getAttribute("aUv"),t.FLOAT,!1,16,8),r.connect({bind:i=>{if(t.bindVertexArray(e),n!==i.version){let e=null;for(const s of i.attributes){const i=s.buffer;e!==i&&(i.bind(),e=i),t.vertexAttribPointer(s.location,s.size,s.type,s.normalized,s.stride,s.start),t.enableVertexAttribArray(s.location)}n=i.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,n)=>{t.drawArrays(n,s,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}),r}_marshalValue(t){return t instanceof Float32Array||t instanceof Int32Array?t:"number"==typeof t?new Float32Array([t]):new Float32Array(t)}}const Su=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);function Bu(t){return t instanceof pi||"object"==typeof t&&null!==t&&"width"in t&&"height"in t&&!(t instanceof Float32Array)&&!(t instanceof Int32Array)&&!Array.isArray(t)}class Cu extends yu{uniforms;_fragmentSource;_vertexSource;_connection=null;constructor(t){if(super(),!t.fragmentSource)throw new Error("WebGpuShaderFilter requires fragmentSource.");this._fragmentSource=t.fragmentSource,this._vertexSource=t.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={...t.uniforms??{}}}apply(t,e,i){if(t.backendType!==jn.WebGpu)throw new Error("WebGpuShaderFilter requires the WebGPU backend. Use WebGl2ShaderFilter on WebGL2.");const s=t;this._ensureConnected(s,i);const n=this._connection;t.execute(new vi(t=>{const s=t,r=n.device,o=new Float32Array([i.width,i.height,0,0]);r.queue.writeBuffer(n.resolutionBuffer,0,o);const a=s.getTextureBinding(e),h=r.createBindGroup({layout:n.autoBindGroupLayout,entries:[{binding:0,resource:{buffer:n.resolutionBuffer}},{binding:1,resource:a.view},{binding:2,resource:n.sampler}]}),l=this._buildUserBindGroup(s,n),u=s._passCoordinator.acquirePass().pass;u.setPipeline(n.pipeline),u.setVertexBuffer(0,n.vertexBuffer),u.setBindGroup(0,h),u.setBindGroup(1,l),u.draw(4),s.stats.drawCalls++,s._passCoordinator.endPass()},{target:i,view:i.view,clearColor:Ee.transparentBlack}))}destroy(){null!==this._connection&&(this._connection.vertexBuffer.destroy(),this._connection.resolutionBuffer.destroy(),this._connection.userUniformBuffer?.destroy(),this._connection=null);for(const t of Object.keys(this.uniforms))delete this.uniforms[t]}_ensureConnected(t,e){if(null!==this._connection)return;const i=t.device,s=i.createShaderModule({code:this._vertexSource}),n=i.createShaderModule({code:this._fragmentSource}),r=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:[r,o]}),h=t.renderTargetFormat,l=i.createRenderPipeline({layout:a,vertex:{module:s,entryPoint:"main",buffers:[{arrayStride:16,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"}]}]},fragment:{module:n,entryPoint:"main",targets:[{format:h}]},primitive:{topology:"triangle-strip"}}),u=i.createBuffer({size:Su.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});i.queue.writeBuffer(u,0,Su);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:r,userBindGroupLayout:o,pipelineLayout:a,pipeline:l,sampler:d,userUniformBuffer:null}}_buildUserBindGroupLayout(t){const e=[];Object.values(this.uniforms).some(t=>!Bu(t))&&e.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});let i=1;for(const t of Object.values(this.uniforms))Bu(t)&&(e.push({binding:i,visibility:GPUShaderStage.FRAGMENT,texture:{}}),i++,e.push({binding:i,visibility:GPUShaderStage.FRAGMENT,sampler:{}}),i++);return 0===e.length&&e.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),t.createBindGroupLayout({entries:e})}_buildUserBindGroup(t,e){const i=e.device,s=[],n=Object.entries(this.uniforms).filter(([,t])=>!Bu(t));if(n.length>0){const t=16*n.length,r=new Float32Array(t/4);let o=0;for(const[,t]of n){const e=4*o;if("number"==typeof t)r[e]=t;else if(t instanceof Float32Array)r.set(t,e);else if(t instanceof Int32Array)for(let i=0;i<t.length;i++)r[e+i]=t[i];else{const i=t;for(let t=0;t<i.length;t++)r[e+t]=i[t]}o++}(null===e.userUniformBuffer||e.userUniformBuffer.size<t)&&(e.userUniformBuffer?.destroy(),e.userUniformBuffer=i.createBuffer({size:t,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),i.queue.writeBuffer(e.userUniformBuffer,0,r),s.push({binding:0,resource:{buffer:e.userUniformBuffer}})}else null===e.userUniformBuffer&&(e.userUniformBuffer=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),s.push({binding:0,resource:{buffer:e.userUniformBuffer}});let r=1;for(const[,e]of Object.entries(this.uniforms)){if(!Bu(e))continue;const i=t.getTextureBinding(e);s.push({binding:r,resource:i.view}),r++,s.push({binding:r,resource:i.sampler}),r++}return i.createBindGroup({layout:e.userBindGroupLayout,entries:s})}}class Tu extends yu{static identityLut1D(t=256){const e=document.createElement("canvas");e.width=t,e.height=1;const i=e.getContext("2d");if(null===i)throw new Error("LutFilter.identityLut1D: 2D canvas context unavailable.");const s=i.createImageData(t,1);for(let e=0;e<t;e++){const i=Math.round(e/(t-1)*255),n=4*e;s.data[n]=i,s.data[n+1]=i,s.data[n+2]=i,s.data[n+3]=255}return i.putImageData(s,0,0),new pi(e,{scaleMode:ri.Linear,wrapMode:oi.ClampToEdge,generateMipMap:!1})}static identityLut3D(t=17){const e=t*t,i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(null===s)throw new Error("LutFilter.identityLut3D: 2D canvas context unavailable.");const n=s.createImageData(e,t),r=t-1;for(let i=0;i<t;i++){const s=Math.round(i/r*255);for(let o=0;o<t;o++){const a=Math.round(o/r*255);for(let h=0;h<t;h++){const l=Math.round(h/r*255),u=4*(o*e+(i*t+h));n.data[u]=l,n.data[u+1]=a,n.data[u+2]=s,n.data[u+3]=255}}}return s.putImageData(n,0,0),new pi(i,{scaleMode:ri.Linear,wrapMode:oi.ClampToEdge,generateMipMap:!1})}static fromImage(t){return new pi(t,{scaleMode:ri.Linear,wrapMode:oi.ClampToEdge,generateMipMap:!1})}_mode;_size;_lut;_backendFilter=null;constructor(t={}){super(),this._mode=t.mode??"3d",this._size=Math.max(2,Math.floor(t.size??17)),this._lut="1d"===this._mode?Tu.identityLut1D():Tu.identityLut3D(this._size)}get mode(){return this._mode}get size(){return this._size}get lut(){return this._lut}setLut(t){return this._lut=t,null!==this._backendFilter&&(this._backendFilter.uniforms.uLut=t),this}apply(t,e,i){null===this._backendFilter&&(this._backendFilter=this._createBackendFilter(t)),this._backendFilter.apply(t,e,i)}destroy(){null!==this._backendFilter&&(this._backendFilter.destroy(),this._backendFilter=null)}_createBackendFilter(t){const e="3d"===this._mode,i={uLut:this._lut};return e&&(i.uLutSize=this._size),t.backendType===jn.WebGpu?new Cu({fragmentSource:e?"\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:i}):new bu({fragmentSource:e?"#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:i})}}const Mu={f32:4,u8:1,u16:2,u32:4,i32:4},Pu=new Set(["triangle-list","triangle-strip"]),Au=new Set(["static","dynamic","stream"]),Eu=new Set(["a_position","position"]),Ru=new WeakMap;let ku=1;const Du=(t,e)=>{const{byteLength:i}=t;if(i%e!==0)throw new Error(`Geometry vertexData byteLength ${i} must be divisible by stride ${e}.`);return i/e},Iu=(t,e,i,s)=>{switch(e){case"f32":return t.getFloat32(i,!0);case"u8":{const e=t.getUint8(i);return s?e/255:e}case"u16":{const e=t.getUint16(i,!0);return s?e/65535:e}case"u32":{const e=t.getUint32(i,!0);return s?e/4294967295:e}case"i32":{const e=t.getInt32(i,!0);return s?Math.max(e/2147483647,-1):e}default:return 0}};class Lu{attributes;stride;topology;usage;indices;vertexData;_version=0;_localBounds=new Zt;_localBoundsDirty=!0;_positionAttribute;_disposeCallbacks=new Set;constructor(t){const{attributes:e,vertexData:i,stride:s,indices:n=null,topology:r="triangle-list",usage:o="static"}=t;if(0===e.length)throw new Error("Geometry attributes must be a non-empty array.");if(!Number.isInteger(s)||s<=0)throw new Error(`Geometry stride must be a positive integer (got ${s}).`);if(!Pu.has(r))throw new Error(`Geometry topology must be one of: triangle-list, triangle-strip (got ${String(r)}).`);if(!Au.has(o))throw new Error(`Geometry usage must be one of: static, dynamic, stream (got ${String(o)}).`);const a=[],h=new Set;for(const t of e){if("string"!=typeof t.name||0===t.name.length)throw new Error("Geometry attribute name must be a non-empty string.");if(h.has(t.name))throw new Error(`Geometry attribute "${t.name}" is declared more than once.`);if(h.add(t.name),!Number.isInteger(t.size)||t.size<1||t.size>4)throw new Error(`Geometry attribute "${t.name}" size must be an integer in [1..4] (got ${t.size}).`);if(!Number.isInteger(t.offset)||t.offset<0)throw new Error(`Geometry attribute "${t.name}" offset must be a non-negative integer (got ${t.offset}).`);const e=Mu[t.type],i=t.offset+e*t.size;if(i>s)throw new Error(`Geometry attribute "${t.name}" range [${t.offset}, ${i}) exceeds stride ${s}.`);for(const e of a)if(t.offset<e.end&&i>e.start)throw new Error(`Geometry attribute "${t.name}" overlaps attribute "${e.name}" in the interleaved layout.`);a.push({name:t.name,start:t.offset,end:i})}const l=(t=>{const e=t.find(t=>Eu.has(t.name));if(e)return e;const i=t.find(t=>t.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Geometry requires a position attribute named `a_position` or `position`.")})(e);if(l.size<2)throw new Error(`Geometry position attribute "${l.name}" must declare at least 2 components.`);const u=Du(i,s);if(null!==n)for(let t=0;t<n.length;t++){const e=n[t];if(e>=u)throw new Error(`Geometry index ${e} at position ${t} is out of range for vertex count ${u}.`)}this.attributes=(t=>t.map(t=>({...t})))(e),this.vertexData=i,this.stride=s,this.indices=n,this.topology=r,this.usage=o,this._positionAttribute={...l}}get vertexCount(){return Du(this.vertexData,this.stride)}get indexCount(){return this.indices?.length??this.vertexCount}get version(){return this._version}get id(){return(t=>{const e=Ru.get(t);if(void 0!==e)return e;const i=ku++;return Ru.set(t,i),i})(this)}invalidate(){return this._version++,this._localBoundsDirty=!0,this}getLocalBounds(t=this._localBounds){return this._localBoundsDirty&&this.recomputeLocalBounds(),t===this._localBounds?this._localBounds:t.copy(this._localBounds)}recomputeLocalBounds(){const t=this.vertexCount;if(0===t)return this._localBounds.set(0,0,0,0),this._localBoundsDirty=!1,this;const e=this.vertexData instanceof Float32Array?new DataView(this.vertexData.buffer,this.vertexData.byteOffset,this.vertexData.byteLength):new DataView(this.vertexData),i=Mu[this._positionAttribute.type];let s=1/0,n=1/0,r=-1/0,o=-1/0;for(let a=0;a<t;a++){const t=a*this.stride+this._positionAttribute.offset,h=Iu(e,this._positionAttribute.type,t,this._positionAttribute.normalized),l=Iu(e,this._positionAttribute.type,t+i,this._positionAttribute.normalized);h<s&&(s=h),h>r&&(r=h),l<n&&(n=l),l>o&&(o=l)}return this._localBounds.set(s,n,r-s,o-n),this._localBoundsDirty=!1,this}destroy(){for(const t of this._disposeCallbacks)t();this._disposeCallbacks.clear()}_onDispose(t){this._disposeCallbacks.add(t)}}const Uu=(t,e)=>t.offset-e.offset;class Fu{_stops;_sample=new Float32Array(4);constructor(t){this._stops=Fu._normalizeStops(t)}get stops(){return this._stops}copy(t){return this._stops=t._stops.map(t=>({offset:t.offset,color:t.color.clone()})),this._copyGeometry(t),this}equals(t){if(this===t)return!0;if(this.type!==t.type||this._stops.length!==t._stops.length)return!1;for(let e=0;e<this._stops.length;e++){const i=this._stops[e],s=t._stops[e];if(i.offset!==s.offset||!i.color.equals(s.color))return!1}return this._geometryEquals(t)}toTexture(t,e,i={}){if(!Number.isInteger(t)||!Number.isInteger(e)||t<=0||e<=0)throw new Error("Gradient.toTexture() width/height must be positive integers.");return"rgba32f"===i.format?this._toRgba32fTexture(t,e,i):this._toRgba8Texture(t,e,i)}destroy(){for(const t of this._stops)t.color.destroy();this._stops=[]}sampleAt(t,e){const i=q(t,0,1),s=this._stops[0];let n=s.offset,r=s.color;for(let t=1;t<this._stops.length;t++){const s=this._stops[t];if(i<=s.offset){const t=Math.max(s.offset-n,1e-6),o=q((i-n)/t,0,1);return e[0]=r.r/255+(s.color.r/255-r.r/255)*o,e[1]=r.g/255+(s.color.g/255-r.g/255)*o,e[2]=r.b/255+(s.color.b/255-r.b/255)*o,void(e[3]=r.a+(s.color.a-r.a)*o)}n=s.offset,r=s.color}e[0]=r.r/255,e[1]=r.g/255,e[2]=r.b/255,e[3]=r.a}static _normalizeStops(t){if(t.length<2)throw new Error("Gradient requires at least 2 color stops.");return t.map(t=>{if(!Number.isFinite(t.offset))throw new Error("Gradient stop offset must be a finite number.");return{offset:q(t.offset,0,1),color:t.color.clone()}}).sort(Uu)}_toRgba8Texture(t,e,i){const s=new In({width:t,height:e,format:"rgba8",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),n=s.buffer;let r=0;for(let i=0;i<e;i++){const s=1===e?0:i/(e-1);for(let e=0;e<t;e++){const i=1===t?0:e/(t-1);this.sampleAt(this.resolveT(i,s),this._sample),n[r]=Gu(this._sample[0]),n[r+1]=Gu(this._sample[1]),n[r+2]=Gu(this._sample[2]),n[r+3]=Gu(this._sample[3]),r+=4}}return s.commit(),s}_toRgba32fTexture(t,e,i){const s=new In({width:t,height:e,format:"rgba32f",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),n=s.buffer;let r=0;for(let i=0;i<e;i++){const s=1===e?0:i/(e-1);for(let e=0;e<t;e++){const i=1===t?0:e/(t-1);this.sampleAt(this.resolveT(i,s),this._sample),n[r]=this._sample[0],n[r+1]=this._sample[1],n[r+2]=this._sample[2],n[r+3]=this._sample[3],r+=4}}return s.commit(),s}}const Gu=t=>255*q(t,0,1)+.5|0;class Nu extends Fu{type="linear";_start;_end;constructor(t,e=[0,0],i=[1,0]){super(t),this._start=[e[0],e[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 Nu(this.stops,this._start,this._end)}resolveT(t,e){const i=this._end[0]-this._start[0],s=this._end[1]-this._start[1],n=i*i+s*s;return n<=1e-6?0:((t-this._start[0])*i+(e-this._start[1])*s)/n}_copyGeometry(t){this._start=[t._start[0],t._start[1]],this._end=[t._end[0],t._end[1]]}_geometryEquals(t){return t instanceof Nu&&this._start[0]===t._start[0]&&this._start[1]===t._start[1]&&this._end[0]===t._end[0]&&this._end[1]===t._end[1]}}class Ou extends Fu{type="radial";_center;_radius;constructor(t,e=[.5,.5],i=.5){super(t),this._center=[e[0],e[1]],this._radius=Math.max(0,i)}get center(){return[this._center[0],this._center[1]]}get radius(){return this._radius}clone(){return new Ou(this.stops,this._center,this._radius)}resolveT(t,e){if(this._radius<=1e-6)return 1;const i=t-this._center[0],s=e-this._center[1];return Math.sqrt(i*i+s*s)/this._radius}_copyGeometry(t){this._center=[t._center[0],t._center[1]],this._radius=t._radius}_geometryEquals(t){return t instanceof Ou&&this._center[0]===t._center[0]&&this._center[1]===t._center[1]&&this._radius===t._radius}}const Vu=new WeakMap;let zu=1;const qu=t=>{const e=Vu.get(t);if(void 0!==e)return e;const i=zu++;return Vu.set(t,i),i},Yu=new Map;let Wu=1;const $u=new Map;let Xu=1;const ju=(t,e,i)=>{const s=t.get(e);if(void 0!==s)return s;const n=i();return t.set(e,n),n},Hu=t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&!ArrayBuffer.isView(t);let Ku=1;class Qu{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??ni.Normal,this.sampler=t.sampler??null,this._id=Ku++}get pipelineKey(){return((t,e,i)=>{const s=`${t}|${e}|${(t=>null===t?"-":[t.scaleMode,t.wrapMode,t.premultiplyAlpha?1:0,t.generateMipMap?1:0,t.flipY?1:0].join(":"))(i)}`;return ju(Yu,s,()=>Wu++)})(this.shader.id,this.blendMode,this.sampler)}get bindKey(){return((t,e,i)=>{const s=[];for(const t of Object.keys(i))s.push(`t:${t}=${qu(i[t])}`);for(const t of Object.keys(e)){const i=e[t];Hu(i)&&s.push(`u:${t}=${qu(i)}`)}s.sort();const n=`${t}|${s.join(",")}`;return ju($u,n,()=>Xu++)})(this._id,this.uniforms,this.textures)}setUniform(t,e){return this.uniforms[t]=e,this}setTexture(t,e){return this.textures[t]=e,this}destroy(){for(const t of this._disposeCallbacks)t();this._disposeCallbacks.clear()}_onDispose(t){this._disposeCallbacks.add(t)}}class Zu extends Qu{target="mesh";constructor(t){super(t)}}let Ju=1;class tc{glsl;wgsl;_id;constructor(t){if(void 0===t.glsl&&void 0===t.wgsl)throw new Error("ShaderSource requires at least one of `glsl` or `wgsl`.");if(void 0!==t.glsl){if("string"!=typeof t.glsl.vertex||0===t.glsl.vertex.length)throw new Error("ShaderSource.glsl.vertex must be a non-empty string.");if("string"!=typeof t.glsl.fragment||0===t.glsl.fragment.length)throw new Error("ShaderSource.glsl.fragment must be a non-empty string.")}if(void 0!==t.wgsl&&("string"!=typeof t.wgsl||0===t.wgsl.length))throw new Error("ShaderSource.wgsl must be a non-empty string.");this.glsl=t.glsl??null,this.wgsl=t.wgsl??null,this._id=Ju++}get id(){return this._id}getDeclaredUniforms(){return{glsl:null!==this.glsl?rc(this.glsl.vertex,this.glsl.fragment):{},wgsl:null!==this.wgsl?oc(this.wgsl):{}}}detectUniformDrift(){if(null===this.glsl||null===this.wgsl)return{onlyInGlsl:[],onlyInWgsl:[]};const t=this.getDeclaredUniforms(),e=new Set(Object.keys(t.glsl).filter(t=>!ec.has(t))),i=new Set(Object.keys(t.wgsl).filter(t=>!ec.has(t))),s=[],n=[];for(const t of e)i.has(t)||s.push(t);for(const t of i)e.has(t)||n.push(t);return{onlyInGlsl:s,onlyInWgsl:n}}}const ec=new Set(["u_projection","u_translation","u_tint","u_texture","u_mesh"]),ic=/\buniform\s+(?:mediump\s+|highp\s+|lowp\s+|)(\w+)\s+(\w+)[^;]*;/g,sc=/@group\(\s*2\s*\)\s*@binding\(\s*\d+\s*\)\s*var(?:<[^>]+>|)\s+(\w+)\s*:\s*([^;]+);/g;function nc(t){return t.replaceAll(/\/\*[\s\S]*?\*\//g,"").replaceAll(/\/\/[^\n]*/g,"")}function rc(t,e){const i={};for(const s of[t,e]){const t=nc(s);let e;for(ic.lastIndex=0;null!==(e=ic.exec(t));){const[,t,s]=e;void 0!==t&&void 0!==s&&(i[s]=t)}}return i}function oc(t){const e={},i=nc(t);let s;for(sc.lastIndex=0;null!==(s=sc.exec(i));){const[,t,i]=s;void 0!==t&&void 0!==i&&(e[t]=i.trim())}return e}class ac extends Qu{target="sprite";constructor(t){super(t)}}class hc{texture;frames=new Map;sprites=new Map;animations=new Map;constructor(t,e){this.texture=t,this.parse(e)}parse(t,e=!1){e||this.clear();for(const[e,i]of Object.entries(t.frames))this.addFrame(e,i);if(t.animations)for(const[e,i]of Object.entries(t.animations))this.defineAnimation(e,i)}addFrame(t,e){const{x:i,y:s,w:n,h:r}=e.frame,o=new Zt(i,s,n,r),a=new Sn(this.texture);a.setTextureFrame(o),this.frames.set(t,o),this.sprites.set(t,a)}defineAnimation(t,e){if(0===t.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(0===e.length)throw new Error(`Spritesheet animation "${t}" must reference at least one frame.`);for(const i of e)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${t}" references missing frame "${i}".`);return this.animations.set(t,[...e]),this}getFrame(t){const e=this.frames.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}getAnimationFrameNames(t){const e=this.animations.get(t);if(!e)throw new Error(`Spritesheet animation named ${t} is not available!`);return e}getFrameSprite(t){const e=this.sprites.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}clear(){for(const t of this.frames.values())t.destroy();this.frames.clear();for(const t of this.sprites.values())t.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}}const lc={woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};class uc extends Bi{_html;_css;_width;_height;_resolution;_canvas;_ctx;_texture;_mesh;_destroyed=!1;_renderVersion=0;_activeRender=null;_fonts=[];constructor(t,e={}){super(),this._html=t,this._css=e.css??"",this._width=e.width??256,this._height=e.height??128,this._resolution=e.resolution??1;const[i,s]=uc._makeCanvas(Math.ceil(this._width*this._resolution),Math.ceil(this._height*this._resolution));this._canvas=i,this._ctx=s,this._texture=new pi(i),this._texture.setSize(this._width,this._height),this._mesh=this._buildMesh(),this.addChild(this._mesh),t.length>0&&this._schedule()}get html(){return this._html}set html(t){this._html!==t&&(this._html=t,this._schedule())}get css(){return this._css}set css(t){this._css!==t&&(this._css=t,this._schedule())}get width(){return this._width}set width(t){this.resize(t,this._height)}get height(){return this._height}set height(t){this.resize(this._width,t)}get resolution(){return this._resolution}set resolution(t){this._resolution!==t&&(this._resolution=t,this._resizeCanvas(),this._schedule())}get ready(){return this._activeRender??Promise.resolve()}addFont(t,e,i="woff2"){const s=`data:${lc[i]};base64,${uc._toBase64(e)}`,n=this._fonts.findIndex(e=>e.family===t);return n>=0?this._fonts[n]={family:t,dataUri:s}:this._fonts.push({family:t,dataUri:s}),this._schedule(),this}removeFont(t){const e=this._fonts.findIndex(e=>e.family===t);return e>=0&&(this._fonts.splice(e,1),this._schedule()),this}resize(t,e){return this._width===t&&this._height===e||(this._width=t,this._height=e,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=>{console.warn("[ExoJS] HTMLText render failed.",t)})}async _render(t){if("undefined"==typeof Blob||"undefined"==typeof Image)return;const e=new Blob([this._buildSvg()],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(e),s=new Image;try{await new Promise((t,e)=>{s.onload=()=>t(),s.onerror=()=>e(new Error("HTMLText: SVG render failed")),s.src=i})}finally{URL.revokeObjectURL(i)}if(this._destroyed||t!==this._renderVersion)return;const n=Math.ceil(this._width*this._resolution),r=Math.ceil(this._height*this._resolution);this._ctx.clearRect(0,0,n,r),this._ctx.drawImage(s,0,0,n,r),this._texture.updateSource()}_buildSvg(){const t=this._width,e=this._height,i=this._fonts.map(({family:t,dataUri:e})=>`@font-face{font-family:'${t.replaceAll("\\","\\\\").replaceAll("'","\\'")}';src:url('${e}');}`).join(""),s=this._css.replaceAll(/<\/style>/gi,"<\\/style>");return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${e}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="width:${t}px;height:${e}px;overflow:hidden;box-sizing:border-box;">${i||s?`<style>${i}${s}</style>`:""}${this._html}</div></foreignObject></svg>`}_buildMesh(){const t=this._width,e=this._height;return new Us({vertices:new Float32Array([0,0,t,0,t,e,0,e]),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 t=Math.ceil(this._width*this._resolution),e=Math.ceil(this._height*this._resolution);this._canvas.width=t,this._canvas.height=e,this._texture.updateSource()}static _toBase64(t){const e=new Uint8Array(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}static _makeCanvas(t,e){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(t,e),s=i.getContext("2d");if(!s)throw new Error("HTMLText: could not obtain 2D context.");return[i,s]}const i=document.createElement("canvas");i.width=t,i.height=e;const s=i.getContext("2d");if(!s)throw new Error("HTMLText: could not obtain 2D context.");return[i,s]}}class cc{_context;_sampler;_scaleMode;_wrapMode;constructor(t,e){const{scaleMode:i,wrapMode:s}=e;this._context=t,this._sampler=t.createSampler(),this._scaleMode=i,this._wrapMode=s,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this.updateScaleModeParameters()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this.updateWrapModeParameters()),this}bind(t){return this._context.bindSampler(t,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 t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_MAG_FILTER,this._scaleMode),t.samplerParameteri(this._sampler,t.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_S,this._wrapMode),t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_T,this._wrapMode)}}const dc=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"];class _c{name;version;_storeNames;_migrations;_onCloseHandler=this.disconnect.bind(this);_connected=!1;_database=null;get connected(){return this._connected}constructor(t,e=1,i=dc,s){if(!c)throw new Error("This browser does not support indexedDB!");this.name=t,this.version=e,this._storeNames=i,this._migrations=s}async getObjectStore(t,e="readonly"){return await this.connect(),this._database.transaction([t],e).objectStore(t)}async connect(){return!(!this._connected||!this._database)||new Promise((t,e)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",t=>{const s=i.result,n=i.transaction,r=[...n.objectStoreNames],{oldVersion:o,newVersion:a}=t;if(s.addEventListener("error",()=>e(new Error("An error occurred while opening the database."))),s.addEventListener("abort",()=>e(new Error("The database opening was aborted."))),this._migrations){const t=Object.keys(this._migrations).map(Number).filter(t=>t>o&&t<=(a??this.version)).sort((t,e)=>t-e);for(const e of t){const t=this._migrations[e];if(void 0===t)continue;if(!t(s,n))return void n.abort()}}else{for(const t of r)this._storeNames.includes(t)||s.deleteObjectStore(t);for(const t of this._storeNames)r.includes(t)||s.createObjectStore(t,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,t(!0)}),i.addEventListener("error",()=>e(new Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>e(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(t,e){const i=await this.getObjectStore(t);return new Promise((t,s)=>{const n=i.get(e);n.addEventListener("success",()=>t(n.result?.data??null)),n.addEventListener("error",()=>s(new Error("An error occurred while loading an item.")))})}async save(t,e,i){const s=await this.getObjectStore(t,"readwrite");return new Promise((t,n)=>{const r=s.put({name:e,data:i});r.addEventListener("success",()=>t()),r.addEventListener("error",()=>n(new Error("An error occurred while saving an item.")))})}async delete(t,e){const i=await this.getObjectStore(t,"readwrite");return new Promise((t,s)=>{const n=i.delete(e);n.addEventListener("success",()=>t(!0)),n.addEventListener("error",()=>s(new Error("An error occurred while deleting an item.")))})}async clearStorage(t){const e=await this.getObjectStore(t,"readwrite");return new Promise((t,i)=>{const s=e.clear();s.addEventListener("success",()=>t(!0)),s.addEventListener("error",()=>i(new Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((t,e)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>t(!0)),i.addEventListener("error",()=>e(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 fc{_db;constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new _c(e.name,e.version??1,e.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"],e.migrations)}async load(t,e){return this._db.load(t,e)}async save(t,e,i){return this._db.save(t,e,i)}async delete(t,e){return this._db.delete(t,e)}async clear(t){return this._db.clearStorage(t)}destroy(){this._db.destroy()}}class pc{_storeName;_store;constructor(t="exojs-kv-store"){const e="string"==typeof t?{name:t}:t,i=e.storeName??"__kv_store";this._storeName=i,this._store=new fc({name:e.name,...void 0!==e.version&&{version:e.version},...void 0!==e.migrations&&{migrations:e.migrations},storeNames:[i]})}async get(t){return await this._store.load(this._storeName,t)}async set(t,e){await this._store.save(this._storeName,t,e)}async has(t){return null!==await this._store.load(this._storeName,t)}async delete(t){return this._store.delete(this._storeName,t)}async clear(){return this._store.clear(this._storeName)}destroy(){this._store.destroy()}}class gc{_map=new Map;get(t){return Promise.resolve(this._map.has(t)?this._map.get(t):null)}set(t,e){return this._map.set(t,e),Promise.resolve()}has(t){return Promise.resolve(this._map.has(t))}delete(t){return Promise.resolve(this._map.delete(t))}clear(){return this._map.clear(),Promise.resolve(!0)}}class mc{async resolve(t,e){const{url:i,requestOptions:s,factory:n,options:r}=t,o=await fetch(i,s);if(!o.ok)throw new Error(`Failed to fetch "${i}" (${o.status} ${o.statusText}).`);const a=await n.process(o);return n.create(a,r)}}class yc{_storage;_prefix;constructor(t,e={}){this._storage=t,this._prefix=e.prefix??""}get(t){const e=this._storage.getItem(this._prefix+t);if(null===e)return Promise.resolve(null);try{return Promise.resolve(JSON.parse(e))}catch{return Promise.reject(new Error(`WebStorageStore.get() failed: stored value for key "${t}" is not valid JSON.`))}}set(t,e){let i;try{i=JSON.stringify(e)}catch{return Promise.reject(new Error("WebStorageStore.set() failed: value is not JSON-serializable."))}return this._storage.setItem(this._prefix+t,i),Promise.resolve()}has(t){return Promise.resolve(null!==this._storage.getItem(this._prefix+t))}delete(t){const e=this._prefix+t,i=null!==this._storage.getItem(e);return this._storage.removeItem(e),Promise.resolve(i)}clear(){if(""===this._prefix)return this._storage.clear(),Promise.resolve(!0);const t=[];for(let e=0;e<this._storage.length;e++){const i=this._storage.key(e);!0===i?.startsWith(this._prefix)&&t.push(i)}for(const e of t)this._storage.removeItem(e);return Promise.resolve(!0)}}class wc extends Ao{storageName="json";async process(t){return t.json()}async create(t){return t}}class xc extends Ao{storageName="text";async process(t){return t.text()}async create(t){return t}}export{Ao as AbstractAssetFactory,Bn as AbstractText,Ah as AnimatedSprite,zl as Application,Dl as ApplicationStatus,zi as ArcadeStickGamepadMapping,Ea as Asset,Oa as Assets,Q as AudioBus,Z as AudioEffect,he as AudioGenerator,le as AudioInput,ue as AudioListener,de as AudioManager,fe as AudioStream,ua as BinaryAsset,Eo as BinaryFactory,pe as BiquadEffect,Rn as BitmapText,ni as BlendModes,wu as BlurFilter,Cn as BmFont,En as BmFontAdapter,Io as BmFontLoaderFactory,Ie as Bounds,hi as BufferTypes,li as BufferUsage,Ia as BundleLoadError,Jh as Button,Va as CacheFirstStrategy,pu as CallbackRenderPass,Zr as Camera,Ha as Capabilities,Mi as ChannelOffset,Ti as ChannelSize,iu as Circle,Ii as Clock,jt as Collision,tt as CollisionType,Ee as Color,xu as ColorFilter,Bi as Container,aa as CsvAsset,Lo as CsvFactory,In as DataTexture,nh as DisposalScope,Ls as Drawable,e as Ease,su as Ellipse,me as Envelope,yu as Filter,Re as Flags,Ri as FocusManager,la as FontAsset,Uo as FontFactory,$i as GameCubeGamepadMapping,Fi as Gamepad,qi as GamepadAxis,Gi as GamepadButton,Vi as GamepadMapping,Oi as GamepadMappingFamily,tu as GamepadPromptLayouts,Wi as GenericDualAnalogGamepadMapping,Lu as Geometry,zn as GlyphAtlas,Fu as Gradient,Mh as Graphics,uc as HTMLText,ye as HighpassFilter,ha as ImageAsset,No as ImageFactory,_c as IndexedDbDatabase,pc as IndexedDbKeyValueStore,fc as IndexedDbStore,Ui as InputBinding,ws as InputManager,vs as InteractionEvent,bs as InteractionManager,ft as Interval,Xi as JoyConLeftGamepadMapping,ji as JoyConRightGamepadMapping,ia as Json,wc as JsonFactory,Ci as KeyEvent,Ei as Keyboard,tl as Label,ru as Line,Nu as LinearGradient,Wa as Loader,Ya as LoadingQueue,we as LowpassFilter,Tu as LutFilter,Qu as Material,K as MathUtils,De as Matrix,gc as MemoryStore,Us as Mesh,Th as MeshBuilder,Zu as MeshMaterial,Vo as MusicFactory,mc as NetworkOnlyStrategy,dn as NineSliceSprite,ii as ObservableSize,Ht as ObservableVector,el as Panel,Wl as Perf,Hi as PlayStationGamepadMapping,gs as Pointer,ps as PointerState,fs as PointerStateFlag,ou as PolarVector,hu as Polygon,$l as Prefab,il as ProgressBar,xs as Quadtree,Ou as RadialGradient,Cs as Random,Zt as Rectangle,jn as RenderBackendType,Jr as RenderBatch,Si as RenderNode,gu as RenderNodePass,fu as RenderPass,mu as RenderPipeline,di as RenderTarget,_i as RenderTexture,io as RenderingContext,ai as RenderingPrimitives,vn as RepeatingSprite,wl as SERIALIZATION_VERSION,cc as Sampler,ri as ScaleModes,El as Scene,kl as SceneManager,Ge as SceneNode,uu as Segment,gl as SerializationRegistry,Xn as Shader,Jn as ShaderAttribute,ui as ShaderPrimitives,tc as ShaderSource,tr as ShaderUniform,m as Signal,o as Size,ae as Sound,zo as SoundFactory,oe as SoundPoolStrategy,Sn as Sprite,bn as SpriteFlags,ac as SpriteMaterial,hc as Spritesheet,sl as Stack,Ki as SteamControllerGamepadMapping,Qi as SteamDeckGamepadMapping,ra as SubtitleAsset,Ho as SubtitleFactory,na as SvgAsset,Ko as SvgFactory,_u as Sweep,Zi as SwitchProGamepadMapping,Ml as SystemRegistry,$n as Text,sa as TextAsset,xc as TextFactory,An as TextStyle,pi as Texture,Qo as TextureFactory,Ws as TextureRegion,Di as Time,Li as Timer,s as Tween,n as TweenManager,i as TweenState,sh as UIRoot,te as Vector,Po as Video,Jo as VideoFactory,ci as View,si as ViewFlags,ca as WasmAsset,ta as WasmFactory,bu as WebGl2ShaderFilter,Cu as WebGpuShaderFilter,yc as WebStorageStore,Zh as Widget,Se as WorkletEffect,oi as WrapModes,Ji as XboxGamepadMapping,oa as XmlAsset,ea as XmlFactory,ql as buildInfo,to as createRenderStats,ge as crossFade,U as decodeAudioData,La as defineAssetManifest,D as getAudioContext,L as getOfflineAudioContext,I as isAudioContextReady,Pi as maxPointers,k as onAudioContextReady,Ai as pointerSlotSize,be as registerAudioWorkletProcessor,yl as registerSerializer,eo as resetRenderStats};
|
|
1
|
+
const t=t=>{const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375};class e{static linear=t=>t;static quadIn=t=>t*t;static quadOut=t=>t*(2-t);static quadInOut=t=>t<.5?2*t*t:(4-2*t)*t-1;static cubicIn=t=>t*t*t;static cubicOut=t=>--t*t*t+1;static cubicInOut=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;static quartIn=t=>t*t*t*t;static quartOut=t=>1- --t*t*t*t;static quartInOut=t=>t<.5?8*t*t*t*t:1-Math.pow(-2*t+2,4)/2;static quintIn=t=>t*t*t*t*t;static quintOut=t=>1+--t*t*t*t*t;static quintInOut=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;static sineIn=t=>1-Math.cos(t*Math.PI/2);static sineOut=t=>Math.sin(t*Math.PI/2);static sineInOut=t=>-(Math.cos(Math.PI*t)-1)/2;static expoIn=t=>0===t?0:Math.pow(2,10*t-10);static expoOut=t=>1===t?1:1-Math.pow(2,-10*t);static expoInOut=t=>0===t?0:1===t?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2;static circIn=t=>1-Math.sqrt(1-Math.pow(t,2));static circOut=t=>Math.sqrt(1-Math.pow(t-1,2));static circInOut=t=>t<.5?(1-Math.sqrt(1-Math.pow(2*t,2)))/2:(Math.sqrt(1-Math.pow(-2*t+2,2))+1)/2;static backIn=t=>{const e=1.70158;return 2.70158*t*t*t-e*t*t};static backOut=t=>{const e=1.70158;return 1+2.70158*Math.pow(t-1,3)+e*Math.pow(t-1,2)};static backInOut=t=>{const e=2.5949095;return t<.5?Math.pow(2*t,2)*(7.189819*t-e)/2:(Math.pow(2*t-2,2)*((e+1)*(2*t-2)+e)+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=t=>{if(0===t)return 0;if(1===t)return 1;const e=2*Math.PI/3;return-Math.pow(2,10*t-10)*Math.sin((10*t-10.75)*e)};static elasticOut=t=>{if(0===t)return 0;if(1===t)return 1;const e=2*Math.PI/3;return Math.pow(2,-10*t)*Math.sin((10*t-.75)*e)+1};static elasticInOut=t=>{if(0===t)return 0;if(1===t)return 1;const e=2*Math.PI/4.5;return t<.5?-Math.pow(2,20*t-10)*Math.sin((20*t-11.125)*e)/2:Math.pow(2,-20*t+10)*Math.sin((20*t-11.125)*e)/2+1}}var i,n;!function(t){t.Idle="idle",t.Active="active",t.Paused="paused",t.Complete="complete",t.Stopped="stopped"}(i||(i={}));class s{_target;_state=i.Idle;_properties={};_startValues=null;_duration=0;_delay=0;_easing=e.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(t){this._target=t}get target(){return this._target}get state(){return this._state}get progress(){if(0===this._duration)return 1;const t=Math.min(this._elapsed/this._duration,1),e=1===this._direction?t:1-t;return this._easing(e)}to(t,e){return this._properties={...t},this._duration=e,this._startValues=null,this}delay(t){return this._delay=t,this}easing(t){return this._easing=t,this}repeat(t){return this._repeatTotal=t,this}yoyo(t=!0){return this._yoyo=t,this}onStart(t){return this._onStart=t,this}onUpdate(t){return this._onUpdate=t,this}onComplete(t){return this._onComplete=t,this}onRepeat(t){return this._onRepeat=t,this}start(){return this._state=i.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===i.Active&&(this._state=i.Paused),this}resume(){return this._state===i.Paused&&(this._state=i.Active),this}stop(){return this._state!==i.Active&&this._state!==i.Paused||(this._state=i.Stopped,this._manager?.remove(this)),this}chain(t){return this._chained=t,t}_attachManager(t){this._manager=t}update(t){if(this._state===i.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 t=this._elapsed-this._duration;this._elapsed=t>0?Math.min(t,this._duration):0,t>0&&this._applyProgress()}else this._complete()}}}_captureStartValues(){const t={},e=Object.keys(this._properties);for(const i of e){const e=this._target[i];"number"==typeof e&&(t[String(i)]=e)}this._startValues=t}_applyProgress(){if(null===this._startValues)return;const t=0===this._duration?1:Math.min(this._elapsed/this._duration,1),e=1===this._direction?t:1-t,i=this._easing(e),n=Object.keys(this._startValues),s=this._properties;for(const t of n){const e=this._startValues[t],n=s[t];void 0!==e&&void 0!==n&&(this._target[t]=e+(n-e)*i)}this._onUpdate?.(i)}_complete(){this._elapsed=this._duration,this._applyProgress(),this._state=i.Complete,this._manager?.remove(this),this._onComplete?.(),this._chained?.start()}}!function(t){t.Idle="idle",t.Active="active",t.Paused="paused",t.Complete="complete",t.Stopped="stopped"}(n||(n={}));class r{_stages=[];_state=n.Idle;_manager;_currentStageIndex=0;_direction=1;_repeatCount=0;_repeatTotal=0;_yoyo=!1;_delayElapsed=0;_onStartCb=null;_onCompleteCb=null;_startFired=!1;constructor(t){this._manager=t??null}get state(){return this._state}get progress(){const t=this._stages.length;return 0===t?1:Math.min(this._currentStageIndex/t,1)}then(t){const e=Array.isArray(t)?t:[t];return this._stages.push({type:"tweens",tweens:e}),this}wait(t){return this._stages.push({type:"delay",seconds:t}),this}repeat(t){return this._repeatTotal=t,this}yoyo(t=!0){return this._yoyo=t,this}onStart(t){return this._onStartCb=t,this}onComplete(t){return this._onCompleteCb=t,this}start(){return this._state=n.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===n.Active&&(this._state=n.Paused,this._pauseCurrentStageTweens()),this}resume(){return this._state===n.Paused&&(this._state=n.Active,this._resumeCurrentStageTweens()),this}stop(){return this._state!==n.Active&&this._state!==n.Paused||(this._state=n.Stopped,this._stopCurrentStageTweens(),this._manager?.removeTicker(this)),this}update(t){if(this._state!==n.Active)return;if(this._startFired||(this._startFired=!0,this._onStartCb?.()),0===this._stages.length)return void this._finish();const e=this._getActualStageIndex(),s=this._stages[e];if(void 0!==s)if("delay"===s.type)this._delayElapsed+=t,this._delayElapsed>=s.seconds&&this._advanceStage();else{if(null===this._manager)for(const e of s.tweens)e.state===i.Active&&e.update(t);s.tweens.every(t=>t.state===i.Complete||t.state===i.Stopped)&&this._advanceStage()}}_getActualStageIndex(){return 1===this._direction?this._currentStageIndex:this._stages.length-1-this._currentStageIndex}_startCurrentStage(){const t=this._getActualStageIndex(),e=this._stages[t];if(void 0!==e&&(this._delayElapsed=0,"tweens"===e.type))for(const t of e.tweens)null!==this._manager&&this._manager.add(t),t.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=n.Complete,this._manager?.removeTicker(this),this._onCompleteCb?.()}_getCurrentStageTweens(){if(0===this._stages.length)return[];const t=this._getActualStageIndex(),e=this._stages[t];return"tweens"===e?.type?e.tweens:[]}_pauseCurrentStageTweens(){for(const t of this._getCurrentStageTweens())t.pause()}_resumeCurrentStageTweens(){for(const t of this._getCurrentStageTweens())t.resume()}_stopCurrentStageTweens(){for(const t of this._getCurrentStageTweens())t.stop()}}class o{order=400;_tweens=[];_tickers=[];_destroyed=!1;create(t){const e=new s(t);return e._attachManager(this),this._tweens.push(e),e}sequence(t){const[e]=t;if(void 0===e)throw new Error("[ExoJS] TweenManager.sequence() requires at least one tween.");for(let e=0;e<t.length-1;e++){const i=t[e],n=t[e+1];void 0!==i&&void 0!==n&&i.chain(n)}for(const e of t)this.add(e);return e}createSequencer(){return new r(this)}add(t){return t._attachManager(this),this._tweens.includes(t)||this._tweens.push(t),this}remove(t){const e=this._tweens.indexOf(t);return-1!==e&&this._tweens.splice(e,1),this}addTicker(t){return this._tickers.includes(t)||this._tickers.push(t),this}removeTicker(t){const e=this._tickers.indexOf(t);return-1!==e&&this._tickers.splice(e,1),this}update(t){if(this._destroyed)return;const e=[...this._tweens];for(const i of e)i.update(t.seconds);const i=[...this._tickers];for(const e of i)e.update(t.seconds)}clear(){return this._tweens=[],this._tickers=[],this}destroy(){this.clear(),this._destroyed=!0}}let a=null;class h{_width;_height;constructor(t=0,e=0){this._width=t,this._height=e}get width(){return this._width}set width(t){this._width=t}get height(){return this._height}set height(t){this._height=t}set(t,e=t){return this._width=t,this._height=e,this}add(t,e=t){return this._width+=t,this._height+=e,this}subtract(t,e=t){return this._width-=t,this._height-=e,this}scale(t,e=t){return this._width*=t,this._height*=e,this}divide(t,e=t){return this._width/=t,this._height/=e,this}copy(t){return this._width=t.width,this._height=t.height,this}clone(){return new h(this._width,this._height)}equals({width:t,height:e}={}){return!(void 0!==t&&this.width!==t||void 0!==e&&this.height!==e)}destroy(){}static zero=new h(0,0);static get temp(){return null===a&&(a=new h),a}}let l=null,u=null;const c=()=>{if("undefined"==typeof document)throw new Error("Canvas operations require a document context.");return null===l&&(l=document.createElement("canvas")),l},d=t=>{t.preventDefault(),t.stopImmediatePropagation()},_="undefined"!=typeof indexedDB,f=()=>performance.now(),p=new ArrayBuffer(0),m=(t,e,i)=>{if(e<t.length&&i>0){const n=e+i>t.length?t.length-e:i,s=t.length-n;for(let i=e;i<s;i++)t[i]=t[i+n];t.length=s}return t},g=t=>{const e=t;return t instanceof HTMLImageElement?h.temp.set(t.naturalWidth,t.naturalHeight):t instanceof HTMLVideoElement?h.temp.set(t.videoWidth,t.videoHeight):t instanceof SVGElement?h.temp.copy(t.getBoundingClientRect()):"number"==typeof e.displayWidth&&"number"==typeof e.displayHeight?h.temp.set(e.displayWidth,e.displayHeight):"number"==typeof e.width&&"number"==typeof e.height?h.temp.set(e.width,e.height):h.zero},y=t=>{const{width:e,height:i}=g(t),n=c();return n.width=e,n.height=i,(()=>{if(null===u){const t=c().getContext("2d");if(!t)throw new Error("Could not create a 2D canvas context.");u=t}return u})().drawImage(t,0,0,e,i),n.toDataURL()};class w{_handlers=[];_dispatching=!1;_pendingRemoves=null;get count(){return this._handlers.length}has(t){return this._handlers.includes(t)}add(t){return this._handlers.includes(t)||this._handlers.push(t),this}once(t){const e=(...i)=>{this.remove(e),t(...i)};return this._handlers.push(e),this}remove(t){if(this._dispatching)(this._pendingRemoves??=[]).push(t);else{const e=this._handlers.indexOf(t);-1!==e&&m(this._handlers,e,1)}return this}clear(){return this._dispatching?this._pendingRemoves=[...this._handlers]:this._handlers.length=0,this}dispatch(...t){const e=this._handlers.length;if(!e)return this;this._dispatching=!0;for(let i=0;i<e&&!1!==this._handlers[i](...t);i++);if(this._dispatching=!1,null!==this._pendingRemoves){for(const t of this._pendingRemoves){const e=this._handlers.indexOf(t);-1!==e&&m(this._handlers,e,1)}this._pendingRemoves=null}return this}destroy(){this._handlers.length=0,this._pendingRemoves=null}}const x=["mousedown","touchstart","touchend","keydown"];let v=null,b=null,S=!1,B=!1,C=!1;const T=()=>"undefined"!=typeof document,M=()=>v,A=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===v&&(v=new AudioContext),v},P=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===b){const t=A();b=new OfflineAudioContext(1,2,t.sampleRate)}return b},E=()=>{const t=M();"running"!==t?.state||C||(C=!0,(()=>{if(S&&T()){for(const t of x)document.removeEventListener(t,D,!1);S=!1}})(),I.dispatch(t))},k=()=>{E()},R=()=>{const t=A();B||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",k),B=!0),E(),C||(()=>{if(!S&&T()){for(const t of x)document.addEventListener(t,D,!1);S=!0}})()},D=()=>{const t=A();"running"!==t.state?t.resume().then(()=>{E()}):E()};const I=new class extends w{add(t){return super.add(t),R(),this}once(t){return super.once(t),R(),this}},L=()=>{const t=A();return R(),t},U=()=>{const t=M();return null!==t&&"running"===t.state},F=()=>P(),G=async t=>P().decodeAudioData(t),N=2*Math.PI,O=Math.PI/180,V=180/Math.PI;var z;!function(t){t[t.left=-1]="left",t[t.middle=0]="middle",t[t.right=1]="right"}(z||(z={}));const q=t=>{const e=t%360;return e<0?e+360:e},W=t=>t*O,Y=(t,e,i)=>Math.min(i,Math.max(e,t)),$=(t,e,i)=>(1-i)*t+i*e,X=t=>0!==t&&!(t&t-1),H=(t,e,i)=>t>=Math.min(e,i)&&t<=Math.max(e,i),j=(t,e,i,n)=>{const s=t-i,r=e-n;return Math.sqrt(s*s+r*r)},K=(t,e,i,n,s,r,o,a,h=[],l=20)=>{h.push(t,e);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*t+3*_*c*i+3*d*p*s+m*o,f*e+3*_*c*n+3*d*p*r+m*a)}return h},Q=(t,e,i,n,s,r,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push($($(t,i,l),$(i,s,l),l),$($(e,n,l),$(n,r,l),l))}return o},Z={tau:N,clamp:Y,sign:t=>t&&(t<0?-1:1),lerp:$,inRange:H,isPowerOfTwo:X,distance:j,trimRotation:q,degreesToRadians:W,radiansToDegrees:t=>t*V,bezierCurveTo:K,quadraticCurveTo:Q};class J{name;_parent;_volume;_muted;_pan;_effects=[];_setup=null;_scheduledStopId=null;_onAudioContextReady=t=>{I.remove(this._onAudioContextReady),this._setupAudio(t)};constructor(t,e={}){if(!t||"string"!=typeof t)throw new Error("AudioBus requires a non-empty string name.");this.name=t,this._parent=e.parent??null,this._volume=Y(e.volume??1,0,2),this._muted=e.muted??!1,this._pan=Y(e.pan??0,-1,1),e.effects&&this._effects.push(...e.effects),U()?this._setupAudio(L()):I.add(this._onAudioContextReady)}get parent(){return this._parent}get volume(){return this._volume}set volume(t){const e=Y(t,0,2);this._volume!==e&&(this._volume=e,this._applyVolume())}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this._applyVolume())}get pan(){return this._pan}set pan(t){const e=Y(t,-1,1);this._pan!==e&&(this._pan=e,this._setup&&this._setup.panNode.pan.setTargetAtTime(e,this._setup.audioContext.currentTime,.01))}get inputNode(){return this._setup?.inputNode??null}addEffect(t){return this._effects.push(t),this._rebuildEffectChain(),this}removeEffect(t){const e=this._effects.indexOf(t);return-1!==e&&(this._effects.splice(e,1),this._rebuildEffectChain()),this}fadeIn(t){if(this._clearScheduledStop(),t<=0||!this._setup)return this;const e=this._setup.audioContext,i=this._setup.outputNode,n=this._muted?0:this._volume;return i.gain.cancelScheduledValues(e.currentTime),i.gain.setValueAtTime(0,e.currentTime),i.gain.linearRampToValueAtTime(n,e.currentTime+t/1e3),this}fadeOut(t,e={}){const i=e.stopAfter??!0;if(this._clearScheduledStop(),t<=0||!this._setup)return i&&(this.muted=!0),this;const n=this._setup.audioContext,s=this._setup.outputNode;return s.gain.cancelScheduledValues(n.currentTime),s.gain.setValueAtTime(s.gain.value,n.currentTime),s.gain.linearRampToValueAtTime(0,n.currentTime+t/1e3),i&&(this._scheduledStopId=setTimeout(()=>{this._scheduledStopId=null,this.muted=!0},t)),this}destroy(){I.remove(this._onAudioContextReady),this._clearScheduledStop();for(const t of this._effects)t.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(t){const e=t.createGain(),i=t.createStereoPanner(),n=t.createGain();n.gain.setTargetAtTime(this._muted?0:this._volume,t.currentTime,.01),i.pan.setTargetAtTime(this._pan,t.currentTime,.01),this._setup={audioContext:t,inputNode:e,outputNode:n,panNode:i},this._rebuildEffectChain(),this._connectUpstream()}_connectUpstream(){if(this._setup)if(this._parent){const t=this._parent._getInputNode();t?this._setup.outputNode.connect(t):this._parent.onceSetup(()=>{if(this._setup&&this._parent){const t=this._parent._getInputNode();t&&this._setup.outputNode.connect(t)}})}else this._setup.outputNode.connect(this._setup.audioContext.destination)}onceSetup(t){this._setup?t():I.once(()=>{this._setup&&t()})}_rebuildEffectChain(){if(!this._setup)return;const{inputNode:t,panNode:e}=this._setup;t.disconnect();for(const t of this._effects)t.inputNode.disconnect(),t.outputNode.disconnect();e.disconnect();let i=t;for(const t of this._effects)i.connect(t.inputNode),i=t.outputNode;i.connect(e),e.connect(this._setup.outputNode)}_applyVolume(){if(!this._setup)return;const t=this._muted?0:this._volume;this._setup.outputNode.gain.setTargetAtTime(t,this._setup.audioContext.currentTime,.01)}_clearScheduledStop(){null!==this._scheduledStopId&&(clearTimeout(this._scheduledStopId),this._scheduledStopId=null)}}class tt{get ready(){return Promise.resolve()}}class et{get angle(){return Math.atan2(this.y,this.x)}set angle(t){const e=this.length;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(t){const e=this.angle;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(t){this.length=Math.sqrt(t)}set(t,e=t){return this.x=t,this.y=e,this}equals({x:t,y:e}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e)}add(t,e=t){return this.x+=t,this.y+=e,this}subtract(t,e=t){return this.x-=t,this.y-=e,this}multiply(t,e=t){return this.x*=t,this.y*=e,this}divide(t,e=t){return 0!==t&&0!==e&&(this.x/=t,this.y/=e),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(t){return this.set(this.x*t.a+this.y*t.b+t.x,this.x*t.c+this.y*t.d+t.y)}transformInverse(t){const e=t.a*t.d-t.b*t.c,i=this.x-t.x,n=this.y-t.y;return this.set((t.d*i-t.b*n)/e,(t.a*n-t.c*i)/e)}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(t,e){return this.x*t+this.y*e}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){return j(this.x,this.y,t.x,t.y)}}var it;!function(t){t[t.Point=0]="Point",t[t.Line=1]="Line",t[t.Rectangle=2]="Rectangle",t[t.Circle=3]="Circle",t[t.Ellipse=4]="Ellipse",t[t.Polygon=5]="Polygon",t[t.SceneNode=6]="SceneNode"}(it||(it={}));const nt=1e-10,st=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),rt=({x:t,y:e,rx:i,ry:n})=>{if(i<=0||n<=0)return[];const s=st(i,n),r=2*Math.PI/s,o=[];for(let a=0;a<s;a++){const s=a*r;o.push({x:t+Math.cos(s)*i,y:e+Math.sin(s)*n})}return o},ot=({x:t,y:e},{x:i,y:n},{x:s,y:r})=>t<=Math.max(i,s)+nt&&t>=Math.min(i,s)-nt&&e<=Math.max(n,r)+nt&&e>=Math.min(n,r)-nt,at=({x:t,y:e},{x:i,y:n},{x:s,y:r})=>{const o=(n-e)*(s-i)-(i-t)*(r-n);return Math.abs(o)<=nt?0:o>0?1:2},ht=(t,e,i,n)=>{const s=at(t,e,i),r=at(t,e,n),o=at(i,n,t),a=at(i,n,e);return s!==r&&o!==a||(!(0!==s||!ot(i,t,e))||(!(0!==r||!ot(n,t,e))||(!(0!==o||!ot(t,i,n))||!(0!==a||!ot(e,i,n)))))},lt=({x:t,y:e},i)=>{const n=i.length;if(n<3)return!1;let s=!1;for(let r=0,o=n-1;r<n;o=r++){const n=i[o],a=i[r];a.y>e!=n.y>e&&t<(n.x-a.x)*((e-a.y)/(n.y-a.y))+a.x&&(s=!s)}return s},ut=(t,e)=>{if(0===t.length||0===e.length)return!1;for(let i=0;i<t.length;i++){const n=t[i],s=t[(i+1)%t.length];for(let t=0;t<e.length;t++){const i=e[t],r=e[(t+1)%e.length];if(ht(n,s,i,r))return!0}}return lt(t[0],e)||lt(e[0],t)},ct=({x:t,y:e},{x:i,y:n},{x:s,y:r},o=.1)=>{const a=j(t,e,i,n),h=j(t,e,s,r),l=j(i,n,s,r);return a+h>=l-o&&a+h<=l+o},dt=(t,e,i,n)=>{const s=(e.x-t.x)*(n.y-i.y)-(n.x-i.x)*(e.y-t.y);if(Math.abs(s)<=nt)return!1;const r=((n.x-i.x)*(t.y-i.y)-(n.y-i.y)*(t.x-i.x))/s,o=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/s;return r>=0&&r<=1&&o>=0&&o<=1},_t=(t,e)=>Math.sqrt(t*t+e*e),ft=(t,e,i,n)=>{const s=i*t+n*e;const r=(o=t)*o+(a=e)*a;var o,a;return s<0?z.left:s>r?z.right:z.middle};let pt=null;class mt{min;max;constructor(t=0,e=t){this.min=t,this.max=e}set(t,e){return this.min=t,this.max=e,this}copy(t){return this.set(t.min,t.max)}clone(){return new mt(this.min,this.max)}containsInterval(t){return t.min>this.min&&t.max<this.max}includes(t){return t<=this.max&&t>=this.min}overlaps(t){return!(this.min>t.max||t.min>this.max)}getOverlap(t){return this.max<t.max?this.max-t.min:t.max-this.min}destroy(){}static zero=new mt(0,0);static get temp(){return null===pt&&(pt=new mt),pt}}const gt=(t,e)=>{const i=t.getNormals(),n=e.getNormals(),s=new mt,r=new mt;for(const n of i)if(t.project(n,s),e.project(n,r),!s.overlaps(r))return!1;for(const i of n)if(t.project(i,s),e.project(i,r),!s.overlaps(r))return!1;return!0},yt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:n},s=0)=>j(t,e,i,n)<=s)(t,e,i),wt=(t,e,i=.1)=>ct(t,e.fromPosition,e.toPosition,i),xt=(t,e)=>(({x:t,y:e},{x:i,y:n,width:s,height:r})=>H(t,i,i+s)&&H(e,n,n+r))(t,e),vt=(t,e)=>(({x:t,y:e},{x:i,y:n,radius:s})=>s>0&&j(t,e,i,n)<=s)(t,e),bt=(t,e)=>(({x:t,y:e},{x:i,y:n,rx:s,ry:r})=>{if(s<=0||r<=0)return!1;const o=(t-i)/s,a=(e-n)/r;return o*o+a*a<=1})(t,e),St=(t,e)=>((t,{x:e,y:i,points:n})=>lt({x:t.x-e,y:t.y-i},n))(t,e),Bt=(t,e)=>dt(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),Ct=(t,e)=>{const{x:i,y:n,width:s,height:r}=e,o={x:i,y:n},a={x:i+s,y:n},h={x:i,y:n+r},l={x:i+s,y:n+r};return dt(t.fromPosition,t.toPosition,o,h)||dt(t.fromPosition,t.toPosition,a,l)||dt(t.fromPosition,t.toPosition,o,a)||dt(t.fromPosition,t.toPosition,h,l)},Tt=(t,e)=>{if(vt(t.fromPosition,e)||vt(t.toPosition,e))return!0;const{fromX:i,fromY:n,toX:s,toY:r}=t,{x:o,y:a,radius:h}=e,l=j(i,n,s,r);if(0===l)return!1;const u=((o-i)*(s-i)+(a-n)*(r-n))/(l*l),c=i+u*(s-i),d=n+u*(r-n);return!!ct({x:c,y:d},t.fromPosition,t.toPosition)&&j(c,d,o,a)<=h},Mt=(t,e)=>{const{x:i,y:n,rx:s,ry:r}=e;if(s<=0||r<=0)return!1;const o=(t.fromX-i)/s,a=(t.fromY-n)/r,h=(t.toX-i)/s-o,l=(t.toY-n)/r-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},At=(t,e)=>{const{x:i,y:n,points:s}=e,r=s.length;for(let e=0;e<r;e++){const o=s[e],a=s[(e+1)%r];if(dt(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+n},{x:a.x+i,y:a.y+n}))return!0}return!1},Pt=(t,e)=>(({x:t,y:e,width:i,height:n},{x:s,y:r,width:o,height:a})=>!(s>t+i||r>e+n||t>s+o||e>r+a))(t,e),Et=({x:t,y:e,width:i,height:n},{x:s,y:r,radius:o})=>{const a=Y(s,t,t+i),h=Y(r,e,e+n);return j(s,r,a,h)<=o},kt=(t,e)=>ut((({x:t,y:e,width:i,height:n})=>[{x:t,y:e},{x:t+i,y:e},{x:t+i,y:e+n},{x:t,y:e+n}])(t),rt(e)),Rt=(t,e)=>gt(t,e),Dt=({x:t,y:e,radius:i},{x:n,y:s,radius:r})=>j(t,e,n,s)<=i+r,It=(t,e)=>ut((({x:t,y:e,radius:i})=>{if(i<=0)return[];const n=st(i),s=2*Math.PI/n,r=[];for(let o=0;o<n;o++){const n=o*s;r.push({x:t+Math.cos(n)*i,y:e+Math.sin(n)*i})}return r})(t),rt(e)),Lt=(t,e,i,n,s,r,o,a,h)=>{if(ft(a,h,s,r)!==z.left)return!1;return ft(n.x,n.y,t-i.x,e-i.y)===z.right&&_t(s,r)>o},Ut=(t,e,i,n,s,r,o,a,h)=>{if(ft(a,h,s,r)!==z.right)return!1;const l=t-i.x,u=e-i.y;return ft(n.x,n.y,l,u)===z.left&&_t(l,u)>o},Ft=(t,e,i,n,s)=>{const r=s,o=-n,a=_t(r,o);if(0===a)return!1;const h=(t*r+e*o)/a;return h>0&&Math.abs(h)>i},Gt=({x:t,y:e,radius:i},{x:n,y:s,points:r,edges:o})=>{const a=t-n,h=e-s,l=r.length;for(let t=0;t<l;t++){const e=r[t],n=a-e.x,s=h-e.y,u=0===t?l-1:t-1,c=(t+1)%l,d=o[t];if(Lt(a,h,r[u],o[u],n,s,i,d.x,d.y))return!1;if(Ut(a,h,r[c],o[c],n,s,i,d.x,d.y))return!1;if(Ft(n,s,i,d.x,d.y))return!1}return!0},Nt=(t,e)=>ut(rt(t),rt(e)),Ot=(t,e)=>ut(rt(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:n})=>({x:i+t,y:n+e})))(e)),Vt=(t,e)=>gt(t,e),zt=(t,e)=>{if(e.left>t.right||e.top>t.bottom)return null;if(t.left>e.right||t.top>e.bottom)return null;const i=Math.min(t.right,e.right)-Math.max(t.left,e.left),n=Math.min(t.bottom,e.bottom)-Math.max(t.top,e.top),s=t.left+.5*t.width,r=t.top+.5*t.height,o=e.left+.5*e.width,a=e.top+.5*e.height;let h,l,u;i<n?(u=i,h=o<s?-1:1,l=0):(u=n,h=0,l=a<r?-1:1);const c=new ie(h,l),d=new ie(h*u,l*u);return{shapeA:t,shapeB:e,overlap:u,shapeAinB:e.containsRect(t),shapeBinA:t.containsRect(e),projectionN:c,projectionV:d}},qt=(t,e)=>{const i=e.position.clone().subtract(t.x,t.y),n=i.length,s=t.radius+e.radius-n;if(s<0)return i.destroy(),null;const r=i.normalize(),o=r.clone().multiply(s);return{shapeA:t,shapeB:e,overlap:s,shapeAinB:t.radius<=e.radius&&n<=e.radius-t.radius,shapeBinA:e.radius<=t.radius&&n<=t.radius-e.radius,projectionN:r,projectionV:o}},Wt=(t,e,i=!1)=>{const n=t.radius,s=Math.max(e.left,Math.min(t.x,e.right)),r=Math.max(e.top,Math.min(t.y,e.bottom)),o=t.x-s,a=t.y-r,h=o*o+a*a;if(h>n*n)return null;const l=Math.sqrt(h),u=n-l,c=e.width/2,d=e.height/2,_=Math.min(c,d),f=Math.max(c,d),p=j(t.x,t.y,e.left+c,e.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=t.x-e.left,n=e.right-t.x,s=t.y-e.top,r=e.bottom-t.y;Math.min(i,n)<Math.min(s,r)?(y=i<n?-1:1,w=0):(y=0,w=s<r?-1:1)}const x=i?-y:y,v=i?-w:w,b=t.position.clone().set(x,v),S=t.position.clone().set(x*u,v*u);return{shapeA:i?e:t,shapeB:i?t:e,overlap:u,shapeAinB:i?g:m,shapeBinA:i?m:g,projectionN:b,projectionV:S}},Yt=(t,e,i=!1)=>{if(!kt(e,t))return null;const n=Math.max(e.left,Math.min(t.x,e.right)),s=Math.max(e.top,Math.min(t.y,e.bottom)),r=t.x-n,o=t.y-s,a=Math.sqrt(r*r+o*o);let h,l,u;if(a>0){h=r/a,l=o/a;u=1/Math.sqrt(h*h/(t.rx*t.rx)+l*l/(t.ry*t.ry))-a}else{const i=t.x-e.left,n=e.right-t.x,s=t.y-e.top,r=e.bottom-t.y,o=Math.min(i,n),a=Math.min(s,r);o<a?(h=i<n?-1:1,l=0,u=o+t.rx):(h=0,l=s<r?-1:1,u=a+t.ry)}const c=i?-h:h,d=i?-l:l,_=t.position.clone().set(c,d),f=t.position.clone().set(c*u,d*u);return{shapeA:i?e:t,shapeB:i?t:e,overlap:u,shapeAinB:!1,shapeBinA:!1,projectionN:_,projectionV:f}},$t=(t,e,i=!1)=>{if(!It(e,t))return null;const n=t.x-e.x,s=t.y-e.y,r=Math.sqrt(n*n+s*s);let o,a,h;if(r>0){o=n/r,a=s/r;h=1/Math.sqrt(o*o/(t.rx*t.rx)+a*a/(t.ry*t.ry))+e.radius-r}else t.rx<=t.ry?(o=1,a=0,h=t.rx+e.radius):(o=0,a=1,h=t.ry+e.radius);const l=i?-o:o,u=i?-a:a,c=t.position.clone().set(l,u),d=t.position.clone().set(l*h,u*h);return{shapeA:i?e:t,shapeB:i?t:e,overlap:h,shapeAinB:!1,shapeBinA:!1,projectionN:c,projectionV:d}},Xt=(t,e,i=!1)=>{const n=e.radius,s=t.points,r=e.x-t.x,o=e.y-t.y,a=e.position.clone().set(0,0),h=s.length;let l=!0,u=!0,c=1/0;for(let t=0;t<h;t++){const e=s[t],i=s[(t+1)%h],d=i.x-e.x,_=i.y-e.y,f=r-e.x,p=o-e.y,m=ft(d,_,f,p),g=_t(f,p);if(g>n&&(l=!1),m===z.left){const i=s[0===t?h-1:t-1],l=e.x-i.x,d=e.y-i.y,_=r-i.x,m=o-i.y;if(ft(l,d,_,m)===z.right){if(g>n)return a.destroy(),null;const t=n-g;Math.abs(t)<Math.abs(c)&&(c=t,a.set(f,p).normalize()),u=!1}}else if(m===z.right){const e=s[(t+2)%h],l=e.x-i.x,d=e.y-i.y,_=r-i.x,f=o-i.y,p=_t(_,f);if(ft(l,d,_,f)===z.left){if(p>n)return a.destroy(),null;const t=n-p;Math.abs(t)<Math.abs(c)&&(c=t,a.set(_,f).normalize()),u=!1}}else{const t=_,e=-d,i=_t(t,e),s=0===i?0:(f*t+p*e)/i;if(s>0&&Math.abs(s)>n)return a.destroy(),null;(s>=0||n-s<2*n)&&(u=!1);const r=n-s;Math.abs(r)<Math.abs(c)&&(c=r,a.set(t,e).normalize())}}const d=a.clone().multiply(c);return{shapeA:i?e:t,shapeB:i?t:e,overlap:c,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:d}},Ht=(t,e)=>{if(!Nt(t,e))return null;const i=t.x-e.x,n=t.y-e.y,s=Math.sqrt(i*i+n*n);let r,o,a;if(s>0){r=i/s,o=n/s;a=Math.sqrt((r*t.rx)**2+(o*t.ry)**2)+Math.sqrt((r*e.rx)**2+(o*e.ry)**2)-s}else t.rx<=t.ry?(r=1,o=0,a=t.rx+e.rx):(r=0,o=1,a=t.ry+e.ry);if(a<=0)return null;const h=t.position.clone().set(r,o),l=t.position.clone().set(r*a,o*a);return{shapeA:t,shapeB:e,overlap:a,shapeAinB:!1,shapeBinA:!1,projectionN:h,projectionV:l}},jt=(t,e)=>{const i=t.getNormals(),n=e.getNormals(),s=(i[0]||n[0]).clone(),r=new mt,o=new mt;let a,h,l,u=1/0,c=!0,d=!0;for(const n of i){if(t.project(n,r),e.project(n,o),!r.overlaps(o))return s.destroy(),null;l=r.getOverlap(o),a=o.containsInterval(r),h=r.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(r.min-o.min),Math.abs(r.max-o.max))),l<u&&(u=l,s.copy(n))}for(const i of n){if(t.project(i,r),e.project(i,o),!r.overlaps(o))return s.destroy(),null;l=r.getOverlap(o),a=o.containsInterval(r),h=r.containsInterval(o),!a&&c&&(c=!1),!h&&d&&(d=!1),(a||h)&&(l+=Math.min(Math.abs(r.min-o.min),Math.abs(r.max-o.max))),l<u&&(u=l,s.copy(i))}const _=s.clone().multiply(u,u);return{shapeA:t,shapeB:e,overlap:u,shapeAinB:c,shapeBinA:d,projectionN:s,projectionV:_}},Kt={intersects:{circleCircle:Dt,circleEllipse:It,circlePoly:Gt,ellipseEllipse:Nt,ellipsePoly:Ot,lineCircle:Tt,lineEllipse:Mt,lineLine:Bt,linePoly:At,lineRect:Ct,pointCircle:vt,pointEllipse:bt,pointLine:wt,pointPoint:yt,pointPoly:St,pointRect:xt,polyPoly:Vt,rectCircle:Et,rectEllipse:kt,rectPoly:Rt,rectRect:Pt},resolve:{circleCircle:qt,circleRectangle:Wt,ellipseCircle:$t,ellipseEllipse:Ht,ellipseRectangle:Yt,polygonCircle:Xt,rectangleRectangle:zt}};class Qt extends et{_x;_y;_owner;_channel;constructor(t,e=0,i=0,n=0){super(),this._x=i,this._y=n,this._owner=t,this._channel=e}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._owner?._onObservableChange(this._channel))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._owner?._onObservableChange(this._channel))}get angle(){return Math.atan2(this._y,this._x)}set angle(t){const e=this.length;this.set(Math.cos(t)*e,Math.sin(t)*e)}get length(){return Math.sqrt(this._x*this._x+this._y*this._y)}set length(t){const e=this.angle;this.set(Math.cos(e)*t,Math.sin(e)*t)}set(t=this._x,e=this._y){return this._x===t&&this._y===e||(this._x=t,this._y=e,this._owner?._onObservableChange(this._channel)),this}add(t,e=t){return this.set(this._x+t,this._y+e)}subtract(t,e=t){return this.set(this._x-t,this._y-e)}scale(t,e=t){return this.set(this._x*t,this._y*e)}divide(t,e=t){return 0!==t&&0!==e?this.set(this._x/t,this._y/e):this}clone(){return new Qt(this._owner,this._channel,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){this._owner=null}}let Zt=null;const Jt=new Qt(null);class te{collisionType=it.Rectangle;_position;_size;_normals=null;_normalsDirty=!1;constructor(t=0,e=t,i=0,n=i){this._position=new Qt(this,0,t,e),this._size=new h(i,n)}_onObservableChange(){this._normalsDirty=!0}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get size(){return this._size}set size(t){this._size.copy(t),this._normalsDirty=!0}get width(){return this._size.width}set width(t){this._size.width=t,this._normalsDirty=!0}get height(){return this._size.height}set height(t){this._size.height=t,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(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setSize(t,e){return this._size.set(t,e),this._normalsDirty=!0,this}set(t,e,i,n){return this.setPosition(t,e),this.setSize(i,n),this}copy(t){return this.position=t.position,this.size=t.size,this}clone(){return new te(this.x,this.y,this.width,this.height)}equals({x:t,y:e,width:i,height:n}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||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 ie,new ie,new ie,new ie])),this._normalsDirty=!1),this._normals}project(t,e=new mt){const i=t.dot(this.left,this.top),n=t.dot(this.right,this.top),s=t.dot(this.right,this.bottom),r=t.dot(this.left,this.bottom);return e.set(Math.min(i,n,s,r),Math.max(i,n,s,r))}transform(t,e=this){const i=Jt.set(this.left,this.top).transform(t);let n=i.x,s=i.x,r=i.y,o=i.y;return i.set(this.left,this.bottom).transform(t),n=Math.min(n,i.x),r=Math.min(r,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(t),n=Math.min(n,i.x),r=Math.min(r,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(t),n=Math.min(n,i.x),r=Math.min(r,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),e.set(n,r,s-n,o-r)}contains(t,e){return xt(Jt.set(t,e),this)}containsRect(t){return H(t.left,this.left,this.right)&&H(t.right,this.left,this.right)&&H(t.top,this.top,this.bottom)&&H(t.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case it.SceneNode:return t.isAlignedBox?Pt(this,t.getBounds()):gt(this,t);case it.Rectangle:return Pt(this,t);case it.Polygon:return Rt(this,t);case it.Circle:return Et(this,t);case it.Ellipse:return kt(this,t);case it.Line:return Ct(t,this);case it.Point:return xt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case it.SceneNode:return t.isAlignedBox?zt(this,t.getBounds()):jt(this,t);case it.Rectangle:return zt(this,t);case it.Polygon:return jt(this,t);case it.Circle:return Wt(t,this,!0);case it.Ellipse:return Yt(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(t){t[0].set(this.right-this.left,0).rperp().normalize(),t[1].set(0,this.bottom-this.top).rperp().normalize(),t[2].set(this.left-this.right,0).rperp().normalize(),t[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===Zt&&(Zt=new te),Zt}}let ee=null;class ie extends et{collisionType=it.Point;x;y;constructor(t=0,e=0){super(),this.x=t,this.y=e}clone(){return new ie(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(t){switch(t.collisionType){case it.SceneNode:return xt(this,t.getBounds());case it.Rectangle:return xt(this,t);case it.Polygon:return St(this,t);case it.Circle:return vt(this,t);case it.Ellipse:return bt(this,t);case it.Line:return wt(this,t);case it.Point:return yt(this,t);default:return!1}}collidesWith(t){return null}getBounds(){return te.temp.set(this.x,this.y,0,0)}contains(t,e){return yt(ie.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new mt){return e}destroy(){}static get temp(){return null===ee&&(ee=new ie),ee}static zero=new ie(0,0);static one=new ie(1,1);static add(t,e){return new ie(t.x+e.x,t.y+e.y)}static subtract(t,e){return new ie(t.x-e.x,t.y-e.y)}static multiply(t,e){return new ie(t.x*e.x,t.y*e.y)}static divide(t,e){return new ie(t.x/e.x,t.y/e.y)}}const ne={distanceModel:"linear",refDistance:50,maxDistance:1e3,rolloffFactor:1};class se{_audioContext;_output;_manager;_bus;_volume;_ended=!1;_stopTimer=null;onEnd=new w;_spatialConfig;_panner=null;_position=null;_followNode=null;_spatialRegistered=!1;_effects=[];constructor(t){this._audioContext=t.audioContext,this._output=t.output,this._bus=t.bus,this._manager=t.manager,this._volume=Y(t.volume,0,1),this._spatialConfig={...ne,...t.spatial},this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01),!1!==t.autoConnect&&this._connectOutput()}get ended(){return this._ended}get output(){return this._output}get volume(){return this._volume}set volume(t){this._volume=Y(t,0,1),this._ended||this._output.gain.setTargetAtTime(this._volume,this._audioContext.currentTime,.01)}get bus(){return this._bus}set bus(t){t!==this._bus&&(this._ended?this._bus=t:(this._tail().disconnect(),this._bus=t,this._connectOutput()))}addEffect(t){return this._ended||(this._effects.push(t),this._rebuildEffectChain()),this}removeEffect(t){const e=this._effects.indexOf(t);return-1!==e&&(this._effects.splice(e,1),t.outputNode.disconnect(),this._rebuildEffectChain()),this}fade(t,e){if(this._ended)return;const i=Y(t,0,1);this._volume=i;const n=this._audioContext,s=this._output;e<=0?s.gain.setTargetAtTime(i,n.currentTime,.01):(s.gain.cancelScheduledValues(n.currentTime),s.gain.setValueAtTime(s.gain.value,n.currentTime),s.gain.linearRampToValueAtTime(i,n.currentTime+e/1e3))}stop(t){if(!this._ended){if(void 0!==t&&t>0){const e=this._audioContext,i=this._output;return i.gain.cancelScheduledValues(e.currentTime),i.gain.setValueAtTime(i.gain.value,e.currentTime),i.gain.linearRampToValueAtTime(0,e.currentTime+t/1e3),this._clearStopTimer(),void(this._stopTimer=setTimeout(()=>{this._stopTimer=null,this._finish()},t))}this._finish()}}get position(){return this._position}set position(t){this._ended||(null!==t?(null===this._position?this._position=new ie(t.x,t.y):this._position.set(t.x,t.y),this._ensurePanner(),this._tickSpatial()):null!==this._position&&(this._position.destroy(),this._position=null))}follow(t){this._ended||(this._followNode=t,null!==t&&(this._ensurePanner(),this._tickSpatial()))}_tickSpatial(){if(null===this._panner||this._ended)return;let t,e;if(null!==this._followNode){const i=this._followNode.getGlobalTransform();t=i.x,e=i.y}else{if(null===this._position)return;t=this._position.x,e=this._position.y}const i=this._panner,n=this._audioContext.currentTime;i.positionX?(i.positionX.setValueAtTime(t,n),i.positionY.setValueAtTime(e,n),i.positionZ.setValueAtTime(0,n)):i.setPosition&&i.setPosition(t,e,0)}_tail(){const t=this._effects[this._effects.length-1];return void 0!==t?t.outputNode:this._output}_connectOutput(){this._connectTail(this._tail())}_connectTail(t){const e=this._bus._getInputNode();null===e?(t.connect(this._audioContext.destination),this._bus.onceSetup(()=>{if(this._ended)return;const t=this._bus._getInputNode();if(null!==t){const e=this._tail();e.disconnect(),e.connect(t)}})):t.connect(e)}_rebuildEffectChain(){if(this._ended)return;this._output.disconnect();for(const t of this._effects)t.outputNode.disconnect();let t=this._output;for(const e of this._effects)t.connect(e.inputNode),t=e.outputNode;this._connectTail(t)}_clearStopTimer(){null!==this._stopTimer&&(clearTimeout(this._stopTimer),this._stopTimer=null)}_ensurePanner(){if(null!==this._panner||this._ended)return;const t=this._audioContext.createPanner();t.panningModel="equalpower",t.distanceModel=this._spatialConfig.distanceModel,t.refDistance=this._spatialConfig.refDistance,t.maxDistance=this._spatialConfig.maxDistance,t.rolloffFactor=this._spatialConfig.rolloffFactor,this._routeThroughPanner(t),this._panner=t,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 t of this._effects)t.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 re extends se{_oscillator;_envelopeGain;_envelope;_frequency;_type;_detune;_playbackRate=1;constructor(t){super(t);const e=this._audioContext,i=e.currentTime;this._frequency=t.frequency,this._type=t.type,this._detune=t.detune,this._envelope=t.envelope,this._envelopeGain=e.createGain(),this._envelopeGain.connect(this._output);const n=e.createOscillator();n.type=t.type,n.frequency.value=t.frequency,n.detune.value=t.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(t){this._frequency=t,this._ended||this._oscillator.frequency.setTargetAtTime(t,this._audioContext.currentTime,.01)}get type(){return this._type}set type(t){this._type=t,this._ended||(this._oscillator.type=t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t}get detune(){return this._detune}set detune(t){this._detune=t,this._ended||this._oscillator.detune.setTargetAtTime(t,this._audioContext.currentTime,.01)}stop(t){if(!this._ended)if(void 0!==t&&t>0)super.stop(t);else{if(this._envelope){const t=this._audioContext.currentTime;this._envelope.release(this._envelopeGain.gain,t);const e=t+this._envelope.releaseMs/1e3;try{this._oscillator.stop(e)}catch{}return}super.stop()}}_routeThroughPanner(t){this._envelopeGain.disconnect(),this._envelopeGain.connect(t),t.connect(this._output)}_teardownSource(){this._oscillator.onended=null;try{this._oscillator.stop(0)}catch{}this._oscillator.disconnect(),this._envelopeGain.disconnect()}}class oe{onEnd=new w;_bus;_output=null;constructor(t){this._bus=t}get ended(){return!0}get output(){return this._output??=L().createGain()}get volume(){return 0}set volume(t){}get bus(){return this._bus}set bus(t){}fade(t,e){}stop(t){}addEffect(t){return this}removeEffect(t){return this}}class ae extends se{_buffer;_window;_source;_loop;_playbackRate;_detune;_offsetAtStart;_startedAt;constructor(t){super(t),this._buffer=t.buffer,this._window=t.window,this._loop=t.loop,this._playbackRate=t.playbackRate,this._detune=t.detune,this._offsetAtStart=t.offset,this._startedAt=this._audioContext.currentTime,this._source=this._startSource(t.offset)}get duration(){return this._window.end-this._window.base}get time(){if(this._ended)return 0;const t=this.duration,e=(this._audioContext.currentTime-this._startedAt)*this._playbackRate;let i=this._offsetAtStart-this._window.base+e;return this._loop&&t>0&&(i%=t,i<0&&(i+=t)),Y(i,0,t)}set time(t){this.seek(t)}seek(t){if(this._ended)return;const e=this._window.base+Y(t,0,this.duration);this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect(),this._source=this._startSource(e),this._offsetAtStart=e,this._startedAt=this._audioContext.currentTime}get loop(){return this._loop}set loop(t){this._loop===t||this._ended?this._loop=t:(this._loop=t,this._source.loop=t,t&&(this._source.loopStart=this._window.loopStart,this._source.loopEnd=this._window.loopEnd))}get playbackRate(){return this._playbackRate}set playbackRate(t){const e=Y(t,.1,20);if(this._playbackRate===e||this._ended)return void(this._playbackRate=e);const i=this.time;this._playbackRate=e,this._offsetAtStart=this._window.base+i,this._startedAt=this._audioContext.currentTime,this._source.playbackRate.setTargetAtTime(e,this._audioContext.currentTime,.01)}get detune(){return this._detune}set detune(t){this._detune=t,this._ended||this._source.detune.setTargetAtTime(t,this._audioContext.currentTime,.01)}_routeThroughPanner(t){this._source.disconnect(),this._source.connect(t),t.connect(this._output)}_teardownSource(){this._source.onended=null;try{this._source.stop(0)}catch{}this._source.disconnect()}_startSource(t){const e=this._audioContext.createBufferSource();e.buffer=this._buffer,e.loop=this._loop,e.playbackRate.value=this._playbackRate,e.detune.value=this._detune,this._loop&&(e.loopStart=this._window.loopStart,e.loopEnd=this._window.loopEnd),e.connect(this._panner??this._output),e.onended=()=>this._finish();const i=this._loop?void 0:this._window.end-t;return!this._loop&&void 0!==i&&i>0?e.start(0,t,i):e.start(0,t),e}}var he;!function(t){t.FirstInFirstOut="fifo",t.LeastRecentlyUsed="lru",t.LowestPriority="priority"}(he||(he={}));class le{_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(t){this.setPoolSize(t)}get poolStrategy(){return this._poolStrategy}set poolStrategy(t){this._poolStrategy=t}get priority(){return this._priority}set priority(t){this._priority=t}get position(){return this._position}set position(t){null!==t?null===this._position?this._position=new ie(t.x,t.y):this._position.set(t.x,t.y):null!==this._position&&(this._position.destroy(),this._position=null)}get velocity(){return this._velocity}set velocity(t){null===t?null!==this._velocity&&(this._velocity.destroy(),this._velocity=null):null===this._velocity?this._velocity=new ie(t.x,t.y):this._velocity.set(t.x,t.y)}get distanceModel(){return this._distanceModel}set distanceModel(t){this._distanceModel=t}get refDistance(){return this._refDistance}set refDistance(t){this._refDistance=Math.max(0,t)}get maxDistance(){return this._maxDistance}set maxDistance(t){this._maxDistance=Math.max(0,t)}get rolloffFactor(){return this._rolloffFactor}set rolloffFactor(t){this._rolloffFactor=Math.max(0,t)}constructor(t,e={}){this._audioBuffer=t,this._clipEnd=t.duration;const{poolSize:i,poolStrategy:n,priority:s,sprites:r,volume:o,loop:a,playbackRate:h,muted:l,distanceModel:u,refDistance:c,maxDistance:d,rolloffFactor:_}=e;this.volume=Y(o??1,0,1),this.loop=a??!1,this.playbackRate=Y(h??1,.1,20),this.muted=l??!1,this._poolSize=Math.max(1,Math.floor(i??8)),this._poolStrategy=n??he.FirstInFirstOut,this._priority=s??0,void 0!==u&&(this._distanceModel=u),void 0!==c&&(this._refDistance=Math.max(0,c)),void 0!==d&&(this._maxDistance=Math.max(0,d)),void 0!==_&&(this._rolloffFactor=Math.max(0,_)),r&&this.setSprites(r)}setPoolSize(t){const e=Math.max(1,Math.floor(t));return this._poolSize===e||(this._poolSize=e,this._trimActiveVoices()),this}setSprites(t){this._sprites.clear();for(const[e,i]of Object.entries(t))this.defineSprite(e,i);return this}defineSprite(t,e){if(0===t.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=e.start,n=e.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${t}" has an invalid start time (${i}).`);if(!Number.isFinite(n)||n<=i)throw new Error(`Sound sprite "${t}" has an invalid end time (${n}).`);if(n>this.duration)throw new Error(`Sound sprite "${t}" ends at ${n}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(t,{start:i,end:n,loop:e.loop??!1}),this}hasSprite(t){return this._sprites.has(t)}removeSprite(t){return this._sprites.delete(t),this}clip(t,e){const i=Y(t,0,this._audioBuffer.duration),n=Y(i+e,i,this._audioBuffer.duration),s=new le(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 s._clipStart=i,s._clipEnd=n,s}_createVoice(t,e){const i=this._clipStart+Math.max(0,e.time??0);return i>=this._clipEnd?new oe(e.bus??t.sound):this._buildVoice(t,e,i,{base:this._clipStart,end:this._clipEnd,loopStart:this._clipStart,loopEnd:this._clipEnd})}_createSpriteVoice(t,e,i={}){const n=this._sprites.get(e);if(!n)throw new Error(`Sound sprite "${e}" is not defined.`);const s=Math.max(0,i.time??0),r=n.start+s;if(r>=n.end)throw new Error(`Sound sprite "${e}" offset (${s}s) exceeds clip duration (${n.end-n.start}s).`);const o=i.loop??n.loop;return this._buildVoice(t,{...i,loop:o},r,{base:n.start,end:n.end,loopStart:n.start,loopEnd:n.end})}_buildVoice(t,e,i,n){const s=e.loop??this.loop,r=Y(e.playbackRate??this.playbackRate,.1,20),o=e.detune??0,a=Y(e.muted?0:e.volume??(this.muted?0:this.volume),0,1),h=e.bus??t.sound;if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const t=this._pickEvictionVictim(),e=this._activeVoices[t];e&&(this._activeVoices.splice(t,1),e.voice.stop())}const l=L(),u=l.createGain(),c=new ae({audioContext:l,output:u,bus:h,manager:t,volume:a,spatial:{distanceModel:this._distanceModel,refDistance:this._refDistance,maxDistance:this._maxDistance,rolloffFactor:this._rolloffFactor},buffer:this._audioBuffer,loop:s,playbackRate:r,detune:o,offset:i,window:n});null!==this._position&&(c.position=this._position);const d={voice:c,startedAt:l.currentTime,effectiveDuration:s?1/0:n.end-i};return c.onEnd.add(()=>{const t=this._activeVoices.indexOf(d);-1!==t&&this._activeVoices.splice(t,1)}),this._activeVoices.push(d),c}_stopAllVoices(){const t=[...this._activeVoices];this._activeVoices.length=0;for(const e of t)e.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 t=this._activeVoices.length-1;t>=0;t--)!0===this._activeVoices[t]?.voice.ended&&this._activeVoices.splice(t,1)}_pickEvictionVictim(){switch(this._poolStrategy){case he.LeastRecentlyUsed:return this._pickClosestToEnd();case he.LowestPriority:case he.FirstInFirstOut:default:return 0}}_pickClosestToEnd(){const t=U()?L().currentTime:0;let e=1/0,i=0;for(let n=0;n<this._activeVoices.length;n++){const s=this._activeVoices[n];if(void 0===s)continue;const r=t-s.startedAt,o=s.effectiveDuration-r;o<e&&(e=o,i=n)}return i}_trimActiveVoices(){for(;this._activeVoices.length>this._poolSize;){const t=this._pickEvictionVictim(),e=this._activeVoices[t];if(!e)break;this._activeVoices.splice(t,1),e.voice.stop()}}}class ue{frequency;type;detune;envelope;volume;muted;_poolSize;_poolStrategy;priority;_activeVoices=[];get poolSize(){return this._poolSize}set poolSize(t){this._poolSize=Math.max(1,Math.floor(t))}get poolStrategy(){return this._poolStrategy}set poolStrategy(t){this._poolStrategy=t}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??he.FirstInFirstOut,this.priority=t.priority??0}setNote(t){return this.frequency=ue.midiToFrequency(t),this}static midiToFrequency(t){return 440*Math.pow(2,(t-69)/12)}_createVoice(t,e){const i=e.bus??t.sound;if(!U())return new oe(i);if(this._pruneEndedVoices(),this._activeVoices.length>=this._poolSize){const t=this._pickEvictionVictim(),e=this._activeVoices[t];e&&(this._activeVoices.splice(t,1),e.voice.stop())}const n=L(),s=n.createGain(),r=e.detune??this.detune,o=Y(e.muted?0:e.volume??(this.muted?0:this.volume),0,1),a=new re({audioContext:n,output:s,bus:i,manager:t,volume:o,frequency:this.frequency,type:this.type,detune:r,envelope:this.envelope}),h={voice:a,startedAt:n.currentTime};return a.onEnd.add(()=>{const t=this._activeVoices.indexOf(h);-1!==t&&this._activeVoices.splice(t,1)}),this._activeVoices.push(h),a}stopAll(){const t=[...this._activeVoices];this._activeVoices.length=0;for(const e of t)e.voice.stop();return this}destroy(){this.stopAll()}_pruneEndedVoices(){for(let t=this._activeVoices.length-1;t>=0;t--)!0===this._activeVoices[t]?.voice.ended&&this._activeVoices.splice(t,1)}_pickEvictionVictim(){if(this._poolStrategy===he.LeastRecentlyUsed){let t=0,e=1/0;for(let i=0;i<this._activeVoices.length;i++){const n=this._activeVoices[i];void 0!==n&&n.startedAt<e&&(e=n.startedAt,t=i)}return t}return 0}}class ce{_stream;constructor(t){this._stream=t}get stream(){return this._stream}static async open(t={}){if("undefined"==typeof navigator||!navigator.mediaDevices?.getUserMedia)throw new Error("AudioInput.open: getUserMedia is not available in this environment.");const e={};void 0!==t.deviceId&&(e.deviceId=t.deviceId),void 0!==t.echoCancellation&&(e.echoCancellation=t.echoCancellation),void 0!==t.noiseSuppression&&(e.noiseSuppression=t.noiseSuppression),void 0!==t.autoGainControl&&(e.autoGainControl=t.autoGainControl);const i=await navigator.mediaDevices.getUserMedia({audio:!(Object.keys(e).length>0)||e});return new ce(i)}close(){for(const t of this._stream.getTracks())t.stop()}}class de{position=new ie(0,0);velocity=new ie(0,0);target=null;_audioListener=null;_ctx=null;_onAudioContextReady=t=>{I.remove(this._onAudioContextReady),this._setup(t)};constructor(){U()?this._setup(L()):I.add(this._onAudioContextReady)}_tick(){if(null!==this.target&&this._readTargetPosition(),null!==this._audioListener&&null!==this._ctx){const t=this._ctx.currentTime,e=this._audioListener;e.positionX&&e.positionY&&e.positionZ?(e.positionX.setValueAtTime(this.position.x,t),e.positionY.setValueAtTime(this.position.y,t),e.positionZ.setValueAtTime(0,t)):e.setPosition&&e.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 t=this.target;if(null===t)return;const e=t;if("function"==typeof e.getGlobalTransform){const t=e.getGlobalTransform();return void this.position.set(t.x,t.y)}const i=t;if(void 0!==i.center&&"object"==typeof i.center)return void this.position.set(i.center.x,i.center.y);const n=t;this.position.set(n.x,n.y)}_setup(t){this._ctx=t,this._audioListener=t.listener;const e=t.currentTime,i=t.listener;i.forwardX&&i.forwardY&&i.forwardZ&&i.upX&&i.upY&&i.upZ?(i.forwardX.setValueAtTime(0,e),i.forwardY.setValueAtTime(0,e),i.forwardZ.setValueAtTime(-1,e),i.upX.setValueAtTime(0,e),i.upY.setValueAtTime(1,e),i.upZ.setValueAtTime(0,e)):i.setOrientation&&i.setOrientation(0,0,-1,0,1,0)}}class _e extends se{_sourceNode;_stream;constructor(t){super({...t,autoConnect:!1}),this._sourceNode=t.sourceNode,this._stream=t.stream,this._sourceNode.connect(this._output)}routeTo(t){return this._ended||(this._tail().disconnect(),this._bus=t,this._connectOutput()),this}async record(t){const e=new MediaRecorder(this._stream),i=[];return e.addEventListener("dataavailable",t=>{t.data.size>0&&i.push(t.data)}),new Promise((n,s)=>{e.addEventListener("stop",()=>{(async()=>{try{const t=new Blob(i,{type:e.mimeType||"audio/webm"}),s=await G(await t.arrayBuffer());n(new le(s))}catch(t){s(t instanceof Error?t:new Error(String(t)))}})()}),e.addEventListener("error",()=>s(new Error("Recording failed."))),e.start(),setTimeout(()=>{"inactive"!==e.state&&e.stop()},Math.max(0,t))})}_routeThroughPanner(t){this._sourceNode.disconnect(),this._sourceNode.connect(t),t.connect(this._output)}_teardownSource(){this._sourceNode.disconnect()}}class fe{order=300;master;music;sound;listener;onUnlock=new w;_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 de,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(t){this._muteOnHidden=t}get locked(){return!U()}play(t,e){return t._createVoice(this,e??{})}open(t){const e=L(),i=e.createMediaStreamSource(t.stream),n=e.createGain();return new _e({audioContext:e,output:n,bus:this.sound,manager:this,volume:1,sourceNode:i,stream:t.stream})}update(t){this.listener._tick();for(const t of this._spatial)t.ended?this._spatial.delete(t):t._tickSpatial()}_registerSpatial(t){this._spatial.add(t)}_applyVisibility(t){this._muteOnHidden&&(this.master.muted=!t)}registerBus(t){if(this._registered.has(t.name))throw new Error(`Audio bus "${t.name}" is already registered.`);return this._registered.set(t.name,t),this}unregisterBus(t){if(t===this.master||t===this.music||t===this.sound)throw new Error(`Cannot unregister built-in bus "${t.name}".`);return this._registered.get(t.name)!==t||(this._registered.delete(t.name),t.destroy()),this}getBus(t){const e=this._registered.get(t);if(!e)throw new Error(`Audio bus "${t}" is not registered.`);return e}hasBus(t){return this._registered.has(t)}destroy(){this.listener.destroy(),this._spatial.clear();for(const t of this._registered.values())t.destroy();this._registered.clear()}}class pe extends se{_element;_sourceNode;_detune=0;_onEnded=()=>this._finish();_unlockHandler=null;constructor(t){super(t),this._element=t.element,this._sourceNode=t.sourceNode,this._sourceNode.connect(this._output),this._element.loop=t.loop,this._element.playbackRate=t.playbackRate,void 0!==t.startTime&&(this._element.currentTime=Math.max(0,t.startTime)),this._element.addEventListener("ended",this._onEnded),this._startPlayback()}get duration(){return this._element.duration}get time(){return this._element.currentTime}set time(t){this.seek(t)}seek(t){this._ended||(this._element.currentTime=Math.max(0,t))}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(t){this._element.loop=t}get playbackRate(){return this._element.playbackRate}set playbackRate(t){this._element.playbackRate=Y(t,.1,20)}get detune(){return this._detune}set detune(t){this._detune=t}_routeThroughPanner(t){this._sourceNode.disconnect(),this._sourceNode.connect(t),t.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 me{_audioElement;volume;loop;playbackRate;muted;_sourceNode=null;_activeVoice=null;constructor(t,e){this._audioElement=t,this.volume=Y(e?.volume??1,0,1),this.loop=e?.loop??!1,this.playbackRate=Y(e?.playbackRate??1,.1,20),this.muted=e?.muted??!1,void 0!==e?.time&&(this._audioElement.currentTime=Math.max(0,e.time))}get audioElement(){return this._audioElement}get duration(){return this._audioElement.duration}_createVoice(t,e){const i=e.bus??t.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 s=n.createGain(),r=e.loop??this.loop,o=Y(e.playbackRate??this.playbackRate,.1,20),a=Y(e.muted?0:e.volume??(this.muted?0:this.volume),0,1),h=new pe({audioContext:n,output:s,bus:i,manager:t,volume:a,element:this._audioElement,sourceNode:this._sourceNode,loop:r,playbackRate:o,...void 0!==e.time&&{startTime:e.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)}}class ge extends tt{_node=null;_type;_frequency;_resonance;_gain;_detune;_onAudioContextReady=t=>{I.remove(this._onAudioContextReady),this._setup(t)};constructor(t={}){super(),this._type=t.type??"lowpass",this._frequency=t.frequency??1e3,this._resonance=t.resonance??1,this._gain=t.gain??0,this._detune=t.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(t){this._type=t,this._node&&(this._node.type=t)}get frequency(){return this._frequency}set frequency(t){this._frequency=t,this._node&&this._node.frequency.setTargetAtTime(t,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(t){this._resonance=t,this._node&&this._node.Q.setTargetAtTime(t,this._node.context.currentTime,.01)}get gain(){return this._gain}set gain(t){this._gain=t,this._node&&this._node.gain.setTargetAtTime(t,this._node.context.currentTime,.01)}get detune(){return this._detune}set detune(t){this._detune=t,this._node&&this._node.detune.setTargetAtTime(t,this._node.context.currentTime,.01)}destroy(){I.remove(this._onAudioContextReady),this._node?.disconnect(),this._node=null}_setup(t){const e=t.createBiquadFilter();e.type=this._type,e.frequency.setValueAtTime(this._frequency,t.currentTime),e.Q.setValueAtTime(this._resonance,t.currentTime),e.gain.setValueAtTime(this._gain,t.currentTime),e.detune.setValueAtTime(this._detune,t.currentTime),this._node=e}}async function ye(t,e,i,n={}){const s=Y(n.toVolume??1,0,1),r=n.stopAfter??!0;return e.fade(s,i),r?t.stop(i):t.fade(0,i),new Promise(t=>{setTimeout(t,Math.max(0,i))})}class we{attackMs;decayMs;sustainLevel;releaseMs;constructor(t={}){this.attackMs=Math.max(0,t.attackMs??10),this.decayMs=Math.max(0,t.decayMs??100),this.sustainLevel=Math.max(0,Math.min(1,t.sustainLevel??.7)),this.releaseMs=Math.max(0,t.releaseMs??200)}trigger(t,e){const i=e+this.attackMs/1e3,n=i+this.decayMs/1e3;t.cancelScheduledValues(e),t.setValueAtTime(0,e),t.linearRampToValueAtTime(1,i),t.linearRampToValueAtTime(this.sustainLevel,n)}release(t,e){this.releaseMs,t.cancelScheduledValues(e),t.setTargetAtTime(0,e,this.releaseMs/1e3/3)}get totalDurationMs(){return this.attackMs+this.decayMs+this.releaseMs}destroy(){}}class xe extends tt{_node=null;_frequency;_resonance;_onAudioContextReady=t=>{I.remove(this._onAudioContextReady),this._setup(t)};constructor(t={}){super(),this._frequency=t.frequency??1e3,this._resonance=t.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(t){this._frequency=Math.max(20,Math.min(2e4,t)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(t){this._resonance=Math.max(1e-4,t),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(t){const e=t.createBiquadFilter();e.type="highpass",e.frequency.setValueAtTime(this._frequency,t.currentTime),e.Q.setValueAtTime(this._resonance,t.currentTime),this._node=e}}class ve extends tt{_node=null;_frequency;_resonance;_onAudioContextReady=t=>{I.remove(this._onAudioContextReady),this._setup(t)};constructor(t={}){super(),this._frequency=t.frequency??1e3,this._resonance=t.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(t){this._frequency=Math.max(20,Math.min(2e4,t)),this._node&&this._node.frequency.setTargetAtTime(this._frequency,this._node.context.currentTime,.01)}get resonance(){return this._resonance}set resonance(t){this._resonance=Math.max(1e-4,t),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(t){const e=t.createBiquadFilter();e.type="lowpass",e.frequency.setValueAtTime(this._frequency,t.currentTime),e.Q.setValueAtTime(this._resonance,t.currentTime),this._node=e}}const be=new WeakMap,Se=new WeakMap;async function Be(t,e,i){let n=be.get(t);if(n||(n=new Set,be.set(t,n)),n.has(e))return;let s=Se.get(t);s||(s=new Map,Se.set(t,s));const r=s.get(e);if(r)return r;const o=new Blob([i],{type:"application/javascript"}),a=URL.createObjectURL(o),h=t.audioWorklet.addModule(a).finally(()=>{URL.revokeObjectURL(a)}).then(()=>{n.add(e),s.delete(e)}).catch(t=>{throw s.delete(e),t});return s.set(e,h),h}class Ce extends tt{_inputGain=null;_outputGain=null;_dryGain=null;_wetGain=null;_dryDelay=null;_workletNode=null;_ready=null;_wet=1;_onAudioContextReady=t=>{I.remove(this._onAudioContextReady),this._setup(t)};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(t){if(this._wet=Math.max(0,Math.min(1,t)),this._dryGain&&this._wetGain){const t=this._wetGain.context;this._dryGain.gain.setTargetAtTime(1-this._wet,t.currentTime,.01),this._wetGain.gain.setTargetAtTime(this._wet*this._wetMakeupGain,t.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(t,e){if(!this._workletNode)return;const i=this._workletNode.parameters.get(t);i&&i.setTargetAtTime(e,this._workletNode.context.currentTime,.01)}_setup(t){const e=t.createGain(),i=t.createGain(),n=t.createGain(),s=t.createGain();this._inputGain=e,this._outputGain=i,e.connect(n),n.connect(i),n.gain.setValueAtTime(1,t.currentTime),s.gain.setValueAtTime(0,t.currentTime),s.connect(i),this._dryGain=n,this._wetGain=s,this._ready=Be(t,this._workletName,this._workletSource).then(()=>{if(!this._inputGain||!this._dryGain||!this._wetGain)return;const e=this._dryLatencySeconds;if(e>0){const i=t.createDelay(Math.max(1,2*e));i.delayTime.setValueAtTime(e,t.currentTime),this._dryDelay=i,this._inputGain.disconnect(this._dryGain),this._inputGain.connect(i),i.connect(this._dryGain)}const i=new AudioWorkletNode(t,this._workletName,this._workletOptions);this._workletNode=i,this._inputGain.connect(i),i.connect(this._wetGain),this.wet=this._wet,this._onWorkletReady?.(t)})}}const Te=Object.freeze({extensions:Object.freeze([]),renderers:Object.freeze([]),assets:Object.freeze([]),serializers:Object.freeze([])});function Me(t){if(0===t.length)return Te;const e=new Map,i=new Set,n=new Set,s=[],r=[];function o(t){const a=e.get(t.id);if(void 0!==a&&a!==t)throw new Error(`Extension "${t.id}" was provided by multiple descriptor objects.`);if(void 0===a&&e.set(t.id,t),!n.has(t)){if(i.has(t)){const e=[...s.slice(s.indexOf(t)),t].map(t=>t.id).join(" → ");throw new Error(`Extension dependency cycle detected: ${e}`)}i.add(t),s.push(t);for(const e of t.dependencies??[])o(e);s.pop(),i.delete(t),n.add(t),r.push(t)}}for(const e of t)o(e);const a=[],h=[],l=[];for(const t of r){if(t.renderers)for(const e of t.renderers)a.push(e);if(t.assets)for(const e of t.assets)h.push(e);if(t.serializers)for(const e of t.serializers)l.push(e)}return Object.freeze({extensions:Object.freeze(r),renderers:Object.freeze(a),assets:Object.freeze(h),serializers:Object.freeze(l)})}let Ae,Pe=new Map;function Ee(t,e){const i=new Set;for(const n of e){if(0===n.targets.length)throw new Error("A RendererBinding must declare at least one target.");for(const t of n.targets){if(i.has(t))throw new Error(`Two bindings target the same drawable type ${t.name}. Remove one of the conflicting bindings.`);i.add(t)}const e=n.create(t);void 0!==e&&t.rendererRegistry.bindRenderer(n.targets,e)}}const ke=t=>0|Y(t,0,255);class Re{_r;_g;_b;_a;_rgba=null;_array=null;constructor(t=0,e=0,i=0,n=1){this._r=ke(t),this._g=ke(e),this._b=ke(i),this._a=Y(n,0,1)}get r(){return this._r}set r(t){this._r=ke(t),this._rgba=null}get g(){return this._g}set g(t){this._g=ke(t),this._rgba=null}get b(){return this._b}set b(t){this._b=ke(t),this._rgba=null}get a(){return this._a}set a(t){this._a=Y(t,0,1),this._rgba=null}set(t=this._r,e=this._g,i=this._b,n=this._a){return this._r=ke(t),this._g=ke(e),this._b=ke(i),this._a=Y(n,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new Re(this._r,this._g,this._b,this._a)}equals({r:t,g:e,b:i,a:n}={}){return!(void 0!==t&&this.r!==t||void 0!==e&&this.g!==e||void 0!==i&&this.b!==i||void 0!==n&&this.a!==n)}toArray(t=!1){return this._array||(this._array=new Float32Array(4)),t?(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(t=!0){return`${t?"#":""}${(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 Re(240,248,255,1);static antiqueWhite=new Re(250,235,215,1);static aqua=new Re(0,255,255,1);static aquamarine=new Re(127,255,212,1);static azure=new Re(240,255,255,1);static beige=new Re(245,245,220,1);static bisque=new Re(255,228,196,1);static black=new Re(0,0,0,1);static blanchedAlmond=new Re(255,235,205,1);static blue=new Re(0,0,255,1);static blueViolet=new Re(138,43,226,1);static brown=new Re(165,42,42,1);static burlyWood=new Re(222,184,135,1);static cadetBlue=new Re(95,158,160,1);static chartreuse=new Re(127,255,0,1);static chocolate=new Re(210,105,30,1);static coral=new Re(255,127,80,1);static cornflowerBlue=new Re(100,149,237,1);static cornsilk=new Re(255,248,220,1);static crimson=new Re(220,20,60,1);static cyan=new Re(0,255,255,1);static darkBlue=new Re(0,0,139,1);static darkCyan=new Re(0,139,139,1);static darkGoldenrod=new Re(184,134,11,1);static darkGray=new Re(169,169,169,1);static darkGreen=new Re(0,100,0,1);static darkKhaki=new Re(189,183,107,1);static darkMagenta=new Re(139,0,139,1);static darkOliveGreen=new Re(85,107,47,1);static darkOrange=new Re(255,140,0,1);static darkOrchid=new Re(153,50,204,1);static darkRed=new Re(139,0,0,1);static darkSalmon=new Re(233,150,122,1);static darkSeaGreen=new Re(143,188,139,1);static darkSlateBlue=new Re(72,61,139,1);static darkSlateGray=new Re(47,79,79,1);static darkTurquoise=new Re(0,206,209,1);static darkViolet=new Re(148,0,211,1);static deepPink=new Re(255,20,147,1);static deepSkyBlue=new Re(0,191,255,1);static dimGray=new Re(105,105,105,1);static dodgerBlue=new Re(30,144,255,1);static firebrick=new Re(178,34,34,1);static floralWhite=new Re(255,250,240,1);static forestGreen=new Re(34,139,34,1);static fuchsia=new Re(255,0,255,1);static gainsboro=new Re(220,220,220,1);static ghostWhite=new Re(248,248,255,1);static gold=new Re(255,215,0,1);static goldenrod=new Re(218,165,32,1);static gray=new Re(128,128,128,1);static green=new Re(0,128,0,1);static greenYellow=new Re(173,255,47,1);static honeydew=new Re(240,255,240,1);static hotPink=new Re(255,105,180,1);static indianRed=new Re(205,92,92,1);static indigo=new Re(75,0,130,1);static ivory=new Re(255,255,240,1);static khaki=new Re(240,230,140,1);static lavender=new Re(230,230,250,1);static lavenderBlush=new Re(255,240,245,1);static lawnGreen=new Re(124,252,0,1);static lemonChiffon=new Re(255,250,205,1);static lightBlue=new Re(173,216,230,1);static lightCoral=new Re(240,128,128,1);static lightCyan=new Re(224,255,255,1);static lightGoldenrodYellow=new Re(250,250,210,1);static lightGray=new Re(211,211,211,1);static lightGreen=new Re(144,238,144,1);static lightPink=new Re(255,182,193,1);static lightSalmon=new Re(255,160,122,1);static lightSeaGreen=new Re(32,178,170,1);static lightSkyBlue=new Re(135,206,250,1);static lightSlateGray=new Re(119,136,153,1);static lightSteelBlue=new Re(176,196,222,1);static lightYellow=new Re(255,255,224,1);static lime=new Re(0,255,0,1);static limeGreen=new Re(50,205,50,1);static linen=new Re(250,240,230,1);static magenta=new Re(255,0,255,1);static maroon=new Re(128,0,0,1);static mediumAquamarine=new Re(102,205,170,1);static mediumBlue=new Re(0,0,205,1);static mediumOrchid=new Re(186,85,211,1);static mediumPurple=new Re(147,112,219,1);static mediumSeaGreen=new Re(60,179,113,1);static mediumSlateBlue=new Re(123,104,238,1);static mediumSpringGreen=new Re(0,250,154,1);static mediumTurquoise=new Re(72,209,204,1);static mediumVioletRed=new Re(199,21,133,1);static midnightBlue=new Re(25,25,112,1);static mintCream=new Re(245,255,250,1);static mistyRose=new Re(255,228,225,1);static moccasin=new Re(255,228,181,1);static navajoWhite=new Re(255,222,173,1);static navy=new Re(0,0,128,1);static oldLace=new Re(253,245,230,1);static olive=new Re(128,128,0,1);static oliveDrab=new Re(107,142,35,1);static orange=new Re(255,165,0,1);static orangeRed=new Re(255,69,0,1);static orchid=new Re(218,112,214,1);static paleGoldenrod=new Re(238,232,170,1);static paleGreen=new Re(152,251,152,1);static paleTurquoise=new Re(175,238,238,1);static paleVioletRed=new Re(219,112,147,1);static papayaWhip=new Re(255,239,213,1);static peachPuff=new Re(255,218,185,1);static peru=new Re(205,133,63,1);static pink=new Re(255,192,203,1);static plum=new Re(221,160,221,1);static powderBlue=new Re(176,224,230,1);static purple=new Re(128,0,128,1);static red=new Re(255,0,0,1);static rosyBrown=new Re(188,143,143,1);static royalBlue=new Re(65,105,225,1);static saddleBrown=new Re(139,69,19,1);static salmon=new Re(250,128,114,1);static sandyBrown=new Re(244,164,96,1);static seaGreen=new Re(46,139,87,1);static seaShell=new Re(255,245,238,1);static sienna=new Re(160,82,45,1);static silver=new Re(192,192,192,1);static skyBlue=new Re(135,206,235,1);static slateBlue=new Re(106,90,205,1);static slateGray=new Re(112,128,144,1);static snow=new Re(255,250,250,1);static springGreen=new Re(0,255,127,1);static steelBlue=new Re(70,130,180,1);static tan=new Re(210,180,140,1);static teal=new Re(0,128,128,1);static thistle=new Re(216,191,216,1);static tomato=new Re(255,99,71,1);static transparentBlack=new Re(0,0,0,0);static transparentWhite=new Re(255,255,255,0);static turquoise=new Re(64,224,208,1);static violet=new Re(238,130,238,1);static wheat=new Re(245,222,179,1);static white=new Re(255,255,255,1);static whiteSmoke=new Re(245,245,245,1);static yellow=new Re(255,255,0,1);static yellowGreen=new Re(154,205,50,1)}class De{_value=0;get value(){return this._value}constructor(...t){t.length&&this.push(...t)}push(...t){for(const e of t)this._value|=e;return this}pop(t){const e=this.has(t);return this.remove(t),e}remove(...t){for(const e of t)this._value&=~e;return this}has(...t){return t.some(t=>0!==(this._value&t))}clear(){return this._value=0,this}destroy(){this.clear()}}let Ie=null;class Le{a;b;x;c;d;y;e;f;z;_array=null;constructor(t=1,e=0,i=0,n=0,s=1,r=0,o=0,a=0,h=1){this.a=t,this.b=e,this.x=i,this.c=n,this.d=s,this.y=r,this.e=o,this.f=a,this.z=h}set(t=this.a,e=this.b,i=this.x,n=this.c,s=this.d,r=this.y,o=this.e,a=this.f,h=this.z){return this.a=t,this.b=e,this.x=i,this.c=n,this.d=s,this.y=r,this.e=o,this.f=a,this.z=h,this}copy(t){return this.a=t.a,this.b=t.b,this.x=t.x,this.c=t.c,this.d=t.d,this.y=t.y,this.e=t.e,this.f=t.f,this.z=t.z,this}clone(){return new Le(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:t,b:e,x:i,c:n,d:s,y:r,e:o,f:a,z:h}={}){return!(void 0!==t&&this.a!==t||void 0!==e&&this.b!==e||void 0!==i&&this.x!==i||void 0!==n&&this.c!==n||void 0!==s&&this.d!==s||void 0!==r&&this.y!==r||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(t){return this.set(this.a*t.a+this.c*t.b+this.e*t.x,this.b*t.a+this.d*t.b+this.f*t.x,this.x*t.a+this.y*t.b+this.z*t.x,this.a*t.c+this.c*t.d+this.e*t.y,this.b*t.c+this.d*t.d+this.f*t.y,this.x*t.c+this.y*t.d+this.z*t.y,this.a*t.e+this.c*t.f+this.e*t.z,this.b*t.e+this.d*t.f+this.f*t.z,this.x*t.e+this.y*t.f+this.z*t.z)}getInverse(t=this){const e=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===e?t.copy(Le.identity):t.set((this.d*this.z-this.y*this.f)/e,(this.x*this.f-this.b*this.z)/e,(this.b*this.y-this.x*this.d)/e,(this.y*this.e-this.c*this.z)/e,(this.a*this.z-this.x*this.e)/e,(this.x*this.c-this.a*this.y)/e,(this.c*this.f-this.d*this.e)/e,(this.b*this.e-this.a*this.f)/e,(this.a*this.d-this.b*this.c)/e)}translate(t,e=t){return this.combine(Le.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const n=W(t),s=Math.cos(n),r=Math.sin(n);return this.combine(Le.temp.set(s,-r,e*(1-s)+i*r,r,s,i*(1-s)-e*r,0,0,1))}scale(t,e=t,i=0,n=i){return this.combine(Le.temp.set(t,0,i*(1-t),0,e,n*(1-e),0,0,1))}toArray(t=!1){const e=this._array||(this._array=new Float32Array(9));return t?(e[0]=this.a,e[1]=this.b,e[2]=this.x,e[3]=this.c,e[4]=this.d,e[5]=this.y,e[6]=this.e,e[7]=this.f,e[8]=this.z):(e[0]=this.a,e[1]=this.c,e[2]=this.e,e[3]=this.b,e[4]=this.d,e[5]=this.f,e[6]=this.x,e[7]=this.y,e[8]=this.z),e}destroy(){this._array&&(this._array=null)}static identity=new Le(1,0,0,0,1,0,0,0,1);static get temp(){return null===Ie&&(Ie=new Le),Ie}}let Ue=null;class Fe{collisionType=it.Polygon;_position;_points=[];_edges=[];_cachedNormals=null;_normalsDirty=!0;constructor(t=[],e=0,i=0){this._position=new ie(e,i),this.setPoints(t)}get position(){return this._position}set position(t){this._position.copy(t),this._normalsDirty=!0}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get points(){return this._points}set points(t){this.setPoints(t)}get edges(){return this._edges}setPosition(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setPoints(t){const e=this._points.length,i=t.length,n=e-i,s=Math.min(e,i);for(let e=0;e<s;e++)this._points[e].copy(t[e]);if(n>0){for(const t of this._points.splice(i))t.destroy();for(const t of this._edges.splice(i))t.destroy();if(null!==this._cachedNormals&&this._cachedNormals.length>i){const t=this._cachedNormals.splice(i);for(const e of t)e.destroy()}}else if(n<0)for(let n=e;n<i;n++)this._points.push(t[n].clone()),this._edges.push(t[n].clone());for(let t=0;t<i;t++){const e=this._points[t],n=this._points[(t+1)%i];this._edges[t].set(n.x-e.x,n.y-e.y)}return this._normalsDirty=!0,this}set(t,e,i){return this._position.set(t,e),this.setPoints(i),this._normalsDirty=!0,this}copy(t){return this._position.copy(t.position),this.setPoints(t.points),this._normalsDirty=!0,this}clone(){return new Fe(this.points,this.x,this.y)}equals({x:t,y:e,points:i}={}){return(void 0===t||this.x===t)&&(void 0===e||this.y===e)&&(void 0===i||this.points.length===i.length&&this.points.every((t,e)=>t.equals(i[e])))}getBounds(){let t=1/0,e=1/0,i=-1/0,n=-1/0;for(const s of this._points)t=Math.min(s.x,t),e=Math.min(s.y,e),i=Math.max(s.x,i),n=Math.max(s.y,n);return new te(this.x+t,this.y+e,i-t,n-e)}getNormals(){if(this._normalsDirty){const t=this._points.length;for(null===this._cachedNormals&&(this._cachedNormals=[]);this._cachedNormals.length<t;)this._cachedNormals.push(new ie);for(let e=0;e<t;e++)this._cachedNormals[e].copy(this._edges[e]).rperp().normalize();this._normalsDirty=!1}return this._cachedNormals}project(t,e=new mt){const i=Math.sqrt(t.x*t.x+t.y*t.y)||1,n=t.x/i,s=t.y/i,r=n*this._position.x+s*this._position.y,o=this._points;let a=1/0,h=-1/0;for(let t=0;t<o.length;t++){const e=o[t],i=n*e.x+s*e.y;i<a&&(a=i),i>h&&(h=i)}return e.set(a+r,h+r)}contains(t,e){return St(ie.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case it.SceneNode:return Rt(t.getBounds(),this);case it.Rectangle:return Rt(t,this);case it.Polygon:return Vt(this,t);case it.Circle:return Gt(t,this);case it.Ellipse:return Ot(t,this);case it.Line:return At(t,this);case it.Point:return St(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case it.SceneNode:case it.Rectangle:case it.Polygon:case it.Ellipse:return jt(this,t);case it.Circle:return Xt(this,t);default:return null}}destroy(){for(const t of this._points)t.destroy();for(const t of this._edges)t.destroy();if(null!==this._cachedNormals){for(const t of this._cachedNormals)t.destroy();this._cachedNormals=null}this._position.destroy(),this._points.length=0,this._edges.length=0}static get temp(){return null===Ue&&(Ue=new Fe),Ue}}class Ge{_minX=1/0;_minY=1/0;_maxX=-1/0;_maxY=-1/0;_dirty=!0;_rect=new te;get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(t,e){return this._minX=Math.min(this._minX,t),this._minY=Math.min(this._minY,e),this._maxX=Math.max(this._maxX,t),this._maxY=Math.max(this._maxY,e),this._dirty=!0,this}addRect(t,e){return e&&(t=t.transform(e,te.temp)),this.addCoords(t.left,t.top).addCoords(t.right,t.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 Ne,Oe;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Skew=32]="Skew",t[t.Transform=47]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.GlobalTransform=256]="GlobalTransform",t[t.BoundsRect=512]="BoundsRect"}(Ne||(Ne={})),function(t){t[t.Position=0]="Position",t[t.Scale=1]="Scale",t[t.Origin=2]="Origin",t[t.Anchor=3]="Anchor"}(Oe||(Oe={}));const Ve=[new ie,new ie,new ie,new ie];class ze{collisionType=it.SceneNode;flags=new De(Ne.Transform|Ne.GlobalTransform|Ne.BoundsRect);_bounds=new Ge;_transform=new Le;_position=new Qt(this,Oe.Position,0,0);_scale=new Qt(this,Oe.Scale,1,1);_origin=new Qt(this,Oe.Origin,0,0);_rotation=0;_skewX=0;_skewY=0;_sin=0;_cos=1;_stage=null;_visible=!0;_globalTransform=new Le;_localBounds=new te;_anchor=new Qt(this,Oe.Anchor,0,0);_parentNode=null;_zIndex=0;_cullable=!0;_cullArea=null;_orientedBounds=null;name=null;get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get origin(){return this._origin}set origin(t){this._origin.copy(t)}get anchor(){return this._anchor}set anchor(t){this._anchor.copy(t)}get parent(){return this._parentNode}set parent(t){this._parentNode=t}get visible(){return this._visible}set visible(t){this._visible=t}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t)}get cullable(){return this._cullable}set cullable(t){this._cullable=t}get cullArea(){return this._cullArea}set cullArea(t){this._cullArea=t}get skewX(){return this._skewX}set skewX(t){this._skewX!==t&&(this._skewX=t,this._setSkewDirty())}get skewY(){return this._skewY}set skewY(t){this._skewY!==t&&(this._skewY=t,this._setSkewDirty())}get isAlignedBox(){return this.rotation%90==0&&0===this._skewX&&0===this._skewY}setPosition(t,e=t){return this._position.set(t,e),this}setRotation(t){const e=q(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}setScale(t,e=t){return this._scale.set(t,e),this}setSkew(t,e=t){return this.skewX=t,this.skewY=e,this}setOrigin(t,e=t){return this._origin.set(t,e),this}move(t,e){return this.setPosition(this.x+t,this.y+e)}rotate(t){return this.setRotation(this._rotation+t)}getTransform(){return this.flags.has(Ne.Transform)&&(this.updateTransform(),this.flags.remove(Ne.Transform)),this._transform}updateTransform(){if(this.flags.has(Ne.Rotation)){const t=W(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}if(this.flags.has(Ne.Rotation|Ne.Scaling|Ne.Skew)){const{x:t,y:e}=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=t*this._cos+i*this._sin,this._transform.b=e*this._sin+n*this._cos,this._transform.c=-t*this._sin+i*this._cos,this._transform.d=-n*this._sin+e*this._cos}else this._transform.a=t*this._cos,this._transform.b=e*this._sin,this._transform.c=-t*this._sin,this._transform.d=e*this._cos}if(this._rotation||0!==this._skewX||0!==this._skewY){const{x:t,y:e}=this._origin;this._transform.x=t*-this._transform.a-e*this._transform.b+this._position.x,this._transform.y=t*-this._transform.c-e*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(t,e=t){return this._anchor.set(t,e),this}getLocalBounds(){return this._localBounds}getBounds(){return this.flags.has(Ne.BoundsRect)&&(this.updateBounds(),this.flags.remove(Ne.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(Ne.GlobalTransform)&&(this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this.flags.remove(Ne.GlobalTransform)),this._globalTransform}getNormals(){return this._isWorldAligned()?this.getBounds().getNormals():this._orientedBoundsPolygon().getNormals()}project(t,e=new mt){return this._isWorldAligned()?this.getBounds().project(t,e):this._orientedBoundsPolygon().project(t,e)}_orientedBoundsPolygon(){const t=this.getLocalBounds(),e=this.getGlobalTransform();return Ve[0].set(t.left,t.top).transform(e),Ve[1].set(t.right,t.top).transform(e),Ve[2].set(t.right,t.bottom).transform(e),Ve[3].set(t.left,t.bottom).transform(e),(this._orientedBounds??=new Fe).setPoints(Ve)}_isWorldAligned(){const t=this.getGlobalTransform(),e=1e-9;return Math.abs(t.b)<e&&Math.abs(t.c)<e||Math.abs(t.a)<e&&Math.abs(t.d)<e}intersectsWith(t){if(this._isWorldAligned())return this.getBounds().intersectsWith(t);switch(t.collisionType){case it.SceneNode:case it.Rectangle:case it.Polygon:return gt(this,t);case it.Circle:return Et(this.getBounds(),t);case it.Ellipse:return kt(this.getBounds(),t);case it.Line:return Ct(t,this.getBounds());case it.Point:return xt(t,this.getBounds());default:return!1}}collidesWith(t){if(this._isWorldAligned())return this.getBounds().collidesWith(t);switch(t.collisionType){case it.SceneNode:case it.Rectangle:case it.Polygon:case it.Circle:return jt(this,t);default:return null}}contains(t,e){if(this._isWorldAligned())return this.getBounds().contains(t,e);const i=this.getGlobalTransform(),n=i.a*i.d-i.b*i.c;if(0===n)return!1;const s=t-i.x,r=e-i.y,o=(i.d*s-i.b*r)/n,a=(i.a*r-i.c*s)/n;return this.getLocalBounds().contains(o,a)}inView(t){if(!this._cullable)return!0;const e=this._cullArea??this.getBounds();return t.getBounds().intersectsWith(e)}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(t){this._stage=t}_getStage(){return this._stage}_onObservableChange(t){switch(t){case Oe.Position:this._setPositionDirty();break;case Oe.Scale:this._setScalingDirty();break;case Oe.Origin:this._setOriginDirty();break;case Oe.Anchor:this._updateOrigin()}}_invalidateSubtreeTransform(){this.flags.push(Ne.GlobalTransform|Ne.BoundsRect),this._invalidateChildrenTransform()}_invalidateChildrenTransform(){}_invalidateBoundsCascade(){this.flags.push(Ne.BoundsRect),this._stage?.interaction._notifyBoundsInvalidated(this);let t=this._parentNode;for(;null!==t&&!t.flags.has(Ne.BoundsRect);)t.flags.push(Ne.BoundsRect),t._stage?.interaction._notifyBoundsInvalidated(t),t=t.parent}_setPositionDirty(){this.flags.push(Ne.Translation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setRotationDirty(){this.flags.push(Ne.Rotation),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setScalingDirty(){this.flags.push(Ne.Scaling),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setOriginDirty(){this.flags.push(Ne.Origin),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_setSkewDirty(){this.flags.push(Ne.Skew),this._invalidateSubtreeTransform(),this._invalidateBoundsCascade()}_updateOrigin(){const{x:t,y:e}=this._anchor,{width:i,height:n}=this.getLocalBounds();this.setOrigin(i*t,n*e)}}var qe;!function(t){t[t.Normal=0]="Normal",t[t.Additive=1]="Additive",t[t.Subtract=2]="Subtract",t[t.Multiply=3]="Multiply",t[t.Screen=4]="Screen",t[t.Darken=5]="Darken",t[t.Lighten=6]="Lighten",t[t.Overlay=7]="Overlay",t[t.ColorDodge=8]="ColorDodge",t[t.ColorBurn=9]="ColorBurn",t[t.HardLight=10]="HardLight",t[t.SoftLight=11]="SoftLight",t[t.Difference=12]="Difference",t[t.Exclusion=13]="Exclusion",t[t.Hue=14]="Hue",t[t.Saturation=15]="Saturation",t[t.Color=16]="Color",t[t.Luminosity=17]="Luminosity"}(qe||(qe={}));const We=t=>t>=qe.Darken;var Ye,$e,Xe,He,je,Ke,Qe;!function(t){t[t.Nearest=9728]="Nearest",t[t.Linear=9729]="Linear",t[t.NearestMipmapNearest=9984]="NearestMipmapNearest",t[t.LinearMipmapNearest=9985]="LinearMipmapNearest",t[t.NearestMipmapLinear=9986]="NearestMipmapLinear",t[t.LinearMipmapLinear=9987]="LinearMipmapLinear"}(Ye||(Ye={})),function(t){t[t.Repeat=10497]="Repeat",t[t.ClampToEdge=33071]="ClampToEdge",t[t.MirroredRepeat=33648]="MirroredRepeat"}($e||($e={})),function(t){t[t.Points=0]="Points",t[t.Lines=1]="Lines",t[t.LineLoop=2]="LineLoop",t[t.LineStrip=3]="LineStrip",t[t.Triangles=4]="Triangles",t[t.TriangleStrip=5]="TriangleStrip",t[t.TriangleFan=6]="TriangleFan"}(Xe||(Xe={})),function(t){t[t.ArrayBuffer=34962]="ArrayBuffer",t[t.ElementArrayBuffer=34963]="ElementArrayBuffer",t[t.CopyReadBuffer=36662]="CopyReadBuffer",t[t.CopyWriteBuffer=36663]="CopyWriteBuffer",t[t.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",t[t.UniformBuffer=35345]="UniformBuffer",t[t.PixelPackBuffer=35051]="PixelPackBuffer",t[t.PixelUnpackBuffer=35052]="PixelUnpackBuffer"}(He||(He={})),function(t){t[t.StaticDraw=35044]="StaticDraw",t[t.StaticRead=35045]="StaticRead",t[t.StaticCopy=35046]="StaticCopy",t[t.DynamicDraw=35048]="DynamicDraw",t[t.DynamicRead=35049]="DynamicRead",t[t.DynamicCopy=35050]="DynamicCopy",t[t.StreamDraw=35040]="StreamDraw",t[t.StreamRead=35041]="StreamRead",t[t.StreamCopy=35042]="StreamCopy"}(je||(je={})),function(t){t[t.Int=5124]="Int",t[t.IntVec2=35667]="IntVec2",t[t.IntVec3=35668]="IntVec3",t[t.IntVec4=35669]="IntVec4",t[t.UnsignedInt=5125]="UnsignedInt",t[t.UnsignedIntVec2=36294]="UnsignedIntVec2",t[t.UnsignedIntVec3=36295]="UnsignedIntVec3",t[t.UnsignedIntVec4=36296]="UnsignedIntVec4",t[t.Float=5126]="Float",t[t.FloatVec2=35664]="FloatVec2",t[t.FloatVec3=35665]="FloatVec3",t[t.FloatVec4=35666]="FloatVec4",t[t.Bool=35670]="Bool",t[t.BoolVec2=35671]="BoolVec2",t[t.BoolVec3=35672]="BoolVec3",t[t.BoolVec4=35673]="BoolVec4",t[t.FloatMat2=35674]="FloatMat2",t[t.FloatMat3=35675]="FloatMat3",t[t.FloatMat4=35676]="FloatMat4",t[t.Sampler2D=35678]="Sampler2D"}(Ke||(Ke={})),function(t){t[t.Draw=0]="Draw",t[t.Group=1]="Group",t[t.Barrier=2]="Barrier"}(Qe||(Qe={}));const Ze=new WeakMap,Je=new WeakMap,ti=new WeakMap,ei=new WeakMap;let ii=1,ni=1,si=1;const ri=(t,e,i)=>{const n=t.get(e);if(void 0!==n)return n;const s=i();return t.set(e,s),s},oi=t=>t.material??null,ai=(t,e,i)=>{const n=((t,e)=>{const i=e?.rendererRegistry;if(i&&"function"==typeof i.resolve)try{const e=i.resolve(t);if(e&&"object"==typeof e)return ri(Ze,e,()=>ii++)}catch{}const n=t.constructor;return n&&"function"==typeof n?ri(Je,n,()=>ii++):0})(e,i),s=e.blendMode,r=(t=>{const e=t.texture;return e&&"object"==typeof e?ri(ti,e,()=>ni++):-1})(e),o=(t=>{const e=t.shader;return e&&"object"==typeof e?ri(ei,e,()=>si++):-1})(e),a=oi(e);return t.rendererId=n,t.blendMode=s,t.textureId=r,t.shaderId=o,t.pipelineKey=null!==a?a.pipelineKey:31*n+s,t.bindKey=null!==a?a.bindKey:31*n+(r>0?r:0),t},hi=(t,e)=>{const i=e.rendererRegistry;if(!i||"function"!=typeof i.resolve)return!0;try{return!1!==i.resolve(t.drawable)._consumesSharedTransform}catch{return!0}};class li{passes=[];nodeCount=0;reset(){this.passes.length=0,this.nodeCount=0}}var ui;!function(t){t[t.None=0]="None",t[t.Rect=1]="Rect",t[t.Stencil=2]="Stencil"}(ui||(ui={}));class ci{static _available=[];static _active=[];static acquire(){const t=ci._available.pop()??new ci;return ci._active.push(t),t}static release(t){const e=ci._active.lastIndexOf(t);-1!==e&&(ci._active.splice(e,1),t._resetRuntimeState(),ci._available.push(t))}backend;_view=null;_plan=new li;_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(t,e){this.backend=e,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=e.transformBufferCount??0;this._nodeIndex=i,this._commandPoolCursor=i;const n=this._acquireGroupScope(!1);return this._scopeStack.push(n),t._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(t,e){this._reserveEntryPlacement(e,t.zIndex);const i=this._reservedSeq,n=this._reservedZ;if(t._renderPlanHasBarrierEffects()){const e=this._createEffectDescriptor(t),s=null!==e.maskSource&&!(e.maskSource instanceof te);let r=0,o=0,a=0,h=0;if(e.cacheAsBitmap||e.filters.length>0||s||(e.needsBackdropBlend??!1)){const e=t.getBounds();if(e.width<=0||e.height<=0)return;r=Math.floor(e.left),o=Math.floor(e.top),a=Math.max(1,Math.ceil(e.width)),h=Math.max(1,Math.ceil(e.height))}const l=e.cacheAsBitmap&&t._renderPlanCanReuseBitmapCache(r,o,a,h)?null:this._acquireGroupScope(this._resolvePreserveDrawOrder(t)),u={kind:Qe.Barrier,node:t,effect:e,childPlan:l,left:r,top:o,width:a,height:h};if(this._pushBarrierEntry(i,n,u),null!==l){this._scopeStack.push(l);try{t._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}return}if(t._isDrawableForRenderPlan()){this._hasPending=!0,this._pendingSeq=i,this._pendingZ=n;try{t._collectForRenderPlan(this)}finally{this._hasPending=!1}return}const s=this._acquireGroupScope(this._resolvePreserveDrawOrder(t));this._pushGroupEntry(i,n,s),this._scopeStack.push(s);try{t._collectForRenderPlan(this)}finally{this._scopeStack.pop()}}emitDraw(t,e){const i=this._hasPending,n=this._pendingSeq,s=this._pendingZ;i&&(this._hasPending=!1);const r=i?s:t.zIndex;this._reserveEntryPlacement(e??(i?n:void 0),r);const o=this._reservedSeq,a=this._reservedZ,h=t.getBounds(),l=this._acquireDrawCommand();l.drawable=t,l.nodeIndex=this._nodeIndex++,l.seq=o,l.zIndex=a,l.groupIndex=void 0,l.material=t._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(t){const e=this._groupPool[this._groupPoolCursor]??{kind:Qe.Group,entries:[],hasMixedZ:!1,preserveDrawOrder:!1,_nextSeq:0,firstZ:null};return this._groupPool[this._groupPoolCursor]=e,this._groupPoolCursor++,e.entries.length=0,e.hasMixedZ=!1,e.preserveDrawOrder=t,e._nextSeq=0,e.firstZ=null,e}_acquireDrawCommand(){const t=this._commandPool[this._commandPoolCursor];if(void 0!==t)return this._commandPoolCursor++,t;const e={kind:Qe.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]=e,this._commandPoolCursor++,e}_pushDrawEntry(t,e,i){let n=this._drawEntryPool[this._drawEntryPoolCursor];void 0===n?(n={kind:Qe.Draw,seq:t,zIndex:e,command:i},this._drawEntryPool[this._drawEntryPoolCursor]=n):(n.seq=t,n.zIndex=e,n.command=i),this._drawEntryPoolCursor++,this._currentScope().entries.push(n)}_pushGroupEntry(t,e,i){let n=this._groupEntryPool[this._groupEntryPoolCursor];void 0===n?(n={kind:Qe.Group,seq:t,zIndex:e,scope:i},this._groupEntryPool[this._groupEntryPoolCursor]=n):(n.seq=t,n.zIndex=e,n.scope=i),this._groupEntryPoolCursor++,this._currentScope().entries.push(n)}_pushBarrierEntry(t,e,i){let n=this._barrierEntryPool[this._barrierEntryPoolCursor];void 0===n?(n={kind:Qe.Barrier,seq:t,zIndex:e,scope:i},this._barrierEntryPool[this._barrierEntryPoolCursor]=n):(n.seq=t,n.zIndex=e,n.scope=i),this._barrierEntryPoolCursor++,this._currentScope().entries.push(n)}_reserveEntryPlacement(t,e){const i=this._currentScope(),n=t??i._nextSeq;n>=i._nextSeq&&(i._nextSeq=n+1),null===i.firstZ?i.firstZ=e:i.hasMixedZ||i.firstZ===e||(i.hasMixedZ=!0),this._reservedSeq=n,this._reservedZ=e}_currentScope(){const t=this._scopeStack[this._scopeStack.length-1];if(!t)throw new Error("RenderPlanBuilder scope stack is empty.");return t}_resolvePreserveDrawOrder(t){return t.preserveDrawOrder}_createEffectDescriptor(t){const e=t._renderPlanGetMaskSource();let i=ui.None,n=null;if(t.clip){const e=t.clipShape;null===e||e instanceof te?(i=ui.Rect,n=e):(i=ui.Stencil,n=e)}const s=t._renderPlanGetBlendMode();return{filters:t._renderPlanGetFilters(),clip:i,clipShape:n,maskSource:e,cacheAsBitmap:t.cacheAsBitmap,blendMode:s,needsBackdropBlend:We(s)}}}const di=t=>`${t.pipelineKey}:${t.bindKey}`,_i=(t,e)=>t.minX<e.maxX&&t.maxX>e.minX&&t.minY<e.maxY&&t.maxY>e.minY;class fi{static optimize(t){for(const e of t.passes)this._optimizeGroup(e.root)}static _optimizeGroup(t){if(t.hasMixedZ){const e=t.entries.map((t,e)=>({entry:t,index:e}));e.sort((t,e)=>t.entry.zIndex-e.entry.zIndex||t.entry.seq-e.entry.seq||t.index-e.index);for(let i=0;i<e.length;i++)t.entries[i]=e[i].entry}this._applyMaterialGrouping(t);for(const e of t.entries)e.kind===Qe.Group?this._optimizeGroup(e.scope):e.kind===Qe.Barrier&&null!==e.scope.childPlan&&this._optimizeGroup(e.scope.childPlan)}static _applyMaterialGrouping(t){const e=t.entries,i=e.length;if(0===i)return;let n=0;for(let s=0;s<=i;s++){const r=s<i?e[s]:null,o=null===r||r.kind===Qe.Group||r.kind===Qe.Barrier;if(o&&s>n){const i=s;i-n>=1&&this._materialGroupSegment(e,n,i,t.preserveDrawOrder),n=s+1}else o&&(n=s+1)}this._assignGroupIndices(t)}static _assignGroupIndices(t){let e=1,i=null,n=null;for(const s of t.entries){if(s.kind!==Qe.Draw){i=null,n=null;continue}const t=di(s.command.material),r=s.zIndex;null!==i&&null!==n&&t===i&&r===n||(e++,i=t,n=r),s.command.groupIndex=e}}static _materialGroupSegment(t,e,i,n){if(i-e<=1)return;const s=[];for(let n=e;n<i;n++){const e=t[n];e.kind===Qe.Draw&&s.push({entry:e,origIdx:n})}if(!(s.length<=1||n)){const n=new Map;for(const t of s){const e=t.entry.zIndex,i=n.get(e)??[];i.push(t),n.set(e,i)}for(const s of n.values())s.length>1&&this._overlapAwareGroup(s,t,e,i)}}static _overlapAwareGroup(t,e,i,n){const s=new Map;for(const e of t){const t=di(e.entry.command.material),i=s.get(t)??[];i.push(e),s.set(t,i)}if(s.size<=1)return;const r=new Map;for(let t=i;t<n;t++)r.set(e[t],t);for(const t of s.values()){if(t.length<=1)continue;const s=[];for(const e of t){const t=r.get(e.entry);void 0!==t&&s.push(t)}if(s.sort((t,e)=>t-e),0===s.length)continue;const o=s[0],a=s[s.length-1];if(a-o+1===s.length)continue;let h=!1;for(let i=o+1;i<a&&!h;i++){const n=e[i];if(n.kind!==Qe.Draw)continue;if(di(n.command.material)!==di(t[0].entry.command.material))for(const e of t)if(_i(e.entry.command,n.command)){h=!0;break}}if(h)continue;const l=[];for(let t=i;t<o;t++)l.push(e[t]);const u=[];for(let t=a+1;t<n;t++)u.push(e[t]);const c=new Set(t.map(t=>t.entry)),d=[];for(let t=o;t<=a;t++){const i=e[t];c.has(i)||d.push(i)}const _=t.map(t=>t.entry),f=[...l,..._,...d,...u];for(let t=i;t<n;t++)e[t]=f[t-i];break}}}class pi extends h{_callback;constructor(t,e=0,i=0){super(e,i),this._callback=t}get width(){return this._width}set width(t){this._width!==t&&(this._width=t,this._callback())}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this._callback())}set(t=this._width,e=this._height){return this._width===t&&this._height===e||(this._width=t,this._height=e,this._callback()),this}add(t,e=t){return this.set(this._width+t,this._height+e)}subtract(t,e=t){return this.set(this._width-t,this._height-e)}scale(t,e=t){return this.set(this._width*t,this._height*e)}divide(t,e=t){return this.set(this._width/t,this._height/e)}copy(t){return this.set(t.width,t.height)}clone(){return new pi(this._callback,this._width,this._height)}}var mi;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint"}(mi||(mi={}));class gi{_center;_size;_viewport=new te(0,0,1,1);_transform=new Le;_inverseTransform=new Le;_bounds=new Ge;_flags=new De;_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,e,i,n){this._center=new Qt(this,0,t,e),this._size=new pi(this._setScalingDirty.bind(this),i,n),this._zoomBaseWidth=i,this._zoomBaseHeight=n,this._flags.push(mi.Transform,mi.TransformInverse,mi.BoundingBox)}static from(t={}){const e=new gi(t.center?.x??0,t.center?.y??0,t.size?.width??0,t.size?.height??0);return t.viewport&&(e.viewport=t.viewport),t.rotation&&0!==t.rotation&&(e.rotation=t.rotation),void 0!==t.zoom&&1!==t.zoom&&e.setZoom(t.zoom),e}_onObservableChange(){this._setPositionDirty()}get center(){return this._center}set center(t){this._center.copy(t)}get size(){return this._size}set size(t){this._size.copy(t)}get width(){return this._size.width}set width(t){this._size.width=t}get height(){return this._size.height}set height(t){this._size.height=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get viewport(){return this._viewport}set viewport(t){this._viewport.equals(t)||(this._viewport.copy(t),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(t,e){return this._center.set(t,e),this}resize(t,e){return this._zoomBaseWidth=t,this._zoomBaseHeight=e,this._zoomLevel=1,this._size.set(t,e),this}setRotation(t){const e=q(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}setViewport(t,e,i,n){return this._viewport.x===t&&this._viewport.y===e&&this._viewport.width===i&&this._viewport.height===n||(this._viewport.set(t,e,i,n),this._setDirty()),this}move(t,e){return this.setCenter(this._center.x+t,this._center.y+e),this}zoom(t){return this.resize(this._size.width*t,this._size.height*t),this}setZoom(t){const e=Math.max(1e-4,t);return this._zoomLevel=e,this._size.set(this._zoomBaseWidth/e,this._zoomBaseHeight/e),this}zoomIn(t=.1){return this.setZoom(this._zoomLevel+t)}zoomOut(t=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-t))}follow(t,e={}){return this._followTarget=t,this._followLerp=Y(e.lerp??1,0,1),this._followOffsetX=e.offsetX??0,this._followOffsetY=e.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(t){return null===t?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=t.clone():this._boundsConstraint.copy(t),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(t,e,i={}){return this._shakeIntensity=Math.max(0,t),this._shakeDurationMs=Math.max(0,e),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(t){return this._updateFollowTarget(),this._updateShake(t),this._applyBoundsConstraint(),this}rotate(t){return this.setRotation(this._rotation+t),this}reset(t,e,i,n){return this._zoomBaseWidth=i,this._zoomBaseHeight=n,this._zoomLevel=1,this._size.set(i,n),this._center.set(t,e),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(mi.Transform),this}getTransform(){return this._flags.has(mi.Transform)&&(this.updateTransform(),this._flags.remove(mi.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=2/this.width,n=-2/this.height;if(this._flags.has(mi.Rotation)){const t=W(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}return this._flags.has(mi.Rotation|mi.Scaling)&&(this._transform.a=i*this._cos,this._transform.b=i*this._sin,this._transform.c=-n*this._sin,this._transform.d=n*this._cos),this._transform.x=i*-this._transform.a-n*this._transform.b+-i*t,this._transform.y=i*-this._transform.c-n*this._transform.d+-n*e,this}getInverseTransform(){return this._flags.has(mi.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(mi.TransformInverse)),this._inverseTransform}screenToWorld(t,e,i,n){let s,r;if(void 0===i||void 0===n){s=t/(this.width||1)*2-1,r=1-e/(this.height||1)*2}else{const o=this._viewport.width*i,a=this._viewport.height*n;s=(t-this._viewport.x*i)/o*2-1,r=1-(e-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=s-o.x,l=r-o.y;return{x:(h*o.d-l*o.b)/a,y:(l*o.a-h*o.c)/a}}worldToScreen(t,e,i,n){const s=this.getTransform(),r=s.a*t+s.b*e+s.x,o=s.c*t+s.d*e+s.y;if(void 0===i||void 0===n)return{x:(r+1)/2*this.width,y:(1-o)/2*this.height};const a=this._viewport.x*i,h=this._viewport.y*n;return{x:a+(r+1)/2*this._viewport.width*i,y:h+(1-o)/2*this._viewport.height*n}}getBounds(){return this._flags.has(mi.BoundingBox)&&(this.updateBounds(),this._flags.remove(mi.BoundingBox)),this._bounds.getRect()}updateBounds(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=this.width/2,n=this.height/2;return this._bounds.reset().addCoords(t-i,e-n).addCoords(t+i,e+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(mi.TransformInverse,mi.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(mi.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(mi.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(mi.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;let t,e;if(this._followTarget instanceof ze){const i=this._followTarget.getGlobalTransform();t=i.x+this._followOffsetX,e=i.y+this._followOffsetY}else t=this._followTarget.x+this._followOffsetX,e=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(t,e):this.setCenter(this._center.x+(t-this._center.x)*this._followLerp,this._center.y+(e-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const t=this._boundsConstraint,e=this.width/2,i=this.height/2,n=t.left+e,s=t.right-e,r=t.top+i,o=t.bottom-i,a=n>s?(t.left+t.right)/2:Y(this._center.x,n,s),h=r>o?(t.top+t.bottom)/2:Y(this._center.y,r,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(t){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,t));const e=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-e):this._shakeIntensity;this._shakePhase+=Math.max(0,t)/1e3*this._shakeFrequency*Math.PI*2;const n=Math.sin(1.7*this._shakePhase)*i,s=Math.cos(1.3*this._shakePhase)*i;n===this._shakeOffsetX&&s===this._shakeOffsetY||(this._shakeOffsetX=n,this._shakeOffsetY=s,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}class yi{needsStencil=!1;_root;_destroyListeners=new Set;_version=0;_size;_viewport=new te;_defaultView;_view;constructor(t,e,i=!1){this._size=new h(t,e),this._root=i,this._defaultView=new gi(t/2,e/2,t,e),this._view=this._defaultView}get view(){return this._view}set view(t){this.setView(t)}get size(){return this._size}set size(t){this.resize(t.width,t.height)}get width(){return this._size.width}set width(t){this.resize(t,this.height)}get height(){return this._size.height}set height(t){this.resize(this.width,t)}get root(){return this._root}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setView(t){const e=t||this._defaultView;return this._view!==e&&(this._view=e,this._touch()),this}resize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}getViewport(t=this._view){const{x:e,y:i,width:n,height:s}=t.viewport;return this._viewport.set(Math.round(e*this.width),Math.round(i*this.height),Math.round(n*this.width),Math.round(s*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(t,e=this._view){const i=this.getViewport(e);return new ie(2*(t.x-i.left)/i.width-1,1-2*(t.y-i.top)/i.height).transform(e.getInverseTransform())}mapCoordsToPixel(t,e=this._view){const i=this.getViewport(e),n=t.clone().transform(e.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 t of[...this._destroyListeners])t();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}class wi extends yi{static defaultSamplerOptions={scaleMode:Ye.Linear,wrapMode:$e.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};_source=null;_textureVersion=0;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;constructor(t,e,i){super(t,e,!1);const{scaleMode:n,wrapMode:s,premultiplyAlpha:r,generateMipMap:o,flipY:a}={...wi.defaultSamplerOptions,...i};this._scaleMode=n,this._wrapMode=s,this._premultiplyAlpha=r,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(t){this.setSource(t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return X(this.width)&&X(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touchTexture()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touchTexture()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touchTexture()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._defaultView.resize(t,e),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}const xi=(t={})=>{const{canvas:e,fillStyle:i,width:n,height:s}=t,r=e??document.createElement("canvas"),o=r.getContext("2d");return r.width=n??10,r.height=s??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,r.width,r.height),r};class vi{static _black=null;static _white=null;static defaultSamplerOptions={scaleMode:Ye.Linear,wrapMode:$e.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1};static empty=new vi(null);static get black(){return null===vi._black&&(vi._black=new vi(xi({fillStyle:"#000"}))),vi._black}static get white(){return null===vi._white&&(vi._white=new vi(xi({fillStyle:"#fff"}))),vi._white}_version=0;_source=null;_size=new h(0,0);_destroyListeners=new Set;_scaleMode;_wrapMode;_premultiplyAlpha=!1;_generateMipMap=!1;_flipY=!1;constructor(t=null,e){const{scaleMode:i,wrapMode:n,premultiplyAlpha:s,generateMipMap:r,flipY:o}={...vi.defaultSamplerOptions,...e};this._scaleMode=i,this._wrapMode=n,this._premultiplyAlpha=s,this._generateMipMap=r,this._flipY=o,null!==t&&this.setSource(t)}get source(){return this._source}set source(t){this.setSource(t)}get size(){return this._size}set size(t){this.setSize(t.width,t.height)}get width(){return this._size.width}set width(t){this.setSize(t,this.height)}get height(){return this._size.height}set height(t){this.setSize(this.width,t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return X(this.width)&&X(this.height)}get version(){return this._version}_bumpVersion(){this._version++}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touch()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touch()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touch()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){const{width:t,height:e}=null===(i=this._source)?h.zero:g(i);var i;return this.setSize(t,e),this._touch(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}destroy(){for(const t of[...this._destroyListeners])t();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}class bi{static play(t,e,i){const{node:n,effect:s}=t,r=s.filters.length>0,o=s.cacheAsBitmap,{left:a,top:h,width:l,height:u}=t;if(!r&&!o&&!s.needsBackdropBlend)return void this._withClip(n,e,t,()=>{null!==t.childPlan&&i(t.childPlan)});if(o&&null===t.childPlan){const i=n._renderPlanGetCacheTexture();return void(null!==i&&this._withClip(n,e,t,()=>{n._renderPlanDrawTexture(e,i,a,h,l,u,s.blendMode)}))}const c=o?n._renderPlanEnsureCacheTexture(l,u):null;let d=null;try{const _=o&&!r?c:e.acquireRenderTexture(l,u);_!==c&&(d=_),n._renderPlanRenderToTexture(e,_,a,h,l,u,()=>{null!==t.childPlan&&i(t.childPlan)});let f=_;if(r)for(let t=0;t<s.filters.length;t++){const i=t===s.filters.length-1&&o?c:e.acquireRenderTexture(l,u);try{s.filters[t].apply(e,f,i)}catch(t){throw i!==c&&e.releaseRenderTexture(i),t}null!==d&&(e.releaseRenderTexture(d),d=null),f=i,i!==c&&(d=i)}o&&n._renderPlanStoreCacheTexture(c,a,h,l,u),this._withClip(n,e,t,()=>{s.needsBackdropBlend?e.composeWithBackdropBlend(f,a,h,l,u,s.blendMode):n._renderPlanDrawTexture(e,f,a,h,l,u,s.blendMode)})}finally{null!==d&&e.releaseRenderTexture(d)}}static _withClip(t,e,i,n){if(i.effect.clip!==ui.Stencil)this._withRectClip(t,e,i,n);else{e.pushStencilClip(i.effect.clipShape,t.getGlobalTransform());try{this._withRectClip(t,e,i,n)}finally{e.popStencilClip()}}}static _withRectClip(t,e,i,n){if(i.effect.clip===ui.Rect){const s=i.effect.clipShape??t.getBounds();if(s.width<=0||s.height<=0)return;e.pushScissorRect(s);try{this._withMask(t,e,i,n)}finally{e.popScissorRect()}return}this._withMask(t,e,i,n)}static _withMask(t,e,i,n){const s=i.effect.maskSource;if(null===s)return void n();if(s instanceof te){if(s.width<=0||s.height<=0)return;e.pushScissorRect(s);try{n()}finally{e.popScissorRect()}return}const r=e.acquireRenderTexture(i.width,i.height),o=[r];try{t._renderPlanRenderToTexture(e,r,i.left,i.top,i.width,i.height,n);const a=this._resolveMaskTexture(t,e,s,i,o);e.composeWithAlphaMask(r,a,i.left,i.top,i.width,i.height,i.effect.blendMode)}finally{for(const t of o)e.releaseRenderTexture(t)}}static _resolveMaskTexture(t,e,i,n,s){if(!(i instanceof vi||i instanceof wi)){const r=e.acquireRenderTexture(n.width,n.height);return s.push(r),t._renderPlanRenderToTexture(e,r,n.left,n.top,n.width,n.height,()=>{i.render(e)}),r}return i}}const Si=(t,e)=>{const i=t[e].command.groupIndex;if(void 0===i)return 1;let n=1;for(let s=e+1;s<t.length;s++){const e=t[s];if(e.kind!==Qe.Draw||e.command.groupIndex!==i)break;n++}return n};class Bi{static play(t,e){const i=e;i._beginDrawPlan?.(t.nodeCount);try{for(const n of t.passes)null!==n.target&&e.renderTarget!==n.target&&e.setRenderTarget(n.target),e.view!==n.view&&e.setView(n.view),null!==n.clearColor&&e.clear(n.clearColor),this._playScope(n.root,e,i,this._createPlaybackContext())}finally{i._endDrawPlan?.()}}static playScope(t,e){const i=e;this._playScope(t,e,i,this._createPlaybackContext())}static _playScope(t,e,i,n){t.kind!==Qe.Barrier?this._playGroup(t,e,i,n):bi.play(t,e,t=>{this._playScope(t,e,i,n)})}static _playGroup(t,e,i,n){const s=t.entries;if(void 0!==i._prepareRenderGroupUpload){let t=n.passInstructionIndex,e=0;for(let r=0;r<s.length;){if(s[r].kind!==Qe.Draw){r++;continue}const o=Si(s,r);i._prepareRenderGroupUpload(s,r,o,this._createRenderGroupPlaybackContext(o,t,n.passGroupIndex+e)),t+=o,e++,r+=o}}let r=-1,o=0,a=0;for(let t=0;t<s.length;t++){const h=s[t];if(h.kind===Qe.Draw){if(-1===r&&(r=t,o=Si(s,t),a=0,i._beginRenderGroup?.(s,r,o),n.passGroupIndex++),void 0!==i._prepareRenderInstructionSlot){const t=this._createRenderInstructionSlot(a,n.passInstructionIndex);i._prepareRenderInstructionSlot(h.command,t)}i._prepareDrawCommand?.(h.command),e.draw(h.command.drawable),a++,n.passInstructionIndex++,a===o&&(i._endRenderGroup?.(s,r,o),r=-1,o=0,a=0)}else h.kind===Qe.Group?this._playGroup(h.scope,e,i,n):bi.play(h.scope,e,t=>{this._playScope(t,e,i,n)})}}static _createPlaybackContext(){return{passInstructionIndex:0,passGroupIndex:0}}static _createRenderGroupPlaybackContext(t,e,i){return Object.freeze({groupInstructionCount:t,firstPassInstructionIndex:e,lastPassInstructionIndex:e+t-1,passGroupIndex:i})}static _createRenderInstructionSlot(t,e){return Object.freeze({groupInstructionIndex:t,passInstructionIndex:e})}}function Ci(t,e){const i=ci.acquire();try{const n=i.build(t,e);fi.optimize(n),Bi.play(n,e)}finally{ci.release(i)}}var Ti;!function(t){t[t.None=0]="None",t[t.Enabled=1]="Enabled"}(Ti||(Ti={}));class Mi{_callback;_target;_view;_clearColor;constructor(t,e={}){this._callback=t,this._target=e.target??null,this._view=e.view??null,this._clearColor=e.clearColor??null}execute(t){const e=t._passCoordinator;if(e)return void e.withChildPass({target:this._target,view:this._view,load:null!==this._clearColor?"clear":"load",clearColor:this._clearColor,stencil:Ti.None},()=>{this._callback(t)});const i=t.renderTarget,n=t.view;t.setRenderTarget(this._target),t.setView(this._view),null!==this._clearColor&&t.clear(this._clearColor);try{this._callback(t)}finally{t.setRenderTarget(i),t.setView(n)}}}const Ai=t=>"destroy"in t&&"function"==typeof t.destroy;class Pi extends ze{static _spriteFactory=null;_interactive=!1;cursor=null;get interactive(){return this._interactive}set interactive(t){this._interactive!==t&&(this._interactive=t,this._stage?.interaction._notifyInteractiveChanged(this,t))}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(t){const e=this._signals??=new Map;let i=e.get(t);return void 0===i&&(i=new w,e.set(t,i)),i}_peekInteractionSignal(t){return this._signals?.get(t)??null}focusable=!1;tabIndex=0;_onFocus=null;_onBlur=null;_onKeyDown=null;_onKeyUp=null;get onFocus(){return this._onFocus??=new w}get onBlur(){return this._onBlur??=new w}get onKeyDown(){return this._onKeyDown??=new w}get onKeyUp(){return this._onKeyUp??=new w}_peekFocusSignal(t){return"focus"===t?this._onFocus:this._onBlur}_peekKeySignal(t){return"keydown"===t?this._onKeyDown:this._onKeyUp}focus(){return this._stage?.focus.focus(this),this}blur(){return this._stage?.focus.blur(this),this}_filters=[];_cacheBounds=new te;_cacheSprite=null;_captureView=null;_mask=null;_cacheAsBitmap=!1;_cacheDirty=!0;_cacheTexture=null;get filters(){return this._filters}set filters(t){this._filters.length=0,this._filters.push(...t),this.invalidateCache()}get mask(){return this._mask}set mask(t){if(t===this)throw new Error("A RenderNode cannot use itself as its own mask source.");this._mask!==t&&(this._mask=t,this.invalidateCache())}render(t){return Ci(this,t),this}_collect(t,e){this.visible&&(this.inView(t.view)?t.emitNode(this,e):t.backend.stats.culledNodes++)}_collectForRenderPlan(t){this._collectContent(t)}_isDrawableForRenderPlan(){return!1}_collectContent(t){}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(t){this._cacheAsBitmap!==t&&(this._cacheAsBitmap=t,this.invalidateCache(),t||this._destroyCacheTexture())}addFilter(t){return this._filters.push(t),this.invalidateCache()}removeFilter(t){const e=this._filters.indexOf(t);return-1!==e&&(this._filters.splice(e,1),this.invalidateCache()),this}static setInternalSpriteFactory(t){Pi._spriteFactory=t}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||We(this._renderPlanGetBlendMode())}_renderPlanGetMaskSource(){return this._mask}_renderPlanGetFilters(){return this._filters}_renderPlanGetBlendMode(){return qe.Normal}_renderPlanCanReuseBitmapCache(t,e,i,n){return this._cacheAsBitmap&&!this._cacheDirty&&null!==this._cacheTexture&&this._cacheBounds.equals({x:t,y:e,width:i,height:n})}_renderPlanGetCacheTexture(){return this._cacheTexture}_renderPlanEnsureCacheTexture(t,e){return this._ensureCacheTexture(t,e)}_renderPlanStoreCacheTexture(t,e,i,n,s){this._cacheTexture=t,this._cacheBounds.set(e,i,n,s),this._cacheDirty=!1}_renderPlanRenderToTexture(t,e,i,n,s,r,o){this._renderContentToTexture(t,e,i,n,s,r,o)}_renderPlanDrawTexture(t,e,i,n,s,r,o){this._drawTexture(t,e,i,n,s,r,o)}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const t of this._filters)Ai(t)&&t.destroy();if(this._filters.length=0,this._mask=null,null!==this._signals){for(const t of this._signals.values())t.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(t,e,i,n,s,r,o){null===this._captureView?this._captureView=new gi(i+s/2,n+r/2,s,r):this._captureView.reset(i+s/2,n+r/2,s,r),t.execute(new Mi(()=>{o()},{target:e,view:this._captureView,clearColor:Re.transparentBlack}))}_drawTexture(t,e,i,n,s,r,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(Re.white).setPosition(i,n).setRotation(0).setScale(1,1),a.width=s,a.height=r,a.render(t)}_ensureCacheTexture(t,e){return null===this._cacheTexture?this._cacheTexture=new wi(t,e):this._cacheTexture.width===t&&this._cacheTexture.height===e||this._cacheTexture.setSize(t,e),this._cacheTexture}_destroyCacheTexture(){null!==this._cacheTexture&&(this._cacheTexture.destroy(),this._cacheTexture=null),this._cacheDirty=!0}_getCacheSprite(){if(null===this._cacheSprite){if(null===Pi._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=Pi._spriteFactory()}return this._cacheSprite}}class Ei extends Pi{_children=[];get children(){return this._children}get width(){return Math.abs(this.scale.x)*this.getBounds().width}set width(t){this.scale.x=t/this.getBounds().width}get height(){return Math.abs(this.scale.y)*this.getBounds().height}set height(t){this.scale.y=t/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(...t){for(const e of t)this.addChildAt(e,this._children.length);return this}addChildAt(t,e){if(e<0||e>this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return t===this||(t.parent&&t.parent.removeChild(t),t.parent=this,this._children.splice(e,0,t),this.invalidateCache(),t._invalidateSubtreeTransform(),this._invalidateBoundsCascade(),t._setStage(this._stage),this._stage?.interaction._notifyNodeAdded(t)),this}swapChildren(t,e){if(t!==e){const i=this.getChildIndex(t),n=this.getChildIndex(e);this._children[i]=e,this._children[n]=t,this.invalidateCache()}return this}getChildIndex(t){const e=this._children.indexOf(t);if(-1===e)throw new Error("Drawable is not a child of the container.");return e}setChildIndex(t,e){if(e<0||e>=this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return m(this._children,this.getChildIndex(t),1),this._children.splice(e,0,t),this.invalidateCache(),this}getChildAt(t){if(t<0||t>=this._children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this._children[t]}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&this.removeChildAt(e),this}removeChildAt(t){const e=this._children[t];return m(this._children,t,1),e?.parent===this&&(this._invalidateBoundsCascade(),e.parent=null,e._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(e),this._stage?.focus._notifyNodeRemoved(e),e._setStage(null)),this.invalidateCache(),this}removeChildren(t=0,e=this._children.length){const i=e-t;if(i<0||i>e)throw new Error("Values are outside the acceptable range.");i>0&&this._invalidateBoundsCascade();for(let i=t;i<e;i++){const t=this._children[i];t?.parent===this&&(t.parent=null,t._invalidateSubtreeTransform(),this._stage?.interaction._notifyNodeRemoved(t),this._stage?.focus._notifyNodeRemoved(t),t._setStage(null))}return m(this._children,t,i),this.invalidateCache(),this}_setStage(t){if(this._stage!==t){this._stage=t;for(const e of this._children)e._setStage(t)}}_collectContent(t){if(0!==this._children.length)for(let e=0;e<this._children.length;e++)this._children[e]._collect(t,e)}contains(t,e){const i=this._children;for(let n=0;n<i.length;n++)if(i[n].contains(t,e))return!0;return!1}_invalidateChildrenTransform(){for(const t of this._children)t._invalidateSubtreeTransform()}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const t of this._children)t.visible&&this._bounds.addRect(t.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}}class ki{type;channel;target;_defaultPrevented=!1;constructor(t,e,i){this.type=t,this.channel=e,this.target=i}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}}var Ri,Di;!function(t){t[t.Container=768]="Container",t[t.Category=256]="Category",t[t.Gamepad=64]="Gamepad"}(Ri||(Ri={})),function(t){t[t.Keyboard=0]="Keyboard",t[t.Pointers=256]="Pointers",t[t.Gamepads=512]="Gamepads"}(Di||(Di={}));const Ii=16,Li=16;var Ui;!function(t){t[t.Backspace=8]="Backspace",t[t.Tab=9]="Tab",t[t.Clear=12]="Clear",t[t.Enter=13]="Enter",t[t.Shift=16]="Shift",t[t.Control=17]="Control",t[t.Alt=18]="Alt",t[t.Pause=19]="Pause",t[t.CapsLock=20]="CapsLock",t[t.Escape=27]="Escape",t[t.Space=32]="Space",t[t.PageUp=33]="PageUp",t[t.PageDown=34]="PageDown",t[t.End=35]="End",t[t.Home=36]="Home",t[t.Left=37]="Left",t[t.Up=38]="Up",t[t.Right=39]="Right",t[t.Down=40]="Down",t[t.Insert=45]="Insert",t[t.Delete=46]="Delete",t[t.Help=47]="Help",t[t.Zero=48]="Zero",t[t.One=49]="One",t[t.Two=50]="Two",t[t.Three=51]="Three",t[t.Four=52]="Four",t[t.Five=53]="Five",t[t.Six=54]="Six",t[t.Seven=55]="Seven",t[t.Eight=56]="Eight",t[t.Nine=57]="Nine",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.NumPad0=96]="NumPad0",t[t.NumPad1=97]="NumPad1",t[t.NumPad2=98]="NumPad2",t[t.NumPad3=99]="NumPad3",t[t.NumPad4=100]="NumPad4",t[t.NumPad5=101]="NumPad5",t[t.NumPad6=102]="NumPad6",t[t.NumPad7=103]="NumPad7",t[t.NumPad8=104]="NumPad8",t[t.NumPad9=105]="NumPad9",t[t.NumPadMultiply=106]="NumPadMultiply",t[t.NumPadAdd=107]="NumPadAdd",t[t.NumPadEnter=108]="NumPadEnter",t[t.NumPadSubtract=109]="NumPadSubtract",t[t.NumPadDecimal=110]="NumPadDecimal",t[t.NumPadDivide=111]="NumPadDivide",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NumLock=144]="NumLock",t[t.ScrollLock=145]="ScrollLock",t[t.Colon=186]="Colon",t[t.Equals=187]="Equals",t[t.Comma=188]="Comma",t[t.Dash=189]="Dash",t[t.Period=190]="Period",t[t.QuestionMark=191]="QuestionMark",t[t.Tilde=192]="Tilde",t[t.OpenBracket=219]="OpenBracket",t[t.BackwardSlash=220]="BackwardSlash",t[t.ClosedBracket=221]="ClosedBracket",t[t.Quotes=222]="Quotes"}(Ui||(Ui={}));class Fi{_app;_focused=null;_shiftDown=!1;_scopeStack=[];_onKeyDownHandler;_onKeyUpHandler;constructor(t){this._app=t,this._onKeyDownHandler=this._handleKeyDown.bind(this),this._onKeyUpHandler=this._handleKeyUp.bind(this),t.input.onKeyDown.add(this._onKeyDownHandler),t.input.onKeyUp.add(this._onKeyUpHandler)}get focused(){return this._focused}focus(t){t!==this._focused&&t.focusable&&(this.blur(),this._focused=t,t._peekFocusSignal("focus")?.dispatch(t))}blur(t){const e=this._focused;null===e||void 0!==t&&t!==e||(this._focused=null,e._peekFocusSignal("blur")?.dispatch(e))}pushScope(t){this._scopeStack.push(t)}popScope(){this._scopeStack.pop()}focusNext(){this._step(1)}focusPrevious(){this._step(-1)}_notifyNodeRemoved(t){let e=this._focused;for(;null!==e;){if(e===t)return void this.blur();e=e.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===Ui.Shift&&(this._shiftDown=!0);const e=this._focused;let i=!1;if(null!==e){const n=new ki("keydown",t,e);e._peekKeySignal("keydown")?.dispatch(n),i=n.defaultPrevented}i||t!==Ui.Tab||(this._shiftDown?this.focusPrevious():this.focusNext())}_handleKeyUp(t){t===Ui.Shift&&(this._shiftDown=!1);const e=this._focused;null!==e&&e._peekKeySignal("keyup")?.dispatch(new ki("keyup",t,e))}_step(t){const e=this._collectFocusables();if(0===e.length)return;const i=null===this._focused?-1:e.indexOf(this._focused),n=e.length;let s;s=-1===i?1===t?0:n-1:(i+t+n)%n;const r=e[s];void 0!==r&&this.focus(r)}_collectFocusables(){const t=this._scopeStack.at(-1)??this._app.scene.currentScene?.root??null;if(null===t)return[];const e=[];return this._collectInto(t,e),e.map((t,e)=>({node:t,index:e})).sort((t,e)=>t.node.tabIndex-e.node.tabIndex||t.index-e.index).map(t=>t.node)}_collectInto(t,e){if(t.visible&&(t.focusable&&e.push(t),t instanceof Ei))for(const i of t.children)this._collectInto(i,e)}}let Gi=null;class Ni{_milliseconds;constructor(t=0,e=Ni.milliseconds){this._milliseconds=t*e}get milliseconds(){return this._milliseconds}set milliseconds(t){this._milliseconds=t}get seconds(){return this._milliseconds/Ni.seconds}set seconds(t){this._milliseconds=t*Ni.seconds}get minutes(){return this._milliseconds/Ni.minutes}set minutes(t){this._milliseconds=t*Ni.minutes}get hours(){return this._milliseconds/Ni.hours}set hours(t){this._milliseconds=t*Ni.hours}set(t=0,e=Ni.milliseconds){return this._milliseconds=t*e,this}setMilliseconds(t){return this.milliseconds=t,this}setSeconds(t){return this.seconds=t,this}setMinutes(t){return this.minutes=t,this}setHours(t){return this.hours=t,this}equals({milliseconds:t,seconds:e,minutes:i,hours:n}={}){return!(void 0!==t&&this.milliseconds!==t||void 0!==e&&this.seconds!==e||void 0!==i&&this.minutes!==i||void 0!==n&&this.hours!==n)}greaterThan(t){return this._milliseconds>t.milliseconds}lessThan(t){return this._milliseconds<t.milliseconds}clone(){return new Ni(this._milliseconds)}copy(t){return this._milliseconds=t.milliseconds,this}add(t=0,e=Ni.milliseconds){return this._milliseconds+=t*e,this}addTime(t){return this._milliseconds+=t.milliseconds,this}subtract(t=0,e=Ni.milliseconds){return this._milliseconds-=t*e,this}subtractTime(t){return this._milliseconds-=t.milliseconds,this}destroy(){}static milliseconds=1;static seconds=1e3;static minutes=6e4;static hours=36e5;static now(){return new Ni(performance.now())}static fromMilliseconds(t){return new Ni(t,Ni.milliseconds)}static fromSeconds(t){return new Ni(t,Ni.seconds)}static fromMinutes(t){return new Ni(t,Ni.minutes)}static fromHours(t){return new Ni(t,Ni.hours)}static zero=new Ni(0);static oneMillisecond=new Ni(1);static oneSecond=new Ni(1,Ni.seconds);static oneMinute=new Ni(1,Ni.minutes);static oneHour=new Ni(1,Ni.hours);static get temp(){return null===Gi&&(Gi=new Ni),Gi}}class Oi{_startTime;_elapsedTime=new Ni(0);_running=!1;constructor(t=Ni.zero,e=!1){this._startTime=t.clone(),e&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const t=f();this._elapsedTime.add(t-this._startTime.milliseconds),this._startTime.milliseconds=t}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=f()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(f()-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 Vi extends Oi{_limit;constructor(t,e=!1){super(),this._limit=t.clone(),e&&this.restart()}get limit(){return this._limit}set limit(t){this._limit.copy(t)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/Ni.seconds}get remainingMinutes(){return this.remainingMilliseconds/Ni.minutes}get remainingHours(){return this.remainingMilliseconds/Ni.hours}}class zi{static defaultTriggerThreshold=300;channels;onStart=new w;onActive=new w;onStop=new w;onTrigger=new w;_triggerTimer;_detacher;_value=0;_unbound=!1;constructor(t,e={},i=null){this.channels=t,this._triggerTimer=new Vi(Ni.fromMilliseconds(e.threshold??zi.defaultTriggerThreshold)),this._detacher=i}get value(){return this._value}get active(){return this._value>0}update(t){if(this._unbound)return;let e=0;for(const i of this.channels){const n=t[i];void 0!==n&&Math.abs(n)>Math.abs(e)&&(e=n)}this._value=e,0!==e?(this._triggerTimer.running||(this._triggerTimer.restart(),this.onStart.dispatch(e)),this.onActive.dispatch(e)):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 qi{onConnect=new w;onDisconnect=new w;onButtonDown=new w;onButtonUp=new w;onAxisChange=new w;onPadReassigned=new w;_slot;_channels;_bindings=new Set;_detacher={detach:t=>{this._bindings.delete(t)}};_channelOffset;_mapping=null;_info=null;_browserGamepad=null;constructor(t,e){this._slot=t,this._channels=e,this._channelOffset=Di.Gamepads+t*Ri.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(t){return this._mapping?.hasChannel(t)??!1}async vibrate(t){const e=this._browserGamepad?.vibrationActuator;e?.playEffect&&await e.playEffect("dual-rumble",{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1,startDelay:t.startDelay??0})}stopVibration(){this._browserGamepad?.vibrationActuator?.reset?.()}onStart(t,e,i){const n=this._createBinding(t,i);return n.onStart.add(e),n}onActive(t,e,i){const n=this._createBinding(t,i);return n.onActive.add(e),n}onStop(t,e,i){const n=this._createBinding(t,i);return n.onStop.add(e),n}onTrigger(t,e,i){const n=this._createBinding(t,i);return n.onTrigger.add(e),n}_bind(t,e){this._browserGamepad=t,this._mapping=e.mapping,this._info={name:e.name,label:e.descriptor.label,vendorId:e.descriptor.vendorId,productId:e.descriptor.productId,productKey:e.descriptor.productKey},this.onConnect.dispatch()}_refreshBrowserGamepad(t){this._browserGamepad=t}_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(t){const e=t._browserGamepad,i=t._mapping,n=t._info;this._clearMappedChannels(),t._clearMappedChannels(),t._browserGamepad=null,t._mapping=null,t._info=null,this._browserGamepad=e,this._mapping=i,this._info=n}update(){if(null===this._browserGamepad||null===this._mapping)return void this._updateBindings();const t=this._channels,{buttons:e,axes:i}=this._browserGamepad;for(const i of this._mapping.buttons){const n=e[i.index];if(void 0===n)continue;const s=this._resolveOffset(i.channel),r=t[s],o=i.transformValue(n.value)||0;r!==o&&(t[s]=o,0===r&&0!==o?this.onButtonDown.dispatch(i,o):0!==r&&0===o&&this.onButtonUp.dispatch(i,o))}for(const e of this._mapping.axes){const n=i[e.index];if(void 0===n)continue;const s=this._resolveOffset(e.channel),r=t[s],o=e.transformValue(n)||0;r!==o&&(t[s]=o,this.onAxisChange.dispatch(e,o))}this._updateBindings()}destroy(){for(const t of[...this._bindings])t.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(t){return this._resolveOffset(t)}static resolveChannelOffset(t,e){return Di.Gamepads+t*Ri.Gamepad+(e^Di.Gamepads)}_resolveOffset(t){return this._channelOffset+(t^Di.Gamepads)}_clearMappedChannels(){if(null!==this._mapping){for(const t of this._mapping.buttons)this._channels[this._resolveOffset(t.channel)]=0;for(const t of this._mapping.axes)this._channels[this._resolveOffset(t.channel)]=0}}_createBinding(t,e={}){const i=(Array.isArray(t)?t:[t]).map(t=>this._resolveExternalChannel(t)),n=new zi(i,e,this._detacher);return this._bindings.add(n),n}_resolveExternalChannel(t){return t>=Di.Gamepads&&t<Di.Gamepads+Ri.Category?this._resolveOffset(t):t}_updateBindings(){for(const t of this._bindings)t.update(this._channels)}}class Wi{index;channel;invert;threshold;constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.threshold=Y(i.threshold??.2,0,1)}transformValue(t){let e=Y(t,0,1);return this.invert&&(e=1-e),e>this.threshold?e:0}}const Yi=t=>Di.Gamepads+t;var $i;!function(t){t.South=Yi(0),t.East=Yi(1),t.West=Yi(2),t.North=Yi(3),t.LeftShoulder=Yi(4),t.RightShoulder=Yi(5),t.LeftTrigger=Yi(6),t.RightTrigger=Yi(7),t.Select=Yi(8),t.Start=Yi(9),t.LeftStick=Yi(10),t.RightStick=Yi(11),t.DPadUp=Yi(12),t.DPadDown=Yi(13),t.DPadLeft=Yi(14),t.DPadRight=Yi(15),t.Guide=Yi(16),t.Share=Yi(17),t.Capture=Yi(18),t.Touchpad=Yi(19),t.Paddle1=Yi(20),t.Paddle2=Yi(21),t.Paddle3=Yi(22),t.Paddle4=Yi(23)}(Wi||(Wi={})),function(t){t.GenericDualAnalog="genericDualAnalog",t.Xbox="xbox",t.PlayStation="playStation",t.SwitchPro="switchPro",t.JoyConLeft="joyConLeft",t.JoyConRight="joyConRight",t.GameCube="gameCube",t.SteamController="steamController",t.SteamDeck="steamDeck",t.ArcadeStick="arcadeStick"}($i||($i={}));class Xi{buttons;axes;constructor(t,e){this.buttons=t,this.axes=e}hasChannel(t){for(const e of this.buttons)if(e.channel===t)return!0;for(const e of this.axes)if(e.channel===t)return!0;return!1}destroy(){this.buttons.length=0,this.axes.length=0}}class Hi extends Xi{family=$i.ArcadeStick;constructor(){super([new Wi(0,Wi.South),new Wi(1,Wi.East),new Wi(2,Wi.West),new Wi(3,Wi.North),new Wi(4,Wi.LeftShoulder),new Wi(5,Wi.RightShoulder),new Wi(6,Wi.LeftTrigger),new Wi(7,Wi.RightTrigger),new Wi(8,Wi.Select),new Wi(9,Wi.Start),new Wi(12,Wi.DPadUp),new Wi(13,Wi.DPadDown),new Wi(14,Wi.DPadLeft),new Wi(15,Wi.DPadRight),new Wi(16,Wi.Guide)],[])}}class ji{index;channel;invert;normalize;threshold;bipolar;constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=Y(i.threshold??.2,0,1),this.bipolar=i.bipolar??!1}transformValue(t){let e=Y(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),this.bipolar?Math.abs(e)>this.threshold?e:0:e>this.threshold?e:0}}const Ki=t=>Di.Gamepads+t;!function(t){t.LeftStickLeft=Ki(32),t.LeftStickRight=Ki(33),t.LeftStickUp=Ki(34),t.LeftStickDown=Ki(35),t.RightStickLeft=Ki(36),t.RightStickRight=Ki(37),t.RightStickUp=Ki(38),t.RightStickDown=Ki(39),t.LeftStickX=Ki(40),t.LeftStickY=Ki(41),t.RightStickX=Ki(42),t.RightStickY=Ki(43),t.TouchpadX=Ki(44),t.TouchpadY=Ki(45),t.Touchpad2X=Ki(46),t.Touchpad2Y=Ki(47),t.AuxiliaryAxis0Negative=Ki(48),t.AuxiliaryAxis0Positive=Ki(49),t.AuxiliaryAxis1Negative=Ki(50),t.AuxiliaryAxis1Positive=Ki(51),t.AuxiliaryAxis2Negative=Ki(52),t.AuxiliaryAxis2Positive=Ki(53),t.AuxiliaryAxis3Negative=Ki(54),t.AuxiliaryAxis3Positive=Ki(55)}(ji||(ji={}));class Qi extends Xi{family=$i.GenericDualAnalog;constructor(){super([new Wi(0,Wi.South),new Wi(1,Wi.East),new Wi(2,Wi.West),new Wi(3,Wi.North),new Wi(4,Wi.LeftShoulder),new Wi(5,Wi.RightShoulder),new Wi(6,Wi.LeftTrigger),new Wi(7,Wi.RightTrigger),new Wi(8,Wi.Select),new Wi(9,Wi.Start),new Wi(10,Wi.LeftStick),new Wi(11,Wi.RightStick),new Wi(12,Wi.DPadUp),new Wi(13,Wi.DPadDown),new Wi(14,Wi.DPadLeft),new Wi(15,Wi.DPadRight),new Wi(16,Wi.Guide),new Wi(17,Wi.Share),new Wi(18,Wi.Capture),new Wi(19,Wi.Touchpad),new Wi(20,Wi.Paddle1)],[new ji(0,ji.LeftStickLeft,{invert:!0}),new ji(0,ji.LeftStickRight),new ji(1,ji.LeftStickUp,{invert:!0}),new ji(1,ji.LeftStickDown),new ji(2,ji.RightStickLeft,{invert:!0}),new ji(2,ji.RightStickRight),new ji(3,ji.RightStickUp,{invert:!0}),new ji(3,ji.RightStickDown),new ji(0,ji.LeftStickX,{bipolar:!0}),new ji(1,ji.LeftStickY,{bipolar:!0}),new ji(2,ji.RightStickX,{bipolar:!0}),new ji(3,ji.RightStickY,{bipolar:!0}),new ji(4,ji.AuxiliaryAxis0Negative,{invert:!0}),new ji(4,ji.AuxiliaryAxis0Positive),new ji(5,ji.AuxiliaryAxis1Negative,{invert:!0}),new ji(5,ji.AuxiliaryAxis1Positive),new ji(6,ji.AuxiliaryAxis2Negative,{invert:!0}),new ji(6,ji.AuxiliaryAxis2Positive),new ji(7,ji.AuxiliaryAxis3Negative,{invert:!0}),new ji(7,ji.AuxiliaryAxis3Positive)])}}class Zi extends Qi{family=$i.GameCube}class Ji extends Xi{family=$i.JoyConLeft;constructor(){super([new Wi(0,Wi.South),new Wi(1,Wi.East),new Wi(2,Wi.West),new Wi(3,Wi.North),new Wi(4,Wi.LeftShoulder),new Wi(5,Wi.RightShoulder),new Wi(8,Wi.Select),new Wi(10,Wi.LeftStick),new Wi(16,Wi.Capture)],[new ji(0,ji.LeftStickLeft,{invert:!0}),new ji(0,ji.LeftStickRight),new ji(1,ji.LeftStickUp,{invert:!0}),new ji(1,ji.LeftStickDown),new ji(0,ji.LeftStickX,{bipolar:!0}),new ji(1,ji.LeftStickY,{bipolar:!0})])}}class tn extends Xi{family=$i.JoyConRight;constructor(){super([new Wi(0,Wi.South),new Wi(1,Wi.East),new Wi(2,Wi.West),new Wi(3,Wi.North),new Wi(4,Wi.LeftShoulder),new Wi(5,Wi.RightShoulder),new Wi(9,Wi.Start),new Wi(10,Wi.LeftStick),new Wi(16,Wi.Guide)],[new ji(0,ji.LeftStickLeft,{invert:!0}),new ji(0,ji.LeftStickRight),new ji(1,ji.LeftStickUp,{invert:!0}),new ji(1,ji.LeftStickDown),new ji(0,ji.LeftStickX,{bipolar:!0}),new ji(1,ji.LeftStickY,{bipolar:!0})])}}class en extends Qi{family=$i.PlayStation}class nn extends Qi{family=$i.SteamController}class sn extends Xi{family=$i.SteamDeck;constructor(){super([new Wi(2,Wi.Capture),new Wi(3,Wi.South),new Wi(4,Wi.East),new Wi(5,Wi.West),new Wi(6,Wi.North),new Wi(7,Wi.LeftShoulder),new Wi(8,Wi.RightShoulder),new Wi(11,Wi.Select),new Wi(12,Wi.Start),new Wi(13,Wi.Guide),new Wi(14,Wi.LeftStick),new Wi(15,Wi.RightStick),new Wi(16,Wi.DPadUp),new Wi(17,Wi.DPadDown),new Wi(18,Wi.DPadLeft),new Wi(19,Wi.DPadRight),new Wi(20,Wi.Paddle2),new Wi(21,Wi.Paddle1),new Wi(22,Wi.Paddle4),new Wi(23,Wi.Paddle3)],[new ji(0,ji.LeftStickLeft,{invert:!0}),new ji(0,ji.LeftStickRight),new ji(1,ji.LeftStickUp,{invert:!0}),new ji(1,ji.LeftStickDown),new ji(2,ji.RightStickLeft,{invert:!0}),new ji(2,ji.RightStickRight),new ji(3,ji.RightStickUp,{invert:!0}),new ji(3,ji.RightStickDown),new ji(0,ji.LeftStickX,{bipolar:!0}),new ji(1,ji.LeftStickY,{bipolar:!0}),new ji(2,ji.RightStickX,{bipolar:!0}),new ji(3,ji.RightStickY,{bipolar:!0}),new ji(8,ji.AuxiliaryAxis0Positive,{normalize:!0}),new ji(9,ji.AuxiliaryAxis1Positive,{normalize:!0})])}}class rn extends Qi{family=$i.SwitchPro}class on extends Qi{family=$i.Xbox}const an=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,hn=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,ln=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,un=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,cn=(t,e,i)=>({...void 0!==i&&{ids:i},name:t,resolve:()=>({name:t,mapping:e()})}),dn=t=>t.trim().toLowerCase(),_n=t=>{const e=t.replace(hn,"").replace(an,"").replace(un,"").replace(ln,"").replaceAll(/\s+/g," ").trim();return e.length>0?e:null},fn=(t,e)=>{if(!e)return!0;for(const i of(t=>t?(Array.isArray(t)?t:[t]).map(dn):[])(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},pn=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=hn.exec(t)||an.exec(t)||un.exec(t)||ln.exec(t);if(!e)return null;const[,i,n]=e;return void 0===i||void 0===n?null:`${i.toLowerCase()}:${n.toLowerCase()}`})(e),n=i?.slice(0,4)??null,s=i?.slice(5)??null;return{id:t.id,index:t.index,label:e,vendorId:n,productId:s,productKey:i,name:_n(e)}},mn=(t,e)=>fn(e,t.ids)?((t,e)=>{const i=t.resolve(e);return null==i?null:"mapping"in i?{descriptor:e,name:i.name??t.name??e.name??e.label,mapping:i.mapping}:{descriptor:e,name:t.name??e.name??e.label,mapping:i}})(t,e):null,gn=[...[cn("Xbox 360 Controller",()=>new on,"045e:028e"),cn("Xbox One Controller",()=>new on,["045e:02d1","045e:02dd"]),cn("Xbox Wireless Controller",()=>new on,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),cn("Xbox One Elite Controller",()=>new on,"045e:02e3"),cn("Xbox Elite Wireless Controller Series 2",()=>new on,["045e:0b00","045e:0b05","045e:0b22"]),cn("Xbox Series Controller",()=>new on,["045e:0b12","045e:0b13"]),cn("PlayStation 3 Controller",()=>new en,"054c:0268"),cn("DualShock 4 Controller",()=>new en,["054c:05c4","054c:09cc","054c:0ba0"]),cn("DualSense Controller",()=>new en,"054c:0ce6"),cn("DualSense Edge Controller",()=>new en,"054c:0df2"),cn("GameCube Controller Adapter",()=>new Zi,"057e:0337"),cn("Joy-Con (L)",()=>new Ji,"057e:2006"),cn("Joy-Con (R)",()=>new tn,"057e:2007"),cn("Joy-Con Charging Grip",()=>new rn,"057e:200e"),cn("Switch Pro Controller",()=>new rn,"057e:2009"),cn("Joy-Con 2 (L)",()=>new Ji,"057e:2066"),cn("Joy-Con 2 (R)",()=>new tn,"057e:2067"),cn("Switch 2 Pro Controller",()=>new rn,"057e:2069"),cn("Switch 2 GameCube Controller",()=>new Zi,"057e:2073"),cn("Steam Controller",()=>new nn,["28de:1102","28de:1142"]),cn("Steam Virtual Gamepad",()=>new Qi,"28de:11ff"),cn("Steam Deck",()=>new sn,"28de:1205"),cn("F310 Gamepad",()=>new Qi,"046d:c216"),cn("F710 Gamepad",()=>new Qi,["046d:c219","046d:c21f"]),cn("8BitDo P30 Controller",()=>new Qi,["2dc8:5107","2dc8:5108"]),cn("8BitDo SF30 Pro Controller",()=>new rn,["2dc8:3000","2dc8:6100","2dc8:6101"]),cn("8BitDo SN30 Controller",()=>new rn,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),cn("8BitDo NES30 Controller",()=>new Qi,"2dc8:ab12"),cn("PowerA Switch Controller",()=>new rn,"20d6:a713"),cn("PowerA OPS Pro Wireless Controller",()=>new Qi,"20d6:4033"),cn("PowerA OPS Wireless Controller",()=>new Qi,"20d6:4026"),cn("Nacon Revolution 3 Controller",()=>new en,"146b:0611"),cn("Nacon Revolution Unlimited Pro Controller",()=>new en,"146b:0d08"),cn("Nacon Revolution Infinity Controller",()=>new en,"146b:0d10"),cn("Nacon Revolution 5 Pro Controller",()=>new en,["3285:0d17","3285:0d19"]),cn("Razer Raiju Controller",()=>new en,"1532:1000"),cn("Razer Raiju Mobile Controller",()=>new en,["1532:0705","1532:0707"]),cn("Razer Raiju Tournament Edition Controller",()=>new en,["1532:1007","1532:100a"]),cn("Razer Raiju Ultimate Controller",()=>new en,["1532:1004","1532:1009"]),cn("Razer Raion Controller",()=>new Hi,"1532:1100")],...[cn("Microsoft Controller",()=>new on,"045e"),cn("Sony Controller",()=>new en,"054c"),cn("Valve Controller",()=>new sn,"28de")],cn("Generic Gamepad",()=>new Qi)];class yn{onPinch;onRotate;onLongPress;touchPointers=new Map;longPressEntries=new Map;prevDistance=-1;prevAngle=0;centerVec=new ie;constructor(t,e,i,n){this.onPinch=e,this.onRotate=i,this.onLongPress=n}onPointerDown(t){"touch"===t.type&&(this.touchPointers.set(t.id,t),this._resetTwoTouchBaseline());const e=setTimeout(()=>{this.longPressEntries.delete(t.id),this.onLongPress.dispatch(t)},500);this.longPressEntries.set(t.id,{pointerId:t.id,pointer:t,timerId:e,startX:t.x,startY:t.y})}onPointerMove(t,e){const i=this.longPressEntries.get(t.id);if(i){const n=t.x-i.startX,s=t.y-i.startY;Math.sqrt(n*n+s*s)>e&&(clearTimeout(i.timerId),this.longPressEntries.delete(t.id))}"touch"===t.type&&(this.touchPointers.size<2||this._processTwoTouchGestures())}onPointerUp(t){this._cancelLongPress(t.id)}onPointerLeave(t){this._cancelLongPress(t.id),"touch"===t.type&&(this.touchPointers.delete(t.id),this._resetTwoTouchBaseline())}onPointerCancel(t){this._cancelLongPress(t.id),"touch"===t.type&&(this.touchPointers.delete(t.id),this._resetTwoTouchBaseline())}destroy(){for(const t of this.longPressEntries.values())clearTimeout(t.timerId);this.longPressEntries.clear(),this.touchPointers.clear(),this.centerVec.destroy()}_cancelLongPress(t){const e=this.longPressEntries.get(t);e&&(clearTimeout(e.timerId),this.longPressEntries.delete(t))}_resetTwoTouchBaseline(){this.prevDistance=-1,this.prevAngle=0}_processTwoTouchGestures(){const t=this.touchPointers.values(),e=t.next().value,i=t.next().value,n=i.x-e.x,s=i.y-e.y,r=Math.sqrt(n*n+s*s),o=Math.atan2(s,n),a=(e.x+i.x)/2,h=(e.y+i.y)/2;if(this.centerVec.set(a,h),this.prevDistance>0){const t=r/this.prevDistance;Math.abs(t-1)>1e-4&&this.onPinch.dispatch(t,this.centerVec);const e=o-this.prevAngle;Math.abs(e)>1e-4&&this.onRotate.dispatch(e,this.centerVec)}this.prevDistance=r,this.prevAngle=o}}const wn=t=>Di.Pointers+t,xn=(t,e)=>wn(16*t+e);var vn,bn;!function(t){t[t.None=0]="None",t[t.Over=1]="Over",t[t.Leave=2]="Leave",t[t.Down=4]="Down",t[t.Move=8]="Move",t[t.Up=16]="Up",t[t.Cancel=32]="Cancel"}(vn||(vn={})),function(t){t[t.Unknown=0]="Unknown",t[t.InsideCanvas=1]="InsideCanvas",t[t.OutsideCanvas=2]="OutsideCanvas",t[t.Pressed=3]="Pressed",t[t.Moving=4]="Moving",t[t.Released=5]="Released",t[t.Cancelled=6]="Cancelled"}(bn||(bn={}));class Sn{id;type;position;startPos=new ie(-1,-1);size;tilt;stateFlags=new De;_app;_canvas;_channels;_slotIndex;_channelBase;_buttons;_pressure;_rotation;_isPrimary;_currentState=bn.Unknown;constructor(t,e,i,n,s){const{pointerId:r,pointerType:o,clientX:a,clientY:l,width:u,height:c,tiltX:d,tiltY:_,buttons:f,pressure:p,twist:m,isPrimary:g}=t;this._app=e,this._canvas=i,this._channels=n,this._slotIndex=s,this._channelBase=Di.Pointers+16*s;const y=this._computeDesignGeometry(a,l,u,c);this.id=r,this.type=o,this.position=new ie(y.x,y.y),this.size=new h(y.width,y.height),this.tilt=new ie(d,_),this._buttons=f,this._pressure=p,this._rotation=m,this._isPrimary=g,this.stateFlags.push(vn.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=bn.InsideCanvas,this._writeChannels(!0)}handleLeave(t){this.handleEvent(t),this.stateFlags.push(vn.Leave),this._currentState=bn.OutsideCanvas,this._writeChannels(!1)}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(vn.Down),this._currentState=bn.Pressed,this._writeChannels(!0)}handleMove(t){this.handleEvent(t),this.stateFlags.push(vn.Move),this._currentState=bn.Moving,this._writeChannels(!0)}handleRelease(t){this.handleEvent(t),this.stateFlags.push(vn.Up),this._currentState=bn.Released,this._writeChannels(!0)}handleCancel(t){this.handleEvent(t),this.stateFlags.push(vn.Cancel),this._currentState=bn.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(t){const{clientX:e,clientY:i,width:n,height:s,tiltX:r,tiltY:o,buttons:a,pressure:h,twist:l,isPrimary:u}=t,c=this._computeDesignGeometry(e,i,n,s);return this.position.set(c.x,c.y),this.size.set(c.width,c.height),this.tilt.set(r,o),this._buttons=a,this._pressure=h,this._rotation=l,this._isPrimary=u,this}_computeDesignGeometry(t,e,i,n){const s=this._app,r=this._canvas;if(!s||!r)return{x:0,y:0,width:0,height:0};const o=r.getBoundingClientRect(),a=o.width>0?(t-o.left)/o.width:0,h=o.height>0?(e-o.top)/o.height:0,l=a*r.width,u=h*r.height,c=o.width>0?i/o.width*r.width:0,d=o.height>0?n/o.height*r.height:0,_=s._backingStoreToDesign(l,u),f=s._backingStoreToDesign(l+c,u+d);return{x:_.x,y:_.y,width:Math.abs(f.x-_.x),height:Math.abs(f.y-_.y)}}_writeChannels(t){const e=this._channels,i=this._canvas;if(!e||!i)return;const n=this._channelBase,s=this._app,r=(s?s.width:i.width)||1,o=(s?s.height:i.height)||1;if(!t){for(let t=0;t<16;t++)e[n+t]=0;return}const a=Math.min(1,Math.max(0,this.position.x/r)),h=Math.min(1,Math.max(0,this.position.y/o));e[n+0]=1,e[n+1]=a,e[n+2]=h,e[n+3]=this._pressure,e[n+4]=Math.min(1,this.size.width/r),e[n+5]=Math.min(1,this.size.height/o),e[n+6]=this._rotation/359,e[n+7]=(this.tilt.x+90)/180,e[n+8]=(this.tilt.y+90)/180,e[n+9]=1&this._buttons?1:0,e[n+10]=2&this._buttons?1:0,e[n+11]=4&this._buttons?1:0,e[n+12]="mouse"===this.type?1:0,e[n+13]="touch"===this.type?1:0,e[n+14]="pen"===this.type?1:0,e[n+15]=this._isPrimary?1:0}_clearChannels(){const t=this._channels;if(!t)return;const e=this._channelBase;for(let i=0;i<16;i++)t[e+i]=0}}!function(t){t.Active=wn(0),t.X=wn(1),t.Y=wn(2),t.Pressure=wn(3),t.Width=wn(4),t.Height=wn(5),t.Twist=wn(6),t.TiltX=wn(7),t.TiltY=wn(8),t.Left=wn(9),t.Right=wn(10),t.Middle=wn(11),t.IsMouse=wn(12),t.IsTouch=wn(13),t.IsPen=wn(14),t.IsPrimary=wn(15),t.Slot0Active=xn(0,0),t.Slot0X=xn(0,1),t.Slot0Y=xn(0,2),t.Slot1Active=xn(1,0),t.Slot1X=xn(1,1),t.Slot1Y=xn(1,2),t.Slot2Active=xn(2,0),t.Slot2X=xn(2,1),t.Slot2Y=xn(2,2),t.Slot3Active=xn(3,0),t.Slot3X=xn(3,1),t.Slot3Y=xn(3,2),t.Slot4Active=xn(4,0),t.Slot4X=xn(4,1),t.Slot4Y=xn(4,2),t.Slot5Active=xn(5,0),t.Slot5X=xn(5,1),t.Slot5Y=xn(5,2),t.Slot6Active=xn(6,0),t.Slot6X=xn(6,1),t.Slot6Y=xn(6,2),t.Slot7Active=xn(7,0),t.Slot7X=xn(7,1),t.Slot7Y=xn(7,2),t.Slot8Active=xn(8,0),t.Slot8X=xn(8,1),t.Slot8Y=xn(8,2),t.Slot9Active=xn(9,0),t.Slot9X=xn(9,1),t.Slot9Y=xn(9,2),t.Slot10Active=xn(10,0),t.Slot10X=xn(10,1),t.Slot10Y=xn(10,2),t.Slot11Active=xn(11,0),t.Slot11X=xn(11,1),t.Slot11Y=xn(11,2),t.Slot12Active=xn(12,0),t.Slot12X=xn(12,1),t.Slot12Y=xn(12,2),t.Slot13Active=xn(13,0),t.Slot13X=xn(13,1),t.Slot13Y=xn(13,2),t.Slot14Active=xn(14,0),t.Slot14X=xn(14,1),t.Slot14Y=xn(14,2),t.Slot15Active=xn(15,0),t.Slot15X=xn(15,1),t.Slot15Y=xn(15,2)}(Sn||(Sn={}));var Bn,Cn;!function(t){t[t.None=0]="None",t[t.KeyDown=1]="KeyDown",t[t.KeyUp=2]="KeyUp",t[t.MouseWheel=4]="MouseWheel",t[t.PointerUpdate=8]="PointerUpdate"}(Bn||(Bn={}));class Tn{order=100;_app;canvas;channels=new Float32Array(Ri.Container);pointers=new Map;_gamepads;gamepadsByBrowserIndex=new Map;bindings=new Set;capturedKeyChannels=new Map;bindingDetacher={detach:t=>{this.bindings.delete(t);for(const e of t.channels)if(e<Ri.Category){const t=this.capturedKeyChannels.get(e);void 0!==t&&(t<=1?this.capturedKeyChannels.delete(e):this.capturedKeyChannels.set(e,t-1))}}};wheelOffset=new ie;flags=new De;channelsPressed=[];channelsReleased=[];gamepadDefinitions;slotStrategy;pointerSlots=new Map;freeSlots=Array.from({length:16},(t,e)=>e);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 w;onPointerEnter=new w;onPointerLeave=new w;onPointerDown=new w;onPointerMove=new w;onPointerUp=new w;onPointerTap=new w;onPointerSwipe=new w;onPointerCancel=new w;onMouseWheel=new w;onKeyDown=new w;onKeyUp=new w;onGamepadConnected=new w;onGamepadDisconnected=new w;onAnyGamepadReassigned=new w;onAnyGamepadButtonDown=new w;onAnyGamepadButtonUp=new w;onAnyGamepadAxisChange=new w;onPinch=new w;onRotate=new w;onLongPress=new w;constructor(t){const e=t.options.input??{},i=e.gamepadDefinitions??[],n=e.pointerDistanceThreshold??10,s=e.gamepadSlotStrategy??"sticky";this._app=t,this.canvas=t.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=n,this.gamepadDefinitions=[...i,...gn],this.slotStrategy=s,this.canvas.style.touchAction="none",this.gestureRecognizer=new yn(n,this.onPinch,this.onRotate,this.onLongPress);const r=new qi(0,this.channels),o=new qi(1,this.channels),a=new qi(2,this.channels),h=new qi(3,this.channels);this._gamepads=[r,o,a,h];for(const t of this._gamepads)this.wireGamepadEvents(t);this.addEventListeners()}getPrimaryPointerPosition(){for(const t of this.pointers.values())if(t.isPrimary&&t.currentState!==bn.Cancelled)return{x:t.x,y:t.y};for(const t of this.pointers.values())if(t.currentState!==bn.Cancelled)return{x:t.x,y:t.y};return null}get pointersInCanvas(){for(const t of this.pointers.values())if(t.currentState!==bn.OutsideCanvas&&t.currentState!==bn.Cancelled)return!0;return!1}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this._gamepads}get gamepadSlotStrategy(){return this.slotStrategy}getGamepad(t){return this._gamepads[t]}get connectedGamepads(){const t=[];for(const e of this._gamepads)e.connected&&t.push(e);return t}get connectedGamepadCount(){let t=0;for(const e of this._gamepads)e.connected&&t++;return t}get firstConnectedGamepad(){for(const t of this._gamepads)if(t.connected)return t;return null}get hasGamepad(){for(const t of this._gamepads)if(t.connected)return!0;return!1}onStart(t,e,i){const n=this.createBinding(t,i);return n.onStart.add(e),n}onActive(t,e,i){const n=this.createBinding(t,i);return n.onActive.add(e),n}onStop(t,e,i){const n=this.createBinding(t,i);return n.onStop.add(e),n}onTrigger(t,e,i){const n=this.createBinding(t,i);return n.onTrigger.add(e),n}update(t){this.updateGamepads();for(const t of this.bindings)t.update(this.channels);this.flags.value!==Bn.None&&this.updateEvents()}destroy(){this.removeEventListeners(),this.gestureRecognizer.destroy();for(const t of this.pointers.values())t.destroy();this.pointers.clear();for(const t of this._gamepads)t.destroy();for(const t of[...this.bindings])t.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,e={}){const i=Array.isArray(t)?t:[t],n=e.gamepadSlot??0,s=i.map(t=>this.resolveExternalChannel(t,n)),r=new zi(s,e,this.bindingDetacher);this.bindings.add(r);for(const t of s)t<Ri.Category&&this.capturedKeyChannels.set(t,(this.capturedKeyChannels.get(t)??0)+1);return r}resolveExternalChannel(t,e){return t>=Di.Gamepads&&t<Di.Gamepads+Ri.Category?Di.Gamepads+e*Ri.Gamepad+(t^Di.Gamepads):t}wireGamepadEvents(t){t.onButtonDown.add((e,i)=>{this.onAnyGamepadButtonDown.dispatch(t,e,i)}),t.onButtonUp.add((e,i)=>{this.onAnyGamepadButtonUp.dispatch(t,e,i)}),t.onAxisChange.add((e,i)=>{this.onAnyGamepadAxisChange.dispatch(t,e,i)})}_assignSlot(t){if(this.pointerSlots.has(t))return this.pointerSlots.get(t);if(0===this.freeSlots.length)return null;const e=this.freeSlots.shift();return this.pointerSlots.set(t,e),e}_releaseSlot(t){const e=this.pointerSlots.get(t);void 0!==e&&(this.pointerSlots.delete(t),this.freeSlots.unshift(e))}handleKeyDown(t){if(!this.canvasFocusedValue)return;const e=Di.Keyboard+t.keyCode;this.channels[e]=1,this.channelsPressed.push(e),this.flags.push(Bn.KeyDown),this.capturedKeyChannels.has(e)&&d(t)}handleKeyUp(t){if(!this.canvasFocusedValue)return;const e=Di.Keyboard+t.keyCode;this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(Bn.KeyUp),this.capturedKeyChannels.has(e)&&d(t)}handlePointerOver(t){const e=this._assignSlot(t.pointerId);null!==e&&(this.pointers.set(t.pointerId,new Sn(t,this._app,this.canvas,this.channels,e)),this.flags.push(Bn.PointerUpdate))}handlePointerLeave(t){const e=this.pointers.get(t.pointerId);e&&(e.handleLeave(t),this.gestureRecognizer.onPointerLeave(e),this._releaseSlot(t.pointerId),this.flags.push(Bn.PointerUpdate))}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0;const e=this.pointers.get(t.pointerId);e&&(e.handlePress(t),this.gestureRecognizer.onPointerDown(e),this.flags.push(Bn.PointerUpdate),d(t))}handlePointerMove(t){const e=this.pointers.get(t.pointerId);e&&(e.handleMove(t),this.gestureRecognizer.onPointerMove(e,this.pointerDistanceThreshold),this.flags.push(Bn.PointerUpdate))}handlePointerUp(t){const e=this.pointers.get(t.pointerId);e&&(e.handleRelease(t),this.gestureRecognizer.onPointerUp(e),this.flags.push(Bn.PointerUpdate),d(t))}handlePointerCancel(t){const e=this.pointers.get(t.pointerId);e&&(e.handleCancel(t),this.gestureRecognizer.onPointerCancel(e),this._releaseSlot(t.pointerId),this.flags.push(Bn.PointerUpdate))}handleMouseWheel(t){this.canvasFocusedValue&&(this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(Bn.MouseWheel),d(t))}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<Ri.Category;t++){const e=Di.Keyboard+t;0!==this.channels[e]&&(this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(Bn.KeyUp))}}addEventListeners(){const t=window,e={capture:!0,passive:!1},i={capture:!0,passive:!0};t.addEventListener("keydown",this.keyDownHandler,!0),t.addEventListener("keyup",this.keyUpHandler,!0),t.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,e),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,e),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",d,e),this.canvas.addEventListener("selectstart",d,e)}removeEventListeners(){const t={capture:!0,passive:!1},e={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,t),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,e),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,e),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,e),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,t),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,e),this.canvas.removeEventListener("contextmenu",d,t),this.canvas.removeEventListener("selectstart",d,t)}updateGamepads(){const t=window.navigator.getGamepads(),e=new Set;for(const i of t){if(!i)continue;const t=i.index;if(t<0)continue;e.add(t);const n=this.gamepadsByBrowserIndex.get(t);if(void 0===n){const e=this.assignSlotForNewPad(i);if(null===e)continue;this.gamepadsByBrowserIndex.set(t,e),this.onGamepadConnected.dispatch(e)}else n._refreshBrowserGamepad(i)}for(const[t,i]of[...this.gamepadsByBrowserIndex.entries()])e.has(t)||(this.gamepadsByBrowserIndex.delete(t),this.handleGamepadDisconnect(i));for(const t of this._gamepads)t.update();return this}assignSlotForNewPad(t){const e=((t,e=gn)=>{const i="connected"in t?pn(t):t;for(const t of e){const e=mn(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new Qi}})(t,this.gamepadDefinitions);for(const i of this._gamepads)if(!i.connected)return i._bind(t,e),i;return null}handleGamepadDisconnect(t){if("compact"!==this.slotStrategy)return t._unbind(),void this.onGamepadDisconnected.dispatch(t);let e=-1;for(let t=3;t>=0;t--){const i=this._gamepads[t];if(void 0!==i&&i.connected){e=t;break}}t._silentUnbind();for(let t=0;t<4;t++){const e=this._gamepads[t];if(void 0!==e&&!e.connected)for(let i=t+1;i<4;i++){const t=this._gamepads[i];if(void 0===t||!t.connected)continue;const n=t.browserGamepad?.index,s=t.slot;e._rebindFrom(t),void 0!==n&&this.gamepadsByBrowserIndex.set(n,e),e.onPadReassigned.dispatch(s),this.onAnyGamepadReassigned.dispatch(e,s);break}}if(e>=0){const t=this._gamepads[e];void 0!==t&&(t._dispatchDisconnect(),this.onGamepadDisconnected.dispatch(t))}}updateEvents(){if(this.flags.pop(Bn.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(Bn.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(Bn.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(Bn.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of this.pointers.values()){const{stateFlags:e}=t;if(e.value!==vn.None){if(e.pop(vn.Over)&&this.onPointerEnter.dispatch(t),e.pop(vn.Down)&&this.onPointerDown.dispatch(t),e.pop(vn.Move)&&this.onPointerMove.dispatch(t),e.pop(vn.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)}e.pop(vn.Cancel)&&this.onPointerCancel.dispatch(t),e.pop(vn.Leave)&&(this.onPointerLeave.dispatch(t),this.pointers.delete(t.id))}}}}class Mn{_bounds;_maxItems;_maxDepth;_depth;_items;_children;constructor(t,e=8,i=5,n=0){this._bounds=t,this._maxItems=e,this._maxDepth=i,this._depth=n,this._items=[],this._children=null}insert(t){if(null===this._children&&this._items.length<this._maxItems)this._items.push(t);else{if(null===this._children&&this._depth<this._maxDepth&&this._subdivide(),null!==this._children)for(const e of this._children)if(e._bounds.containsRect(t.bounds))return void e.insert(t);this._items.push(t)}}queryPoint(t,e,i=[]){if(!this._bounds.contains(t,e))return i;for(const n of this._items)n.bounds.contains(t,e)&&i.push(n);if(null!==this._children)for(const n of this._children)n.queryPoint(t,e,i);return i}queryRect(t,e=[]){if(t.right<this._bounds.left||t.left>this._bounds.right||t.bottom<this._bounds.top||t.top>this._bounds.bottom)return e;for(const i of this._items)i.bounds.right<t.left||i.bounds.left>t.right||i.bounds.bottom<t.top||i.bounds.top>t.bottom||e.push(i);if(null!==this._children)for(const i of this._children)i.queryRect(t,e);return e}remove(t){const e=this._items.indexOf(t);if(-1!==e)return this._items.splice(e,1),!0;if(null!==this._children)for(const e of this._children)if(e.remove(t))return!0;return!1}clear(){if(this._items.length=0,null!==this._children){for(const t of this._children)t.clear();this._children=null}}_walkBounds(t){if(t(this._bounds),null!==this._children)for(const e of this._children)e._walkBounds(t)}destroy(){if(this._items.length=0,this._bounds.destroy(),null!==this._children){for(const t of this._children)t.destroy();this._children=null}}_subdivide(){const{x:t,y:e,width:i,height:n}=this._bounds,s=i/2,r=n/2,o=this._depth+1,a=this._maxItems,h=this._maxDepth;this._children=[new Mn(new te(t,e,s,r),a,h,o),new Mn(new te(t+s,e,s,r),a,h,o),new Mn(new te(t,e+r,s,r),a,h,o),new Mn(new te(t+s,e+r,s,r),a,h,o)]}}class An{type;target;currentTarget;pointer;worldX;worldY;_stopped=!1;constructor(t,e,i,n,s){this.type=t,this.target=e,this.currentTarget=e,this.pointer=i,this.worldX=n,this.worldY=s}get propagationStopped(){return this._stopped}stopPropagation(){this._stopped=!0}}!function(t){t[t.None=0]="None",t[t.Down=1]="Down",t[t.Move=2]="Move",t[t.Up=4]="Up",t[t.Tap=8]="Tap",t[t.Cancel=16]="Cancel",t[t.Leave=32]="Leave"}(Cn||(Cn={}));class Pn{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(t){this._app=t,this._stage={interaction:this,focus:t.focus,app:t},this._uiStage={interaction:this._uiInteraction,focus:t.focus,app:t},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),t.input.onPointerDown.add(this._onPointerDownHandler),t.input.onPointerMove.add(this._onPointerMoveHandler),t.input.onPointerUp.add(this._onPointerUpHandler),t.input.onPointerTap.add(this._onPointerTapHandler),t.input.onPointerCancel.add(this._onPointerCancelHandler),t.input.onPointerLeave.add(this._onPointerLeaveHandler)}getHoveredNode(t){if(void 0!==t)return this._lastHit.get(t)??null;const e=this._lastHit.values().next();return e.done?null:e.value}getCapturedNodes(){return[...this._capturedPointers.values()]}pushInputCapture(t){this._captureStack.push(t)}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(t){if(this._dirty){this._dirty=!1,this._flushStaleEntries();for(const t of this._pending.values())this._processQueue(t);this._pending.clear(),this._updateCursor()}}attachRoot(t){t._setStage(this._stage),this._notifyNodeAdded(t)}detachRoot(t){this._app.focus.blur(),this._captureStack.length=0,this._notifyNodeRemoved(t),t._setStage(null)}attachUIRoot(t){t._setStage(this._uiStage)}detachUIRoot(t){t._setStage(null)}_notifyNodeAdded(t){for(const e of this._iterateSubtree(t))e.interactive&&this._registerNode(e)}_notifyNodeRemoved(t){for(const e of this._iterateSubtree(t))this._interactiveNodes.has(e)&&this._unregisterNode(e)}_notifyInteractiveChanged(t,e){e?this._registerNode(t):this._unregisterNode(t)}_notifyBoundsInvalidated(t){this._interactiveNodes.has(t)&&this._staleNodes.add(t)}_handlePointerDown(t){this._enqueue(t,Cn.Down)}_handlePointerMove(t){this._enqueue(t,Cn.Move)}_handlePointerUp(t){this._enqueue(t,Cn.Up)}_handlePointerTap(t){this._enqueue(t,Cn.Tap)}_handlePointerCancel(t){this._enqueue(t,Cn.Cancel)}_handlePointerLeave(t){this._enqueue(t,Cn.Leave)}_enqueue(t,e){let i=this._pending.get(t.id);i?i.pointer=t:(i={pointer:t,events:0},this._pending.set(t.id,i)),i.events|=e,this._dirty=!0}_processQueue(t){const{pointer:e,events:i}=t,{id:n}=e,s=this._capturedPointers.get(n)??null;let r,o,a;if(null!==s){const t=this._pointerCoords(e,this._isUINode(s));r=s,o=t.x,a=t.y}else{const t=this._resolveHit(e);r=t.node,o=t.x,a=t.y}const h=this._drags.get(n)??null,l=this._lastHit.get(n)??null,u=0!==(i&(Cn.Cancel|Cn.Leave));if(null!==s||r===l||u||(null!==l&&this._dispatchBubble(new An("pointerout",l,e,o,a)),null!==r&&this._dispatchBubble(new An("pointerover",r,e,o,a)),this._setLastHit(n,r)),0!==(i&Cn.Down)&&null!==r&&(this._dispatchBubble(new An("pointerdown",r,e,o,a)),r.draggable&&!this._drags.has(n))){const t=r.position.x-o,i=r.position.y-a;this._drags.set(n,{pointerId:n,node:r,offsetX:t,offsetY:i}),this._capturedPointers.set(n,r);try{this._app.canvas.setPointerCapture(n)}catch{}this._dispatchDirect(new An("dragstart",r,e,o,a),r._peekInteractionSignal("dragstart"))}0!==(i&Cn.Move)&&(null!==h&&(h.node.position.x=o+h.offsetX,h.node.position.y=a+h.offsetY),null!==r&&this._dispatchBubble(new An("pointermove",r,e,o,a)),null!==h&&this._dispatchDirect(new An("drag",h.node,e,o,a),h.node._peekInteractionSignal("drag"))),0!==(i&Cn.Up)&&(null!==r&&this._dispatchBubble(new An("pointerup",r,e,o,a)),null!==h&&(this._dispatchDirect(new An("dragend",h.node,e,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(n))),0!==(i&Cn.Tap)&&null!==r&&this._dispatchBubble(new An("pointertap",r,e,o,a)),u&&(null!==h?(this._dispatchDirect(new An("dragend",h.node,e,o,a),h.node._peekInteractionSignal("dragend")),this._endDrag(n)):null!==l&&this._dispatchBubble(new An("pointerout",l,e,o,a)),this._lastHit.delete(n))}_endDrag(t){this._drags.delete(t),this._capturedPointers.delete(t);try{this._app.canvas.releasePointerCapture(t)}catch{}}_resolveHit(t){const e=this._captureStack.at(-1);if(void 0!==e){const i=this._pointerCoords(t,this._isUINode(e));return{node:this._hitTestNode(e,i.x,i.y),x:i.x,y:i.y}}const i=this._app.scene.currentScene?._peekUI()??null;if(null!==i){const e=this._app.rendering.screenView.screenToWorld(t.x,t.y),n=this._hitTestNode(i,e.x,e.y);if(null!==n)return{node:n,x:e.x,y:e.y}}const n=this._app.rendering.view.screenToWorld(t.x,t.y);return{node:this._hitTest(n.x,n.y),x:n.x,y:n.y}}_pointerCoords(t,e){return(e?this._app.rendering.screenView:this._app.rendering.view).screenToWorld(t.x,t.y)}_isUINode(t){const e=this._app.scene.currentScene?._peekUI()??null;if(null===e)return!1;let i=t;for(;null!==i;){if(i===e)return!0;i=i.parent}return!1}_hitTest(t,e){if(null!==this._quadtree)return this._hitTestIndexed(t,e);const i=this._app.scene.currentScene?.root;return i?this._hitTestNode(i,t,e):null}_hitTestIndexed(t,e){const i=this._quadtreeQueryBuffer;i.length=0,this._quadtree.queryPoint(t,e,i);let n=-1,s=null;for(const r of i){const i=r.payload;i.order>n&&i.node.contains(t,e)&&(n=i.order,s=i.node)}return s}_hitTestNode(t,e,i){if(!t.visible)return null;if(t instanceof Ei){const n=t.children;for(let t=n.length-1;t>=0;t--){const s=n[t];if(void 0===s)continue;const r=this._hitTestNode(s,e,i);if(r)return r}}return t.interactive&&t.contains(e,i)?t:null}_registerNode(t){this._interactiveNodes.has(t)||(this._interactiveNodes.add(t),null===this._quadtree&&(this._quadtree=this._createQuadtree()),this._insertNode(t))}_unregisterNode(t){if(!this._interactiveNodes.has(t))return;this._interactiveNodes.delete(t),this._staleNodes.delete(t);const e=this._quadtreeItems.get(t);void 0!==e&&null!==this._quadtree&&this._quadtree.remove(e),this._quadtreeItems.delete(t),0===this._interactiveNodes.size&&null!==this._quadtree&&(this._quadtree.destroy(),this._quadtree=null,this._quadtreeOrderCounter=0)}_insertNode(t){if(null===this._quadtree)return;const e=t.getBounds(),i={bounds:new te(e.x,e.y,e.width,e.height),payload:{node:t,order:this._quadtreeOrderCounter++}};this._quadtree.insert(i),this._quadtreeItems.set(t,i)}_flushStaleEntries(){if(null!==this._quadtree&&0!==this._staleNodes.size){for(const t of this._staleNodes){const e=this._quadtreeItems.get(t);void 0!==e&&(this._quadtree.remove(e),e.bounds.destroy()),this._quadtreeItems.delete(t);const i=t.getBounds(),n={bounds:new te(i.x,i.y,i.width,i.height),payload:{node:t,order:e?.payload.order??this._quadtreeOrderCounter++}};this._quadtree.insert(n),this._quadtreeItems.set(t,n)}this._staleNodes.clear()}}_createQuadtree(){const t=this._app.width||800,e=this._app.height||600,i=new te(0,0,t,e),n=this._app.scene.currentScene?.root;if(n){const t=n.getBounds(),e=Math.min(i.left,t.left),s=Math.min(i.top,t.top),r=Math.max(i.right,t.right),o=Math.max(i.bottom,t.bottom);i.set(e,s,r-e,o-s)}return new Mn(i)}*_iterateSubtree(t){const e=[t];for(;e.length>0;){const t=e.pop();if(yield t,t instanceof Ei)for(let i=t.children.length-1;i>=0;i--){const n=t.children[i];void 0!==n&&e.push(n)}}}_dispatchBubble(t){let e=t.target;for(;null!==e&&!t.propagationStopped;){t.currentTarget=e;const i=this._signalFor(t.type,e);if(i?.dispatch(t),t.propagationStopped)break;const n=e.parent;e=null!==n&&n.interactive?n:null}}_dispatchDirect(t,e){t.currentTarget=t.target,e?.dispatch(t)}_signalFor(t,e){return e._peekInteractionSignal(t)}_setLastHit(t,e){null!==e?this._lastHit.set(t,e):this._lastHit.delete(t)}_updateCursor(){let t=null;for(const e of this._lastHit.values()){let i=e;for(;null!==i;){if(null!==i.cursor){t=i.cursor;break}i=i.parent}if(null!==t)break}this._app.canvas.style.cursor=t??""}}const En=(t,e)=>(t<<e|t>>>32-e)>>>0,kn=1/2**32;class Rn{_state=new Uint32Array(4);_seed=0;_value=0;constructor(t=Date.now()){this.setSeed(t)}get seed(){return this._seed}get value(){return this._value}setSeed(t){return this._seed=t,this.reset(),this}reset(){let t=0|this._seed;for(let e=0;e<4;e++){t=t+2654435769|0;let i=t^t>>>16;i=Math.imul(i,569420461),i^=i>>>15,i=Math.imul(i,1935289751),i^=i>>>15,this._state[e]=i>>>0}return this._value=0,this}next(t=0,e=1){const i=this._state;let n=i[0],s=i[1],r=i[2],o=i[3];const a=Math.imul(En(Math.imul(s,5),7),9)>>>0,h=s<<9;return r^=n,o^=s,s^=r,n^=o,r^=h,o=En(o,11),i[0]=n,i[1]=s,i[2]=r,i[3]=o,this._value=a*kn*(e-t)+t,this._value}destroy(){}}const Dn=new Set(["none","position","geometry"]);function In(t){return"string"==typeof t&&Dn.has(t)}const Ln=1e-6;function Un(t,e,i,n){const s=t.x,r=t.y;if(!(i>0&&n>0))return Fn(s,r);const o=e.worldToScreen(s,r,i,n);if(!Number.isFinite(o.x)||!Number.isFinite(o.y))return Fn(s,r);const a=e.worldToScreen(s+1,r,i,n),h=e.worldToScreen(s,r+1,i,n),l=a.x-o.x,u=a.y-o.y,c=h.x-o.x,d=h.y-o.y,_=t.a*l+t.c*c,f=t.a*u+t.c*d,p=t.b*l+t.d*c,m=t.b*u+t.d*d,g=Math.abs(f)<Ln&&Math.abs(p)<Ln,y=Math.round(o.x),w=Math.round(o.y);let x=s,v=r;const b=l*d-c*u;if(Math.abs(b)>Ln){const t=y-o.x,e=w-o.y;x=s+(d*t-c*e)/b,v=r+(l*e-u*t)/b}return{originX:o.x,originY:o.y,snappedOriginX:y,snappedOriginY:w,worldX:x,worldY:v,scaleX:_,scaleY:m,axisAligned:g}}function Fn(t,e){return{originX:t,originY:e,snappedOriginX:t,snappedOriginY:e,worldX:t,worldY:e,scaleX:0,scaleY:0,axisAligned:!1}}function Gn(t,e){return!Number.isFinite(t)||Math.abs(e)<Ln?t:Math.round(t*e)/e}function Nn(t,e,i){const{scaleX:n,scaleY:s}=e;i.length=t.length;for(let e=0;e<t.length;e++){const r=t[e];let o=i[e];void 0===o&&(o=i[e]={x0:0,y0:0,x1:0,y1:0,u0:0,v0:0,u1:0,v1:0}),o.x0=Gn(r.x0,n),o.x1=Gn(r.x1,n),o.y0=Gn(r.y0,s),o.y1=Gn(r.y1,s),o.u0=r.u0,o.v0=r.v0,o.u1=r.u1,o.v1=r.v1}return i}function On(t,e,i,n,s){const r=t.getGlobalTransform();if("none"===t.pixelSnapMode)return r;return function(t,e,i){return t.copy(e),t.x=i.worldX,t.y=i.worldY,t}(s,r,Un(r,e,i,n))}function Vn(t,e,i){const n=Gn(t.left,e.scaleX),s=Gn(t.top,e.scaleY),r=Gn(t.right,e.scaleX),o=Gn(t.bottom,e.scaleY);return i.set(n,s,r-n,o-s)}class zn extends Pi{_tint=Re.white.clone();_blendMode=qe.Normal;_pixelSnapMode="none";_materialKey=null;_materialKeyBackend=null;get tint(){return this._tint}set tint(t){this.setTint(t)}get blendMode(){return this._blendMode}set blendMode(t){this.setBlendMode(t)}get pixelSnapMode(){return this._pixelSnapMode}set pixelSnapMode(t){if(t!==this._pixelSnapMode){if(!In(t))throw new Error(`Drawable.pixelSnapMode must be 'none', 'position', or 'geometry' (got ${String(t)}).`);this._pixelSnapMode=t,this.invalidateCache()}}setTint(t){return t&&(this._tint.copy(t),this.invalidateCache()),this}setBlendMode(t){return this._blendMode!==t&&(this._blendMode=t,this.invalidateCache()),this}_collectContent(t){t.emitDraw(this)}_isDrawableForRenderPlan(){return!0}_renderPlanGetBlendMode(){return this._blendMode}_getOrComputeMaterialKey(t){const e=this._materialKey;if(null!==e)return null!==oi(this)?ai(e,this,t):this._materialKeyBackend===t?e:(this._materialKeyBackend=t,ai(e,this,t));const i=ai({rendererId:0,blendMode:this._blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},this,t);return this._materialKey=i,this._materialKeyBackend=t,i}invalidateCache(){return super.invalidateCache(),this._materialKeyBackend=null,this}destroy(){super.destroy(),this._tint.destroy()}}class qn extends zn{_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(t){super();const{texture:e=null,material:i=null}=t;let n,s,r,o,a;if(void 0!==t.geometry){if(void 0!==t.vertices)throw new Error("Mesh accepts either `vertices` or `geometry`, not both.");a=t.geometry;const e=Hn(a);n=e.vertices,r=e.uvs,o=e.colors,s=e.indices}else{if(void 0===t.vertices)throw new Error("Mesh requires either `vertices` or `geometry`.");a=null,n=t.vertices,s=t.indices??null,r=t.uvs??null,o=t.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!==r&&r.length!==n.length)throw new Error(`Mesh uvs length ${r.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!==s){if(0===s.length||s.length%3!=0)throw new Error(`Mesh indices must be a non-empty multiple of 3 (got length ${s.length}).`);for(let t=0;t<s.length;t++)if(s[t]>=h)throw new Error(`Mesh index ${s[t]} at position ${t} 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=s,this._uvs=r,this._colors=o,this._material=i,this._geometry=a,this._texture=e,this.recomputeLocalBounds()}get vertexCount(){return this.vertices.length/2}get indexCount(){return this.indices?.length??this.vertexCount}get texture(){return this._texture}set texture(t){this._texture=t,this.invalidateCache()}recomputeLocalBounds(){let t=1/0,e=1/0,i=-1/0,n=-1/0;for(let s=0;s<this.vertices.length;s+=2){const r=this.vertices[s],o=this.vertices[s+1];r<t&&(t=r),r>i&&(i=r),o<e&&(e=o),o>n&&(n=o)}return this.getLocalBounds().set(t,e,i-t,n-e),this._invalidateBoundsCascade(),this}}const Wn=new Set(["a_position","position"]),Yn=new Set(["a_texcoord","texcoord","a_uv","uv"]),$n=new Set(["a_color","color"]),Xn=(t,e)=>t.find(t=>e.has(t.name));function Hn(t){if("triangle-list"!==t.topology)throw new Error(`Mesh only supports triangle-list geometry (got "${t.topology}").`);const e=Xn(t.attributes,Wn);if(void 0===e)throw new Error("Mesh geometry requires a position attribute named `a_position` or `position`.");if("f32"!==e.type||e.size<2)throw new Error("Mesh geometry position attribute must be a float vector with at least 2 components.");const i=Xn(t.attributes,Yn);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=Xn(t.attributes,$n),s=t.vertexCount,{stride:r}=t,o=t.vertexData,a=o instanceof Float32Array?new DataView(o.buffer,o.byteOffset,o.byteLength):new DataView(o),h=new Float32Array(2*s),l=void 0!==i?new Float32Array(2*s):null,u=void 0!==n?new Uint32Array(s):null;for(let t=0;t<s;t++){const s=t*r;h[2*t]=a.getFloat32(s+e.offset,!0),h[2*t+1]=a.getFloat32(s+e.offset+4,!0),null!==l&&void 0!==i&&(l[2*t]=a.getFloat32(s+i.offset,!0),l[2*t+1]=a.getFloat32(s+i.offset+4,!0)),null!==u&&void 0!==n&&(u[t]=jn(a,s+n.offset,n))}const c=function(t,e){if(null===t)return null;if(t instanceof Uint16Array)return t;if(e>65535)throw new Error(`Mesh geometry with ${e} vertices exceeds the 16-bit index limit.`);return Uint16Array.from(t)}(t.indices,s);return{vertices:h,uvs:l,colors:u,indices:c}}function jn(t,e,i){if("u32"===i.type&&1===i.size)return t.getUint32(e,!0)>>>0;if("u8"===i.type&&4===i.size){return(t.getUint8(e)|t.getUint8(e+1)<<8|t.getUint8(e+2)<<16|t.getUint8(e+3)<<24)>>>0}if("f32"===i.type&&4===i.size){return(Math.round(255*Kn(t.getFloat32(e,!0)))|Math.round(255*Kn(t.getFloat32(e+4,!0)))<<8|Math.round(255*Kn(t.getFloat32(e+8,!0)))<<16|Math.round(255*Kn(t.getFloat32(e+12,!0)))<<24)>>>0}throw new Error("Mesh geometry color attribute must be u8x4, u32x1, or f32x4.")}function Kn(t){return t<0?0:t>1?1:t}function Qn(t){return"number"==typeof t&&Number.isFinite(t)}class Zn{texture;x;y;width;height;u0;v0;u1;v1;extrusion;constructor(t,e){if(!t)throw new Error("TextureRegion requires a non-null Texture.");const i=t.width,n=t.height;!function(t,e,i){const{x:n,y:s,width:r,height:o}=t;if(!(Qn(n)&&Qn(s)&&Qn(r)&&Qn(o)))throw new Error(`TextureRegion coordinates and dimensions must be finite numbers (got x=${n}, y=${s}, width=${r}, height=${o}).`);if(r<=0||o<=0)throw new Error(`TextureRegion dimensions must be positive (got width=${r}, height=${o}).`);if(e<=0||i<=0)throw new Error(`Texture must have positive dimensions (got ${e}x${i}).`);if(n<0||s<0)throw new Error(`TextureRegion origin must be non-negative (got x=${n}, y=${s}).`);if(n>=e||s>=i)throw new Error(`TextureRegion origin (${n}, ${s}) is outside texture bounds (${e}x${i}).`);if(n+r>e)throw new Error(`TextureRegion right edge (${n+r}) exceeds texture width (${e}).`);if(s+o>i)throw new Error(`TextureRegion bottom edge (${s+o}) exceeds texture height (${i}).`)}(e,i,n);const s=function(t){return void 0===t?Object.freeze({left:0,top:0,right:0,bottom:0}):"number"==typeof t?Object.freeze({left:t,top:t,right:t,bottom:t}):Object.freeze({left:t.left,top:t.top,right:t.right,bottom:t.bottom})}(e.extrusion);!function(t,e,i,n,s,r,o){const{left:a,top:h,right:l,bottom:u}=t;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>e||h>i||l>r-(e+n)||u>o-(i+s))throw new Error(`TextureRegion extrusion exceeds available source texture bounds: left=${a} (>${e}), top=${h} (>${i}), right=${l} (>${r-(e+n)}), bottom=${u} (>${o-(i+s)}).`)}(s,e.x,e.y,e.width,e.height,i,n),this.texture=t,this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this.u0=e.x/i,this.v0=e.y/n,this.u1=(e.x+e.width)/i,this.v1=(e.y+e.height)/n,this.extrusion=s}}function Jn(t,e,i){if(0===t)return{destinationLength:0,sourceLength:e,segments:[]};const n=[];let s=0,r=0;for(;s<t;){const o=t-s,a=Math.min(e,o),h=a/e,l=i&&r%2==1,u={destinationStart:s,destinationLength:a,sourceStart:l?1:0,sourceEnd:l?1-h:h,mirrored:l};n.push(u),s+=a,r++}return{destinationLength:t,sourceLength:e,segments:n}}function ts(t,e,i){if(0===t)return{destinationLength:0,sourceLength:e,segments:[]};const n=t/e,s=Math.max(1,Math.round(n)),r=t/s,o=[];for(let t=0;t<s;t++){const e=i&&t%2==1,n={destinationStart:t*r,destinationLength:r,sourceStart:e?1:0,sourceEnd:e?0:1,mirrored:e};o.push(n)}return{destinationLength:t,sourceLength:e,segments:o}}function es(t,e,i,n="round"){switch(function(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`RepeatPlanner: sourceLength and destinationLength must be finite numbers (got ${t}, ${e}).`);if(t<=0)throw new Error(`RepeatPlanner: sourceLength must be positive (got ${t}).`);if(e<0)throw new Error(`RepeatPlanner: destinationLength must be non-negative (got ${e}).`)}(t,e),i){case"stretch":return function(t,e){return 0===t?{destinationLength:0,sourceLength:e,segments:[]}:{destinationLength:t,sourceLength:e,segments:[{destinationStart:0,destinationLength:t,sourceStart:0,sourceEnd:1,mirrored:!1}]}}(e,t);case"repeat":return"round"===n?ts(e,t,!1):Jn(e,t,!1);case"mirror-repeat":return"round"===n?ts(e,t,!0):Jn(e,t,!0);default:throw new Error("RepeatPlanner: unknown RepeatMode.")}}const is=.5;function ns(t){return"number"==typeof t&&Number.isFinite(t)}function ss(t,e,i){const{left:n,top:s,right:r,bottom:o}=t;if(!(ns(n)&&ns(s)&&ns(r)&&ns(o)))throw new Error(`NineSliceSprite: slice values must be finite numbers (got left=${n}, top=${s}, right=${r}, bottom=${o}).`);if(n<0||s<0||r<0||o<0)throw new Error(`NineSliceSprite: slice values must be non-negative (got left=${n}, top=${s}, right=${r}, bottom=${o}).`);if(n+r>e)throw new Error(`NineSliceSprite: slices.left (${n}) + slices.right (${r}) exceeds region width (${e}).`);if(s+o>i)throw new Error(`NineSliceSprite: slices.top (${s}) + slices.bottom (${o}) exceeds region height (${i}).`)}function rs(t){const{left:e,top:i,right:n,bottom:s}=t;if(!(ns(e)&&ns(i)&&ns(n)&&ns(s)))throw new Error(`NineSliceSprite: border values must be finite numbers (got left=${e}, top=${i}, right=${n}, bottom=${s}).`);if(e<0||i<0||n<0||s<0)throw new Error(`NineSliceSprite: border values must be non-negative (got left=${e}, top=${i}, right=${n}, bottom=${s}).`)}function os(t,e){return"number"==typeof t?Object.freeze({left:t,top:t,right:t,bottom:t}):Object.freeze({left:t.left??e?.left??0,top:t.top??e?.top??0,right:t.right??e?.right??0,bottom:t.bottom??e?.bottom??0})}const as=new Set(["stretch","repeat","mirror-repeat"]),hs=new Set(["clip","round"]);function ls(t,e){if("string"!=typeof t||!as.has(t))throw new Error(`NineSliceSprite: ${e} must be "stretch", "repeat", or "mirror-repeat".`)}function us(t,e){if("string"!=typeof t||!hs.has(t))throw new Error(`NineSliceSprite: ${e} must be "clip" or "round".`)}function cs(t){if(!t)return ds;const e={};return void 0!==t.edges&&(ls(t.edges,"modes.edges"),e.edges=t.edges),void 0!==t.center&&(ls(t.center,"modes.center"),e.center=t.center),void 0!==t.top&&(ls(t.top,"modes.top"),e.top=t.top),void 0!==t.right&&(ls(t.right,"modes.right"),e.right=t.right),void 0!==t.bottom&&(ls(t.bottom,"modes.bottom"),e.bottom=t.bottom),void 0!==t.left&&(ls(t.left,"modes.left"),e.left=t.left),void 0!==t.edgeFit&&(us(t.edgeFit,"modes.edgeFit"),e.edgeFit=t.edgeFit),void 0!==t.centerFit&&(us(t.centerFit,"modes.centerFit"),e.centerFit=t.centerFit),Object.freeze(e)}const ds=Object.freeze({});function _s(t,e){return t.left===e.left&&t.top===e.top&&t.right===e.right&&t.bottom===e.bottom}function fs(t,e){return t?.[e]??t?.edges??"stretch"}function ps(t,e,i){return!ns(t)||t<e?e:t>i?i:t}function ms(t,e,i,n,s,r){const o=function(t,e){const i=t.texture.width,n=t.texture.height,s=t.x,r=t.y,o=t.width,a=t.height,h=t.extrusion,l=h.left>0||h.right>0?0:is/i,u=h.top>0||h.bottom>0?0:is/n,c=is/i,d=is/n,_=(s+e.left)/i,f=(s+o-e.right)/i,p=(r+e.top)/n,m=(r+a-e.bottom)/n,g=t.u0+l,y=t.u1-l,w=t.v0+u,x=t.v1-u,v=ps(_-c,g,y),b=ps(f+c,g,y),S=ps(p-d,w,x),B=ps(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}}}(t,e),a=function(t,e,i){let n=t.left,s=t.right,r=t.top,o=t.bottom;if(n+s>e&&n+s>0){const t=e/(n+s);n*=t,s*=t}if(r+o>i&&r+o>0){const t=i/(r+o);r*=t,o*=t}return{bl:n,br:s,bt:r,bb:o}}(i,n,s),h=a.bl,l=a.br,u=a.bt,c=a.bb,d=Math.max(0,n-h-l),_=Math.max(0,s-u-c),f=h,p=h+d,m=n,g=u,y=u+_,w=s,x=Math.max(0,t.width-e.left-e.right),v=Math.max(0,t.height-e.top-e.bottom),b=x*(e.top>0?u/e.top:1),S=x*(e.bottom>0?c/e.bottom:1),B=v*(e.left>0?h/e.left:1),C=v*(e.right>0?l/e.right:1),T=b,M=B,A=fs(r,"top"),P=fs(r,"bottom"),E=fs(r,"left"),k=fs(r,"right"),R=function(t){return t?.center??"stretch"}(r),D=function(t){return t?.edgeFit??"round"}(r),I=function(t){return t?.centerFit??"round"}(r),L=[],{col0:U,col1:F,col2:G,row0:N,row1:O,row2:V}=o;h>0&&u>0&&L.push({x0:0,y0:0,x1:f,y1:g,u0:U.u0,v0:N.u0,u1:U.u1,v1:N.u1}),l>0&&u>0&&L.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&&L.push({x0:0,y0:y,x1:f,y1:w,u0:U.u0,v0:V.u0,u1:U.u1,v1:V.u1}),l>0&&c>0&&L.push({x0:p,y0:y,x1:m,y1:w,u0:G.u0,v0:V.u0,u1:G.u1,v1:V.u1});const z=F.u0,q=F.u1,W=O.u0,Y=O.u1;if(d>0&&u>0&&x>0&&b>0){const t=es(b,d,A,D);for(const e of t.segments){const t=f+e.destinationStart,i=f+e.destinationStart+e.destinationLength,n=z+e.sourceStart*(q-z),s=z+e.sourceEnd*(q-z);L.push({x0:t,y0:0,x1:i,y1:g,u0:n,v0:N.u0,u1:s,v1:N.u1})}}if(d>0&&c>0&&x>0&&S>0){const t=es(S,d,P,D);for(const e of t.segments){const t=f+e.destinationStart,i=f+e.destinationStart+e.destinationLength,n=z+e.sourceStart*(q-z),s=z+e.sourceEnd*(q-z);L.push({x0:t,y0:y,x1:i,y1:w,u0:n,v0:V.u0,u1:s,v1:V.u1})}}if(h>0&&_>0&&v>0&&B>0){const t=es(B,_,E,D);for(const e of t.segments){const t=g+e.destinationStart,i=g+e.destinationStart+e.destinationLength,n=W+e.sourceStart*(Y-W),s=W+e.sourceEnd*(Y-W);L.push({x0:0,y0:t,x1:f,y1:i,u0:U.u0,v0:n,u1:U.u1,v1:s})}}if(l>0&&_>0&&v>0&&C>0){const t=es(C,_,k,D);for(const e of t.segments){const t=g+e.destinationStart,i=g+e.destinationStart+e.destinationLength,n=W+e.sourceStart*(Y-W),s=W+e.sourceEnd*(Y-W);L.push({x0:p,y0:t,x1:m,y1:i,u0:G.u0,v0:n,u1:G.u1,v1:s})}}if(d>0&&_>0&&x>0&&v>0&&T>0&&M>0){const t=es(T,d,R,I),e=es(M,_,R,I);for(const i of e.segments){const e=g+i.destinationStart,n=g+i.destinationStart+i.destinationLength,s=W+i.sourceStart*(Y-W),r=W+i.sourceEnd*(Y-W);for(const i of t.segments){const t=f+i.destinationStart,o=f+i.destinationStart+i.destinationLength,a=z+i.sourceStart*(q-z),h=z+i.sourceEnd*(q-z);L.push({x0:t,y0:e,x1:o,y1:n,u0:a,v0:s,u1:h,v1:r})}}}return L}function gs(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`NineSliceSprite: width and height must be finite numbers (got ${t}, ${e}).`);if(t<0)throw new Error(`NineSliceSprite: width must be non-negative (got ${t}).`);if(e<0)throw new Error(`NineSliceSprite: height must be non-negative (got ${e}).`)}class ys extends zn{_region;_slices;_border;_width;_height;_modes;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(t,e){super(),this._region=t instanceof Zn?t:new Zn(t,{x:0,y:0,width:t.width,height:t.height});const i=this._region,n=os(e.slices);ss(n,i.width,i.height),this._slices=n;const s=void 0!==e.border?os(e.border):os(e.slices);rs(s),this._border=s;const r=e.width??i.width,o=e.height??i.height;gs(r,o),this._width=r,this._height=o,this._modes=cs(e.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(t){this.setSize(t,this._height)}get height(){return this._height}set height(t){this.setSize(this._width,t)}setSize(t,e){return gs(t,e),this._width===t&&this._height===e||(this._width=t,this._height=e,this._geometryDirty=!0,this.invalidateCache()),this}setSlices(t){const e=this._region,i=os(t);return ss(i,e.width,e.height),_s(i,this._slices)||(this._slices=i,this._geometryDirty=!0,this.invalidateCache()),this}setBorder(t){const e=os(t);return rs(e),_s(e,this._border)||(this._border=e,this._geometryDirty=!0,this.invalidateCache()),this}setModes(t){const e=cs(t);return i=e,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=e,this._geometryDirty=!0,this.invalidateCache()),this;var i,n}getLocalBounds(){const t=super.getLocalBounds();return t.set(0,0,this._width,this._height),t}get quads(){return this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(t,e,i){const n=this.quads;if(0===n.length)return n;const s=Un(this.getGlobalTransform(),t,e,i);return s.axisAligned?Nn(n,s,this._renderQuads):n}_rebuildGeometry(){this._quads=ms(this._region,this._slices,this._border,this._width,this._height,this._modes),this._geometryDirty=!1}}const ws=new Set(["stretch","repeat","mirror-repeat"]),xs=new Set(["clip","round"]);function vs(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))throw new Error(`RepeatingSprite: width and height must be finite numbers (got ${t}, ${e}).`);if(t<0)throw new Error(`RepeatingSprite: width must be non-negative (got ${t}).`);if(e<0)throw new Error(`RepeatingSprite: height must be non-negative (got ${e}).`)}function bs(t,e){if("string"!=typeof t||!ws.has(t))throw new Error(`RepeatingSprite: ${e} must be "stretch", "repeat", or "mirror-repeat" (got ${String(t)}).`)}function Ss(t,e){if("string"!=typeof t||!xs.has(t))throw new Error(`RepeatingSprite: ${e} must be "clip" or "round" (got ${String(t)}).`)}function Bs(t,e){if(!Number.isFinite(t))throw new Error(`RepeatingSprite: ${e} must be a finite number (got ${t}).`)}function Cs(t,e,i,n){return"stretch"===i||t<=0||e<=0?1:"round"===n?Math.max(1,Math.round(e/t)):e/t}function Ts(t,e,i,n,s){if(0===e||t<=0)return[];if("stretch"===i)return[...es(t,e,i,n).segments];const r=(s%t+t)%t;if(0===r)return[...es(t,e,i,n).segments];const o=es(t,e+r,i,n),a=[];for(const t of o.segments){const i=t.destinationStart-r,n=i+t.destinationLength;if(n<=0||i>=e)continue;const s=Math.max(0,i),o=Math.min(e,n),h=o-s;if(h<=0)continue;const l=(s-i)/t.destinationLength,u=(o-i)/t.destinationLength,c=t.sourceEnd-t.sourceStart;a.push({destinationStart:s,destinationLength:h,sourceStart:t.sourceStart+l*c,sourceEnd:t.sourceStart+u*c,mirrored:t.mirrored})}return a}class Ms extends zn{_source;_region;_width;_height;_modeX;_modeY;_fitX;_fitY;_offsetX;_offsetY;_quads=[];_geometryDirty=!0;_renderQuads=[];constructor(t,e){super(),this._source=t,this._region=t instanceof Zn?t:new Zn(t,{x:0,y:0,width:t.width,height:t.height});const i=this._region,n=e??{},s=n.modeX??"repeat",r=n.modeY??"repeat";bs(s,"modeX"),bs(r,"modeY"),this._modeX=s,this._modeY=r;const o=n.fitX??"round",a=n.fitY??"round";Ss(o,"fitX"),Ss(a,"fitY"),this._fitX=o,this._fitY=a;const h=n.offsetX??0,l=n.offsetY??0;Bs(h,"offsetX"),Bs(l,"offsetY"),this._offsetX=h,this._offsetY=l;const u=n.width??i.width,c=n.height??i.height;vs(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(t){this.setSize(t,this._height)}get height(){return this._height}set height(t){this.setSize(this._width,t)}get modeX(){return this._modeX}set modeX(t){bs(t,"modeX"),this._modeX!==t&&(this._modeX=t,this._geometryDirty=!0,this.invalidateCache())}get modeY(){return this._modeY}set modeY(t){bs(t,"modeY"),this._modeY!==t&&(this._modeY=t,this._geometryDirty=!0,this.invalidateCache())}get fitX(){return this._fitX}set fitX(t){Ss(t,"fitX"),this._fitX!==t&&(this._fitX=t,this._geometryDirty=!0,this.invalidateCache())}get fitY(){return this._fitY}set fitY(t){Ss(t,"fitY"),this._fitY!==t&&(this._fitY=t,this._geometryDirty=!0,this.invalidateCache())}get offsetX(){return this._offsetX}set offsetX(t){this.setOffset(t,this._offsetY)}get offsetY(){return this._offsetY}set offsetY(t){this.setOffset(this._offsetX,t)}setSize(t,e){return vs(t,e),this._width===t&&this._height===e||(this._width=t,this._height=e,this._geometryDirty=!0,this.invalidateCache()),this}setOffset(t,e){return Bs(t,"offsetX"),Bs(e,"offsetY"),this._offsetX===t&&this._offsetY===e||(this._offsetX=t,this._offsetY=e,"geometry"===this.resolvedStrategy&&(this._geometryDirty=!0),this.invalidateCache()),this}getLocalBounds(){const t=super.getLocalBounds();return t.set(0,0,this._width,this._height),t}get resolvedStrategy(){return this._source instanceof Zn?"geometry":"shader"}get quads(){return"geometry"===this.resolvedStrategy&&this._geometryDirty&&this._rebuildGeometry(),this._quads}getRenderQuads(t,e,i){const n=this.quads;if("geometry"!==this.pixelSnapMode||0===n.length)return n;const s=Un(this.getGlobalTransform(),t,e,i);return s.axisAligned?Nn(n,s,this._renderQuads):n}getRenderBounds(t,e,i,n){const s=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return s;const r=Un(this.getGlobalTransform(),t,e,i);return r.axisAligned?Vn(s,r,n):s}_rebuildGeometry(){this._quads=function(t,e,i,n,s,r,o,a,h){if(0===e||0===i||t.width<=0||t.height<=0)return[];const l=t.texture.width,u=t.texture.height,c=t.extrusion,d=c.left>0||c.right>0?0:.5/l,_=c.top>0||c.bottom>0?0:.5/u,f=t.u0+d,p=t.u1-d,m=t.v0+_,g=t.v1-_,y=t.width,w=t.height,x=p-f,v=g-m,b=Ts(y,e,n,r,a),S=Ts(w,i,s,o,h),B=[];for(const t of S){const e=t.destinationStart,i=t.destinationStart+t.destinationLength,n=m+t.sourceStart*v,s=m+t.sourceEnd*v;for(const t of b){const r=t.destinationStart,o=t.destinationStart+t.destinationLength,a=f+t.sourceStart*x,h=f+t.sourceEnd*x;B.push({x0:r,y0:e,x1:o,y1:i,u0:a,v0:n,u1:h,v1:s})}}return B}(this._region,this._width,this._height,this._modeX,this._modeY,this._fitX,this._fitY,this._offsetX,this._offsetY),this._geometryDirty=!1}}var As;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint",t[t.Vertices=1024]="Vertices",t[t.Normals=2048]="Normals"}(As||(As={}));class Ps extends zn{_texture=null;_textureFrame=new te;_material=null;_vertices=new Float32Array(8);_texCoords=new Uint32Array(4);_normals=[new ie,new ie,new ie,new ie];constructor(t){super(),this.flags.push(As.Vertices|As.Normals),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get material(){return this._material}set material(t){if(null!==t&&"sprite"!==t.target)throw new Error(`Sprite requires a SpriteMaterial (got a ${t.target} material).`);this._material=t,this.invalidateCache()}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(t){this.scale.x=t/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(t){this.scale.y=t/this._textureFrame.height}get vertices(){if(this.flags.has(As.Vertices)){const{left:t,top:e,right:i,bottom:n}=this.getLocalBounds(),{a:s,b:r,x:o,c:a,d:h,y:l}=this.getGlobalTransform();this._vertices[0]=t*s+e*r+o,this._vertices[1]=t*a+e*h+l,this._vertices[2]=i*s+e*r+o,this._vertices[3]=i*a+e*h+l,this._vertices[4]=i*s+n*r+o,this._vertices[5]=i*a+n*h+l,this._vertices[6]=t*s+n*r+o,this._vertices[7]=t*a+n*h+l,this.flags.remove(As.Vertices)}return this._vertices}getRenderBounds(t,e,i,n){const s=this.getLocalBounds();if("geometry"!==this.pixelSnapMode)return s;const r=Un(this.getGlobalTransform(),t,e,i);return r.axisAligned?Vn(s,r,n):s}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(As.TextureCoords)){const{width:t,height:e}=this._texture,{left:i,top:n,right:s,bottom:r}=this._textureFrame,o=i/t*65535&65535,a=(n/e*65535&65535)<<16,h=s/t*65535&65535,l=(r/e*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(t){return this._texture!==t&&(this._texture=t,null!==t&&this.resetTextureFrame(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,e=!0){const i=this.width,n=this.height;return this._textureFrame.copy(t),this.flags.push(As.TextureCoords),this.getLocalBounds().set(0,0,t.width,t.height),this._invalidateBoundsCascade(),e?(this.width=t.width,this.height=t.height):(this.width=i,this.height=n),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(te.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){if(this.flags.has(As.Normals)){const t=this.vertices,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],o=t[5],a=t[6],h=t[7];this._normals[0].set(n-e,s-i).rperp().normalize(),this._normals[1].set(r-n,o-s).rperp().normalize(),this._normals[2].set(a-r,h-o).rperp().normalize(),this._normals[3].set(e-a,i-h).rperp().normalize(),this.flags.remove(As.Normals)}return this._normals}project(t,e=new mt){const i=this.vertices,n=i[0],s=i[1],r=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=t.dot(n,s),d=t.dot(r,o),_=t.dot(a,h),f=t.dot(l,u);return e.set(Math.min(c,d,_,f),Math.max(c,d,_,f))}contains(t,e){if(this.isAlignedBox)return this.getBounds().contains(t,e);const i=this.vertices,n=i[0],s=i[1],r=i[2],o=i[3],a=i[4],h=i[5],l=i[6],u=i[7],c=(r-n)*(e-s)-(o-s)*(t-n),d=(a-r)*(e-o)-(h-o)*(t-r),_=(l-a)*(e-h)-(u-h)*(t-a),f=(n-l)*(e-u)-(s-u)*(t-l);return c>=0&&d>=0&&_>=0&&f>=0||c<=0&&d<=0&&_<=0&&f<=0}_invalidateSubtreeTransform(){super._invalidateSubtreeTransform(),this.flags.push(As.Vertices|As.Normals)}_invalidateBoundsCascade(){super._invalidateBoundsCascade(),this.flags.push(As.Vertices|As.Normals)}destroy(){super.destroy();for(const t of this._normals)t.destroy();this._textureFrame.destroy(),this._texture=null,this._material=null}}Pi.setInternalSpriteFactory(()=>new Ps(null));class Es extends zn{_text;constructor(t){super(),this._text=t}get text(){return this._text}get textBounds(){return{width:0,height:0}}syncDirty(){}update(t){this.syncDirty()}}class ks{fontData;textures;constructor(t,e){e.length,t.pages.length,e.length,t.pages.length,this.fontData=t,this.textures=e}}function Rs(t,e,i,n){if(0===t.length)return[];const{fontSize:s,lineHeight:r,leading:o,align:a}=e,h=s*r+o,l=i.letterSpacing??0,u=i.maxWidth,c=i.breakWords??!1,d=function(t,e){if("pre"===e)return t;if("normal"===e)return t.replaceAll("\n"," ").replaceAll(/[ \t]+/g," ");return t.split("\n").map(t=>t.replaceAll(/[ \t]+/g," ")).join("\n")}(t,i.whiteSpace??"pre-line"),_=d.split("\n"),f=[];for(const t of _)void 0===u?f.push(t):f.push(...Is(t,s,n,u,l,c));const p=[];let m=0;for(let t=0;t<f.length;t++){const e=f[t],i=t*h;let r=0,o=0,a=!1;const u=[];let c=null;for(const t of e){null!==c&&void 0!==n.getKerning&&(r+=n.getKerning(c,t,s));const e=n.getGlyph(t,s);u.push({info:e,x:r,y:i,char:t}),r+=e.advance+l," "===t?a=!1:a||(a=!0,o++),c=t}const d=r-(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 t=0;t<p.length;t++){const e=p[t];let i=0;if("right"===a)i=m-e.width;else if("center"===a)i=(m-e.width)/2;else if("justify"===a&&t!==y&&e.wordCount>1){const t=e.wordCount-1,n=(m-e.width)/t;let s=-1,r=!0;for(const t of e.placements)r&&" "!==t.char?(s++,r=!1):r||" "!==t.char||(r=!0),g.push({x:t.x+i+s*n+(t.info.xBearing??0),y:t.y+(t.info.yBearing??0),width:t.info.width,height:t.info.height,page:t.info.page,uvLeft:t.info.uvLeft,uvTop:t.info.uvTop,uvRight:t.info.uvRight,uvBottom:t.info.uvBottom});continue}for(const{info:t,x:n,y:s}of e.placements)g.push({x:n+i+(t.xBearing??0),y:s+(t.yBearing??0),width:t.width,height:t.height,page:t.page,uvLeft:t.uvLeft,uvTop:t.uvTop,uvRight:t.uvRight,uvBottom:t.uvBottom})}return g}function Ds(t){const e=new Map;for(const i of t){if(i.width<=0||i.height<=0)continue;let t=e.get(i.page);void 0===t&&e.set(i.page,t=[]),t.push(i)}const i=[];for(const[t,n]of e){const e=n.length,s=new Float32Array(8*e),r=new Float32Array(8*e),o=new Uint16Array(6*e);for(let t=0;t<e;t++){const e=n[t],i=8*t,a=4*t,h=6*t;s[i+0]=e.x,s[i+1]=e.y,s[i+2]=e.x+e.width,s[i+3]=e.y,s[i+4]=e.x+e.width,s[i+5]=e.y+e.height,s[i+6]=e.x,s[i+7]=e.y+e.height,r[i+0]=e.uvLeft,r[i+1]=e.uvTop,r[i+2]=e.uvRight,r[i+3]=e.uvTop,r[i+4]=e.uvRight,r[i+5]=e.uvBottom,r[i+6]=e.uvLeft,r[i+7]=e.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:t,vertices:s,uvs:r,indices:o,quadCount:e})}return i}function Is(t,e,i,n,s,r){if(0===t.length)return[""];const o=t.split(" "),a=[];let h="",l=0;const u=i.getGlyph(" ",e).advance+s;for(const t of o){let o=0;for(const n of t)o+=i.getGlyph(n,e).advance+s;if(o=Math.max(0,o-s),r&&o>n){h.length>0&&(a.push(h),h="",l=0);let r="",o=0;for(const h of t){const t=i.getGlyph(h,e).advance+s;r.length>0&&o+t>n?(a.push(r),r=h,o=t):(r+=h,o+=t)}r.length>0&&(h=r,l=o)}else if(0===h.length)h=t,l=o;else{const e=l+u+o;e<=n?(h+=` ${t}`,l=e):(a.push(h),h=t,l=o)}}return a.push(h),a}class Ls{_dirty=!1;_pendingHint="tint";onChange=new w;_fontFamily;_fontWeight;_fontStyle;_fontSize;_fillColor;_outlineColor;_outlineWidth;_align;_lineHeight;_leading;_shadowColor;_shadowOffsetX;_shadowOffsetY;_shadowAlpha;_shadowBlur;_gradientColors;_gradientAxis;constructor(t={}){const e="undefined"!=typeof FontFace&&t.font instanceof FontFace?t.font:null;this._fontFamily=e?e.family:t.fontFamily??"Arial",this._fontWeight=t.fontWeight??"normal",this._fontStyle=t.fontStyle??"normal",this._fontSize=t.fontSize??20,this._fillColor=t.fillColor?t.fillColor.clone():Re.white.clone(),this._outlineColor=t.outlineColor?t.outlineColor.clone():Re.black.clone(),this._outlineWidth=t.outlineWidth??0,this._align=t.align??"left",this._lineHeight=t.lineHeight??1.2,this._leading=t.leading??0,this._shadowColor=t.shadowColor?t.shadowColor.clone():Re.black.clone(),this._shadowOffsetX=t.shadowOffsetX??0,this._shadowOffsetY=t.shadowOffsetY??0,this._shadowAlpha=t.shadowAlpha??0,this._shadowBlur=t.shadowBlur??0,this._gradientColors=t.gradientColors?[t.gradientColors[0].clone(),t.gradientColors[1].clone()]:null,this._gradientAxis=t.gradientAxis??"vertical",this._dirty=!0,this._pendingHint="font"}consumeDirty(){if(!this._dirty)return null;const t=this._pendingHint;return this._dirty=!1,this._pendingHint="tint",t}_markDirty(t){var e,i;this._pendingHint=(e=this._pendingHint,i=t,"font"===e||"font"===i?"font":"layout"===e||"layout"===i?"layout":"tint"),this._dirty||(this._dirty=!0,this.onChange.dispatch())}get fontFamily(){return this._fontFamily}set fontFamily(t){const e="undefined"!=typeof FontFace&&t instanceof FontFace?t.family:t;this._fontFamily!==e&&(this._fontFamily=e,this._markDirty("font"))}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this._markDirty("font"))}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this._markDirty("font"))}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this._markDirty("layout"))}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this._markDirty("layout"))}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this._markDirty("layout"))}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this._markDirty("layout"))}get fillColor(){return this._fillColor}set fillColor(t){this._fillColor=t.clone(),this._markDirty("tint")}get outlineColor(){return this._outlineColor}set outlineColor(t){this._outlineColor=t.clone(),this._markDirty("tint")}get outlineWidth(){return this._outlineWidth}set outlineWidth(t){this._outlineWidth!==t&&(this._outlineWidth=t,this._markDirty("tint"))}get shadowColor(){return this._shadowColor}set shadowColor(t){this._shadowColor=t.clone(),this._markDirty("tint")}get shadowOffsetX(){return this._shadowOffsetX}set shadowOffsetX(t){this._shadowOffsetX!==t&&(this._shadowOffsetX=t,this._markDirty("tint"))}get shadowOffsetY(){return this._shadowOffsetY}set shadowOffsetY(t){this._shadowOffsetY!==t&&(this._shadowOffsetY=t,this._markDirty("tint"))}get shadowAlpha(){return this._shadowAlpha}set shadowAlpha(t){this._shadowAlpha!==t&&(this._shadowAlpha=t,this._markDirty("tint"))}get shadowBlur(){return this._shadowBlur}set shadowBlur(t){this._shadowBlur!==t&&(this._shadowBlur=t,this._markDirty("tint"))}get gradientColors(){return this._gradientColors}set gradientColors(t){this._gradientColors=t?[t[0].clone(),t[1].clone()]:null,this._markDirty("tint")}get gradientAxis(){return this._gradientAxis}set gradientAxis(t){this._gradientAxis!==t&&(this._gradientAxis=t,this._markDirty("tint"))}get font(){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}copy(t){return t!==this&&(this._fontFamily=t._fontFamily,this._fontWeight=t._fontWeight,this._fontStyle=t._fontStyle,this._fontSize=t._fontSize,this._fillColor=t._fillColor.clone(),this._outlineColor=t._outlineColor.clone(),this._outlineWidth=t._outlineWidth,this._align=t._align,this._lineHeight=t._lineHeight,this._leading=t._leading,this._shadowColor=t._shadowColor.clone(),this._shadowOffsetX=t._shadowOffsetX,this._shadowOffsetY=t._shadowOffsetY,this._shadowAlpha=t._shadowAlpha,this._shadowBlur=t._shadowBlur,this._gradientColors=t._gradientColors?[t._gradientColors[0].clone(),t._gradientColors[1].clone()]:null,this._gradientAxis=t._gradientAxis,this._markDirty("font")),this}clone(){const t=new Ls;return t._fontFamily=this._fontFamily,t._fontWeight=this._fontWeight,t._fontStyle=this._fontStyle,t._fontSize=this._fontSize,t._fillColor=this._fillColor.clone(),t._outlineColor=this._outlineColor.clone(),t._outlineWidth=this._outlineWidth,t._align=this._align,t._lineHeight=this._lineHeight,t._leading=this._leading,t._shadowColor=this._shadowColor.clone(),t._shadowOffsetX=this._shadowOffsetX,t._shadowOffsetY=this._shadowOffsetY,t._shadowAlpha=this._shadowAlpha,t._shadowBlur=this._shadowBlur,t._gradientColors=this._gradientColors?[this._gradientColors[0].clone(),this._gradientColors[1].clone()]:null,t._gradientAxis=this._gradientAxis,t._dirty=!0,t._pendingHint="font",t}}class Us{_fontData;_textures;_scale;_fallbackAdvance;_fontId;constructor(t,e,i){this._fontData=t,this._textures=e,this._scale=i,this._fallbackAdvance=t.lineHeight*i*.5,this._fontId=t.pages[0]??"unknown"}getGlyph(t,e){const i=t.codePointAt(0)??0,n=this._fontData.chars.get(i),s=this._scale,r=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*s,height:n.height*s,advance:n.xAdvance*s,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*s,yBearing:(n.yOffset-o)*s+r*s}}getKerning(t,e,i){const n=t.codePointAt(0),s=e.codePointAt(0);return void 0===n||void 0===s?0:(this._fontData.kernings.get(`${n},${s}`)??0)*this._scale}}class Fs extends Es{_font;_fontScale;_msdf;_style;_layout;_pageQuads=[];_textBounds={width:0,height:0};_adapter;constructor(t,e,i={}){super(t),this._font=e,this._fontScale=i.scale??1,this._msdf=i.msdf??!1,this._style=new Ls(i),this._layout=i.layout??{},this._adapter=new Us(e.fontData,e.textures,this._fontScale),this._rebuild()}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this._rebuild())}get style(){return this._style}set style(t){this._style=t instanceof Ls?t:new Ls(t),this._rebuild()}get layout(){return this._layout}set layout(t){this._layout=t,this._rebuild()}get fontScale(){return this._fontScale}set fontScale(t){this._fontScale!==t&&(this._fontScale=t,this._adapter=new Us(this._font.fontData,this._font.textures,t),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(t){this._font=t,this._adapter=new Us(t.fontData,t.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 t={fontSize:this._font.fontData.lineHeight*this._fontScale,lineHeight:this._style.lineHeight,leading:this._style.leading,align:this._style.align},e=Rs(this._text,t,this._layout,this._adapter);let i=0,n=0;for(const t of e){const e=t.x+t.width,s=t.y+t.height;e>i&&(i=e),s>n&&(n=s)}this._textBounds={width:i,height:n},this.getLocalBounds().set(0,0,i,n),this._invalidateBoundsCascade(),this._pageQuads=Ds(e)}}const Gs={r8:1,r32f:1,rgba8:4,rgba32f:4},Ns={r8:1,r32f:4,rgba8:1,rgba32f:4};class Os extends vi{static defaultSamplerOptions={scaleMode:Ye.Nearest,wrapMode:$e.ClampToEdge,premultiplyAlpha:!1,generateMipMap:!1,flipY:!1};format;buffer;_dirty=null;constructor(t){super(null,{...Os.defaultSamplerOptions,...t.samplerOptions});const{width:e,height:i,format:n,data:s}=t;if(!Number.isInteger(e)||e<=0)throw new Error(`DataTexture width must be a positive integer (got ${e}).`);if(!Number.isInteger(i)||i<=0)throw new Error(`DataTexture height must be a positive integer (got ${i}).`);const r=e*i*Gs[n]*Ns[n];let o;if(void 0===s)o=Vs(n)?new Float32Array(r/4):new Uint8Array(r);else if(s instanceof ArrayBuffer){if(s.byteLength!==r)throw new Error(`DataTexture data byteLength ${s.byteLength} does not match ${e}x${i} ${n} (${r} bytes expected).`);o=Vs(n)?new Float32Array(s):new Uint8Array(s)}else if(s instanceof Uint8Array){if(Vs(n))throw new Error(`DataTexture format '${n}' requires a Float32Array, got Uint8Array.`);if(s.byteLength!==r)throw new Error(`DataTexture Uint8Array length ${s.length} does not match ${e}x${i} ${n} (${r} expected).`);o=s}else{if(!Vs(n))throw new Error(`DataTexture format '${n}' requires a Uint8Array, got Float32Array.`);if(s.byteLength!==r)throw new Error(`DataTexture Float32Array byteLength ${s.byteLength} does not match ${e}x${i} ${n} (${r} expected).`);o=s}this.format=n,this.buffer=o,this.setSize(e,i),this._dirty={full:!0,x:0,y:0,width:e,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(t,e,i,n){if(!(Number.isInteger(t)&&Number.isInteger(e)&&Number.isInteger(i)&&Number.isInteger(n)))throw new Error(`DataTexture commitRect requires integer coordinates (got ${t}, ${e}, ${i}, ${n}).`);if(i<=0||n<=0)throw new Error(`DataTexture commitRect requires positive width and height (got ${i}, ${n}).`);if(t<0||e<0||t+i>this.width||e+n>this.height)throw new Error(`DataTexture commitRect (${t}, ${e}, ${i}, ${n}) is out of bounds for ${this.width}x${this.height}.`);if(null===this._dirty)this._dirty={full:!1,x:t,y:e,width:i,height:n};else if(this._dirty.full);else{const s=Math.min(this._dirty.x,t),r=Math.min(this._dirty.y,e),o=Math.max(this._dirty.x+this._dirty.width,t+i),a=Math.max(this._dirty.y+this._dirty.height,e+n);this._dirty={full:!1,x:s,y:r,width:o-s,height:a-r}}return this._bumpVersion(),this}_consumeDirtyRegion(){const t=this._dirty;return this._dirty=null,t}}function Vs(t){return"r32f"===t||"rgba32f"===t}const zs=1e20;class qs{_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(t){this._buffer=t.buffer??8,this._radius=t.radius??this._buffer,this._cutoff=t.cutoff??.5,this._fontSize=t.fontSize;const e=t.fontStyle&&"normal"!==t.fontStyle?`${t.fontStyle} `:"",i=t.fontWeight??"normal";if(this._font=`${e}${i} ${t.fontSize}px ${t.fontFamily}`,"undefined"!=typeof OffscreenCanvas){const t=new OffscreenCanvas(1,1);this._canvas=t,this._ctx=t.getContext("2d",{willReadFrequently:!0})}else{const t=document.createElement("canvas");this._canvas=t,this._ctx=t.getContext("2d",{willReadFrequently:!0})}}_ensureFontMetrics(){if(this._metricsReady)return;const t=this._ctx;t.font=this._font,t.textBaseline="alphabetic";const e=t.measureText("HgjpqyÉÅ");this._fontAscent=Math.max(1,Math.ceil(e.fontBoundingBoxAscent??e.actualBoundingBoxAscent??.8*this._fontSize)),this._fontDescent=Math.max(1,Math.ceil(e.fontBoundingBoxDescent??e.actualBoundingBoxDescent??.2*this._fontSize)),this._metricsReady=!0}draw(t){this._ensureFontMetrics();const e=this._ctx,i=this._buffer;e.font=this._font,e.textBaseline="alphabetic";const n=e.measureText(t),s=n.width,r=Math.max(0,Math.ceil(n.actualBoundingBoxLeft??0)),o=Math.max(0,Math.ceil(n.actualBoundingBoxRight??s)),a=Math.max(1,r+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),e.clearRect(0,0,l,u),e.font=this._font,e.textBaseline="alphabetic",e.fillStyle="#ffffff",e.fillText(t,i+r,i+this._fontAscent);const c=e.getImageData(0,0,l,u).data,d=l*u;if(d>this._gridOuter.length){const t=Math.max(l,u);this._gridOuter=new Float64Array(d),this._gridInner=new Float64Array(d),this._f=new Float64Array(t),this._d=new Float64Array(t),this._z=new Float64Array(t+1),this._v=new Int16Array(t)}d>this._out.length&&(this._out=new Uint8ClampedArray(d));for(let t=0;t<d;t++){const e=c[4*t+3]/255;1===e?(this._gridOuter[t]=0,this._gridInner[t]=zs):0===e?(this._gridOuter[t]=zs,this._gridInner[t]=0):(this._gridOuter[t]=Math.max(0,.5-e)**2,this._gridInner[t]=Math.max(0,e-.5)**2)}Ws(this._gridOuter,l,u,this._f,this._d,this._v,this._z),Ws(this._gridInner,l,u,this._f,this._d,this._v,this._z);for(let t=0;t<d;t++){const e=this._gridOuter[t]-this._gridInner[t];this._out[t]=Math.max(0,Math.min(255,Math.round(255-255*(e/this._radius+this._cutoff))))}return{data:this._out.slice(0,d),width:l,height:u,glyphWidth:a,glyphHeight:h,glyphTop:i,glyphLeft:i,glyphAdvance:s}}}function Ws(t,e,i,n,s,r,o){for(let a=0;a<e;a++){for(let s=0;s<i;s++)n[s]=t[s*e+a];Ys(n,s,r,o,i);for(let n=0;n<i;n++)t[n*e+a]=s[n]}for(let a=0;a<i;a++){for(let i=0;i<e;i++)n[i]=t[a*e+i];Ys(n,s,r,o,e);for(let i=0;i<e;i++)t[a*e+i]=Math.sqrt(s[i])}}function Ys(t,e,i,n,s){let r=0;i[0]=0,n[0]=-zs,n[1]=zs;for(let e=1;e<s;e++){let s;do{const o=i[r];if(s=(t[e]+e*e-t[o]-o*o)/(2*(e-o)),s>n[r])break;r--}while(r>=0);r++,i[r]=e,n[r]=s,n[r+1]=zs}r=0;for(let o=0;o<s;o++){for(;n[r+1]<o;)r++;const s=i[r];e[o]=(o-s)*(o-s)+t[s]}}class $s{_shelves=[];_width;_height;constructor(t,e){this._width=t,this._height=e}insert(t,e){for(const i of this._shelves)if(i.height>=e&&i.cursorX+t<=this._width){const e=i.cursorX;return i.cursorX+=t,{x:e,y:i.y}}const i=this._shelves[this._shelves.length-1],n=void 0===i?0:i.y+i.height;return n+e>this._height?null:(this._shelves.push({y:n,height:e,cursorX:t}),{x:0,y:n})}reset(){this._shelves.length=0}}class Xs{texture;index;mode;_packer;_width;_height;_sdfBuffer=null;_sdfTexture=null;_ctx=null;_colorGlyphs;constructor(t,e,i,n){if(this.index=t,this.mode=n,this._width=e,this._height=i,this._colorGlyphs="color"===n,this._packer=new $s(e,i),"sdf"===n)this._sdfBuffer=new Uint8Array(e*i),this._sdfTexture=new Os({width:e,height:i,format:"r8",data:this._sdfBuffer}),this._sdfTexture.setSize(e,i),this.texture=this._sdfTexture;else{const{canvas:t,ctx:n}=function(t,e){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(t,e),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=t,i.height=e;const n=i.getContext("2d");if(!n)throw new Error("GlyphAtlas: could not obtain canvas 2D context.");return{canvas:i,ctx:n}}(e,i);this._ctx=n,this.texture=new vi(t),this.texture.setSize(e,i)}}insert(t,e){return this._packer.insert(t,e)}writeSdf(t,e,i,n,s){const r=this._sdfBuffer,o=this._width;for(let a=0;a<s;a++){const s=a*n,h=(i+a)*o+e;r.set(t.subarray(s,s+n),h)}this._sdfTexture.commitRect(e,i,n,s)}measureGlyph(t,e){if(null!==this._ctx)return this._ctx.font=e,this._ctx.textBaseline="alphabetic",this._ctx.measureText(t);const i=("undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(1,1):document.createElement("canvas")).getContext("2d");return i.font=e,i.textBaseline="alphabetic",i.measureText(t)}rasterize(t,e,i,n,s,r){const o=this._ctx;o.font=r,o.textBaseline="alphabetic",this._colorGlyphs||(o.fillStyle="#ffffff"),o.fillText(t,e+2+s,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 Hs{_pages=[];_cache=new Map;_kerningCache=new Map;_pageSize;_family;_fontStyle;_fontWeight;_mode;_sdfRadius;onPageAdded=new w;_sdfInstances=new Map;constructor(t,e,i,n=1024,s="sdf",r=8){this._family=t,this._fontStyle=e,this._fontWeight=i,this._pageSize=n,this._mode=s,this._sdfRadius=r,this._addPage()}get pages(){return this._pages}get mode(){return this._mode}getGlyph(t,e){const i=`${t}:${e}`,n=this._cache.get(i);return void 0!==n?n:"sdf"===this._mode?this._rasterizeSdf(t,e,i):this._rasterizeCanvas(t,e,i)}getKerning(t,e,i){const n=`${t}${e}:${i}`,s=this._kerningCache.get(n);if(void 0!==s)return s;const r=this._cssFont(i),o=this._pages[0],a=o.measureGlyph(t+e,r).width-o.measureGlyph(t,r).width-o.measureGlyph(e,r).width;return this._kerningCache.set(n,a),a}clear(){this._cache.clear(),this._kerningCache.clear(),this._sdfInstances.clear();for(const t of this._pages)t.reset();this._pages=[],this._addPage()}_addPage(){const t=this._pages.length,e=new Xs(t,this._pageSize,this._pageSize,this._mode);return this._pages.push(e),t>0&&this.onPageAdded.dispatch(t),e}_cssFont(t){return`${"normal"!==this._fontStyle?`${this._fontStyle} `:""}${this._fontWeight} ${t}px ${this._family}`}_getSdf(t){let e=this._sdfInstances.get(t);return void 0===e&&(e=new qs({fontSize:t,fontFamily:this._family,fontWeight:this._fontWeight,fontStyle:this._fontStyle,buffer:this._sdfRadius,radius:this._sdfRadius,cutoff:.5}),this._sdfInstances.set(t,e)),e}_rasterizeSdf(t,e,i){const n=this._getSdf(e).draw(t),{page:s,slot:r}=this._allocateSlot(n.width,n.height);s.writeSdf(n.data,r.x,r.y,n.width,n.height);const o=this._pageSize,a={x:r.x,y:r.y,width:n.width,height:n.height,advance:n.glyphAdvance,ascent:n.glyphTop+n.glyphHeight,page:s.index,uvLeft:r.x/o,uvTop:r.y/o,uvRight:(r.x+n.width)/o,uvBottom:(r.y+n.height)/o,xBearing:-n.glyphLeft,yBearing:-n.glyphTop};return this._cache.set(i,a),a}_rasterizeCanvas(t,e,i){const n=this._cssFont(e),s=this._pages[0].measureGlyph(t,n),r=Math.ceil(s.fontBoundingBoxAscent??s.actualBoundingBoxAscent??.8*e),o=Math.ceil(s.fontBoundingBoxDescent??s.actualBoundingBoxDescent??.2*e),a=s.width,h=s.actualBoundingBoxLeft??0,l=s.actualBoundingBoxRight??0,u=Math.max(1,Math.ceil(h+l)||Math.ceil(a)),c=Math.max(1,r+o),d=u+4,_=c+4,{page:f,slot:p}=this._allocateSlot(d,_);f.rasterize(t,p.x,p.y,r,h,n),f.uploadDirtyRegion();const m=this._pageSize,g={x:p.x,y:p.y,width:u,height:c,advance:a,ascent:r,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(t,e){for(const i of this._pages){const n=i.insert(t,e);if(null!==n)return{page:i,slot:n}}const i=this._addPage(),n=i.insert(t,e);if(null===n)throw new Error(`GlyphAtlas: glyph (${t}×${e}px) exceeds page size (${this._pageSize}px).`);return{page:i,slot:n}}}class js{_atlases=new Map;_pageSize;constructor(t=1024){this._pageSize=t}getAtlas(t,e,i,n="sdf",s=8){const r=`${t}:${e}:${i}:${n}:${s}`;let o=this._atlases.get(r);return void 0===o&&(o=new Hs(t,e,i,this._pageSize,n,s),this._atlases.set(r,o)),o}clearAll(){for(const t of this._atlases.values())t.clear()}}let Ks=null;function Qs(){return null===Ks&&(Ks=new js),Ks}class Zs extends Es{_style;_layout;_colorGlyphs;_sdfRadius;_atlas=null;_destroyed=!1;_faceLoadVersion=0;_pageQuads=[];_textBounds={width:0,height:0};constructor(t,e={}){super(t),this._style=new Ls(e),this._layout=e,this._colorGlyphs=e.colorGlyphs??!1,this._sdfRadius=e.sdfRadius??8;const i=this._extractFace(e);null!==i&&this._loadFace(i),this._rebuild("font")}get style(){return this._style}set style(t){if(this._style=t instanceof Ls?t:new Ls(t),!(t instanceof Ls)){const e=this._extractFace(t);null!==e&&this._loadFace(e)}this._rebuild("font")}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this._rebuild("layout"))}get layout(){return this._layout}set layout(t){this._layout=t,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 t=this._style.consumeDirty();null!==t&&"tint"!==t&&this._rebuild(t)}destroy(){this._destroyed=!0,this._faceLoadVersion++,this._pageQuads=[],this._atlas=null,super.destroy()}_extractFace(t){return"undefined"==typeof FontFace?null:t.font instanceof FontFace?t.font:null}async _loadFace(t){if("undefined"==typeof document||!document.fonts)return;const e=++this._faceLoadVersion;document.fonts.has(t)||document.fonts.add(t);try{await t.load()}catch{return}if(this._destroyed||e!==this._faceLoadVersion)return;Qs().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius).clear(),this._rebuild("font")}_rebuild(t){if(this._pageQuads=[],this._textBounds={width:0,height:0},0===this._text.length)return void this._style.consumeDirty();const e=Qs().getAtlas(this._style.fontFamily,this._style.fontStyle,this._style.fontWeight,this.atlasMode,this._sdfRadius);this._atlas=e;const i=Rs(this._text,this._style,this._layout,e);if(0===i.length)return void this._style.consumeDirty();let n=0,s=0;for(const t of i){const e=t.x+t.width,i=t.y+t.height;e>n&&(n=e),i>s&&(s=i)}this._textBounds={width:n,height:s},this.getLocalBounds().set(0,0,n,s),this._invalidateBoundsCascade(),this._pageQuads=Ds(i),this._style.consumeDirty()}}class Js{attributes=new Map;uniforms=new Map;_vertexSource;_fragmentSource;_program=null;constructor(t,e){this._vertexSource=t,this._fragmentSource=e}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(t){return this._program=t,t.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(t){const e=this.attributes.get(t);if(!e)throw new Error(`Attribute "${t}" is not available.`);return e}getUniform(t){const e=this.uniforms.get(t);if(!e)throw new Error(`Uniform "${t}" is not available.`);return e}destroy(){this._program?.destroy(this),this._program=null,this.attributes.clear(),this.uniforms.clear()}}var tr;!function(t){t[t.WebGl2=0]="WebGl2",t[t.WebGpu=1]="WebGpu"}(tr||(tr={}));class er{backendType=tr.WebGl2;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==tr.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 ir{_type;_usage;_runtime=null;_data=p;_version=0;_accountant=null;_accountedBytes=0;constructor(t,e,i){this._type=t,this._usage=i,e&&this.upload(e)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(t,e){return this._runtime=t,this._accountant=e??null,this._data.byteLength>0&&(t.upload(this,0),this._bookUpload()),this}disconnect(){return this._runtime=null,this}upload(t,e=0){this._data=t,this._version++,this._runtime?.upload(this,e),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 t=this._accountant;if(null===t||null===this._runtime)return;const e=this._data.byteLength;t.recordBufferUpload(e),e>this._accountedBytes&&(this._accountedBytes=t.reallocate(this._accountedBytes,e))}}const nr={[Ke.Float]:1,[Ke.FloatVec2]:2,[Ke.FloatVec3]:3,[Ke.FloatVec4]:4,[Ke.Int]:1,[Ke.IntVec2]:2,[Ke.IntVec3]:3,[Ke.IntVec4]:4,[Ke.UnsignedInt]:1,[Ke.UnsignedIntVec2]:2,[Ke.UnsignedIntVec3]:3,[Ke.UnsignedIntVec4]:4,[Ke.Bool]:1,[Ke.BoolVec2]:2,[Ke.BoolVec3]:3,[Ke.BoolVec4]:4,[Ke.FloatMat2]:4,[Ke.FloatMat3]:9,[Ke.FloatMat4]:16,[Ke.Sampler2D]:1},sr={[Ke.Float]:Float32Array,[Ke.FloatVec2]:Float32Array,[Ke.FloatVec3]:Float32Array,[Ke.FloatVec4]:Float32Array,[Ke.Int]:Int32Array,[Ke.IntVec2]:Int32Array,[Ke.IntVec3]:Int32Array,[Ke.IntVec4]:Int32Array,[Ke.UnsignedInt]:Int32Array,[Ke.UnsignedIntVec2]:Int32Array,[Ke.UnsignedIntVec3]:Int32Array,[Ke.UnsignedIntVec4]:Int32Array,[Ke.Bool]:Uint8Array,[Ke.BoolVec2]:Uint8Array,[Ke.BoolVec3]:Uint8Array,[Ke.BoolVec4]:Uint8Array,[Ke.FloatMat2]:Float32Array,[Ke.FloatMat3]:Float32Array,[Ke.FloatMat4]:Float32Array,[Ke.Sampler2D]:Uint8Array};Ke.Float,Ke.FloatVec2,Ke.FloatVec3,Ke.FloatVec4,Ke.Int,Ke.IntVec2,Ke.IntVec3,Ke.IntVec4,Ke.UnsignedInt,Ke.UnsignedIntVec2,Ke.UnsignedIntVec3,Ke.UnsignedIntVec4,Ke.Bool,Ke.BoolVec2,Ke.BoolVec3,Ke.BoolVec4,Ke.FloatMat2,Ke.FloatMat3,Ke.FloatMat4,Ke.Sampler2D;class rr{index;name;type;size;location=-1;constructor(t,e,i){this.index=t,this.name=e,this.type=i,this.size=nr[i]}destroy(){}}class or{index;type;size;name;_value;_dirty=!0;constructor(t,e,i,n,s){this.name=n.replace(/\[.*?]/,""),this.index=t,this.type=e,this.size=i,this._value=s}get propName(){return this.name.substring(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(t){return this._value.set(t),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class ar{index;name;binding;dataSize;_context;_program;_blockData;_uniformBuffer;_uniforms=new Map;constructor(t,e,i){this._context=t,this._program=e,this.index=i,this.name=t.getActiveUniformBlockName(e,i)||"",this.binding=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_BINDING),this.dataSize=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=t.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferData(t.UNIFORM_BUFFER,this._blockData,t.DYNAMIC_DRAW),t.bindBufferBase(t.UNIFORM_BUFFER,this.binding,this._uniformBuffer),t.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(t){if(!this._uniforms.has(t))throw new Error(`Uniform "${t}" is not available.`);return this._uniforms.get(t)}upload(){const t=this._context;t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferSubData(t.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const t of this._uniforms.values())t.destroy();this._uniforms.clear()}_extractUniforms(){const t=this._context,e=this._program,i=this._blockData,n=t.getActiveUniformBlockParameter(e,this.index,t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),s=t.getActiveUniforms(e,n,t.UNIFORM_OFFSET),r=n.length;for(let o=0;o<r;o++){const r=n[o],{type:a,size:h,name:l}=t.getActiveUniform(e,r),u=sr[a],c=nr[a];if(void 0===u||void 0===c)throw new Error(`Unsupported uniform type ${a} for uniform "${l}".`);const d=new u(i,s[o],c*h),_=new or(r,a,h,l,d);this._uniforms.set(_.propName,_)}}}const hr={[Ke.Float]:(t,e,i)=>{t.uniform1f(e,i[0])},[Ke.FloatVec2]:(t,e,i)=>{t.uniform2fv(e,i)},[Ke.FloatVec3]:(t,e,i)=>{t.uniform3fv(e,i)},[Ke.FloatVec4]:(t,e,i)=>{t.uniform4fv(e,i)},[Ke.Int]:(t,e,i)=>{t.uniform1i(e,i[0])},[Ke.IntVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[Ke.IntVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[Ke.IntVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[Ke.Bool]:(t,e,i)=>{t.uniform1i(e,i[0])},[Ke.BoolVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[Ke.BoolVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[Ke.BoolVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[Ke.FloatMat2]:(t,e,i)=>{t.uniformMatrix2fv(e,!1,i)},[Ke.FloatMat3]:(t,e,i)=>{t.uniformMatrix3fv(e,!1,i)},[Ke.FloatMat4]:(t,e,i)=>{t.uniformMatrix4fv(e,!1,i)},[Ke.Sampler2D]:(t,e,i)=>{t.uniform1i(e,i[0])}};function lr(t){let e=null,i=null,n=null,s=null;const r=[],o=[],a=t.getExtension("KHR_parallel_shader_compile"),h=a?.COMPLETION_STATUS_KHR??37297;function l(r){e||(i=ur(t,t.VERTEX_SHADER,r.vertexSource),n=ur(t,t.FRAGMENT_SHADER,r.fragmentSource),e=function(t,e,i){const n=t.createProgram();if(!n)throw new Error("Could not create shader program.");return t.attachShader(n,e),t.attachShader(n,i),t.linkProgram(n),n}(t,i,n),s=r)}function u(){if(null!==s&&null!==e&&null!==i&&null!==n){if(null!==a&&t.getProgramParameter(e,h),!t.getShaderParameter(i,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(i);throw new Error(`Vertex shader compilation failed: ${e??"<no log>"}`)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(n);throw new Error(`Fragment shader compilation failed: ${e??"<no log>"}`)}if(!t.getProgramParameter(e,t.LINK_STATUS)){const i=t.getProgramInfoLog(e);throw new Error(`Shader program linking failed: ${i??"<no log>"}`)}!function(t,e,i){const n=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let s=0;s<n;s++){const n=t.getActiveAttrib(e,s);if(!n)continue;const r=new rr(s,n.name,n.type);r.location=t.getAttribLocation(e,n.name),i.attributes.set(n.name,r)}}(t,e,s),function(t,e,i,n){const s=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),r=new Uint8Array(s).map((t,e)=>e),o=t.getActiveUniforms(e,r,t.UNIFORM_BLOCK_INDEX),a=r.filter(t=>-1===o[t]);for(const s of a){const r=t.getActiveUniform(e,s);if(!r)continue;const o=sr[r.type],a=nr[r.type],h=hr[r.type];if(void 0===o||void 0===a||void 0===h)throw new Error(`Unsupported uniform type ${r.type} for uniform "${r.name}".`);const l=new o(a*r.size),u=new or(s,r.type,r.size,r.name,l),c=t.getUniformLocation(e,u.name);i.uniforms.set(u.name,u),c&&n.push({location:c,uploadFn:h,uniform:u})}}(t,e,s,r),function(t,e,i){const n=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let s=0;s<n;s++){const n=new ar(t,e,s);i.push(n)}}(t,e,o),s=null}}function c(){for(const e of r)e.uniform.dirty&&(e.uploadFn(t,e.location,e.uniform.value),e.uniform.markClean());for(const t of o)t.upload()}return{initialize:l,bind:i=>{l(i),u(),t.useProgram(e),c()},unbind:()=>{t.useProgram(null)},sync:()=>{u(),t.useProgram(e),c()},destroy:a=>{t.deleteShader(i),t.deleteShader(n),t.deleteProgram(e);for(const t of o)t.destroy();i=null,n=null,e=null,s=null,r.length=0,o.length=0,a.disconnect()}}}function ur(t,e,i){const n=t.createShader(e);if(!n)throw new Error("Could not create shader.");return t.shaderSource(n,i),t.compileShader(n),n}class cr{_attributes=[];_indexBuffer=null;_drawMode;_runtime=null;_version=0;constructor(t=Xe.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(t){return this._runtime=t,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(t,e,i=Ke.Float,n=!1,s=0,r=0,o=!1,a=0){const{location:h,size:l}=e;return this._attributes.push({buffer:t,location:h,size:l,type:i,normalized:n,stride:s,start:r,integer:o,divisor:a}),this._version++,this}addIndex(t){return this._indexBuffer=t,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(t,e,i=this._drawMode){return this._runtime?.draw(this,t,e,i),this}drawInstanced(t,e,i,n=this._drawMode){return this._runtime?.drawInstanced?.(this,t,e,i,n),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}const dr=20;class _r extends er{_defaultShader=new Js("#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)},(t,e)=>new Int32Array([e]));_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 e=this._connection;if(!e)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(0===t.vertexCount)return;const i=this.getBackend(),n=t.material,s=null===n?this._defaultShader:this._getOrCreateCustomShader(n,e.gl),r=null!==n&&t.blendMode===qe.Normal?n.blendMode:t.blendMode,o=t.texture??vi.white,a=i.activeDrawCommand,h=null===n||this._isInstancingCompatible(s);let l=this._pendingDraws[this._pendingCount];void 0===l?(l={mesh:t,command:a,material:n,shader:s,blendMode:r,texture:o,supportsInstancing:h},this._pendingDraws.push(l)):(l.mesh=t,l.command=a,l.material=n,l.shader=s,l.blendMode=r,l.texture=o,l.supportsInstancing=h),this._pendingCount++}drawInstancedBatch(t,e,i){const n=this._connection;if(!n)throw new Error("WebGl2MeshRenderer is not connected to a backend.");if(i<=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 r=this.getBackend(),o=this._defaultShader,a=t.blendMode,h=t.texture??vi.white,l=this._getOrCreateStaticGeometryEntry(s,t,n),u=this._getOrCreateStaticGeometryVao(l,o,n.gl,n.dynamicNodeIndexBuffer);this._setBlendMode(a,r),this._ensureNodeIndexCapacity(i);const c=e+i-1>>>0;for(let t=0;t<i;t++)this._nodeIndexData[t]=e+t>>>0;this._bindInstancedShaderState(o,h,null,r,c),r.bindVertexArrayObject(u),n.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,i)),u.drawInstanced(l.indexCount,0,i,Xe.Triangles),r.stats.batches++,r.stats.drawCalls++}flush(){const t=this.getBackendOrNull(),e=this._connection,i=this._pendingCount;if(null!==t&&null!==e&&0!==i){for(let n=0;n<i;n++){const s=this._pendingDraws[n];if(this._canBatchStatic(s)){let s=n+1;for(;s<i&&this._isSameBatch(this._pendingDraws[s-1],this._pendingDraws[s]);)s++;if(s-n>=2){this._drawStaticBatch(n,s,t,e),n=s-1;continue}}this._drawSingle(n,t,e)}this._pendingCount=0}else this._pendingCount=0}destroy(){this.disconnect(),this._defaultShader.destroy();for(const t of this._customShaders.values())t.destroy();this._customShaders.clear(),this._compatibilityCache.clear()}onConnect(t){const e=t.context;this._defaultShader.connect(lr(e)),this._defaultShader.sync();for(const t of this._customShaders.values())t.connect(lr(e)),t.sync();const i=new Map,n=new ir(He.ElementArrayBuffer,this._indexData,je.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),s=new ir(He.ArrayBuffer,this._vertexData,je.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),r=new ir(He.ArrayBuffer,this._nodeIndexData,je.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),o=e.createVertexArray();if(null===o)throw new Error("Could not create vertex array object.");const a=(new cr).addIndex(n).addAttribute(s,this._defaultShader.getAttribute("a_position"),e.FLOAT,!1,dr,0).addAttribute(s,this._defaultShader.getAttribute("a_texcoord"),e.FLOAT,!1,dr,8).addAttribute(s,this._defaultShader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,dr,16).addAttribute(r,this._defaultShader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(e,o));this._connection={gl:e,buffers:i,dynamicVao:a,dynamicVertexBuffer:s,dynamicIndexBuffer:n,dynamicNodeIndexBuffer:r}}onDisconnect(){const t=this._connection;if(t){this._defaultShader.disconnect();for(const t of this._customShaders.values())t.disconnect();for(const t of this._staticGeometryCache.values()){for(const e of t.vaos.values())e.destroy();t.vaos.clear(),t.indexBuffer.destroy(),t.vertexBuffer.destroy()}this._staticGeometryCache.clear(),t.dynamicNodeIndexBuffer.destroy(),t.dynamicIndexBuffer.destroy(),t.dynamicVertexBuffer.destroy(),t.dynamicVao.destroy(),this._connection=null,this._currentBlendMode=null,this._pendingDraws.length=0,this._pendingCount=0}}_drawSingle(t,e,i){const n=this._pendingDraws[t];this._canBatchStatic(n)?this._drawStaticBatch(t,t+1,e,i):n.supportsInstancing&&null===n.material?this._drawDynamicInstancedSingle(n,e,i):this._drawLegacyImmediate(n,e,i)}_drawDynamicInstancedSingle(t,e,i){const n=t.command?.nodeIndex??0;null===t.command&&e._writeTransformCommand(this._createSyntheticCommand(t.mesh,n)),this._setBlendMode(t.blendMode,e),this._bindInstancedShaderState(t.shader,t.texture,t.material,e,n),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]=n>>>0,e.bindVertexArrayObject(i.dynamicVao),i.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*t.mesh.vertexCount)),i.dynamicIndexBuffer.upload(this._indexData.subarray(0,t.mesh.indexCount)),i.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,1)),i.dynamicVao.drawInstanced(t.mesh.indexCount,0,1,Xe.Triangles),e.stats.batches++,e.stats.drawCalls++}_drawStaticBatch(t,e,i,n){const s=this._pendingDraws[t],r=s.mesh.geometry,o=e-t,a=this._getOrCreateStaticGeometryEntry(r,s.mesh,n),h=this._getOrCreateStaticGeometryVao(a,s.shader,n.gl,n.dynamicNodeIndexBuffer);this._setBlendMode(s.blendMode,i);let l=0;this._ensureNodeIndexCapacity(o);for(let e=0;e<o;e++){const i=this._pendingDraws[t+e].command.nodeIndex>>>0;this._nodeIndexData[e]=i,i>l&&(l=i)}this._bindInstancedShaderState(s.shader,s.texture,s.material,i,l),i.bindVertexArrayObject(h),n.dynamicNodeIndexBuffer.upload(this._nodeIndexData.subarray(0,o)),h.drawInstanced(a.indexCount,0,o,Xe.Triangles),i.stats.batches++,i.stats.drawCalls++}_drawLegacyImmediate(t,e,i){const n=t.mesh,s=t.shader;this._setBlendMode(t.blendMode,e),s.uniforms.has("u_projection")&&s.getUniform("u_projection").setValue(e.view.getTransform().toArray(!1)),s.uniforms.has("u_translation")&&s.getUniform("u_translation").setValue(n.getGlobalTransform().toArray(!1)),s.uniforms.has("u_tint")&&s.getUniform("u_tint").setValue(n.tint.toArray(!1)),s.uniforms.has("u_texture")&&(s.getUniform("u_texture").setValue(this._textureUnitScratch),e.bindTexture(t.texture,0)),null!==t.material&&this._bindCustomUniforms(s,t.material,e),this._ensureVertexCapacity(n.vertexCount),this._ensureIndexCapacity(n.indexCount),this._packVertices(n,0),this._packIndices(n,0),s.sync(),e.bindVertexArrayObject(i.dynamicVao),i.dynamicVertexBuffer.upload(this._float32View.subarray(0,5*n.vertexCount)),i.dynamicIndexBuffer.upload(this._indexData.subarray(0,n.indexCount)),i.dynamicVao.draw(n.indexCount,0,Xe.Triangles),e.stats.batches++,e.stats.drawCalls++}_bindInstancedShaderState(t,e,i,n,s){t.uniforms.has("u_projection")&&t.getUniform("u_projection").setValue(n.view.getTransform().toArray(!1)),t.uniforms.has("u_transforms")&&(n.bindTransformBufferTexture(8,s+1),t.getUniform("u_transforms").setValue(this._transformUnitScratch)),t.uniforms.has("u_texture")&&(t.getUniform("u_texture").setValue(this._textureUnitScratch),n.bindTexture(e,0)),null!==i&&this._bindCustomUniforms(t,i,n),t.sync()}_canBatchStatic(t){if(!t.supportsInstancing)return!1;if(void 0===t.command?.groupIndex)return!1;const e=t.mesh.geometry;return"static"===e?.usage}_isSameBatch(t,e){return!(!this._canBatchStatic(t)||!this._canBatchStatic(e))&&(t.command.groupIndex===e.command.groupIndex&&t.mesh.geometry===e.mesh.geometry&&t.shader===e.shader&&t.material===e.material&&t.blendMode===e.blendMode&&t.texture===e.texture&&t.command.material.pipelineKey===e.command.material.pipelineKey&&t.command.material.bindKey===e.command.material.bindKey)}_isInstancingCompatible(t){const e=this._compatibilityCache.get(t);if(void 0!==e)return e;const i=t.attributes.has("a_nodeIndex")&&t.uniforms.has("u_transforms")&&!t.uniforms.has("u_translation")&&!t.uniforms.has("u_tint");return this._compatibilityCache.set(t,i),i}_getOrCreateStaticGeometryEntry(t,e,i){const n=this._staticGeometryCache.get(t);if(void 0!==n)return n;const s=e.vertexCount,r=e.indexCount,o=new ArrayBuffer(s*dr),a=new Float32Array(o),h=new Uint32Array(o);this._packVertices(e,0,a,h);const l=new Uint16Array(r);this._packIndices(e,0,l);const u=this.getBackend().accountant,c=new ir(He.ArrayBuffer,a,je.StaticDraw).connect(this._createBufferRuntime(i.gl,i.buffers),u),d=new ir(He.ElementArrayBuffer,l,je.StaticDraw).connect(this._createBufferRuntime(i.gl,i.buffers),u);c.upload(a),d.upload(l);const _=()=>{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(_);const f={geometry:t,vertexBuffer:c,indexBuffer:d,vaos:new Map,disposeListener:_,indexCount:r};return this._staticGeometryCache.set(t,f),f}_getOrCreateStaticGeometryVao(t,e,i,n){const s=t.vaos.get(e);if(void 0!==s)return s;const r=i.createVertexArray();if(null===r)throw new Error("Could not create vertex array object.");const o=e.getAttribute("a_nodeIndex"),a=(new cr).addIndex(t.indexBuffer).addAttribute(t.vertexBuffer,e.getAttribute("a_position"),i.FLOAT,!1,dr,0).addAttribute(t.vertexBuffer,e.getAttribute("a_texcoord"),i.FLOAT,!1,dr,8).addAttribute(t.vertexBuffer,e.getAttribute("a_color"),i.UNSIGNED_BYTE,!0,dr,16).addAttribute(n,o,i.UNSIGNED_INT,!1,Uint32Array.BYTES_PER_ELEMENT,0,!0,1).connect(this._createVaoRuntime(i,r));return t.vaos.set(e,a),a}_setBlendMode(t,e){this._currentBlendMode!==t&&(this._currentBlendMode=t,e.setBlendMode(t))}_packVertices(t,e,i=this._float32View,n=this._uint32View){const s=t.vertices,r=t.uvs,o=t.colors,a=t.vertexCount;for(let t=0;t<a;t++){const a=5*(e+t),h=2*t;i[a]=s[h],i[a+1]=s[h+1],null!==r?(i[a+2]=r[h],i[a+3]=r[h+1]):(i[a+2]=0,i[a+3]=0),n[a+4]=null!==o?o[t]:4294967295}}_packIndices(t,e,i=this._indexData){const n=t.indexCount;if(null===t.indices)for(let t=0;t<n;t++)i[e+t]=t;else i.set(t.indices,e)}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*dr),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeIndexCapacity(t){if(!(t<=this._nodeIndexCapacity)){for(;this._nodeIndexCapacity<t;)this._nodeIndexCapacity*=2;this._nodeIndexData=new Uint32Array(this._nodeIndexCapacity)}}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(n,s)=>{const r=e.get(n),o=n.data;t.bindBuffer(n.type,i),r&&r.dataByteLength>=o.byteLength?(t.bufferSubData(n.type,s,o),r.dataByteLength=o.byteLength):(t.bufferData(n.type,o,n.usage),e.set(n,{handle:i,dataByteLength:o.byteLength}))},destroy:n=>{t.deleteBuffer(i),e.delete(n),n.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:n=>{if(t.bindVertexArray(e),i!==n.version){let e=null;for(const i of n.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),i.integer?t.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location),t.vertexAttribDivisor(i.location,i.divisor);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,s)=>{e.indexBuffer?t.drawElements(s,i,t.UNSIGNED_SHORT,n):t.drawArrays(s,n,i)},drawInstanced:(e,i,n,s,r)=>{e.indexBuffer?t.drawElementsInstanced(r,i,t.UNSIGNED_SHORT,n,s):t.drawArraysInstanced(r,n,i,s)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}_getOrCreateCustomShader(t,e){const i=this._customShaders.get(t);if(void 0!==i)return i;const n=t.shader.glsl;if(null===n)throw new Error("Mesh material shader has no `glsl` source; cannot render through the WebGL2 backend.");const s=new Js(n.vertex,n.fragment);return s.connect(lr(e)),s.sync(),this._customShaders.set(t,s),t._onDispose(()=>{const e=this._customShaders.get(t);void 0!==e&&(e.destroy(),this._customShaders.delete(t))}),s}_bindCustomUniforms(t,e,i){let n=1;const s=e.uniforms;for(const e in s){if(!t.uniforms.has(e))continue;const r=s[e],o=t.getUniform(e);if(r instanceof vi||r instanceof wi){if(n>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(r,n),o.setValue(this._slotScratches[n]),n++}else o.setValue(this._marshalUniformValue(r))}const r=e.textures;for(const e in r)if(t.uniforms.has(e)){if(n>=8)throw new Error("Mesh material requested more than 7 texture bindings.");i.bindTexture(r[e],n),t.getUniform(e).setValue(this._slotScratches[n]),n++}}_marshalUniformValue(t){return t instanceof Float32Array||t instanceof Int32Array?t:"number"==typeof t?new Float32Array([t]):new Float32Array(t)}_createSyntheticCommand(t,e){return{kind:Qe.Draw,drawable:t,nodeIndex:e,seq:0,zIndex:t.zIndex,material:{rendererId:0,blendMode:t.blendMode,textureId:-1,shaderId:-1,pipelineKey:0,bindKey:0},minX:0,minY:0,maxX:0,maxY:0,groupIndex:0}}}const fr=32,pr=fr/Uint32Array.BYTES_PER_ELEMENT;class mr extends er{_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(t){super(),this._batchSize=t,this._shader=new Js("#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(t*fr),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(t){const e=this.getBackend();let i=t.quads;if("geometry"===t.pixelSnapMode){const n=e._getSnapPixelSize();i=t.getRenderQuads(e.view,n.width,n.height)}if(0===i.length)return;const n=t.texture,s=t.blendMode,r=t.tint.toRgba(),o=e.activeDrawCommand,a=null!==o?o.nodeIndex:e._pushTransform(t),h=null!==this._currentTexture&&n!==this._currentTexture,l=s!==this._currentBlendMode;this._quadIndex>0&&(l||h||this._quadIndex+i.length>this._batchSize)&&this.flush(),null!==this._currentBlendMode&&this._currentBlendMode===s||(this._currentBlendMode=s,e.setBlendMode(s)),this._currentTexture!==n&&(this._currentTexture=n,e.bindTexture(n,0));let u=0;for(;u<i.length;){const t=Math.min(u+this._batchSize,i.length);this._writeQuadChunk(i,u,t,n,r,a),u=t,u<i.length&&(this.flush(),this._currentBlendMode=s,e.setBlendMode(s),this._currentTexture=n,e.bindTexture(n,0))}}_writeQuadChunk(t,e,i,n,s,r){const o=this._instanceFloat32,a=this._instanceUint32,h=n.flipY;for(let n=e;n<i;n++){const e=t[n],i=this._quadIndex*pr;o[i+0]=e.x0,o[i+1]=e.y0,o[i+2]=e.x1,o[i+3]=e.y1;const l=65535*e.u0&65535,u=65535*e.u1&65535,c=65535*e.v0&65535,d=65535*e.v1&65535,_=h?d:c,f=h?c:d;a[i+4]=l|_<<16,a[i+5]=u|f<<16,a[i+6]=s,a[i+7]=r>>>0,this._quadIndex++,r>this._maxNodeIndex&&(this._maxNodeIndex=r)}}flush(){const t=this.getBackendOrNull(),e=this._instanceBuffer,i=this._vao;if(0===this._quadIndex||null===t||null===e||null===i)return this._quadIndex=0,void(this._maxNodeIndex=0);const n=t.view;this._currentView===n&&this._currentViewId===n.updateId||(this._currentView=n,this._currentViewId=n.updateId,this._shader.getUniform("u_projection").setValue(n.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(i),e.upload(this._instanceFloat32.subarray(0,this._quadIndex*pr)),i.drawInstanced(4,0,this._quadIndex,Xe.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._quadIndex=0,this._maxNodeIndex=0}onConnect(t){const e=t.context;this._shader.connect(lr(e)),this._connection=this._createConnection(e),this._instanceBuffer=new ir(He.ArrayBuffer,this._instanceData,je.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new cr(Xe.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_quadBounds"),e.FLOAT,!1,fr,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),e.UNSIGNED_SHORT,!0,fr,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,fr,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,fr,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(t){const e=t.createVertexArray();if(null===e)throw new Error("WebGl2NineSliceSpriteRenderer: could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}_createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("WebGl2NineSliceSpriteRenderer: could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,n)=>{const s=t.gl,r=i.data,o=t.buffers.get(i);s.bindBuffer(i.type,e),o&&o.dataByteLength>=r.byteLength?(s.bufferSubData(i.type,n,r),o.dataByteLength=r.byteLength):(s.bufferData(i.type,r,i.usage),t.buffers.set(i,{handle:e,dataByteLength:r.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(t){let e=-1;return{bind:i=>{const n=t.gl;if(n.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),e.integer?n.vertexAttribIPointer(e.location,e.size,e.type,e.stride,e.start):n.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),n.enableVertexAttribArray(e.location),n.vertexAttribDivisor(e.location,e.divisor);e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,n,s)=>{t.gl.drawArrays(s,n,i)},drawInstanced:(e,i,n,s,r)=>{t.gl.drawArraysInstanced(r,n,i,s)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}const gr="#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}",yr=40,wr=yr/Uint32Array.BYTES_PER_ELEMENT,xr=32,vr=xr/Uint32Array.BYTES_PER_ELEMENT;function br(t){return"repeat"===t?$e.Repeat:"mirror-repeat"===t?$e.MirroredRepeat:$e.ClampToEdge}class Sr extends er{_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 te;_currentView=null;_currentViewId=-1;constructor(t){super(),this._batchSize=t,this._shaderPathShader=new Js("#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}",gr),this._geoPathShader=new Js("#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}",gr),this._shaderData=new ArrayBuffer(t*yr),this._shaderF32=new Float32Array(this._shaderData),this._shaderU32=new Uint32Array(this._shaderData),this._geoData=new ArrayBuffer(t*xr),this._geoF32=new Float32Array(this._geoData),this._geoU32=new Uint32Array(this._geoData)}render(t){const e=t.resolvedStrategy,i=t.texture,n=t.blendMode,s=t.modeX,r=t.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const t=this._currentPath!==e,o=this._currentTexture!==i,a=this._currentBlendMode!==n,h="shader"===e&&(this._currentModeX!==s||this._currentModeY!==r);(t||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=e;const a=o.activeDrawCommand,h=null!==a?a.nodeIndex:o._pushTransform(t);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===e?(this._currentModeX=s,this._currentModeY=r,this._writeShaderInstance(t,h)):this._writeGeoQuads(t,h)}_writeShaderInstance(t,e){const i=t.texture,n=t.region.width,s=t.region.height;let r=t.width,o=t.height;const a=i instanceof vi&&i.flipY;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),i=e._getSnapPixelSize(),n=t.getRenderBounds(e.view,i.width,i.height,this._snapBounds);r=n.width,o=n.height}const h=Cs(n,r,t.modeX,t.fitX),l=Cs(s,o,t.modeY,t.fitY),u=t.offsetX/(n>0?n:1),c=t.offsetY/(s>0?s:1),d=a?-l:l,_=a?l+c:c;this._shaderQuadCount>=this._batchSize&&this.flush();const f=this._shaderQuadCount*wr,p=this._shaderF32,m=this._shaderU32;p[f+0]=0,p[f+1]=0,p[f+2]=r,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,m[f+8]=t.tint.toRgba(),m[f+9]=e>>>0,this._shaderQuadCount++}_writeGeoQuads(t,e){let i=t.quads;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),n=e._getSnapPixelSize();i=t.getRenderQuads(e.view,n.width,n.height)}const n=t.texture instanceof vi&&t.texture.flipY,s=t.tint.toRgba();let r=0;for(;r<i.length;){const o=i.length-r,a=Math.min(o,this._batchSize-this._geoQuadCount);if(a<=0){this.flush();const i=this.getBackend();i.bindTexture(t.texture,0),i.setBlendMode(t.blendMode),this._currentTexture=t.texture,this._currentBlendMode=t.blendMode,this._currentPath="geometry",e>this._maxNodeIndex&&(this._maxNodeIndex=e);continue}const h=this._geoF32,l=this._geoU32;for(let t=0;t<a;t++){const o=i[r+t],a=(this._geoQuadCount+t)*vr;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]=s,l[a+7]=e>>>0}this._geoQuadCount+=a,r+=a}}flush(){const t=this.getBackendOrNull();if(null===t)return void this._resetBatchState();const e=t.view;if(this._currentView!==e||this._currentViewId!==e.updateId){this._currentView=e,this._currentViewId=e.updateId;const t=e.getTransform().toArray(!1);this._shaderPathShader.getUniform("u_projection").setValue(t),this._geoPathShader.getUniform("u_projection").setValue(t)}this._shaderQuadCount>0&&this._flushShaderBatch(t),this._geoQuadCount>0&&this._flushGeoBatch(t),this._resetBatchState()}_flushShaderBatch(t){const e=this._connection,i=this._shaderBuf,n=this._shaderVao;if(!e||!i||!n||0===this._shaderQuadCount)return;const s=e.gl,r=this._currentTexture,o=r instanceof vi?r.scaleMode:Ye.Linear,a=br(this._currentModeX??"repeat"),h=br(this._currentModeY??"repeat"),l=this._getOrCreateSampler(s,a,h,o);s.bindSampler(0,l),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(n),i.upload(this._shaderF32.subarray(0,this._shaderQuadCount*wr)),n.drawInstanced(4,0,this._shaderQuadCount,Xe.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,s.bindSampler(0,null),this._shaderQuadCount=0}_flushGeoBatch(t){const e=this._connection,i=this._geoBuf,n=this._geoVao;e&&i&&n&&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(n),i.upload(this._geoF32.subarray(0,this._geoQuadCount*vr)),n.drawInstanced(4,0,this._geoQuadCount,Xe.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(t,e,i,n){const s=`${e}:${i}:${n}`,r=this._samplers.get(s);if(void 0!==r)return r;const o=t.createSampler();if(null===o)throw new Error("WebGl2RepeatingSpriteRenderer: could not create sampler.");return t.samplerParameteri(o,t.TEXTURE_WRAP_S,e),t.samplerParameteri(o,t.TEXTURE_WRAP_T,i),t.samplerParameteri(o,t.TEXTURE_MAG_FILTER,n),t.samplerParameteri(o,t.TEXTURE_MIN_FILTER,n),this._samplers.set(s,o),o}onConnect(t){const e=t.context;this._shaderPathShader.connect(lr(e)),this._geoPathShader.connect(lr(e)),this._shaderPathShader.sync(),this._geoPathShader.sync();const i=this._createConnection(e);this._connection=i,this._shaderBuf=new ir(He.ArrayBuffer,this._shaderData,je.DynamicDraw).connect(this._createBufRuntime(i,"shader"),t.accountant),this._shaderVao=new cr(Xe.TriangleStrip).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_quadBounds"),e.FLOAT,!1,yr,0,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_uvParams"),e.FLOAT,!1,yr,16,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,yr,32,!1,1).addAttribute(this._shaderBuf,this._shaderPathShader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,yr,36,!0,1).connect(this._createVaoRuntime(i,"shader")),this._geoBuf=new ir(He.ArrayBuffer,this._geoData,je.DynamicDraw).connect(this._createBufRuntime(i,"geo"),t.accountant),this._geoVao=new cr(Xe.TriangleStrip).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_quadBounds"),e.FLOAT,!1,xr,0,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_uvBounds"),e.UNSIGNED_SHORT,!0,xr,16,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,xr,24,!1,1).addAttribute(this._geoBuf,this._geoPathShader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,xr,28,!0,1).connect(this._createVaoRuntime(i,"geo"))}onDisconnect(){const t=this._connection?.gl;if(void 0!==t)for(const e of this._samplers.values())t.deleteSampler(e);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(t){const e=t.createVertexArray(),i=t.createVertexArray();if(null===e||null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create vertex array object.");return{gl:t,buffers:new Map,shaderVaoHandle:e,geoVaoHandle:i}}_createBufRuntime(t,e){const i=t.gl.createBuffer();if(null===i)throw new Error("WebGl2RepeatingSpriteRenderer: could not create render buffer.");return{bind:e=>{t.gl.bindBuffer(e.type,i)},upload:(e,n)=>{const s=t.gl,r=e.data,o=t.buffers.get(e);s.bindBuffer(e.type,i),o&&o.dataByteLength>=r.byteLength?(s.bufferSubData(e.type,n,r),o.dataByteLength=r.byteLength):(s.bufferData(e.type,r,e.usage),t.buffers.set(e,{handle:i,dataByteLength:r.byteLength}))},destroy:e=>{t.gl.deleteBuffer(i),t.buffers.delete(e),e.disconnect()}}}_createVaoRuntime(t,e){const i="shader"===e?t.shaderVaoHandle:t.geoVaoHandle;let n=-1;return{bind:e=>{const s=t.gl;if(s.bindVertexArray(i),n!==e.version){let t=null;for(const i of e.attributes)t!==i.buffer&&(i.buffer.bind(),t=i.buffer),i.integer?s.vertexAttribIPointer(i.location,i.size,i.type,i.stride,i.start):s.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),s.enableVertexAttribArray(i.location),s.vertexAttribDivisor(i.location,i.divisor);n=e.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,n,s)=>{t.gl.drawArrays(s,n,i)},drawInstanced:(e,i,n,s,r)=>{t.gl.drawArraysInstanced(r,n,i,s)},destroy:e=>{t.gl.deleteVertexArray(i),e.disconnect()}}}}const Br=36,Cr=Br/Uint32Array.BYTES_PER_ELEMENT;class Tr extends er{_shader;_batchSize;_instanceData;_instanceFloat32;_instanceUint32;_activeTextures=new Array(8).fill(null);_textureSlots=new Map;_slotCount=0;_customShaders=new Map;_slotScratches=Array.from({length:8},(t,e)=>new Int32Array([e]));_transformUnitScratch=new Int32Array([8]);_currentMaterial=null;_currentBaseTexture=null;_snapBounds=new te;_activeBounds=null;_instanceCount=0;_maxNodeIndex=0;_currentBlendMode=null;_currentView=null;_currentViewId=-1;_instanceBuffer=null;_vao=null;_connection=null;constructor(t){super(),this._batchSize=t,this._shader=new Js("#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(t*Br),this._instanceFloat32=new Float32Array(this._instanceData),this._instanceUint32=new Uint32Array(this._instanceData)}render(t){const e=t.texture;if(null===e)return this;const i=this.getBackend(),n=t.material,s=i.activeDrawCommand,r=null!==s?s.nodeIndex:i._pushTransform(t);return this._activeBounds=this._resolveBounds(t,i),null===n?this._renderDefault(t,e,i,r):this._renderCustom(t,e,n,i,r),this}_resolveBounds(t,e){if("geometry"!==t.pixelSnapMode)return t.getLocalBounds();const i=e._getSnapPixelSize();return t.getRenderBounds(e.view,i.width,i.height,this._snapBounds)}flush(){const t=this.getBackendOrNull(),e=this._instanceBuffer,i=this._vao,n=this._connection;if(0===this._instanceCount||null===t||null===e||null===i||null===n)return this._maxNodeIndex=0,void this._resetSlots();const s=this._currentMaterial,r=null===s?this._shader:this._getOrCreateCustomShader(s,n.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{r.uniforms.has("u_projection")&&r.getUniform("u_projection").setValue(t.view.getTransform().toArray(!1));const e=this._currentBaseTexture;null!==e&&r.uniforms.has("u_texture")&&(t.bindTexture(e,0),r.getUniform("u_texture").setValue(this._slotScratches[0])),this._bindCustomUniforms(r,s,t)}t.bindTransformBufferTexture(8,this._maxNodeIndex+1),r.uniforms.has("u_transforms")&&r.getUniform("u_transforms").setValue(this._transformUnitScratch),r.sync(),t.bindVertexArrayObject(i),e.upload(this._instanceFloat32.subarray(0,this._instanceCount*Cr)),i.drawInstanced(4,0,this._instanceCount,Xe.TriangleStrip),t.stats.batches++,t.stats.drawCalls++,this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots()}onConnect(t){const e=t.context;this._shader.connect(lr(e)),this._connection=this._createConnection(e),this._instanceBuffer=new ir(He.ArrayBuffer,this._instanceData,je.DynamicDraw).connect(this._createBufferRuntime(this._connection),t.accountant),this._shader.sync(),this._vao=new cr(Xe.TriangleStrip).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_localBounds"),e.FLOAT,!1,Br,0,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_uvBounds"),e.UNSIGNED_SHORT,!0,Br,16,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,Br,24,!1,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_textureSlot"),e.UNSIGNED_INT,!1,Br,28,!0,1).addAttribute(this._instanceBuffer,this._shader.getAttribute("a_nodeIndex"),e.UNSIGNED_INT,!1,Br,32,!0,1).connect(this._createVaoRuntime(this._connection));const i=new Int32Array(1);for(let t=0;t<8;t++)i[0]=t,this._shader.getUniform(`u_texture${t}`).setValue(i)}onDisconnect(){this._shader.disconnect();for(const t of this._customShaders.values())t.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(t,e,i,n){const s=t.blendMode,r=this._instanceCount>=this._batchSize,o=s!==this._currentBlendMode,a=!this._textureSlots.has(e)&&this._slotCount>=8,h=null!==this._currentMaterial&&this._instanceCount>0;(r||o||a||h)&&(this.flush(),o&&(this._currentBlendMode=s,i.setBlendMode(s))),this._currentMaterial=null;let l=this._textureSlots.get(e);void 0===l&&(l=this._slotCount++,this._textureSlots.set(e,l),this._activeTextures[l]=e,i.bindTexture(e,l)),this._packInstance(t,e,l,n),this._instanceCount++}_renderCustom(t,e,i,n,s){const r=t.blendMode===qe.Normal?i.blendMode:t.blendMode,o=this._instanceCount>=this._batchSize,a=r!==this._currentBlendMode,h=i!==this._currentMaterial,l=e!==this._currentBaseTexture;this._instanceCount>0&&(o||a||h||l)&&this.flush(),a&&(this._currentBlendMode=r,n.setBlendMode(r)),this._currentMaterial=i,this._currentBaseTexture=e,this._packInstance(t,e,0,s),this._instanceCount++}_packInstance(t,e,i,n){const s=this._instanceCount*Cr,r=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??t.getLocalBounds();r[s+0]=a.left,r[s+1]=a.top,r[s+2]=a.right,r[s+3]=a.bottom;const h=t.textureFrame,l=e.width,u=e.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=e.flipY?f:_,m=e.flipY?_:f;o[s+4]=c|p<<16,o[s+5]=d|m<<16,o[s+6]=t.tint.toRgba(),o[s+7]=i;const g=n>>>0;o[s+8]=g,g>this._maxNodeIndex&&(this._maxNodeIndex=g)}_getOrCreateCustomShader(t,e){const i=this._customShaders.get(t);if(void 0!==i)return i;const n=t.shader.glsl;if(null===n)throw new Error("SpriteMaterial shader has no `glsl` source; cannot render through the WebGL2 backend.");const s=new Js("#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 s.connect(lr(e)),s.sync(),this._customShaders.set(t,s),t._onDispose(()=>{const e=this._customShaders.get(t);void 0!==e&&(e.destroy(),this._customShaders.delete(t))}),s}_bindCustomUniforms(t,e,i){let n=1;const s=e.uniforms;for(const e in s){if(!t.uniforms.has(e))continue;const r=s[e],o=t.getUniform(e);if(r instanceof vi||r instanceof wi){if(n>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(r,n),o.setValue(this._slotScratches[n]),n++}else o.setValue(this._marshalUniformValue(r))}const r=e.textures;for(const e in r)if(t.uniforms.has(e)){if(n>=8)throw new Error("SpriteMaterial requested more than 7 texture bindings.");i.bindTexture(r[e],n),t.getUniform(e).setValue(this._slotScratches[n]),n++}}_marshalUniformValue(t){return t instanceof Float32Array||t instanceof Int32Array?t:"number"==typeof t?new Float32Array([t]):new Float32Array(t)}_resetSlots(){if(this._slotCount>0){for(let t=0;t<this._slotCount;t++)this._activeTextures[t]=null;this._textureSlots.clear(),this._slotCount=0}}_createConnection(t){const e=t.createVertexArray();if(null===e)throw new Error("WebGl2SpriteRenderer: could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}_createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("WebGl2SpriteRenderer: could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,n)=>{const s=t.gl,r=i.data,o=t.buffers.get(i);s.bindBuffer(i.type,e),o&&o.dataByteLength>=r.byteLength?(s.bufferSubData(i.type,n,r),o.dataByteLength=r.byteLength):(s.bufferData(i.type,r,i.usage),t.buffers.set(i,{handle:e,dataByteLength:r.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}_createVaoRuntime(t){let e=-1;return{bind:i=>{const n=t.gl;if(n.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),e.integer?n.vertexAttribIPointer(e.location,e.size,e.type,e.stride,e.start):n.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),n.enableVertexAttribArray(e.location),n.vertexAttribDivisor(e.location,e.divisor);e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,n,s)=>{t.gl.drawArrays(s,n,i)},drawInstanced:(e,i,n,s,r)=>{t.gl.drawArraysInstanced(r,n,i,s)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}var Mr="#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 Ar=28;class Pr extends er{_consumesSharedTransform=!1;_sdfShader=new Js(Mr,"#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 Js(Mr,"#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 Js(Mr,"#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(t){if(!this._connection)throw new Error("WebGl2TextRenderer is not connected to a backend.");t instanceof Zs?this._collectText(t):this._collectBitmapText(t)}flush(){const t=this._connection;t&&0!==this._pendingQuads.length?(this._uploadNodeData(t),this._drawBatches(t),this._resetFrameState()):this._resetFrameState()}destroy(){this.disconnect(),this._sdfShader.destroy(),this._msdfShader.destroy(),this._colorShader.destroy()}onConnect(t){const e=t.context,i=new Map;this._sdfShader.connect(lr(e)),this._msdfShader.connect(lr(e)),this._colorShader.connect(lr(e)),this._sdfShader.sync(),this._msdfShader.sync(),this._colorShader.sync();const n=new ir(He.ElementArrayBuffer,this._indexData,je.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),s=new ir(He.ArrayBuffer,this._vertexData,je.DynamicDraw).connect(this._createBufferRuntime(e,i),t.accountant),r=e.createVertexArray();if(null===r)throw new Error("WebGl2TextRenderer: could not create VAO.");const o=(new cr).addIndex(n).addAttribute(s,this._sdfShader.getAttribute("a_position"),e.FLOAT,!1,Ar,0).addAttribute(s,this._sdfShader.getAttribute("a_texcoord"),e.FLOAT,!1,Ar,8).addAttribute(s,this._sdfShader.getAttribute("a_nodeIndex"),e.FLOAT,!1,Ar,16);this._sdfShader.attributes.has("a_gradUV")&&o.addAttribute(s,this._sdfShader.getAttribute("a_gradUV"),e.FLOAT,!1,Ar,20),o.connect(this._createVaoRuntime(e,r));const a=this._createNodeDataTexture(e,32);this._connection={gl:e,buffers:i,vertexBuffer:s,indexBuffer:n,vao:o,nodeDataTexture:a,nodeDataCapacity:32}}onDisconnect(){const t=this._connection;t&&(this._sdfShader.disconnect(),this._msdfShader.disconnect(),this._colorShader.disconnect(),t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),t.gl.deleteTexture(t.nodeDataTexture),this._connection=null)}_collectText(t){t.syncDirty();const{pageQuads:e,atlas:i}=t;if(0===e.length||null===i)return;const n=this._assignNodeIndex(t),s=t.colorGlyphs?"color":"sdf",r=i.pages;for(const t of e){const e=r[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:n,shaderType:s,atlasTexture:e.texture})}}_collectBitmapText(t){const{pageQuads:e,textures:i,msdf:n}=t;if(0===e.length)return;const s=this._assignNodeIndex(t),r=n?"msdf":"color";for(const t of e){const e=i[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:s,shaderType:r,atlasTexture:e})}}_assignNodeIndex(t){const e=this._nodeIndexMap.get(t);if(void 0!==e)return e;const i=this._nodeCount++;return this._nodeIndexMap.set(t,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,t),i}_packNodeData(t,e){const i=this._nodeDataArray,n=40*t,s=e.style,r=e.getGlobalTransform().toArray(!1);i[n+0]=r[0],i[n+1]=r[1],i[n+2]=r[2],i[n+3]=r[6],i[n+4]=r[3],i[n+5]=r[4],i[n+6]=r[5],i[n+7]=r[7];const o=s.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=s.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=s.outlineWidth>0?Math.max(0,.5-s.outlineWidth):.5;i[n+16]=h,i[n+17]=s.shadowAlpha,i[n+18]=Math.max(.03,.1*s.shadowBlur),i[n+19]=null!==s.gradientColors?1:0;const l=s.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]=s.shadowOffsetX,i[n+25]=s.shadowOffsetY,i[n+26]="vertical"===s.gradientAxis?1:0,i[n+27]=0;const u=s.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=e.textBounds;i[n+36]=0,i[n+37]=0,i[n+38]=c.width,i[n+39]=c.height}_uploadNodeData(t){const e=t.gl,i=this._nodeCount;if(i>t.nodeDataCapacity){let n=t.nodeDataCapacity;for(;n<i;)n*=2;e.deleteTexture(t.nodeDataTexture),t.nodeDataTexture=this._createNodeDataTexture(e,n),t.nodeDataCapacity=n}this.getBackend().setActiveTextureUnit(1),e.bindTexture(e.TEXTURE_2D,t.nodeDataTexture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,10,i,e.RGBA,e.FLOAT,this._nodeDataArray.subarray(0,40*i))}_drawBatches(t){const e=this.getBackend(),i=e.view;for(const t of this._pendingQuads)this._textureKeyMap.has(t.atlasTexture)||this._textureKeyMap.set(t.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((t,e)=>{const i=t.shaderType.localeCompare(e.shaderType);return 0!==i?i:(this._textureKeyMap.get(t.atlasTexture)??0)-(this._textureKeyMap.get(e.atlasTexture)??0)});const n=this._pendingQuads;let s=0;for(;s<n.length;){const r=n[s],o=this._textureKeyMap.get(r.atlasTexture);let a=s+1;for(;a<n.length;){const t=n[a];if(t.shaderType!==r.shaderType||this._textureKeyMap.get(t.atlasTexture)!==o)break;a++}const h=this._shaderFor(r.shaderType);let l=0,u=0;for(let t=s;t<a;t++)l+=4*n[t].quads.quadCount,u+=n[t].quads.indices.length;this._ensureVertexCapacity(l),this._ensureIndexCapacity(u);let c=0,d=0,_=0;for(let t=s;t<a;t++){const{quads:e,nodeIndex:i}=n[t],s=4*e.quadCount,{vertices:r,uvs:o,indices:a}=e,h=40*i,l=this._nodeDataArray[h+0],u=this._nodeDataArray[h+1],f=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 t=0;t<s;t++){const e=7*(c+t),n=2*t,s=r[n],a=r[n+1];this._float32View[e+0]=l*s+p*a+f,this._float32View[e+1]=u*s+m*a+g,this._float32View[e+2]=o[n],this._float32View[e+3]=o[n+1],this._float32View[e+4]=i,this._float32View[e+5]=b?Math.min(1,Math.max(0,(s-y)/x)):0,this._float32View[e+6]=b?Math.min(1,Math.max(0,(a-w)/v)):0}for(let t=0;t<a.length;t++)this._indexData[d+t]=a[t]+_;c+=s,d+=a.length,_+=s}t.vertexBuffer.upload(this._float32View.subarray(0,7*l)),t.indexBuffer.upload(this._indexData.subarray(0,u)),h.sync(),e.bindVertexArrayObject(t.vao),e.bindTexture(r.atlasTexture,0),h.uniforms.has("u_projection")&&h.getUniform("u_projection").setValue(i.getTransform().toArray(!1)),h.uniforms.has("u_texture")&&h.getUniform("u_texture").setValue(this._textureUnitScratch),h.uniforms.has("u_nodeData")&&h.getUniform("u_nodeData").setValue(this._nodeDataUnitScratch),h.uniforms.has("u_pageSize")&&(this._floatScratch[0]=r.atlasTexture.width,h.getUniform("u_pageSize").setValue(this._floatScratch)),t.vao.draw(u,0,Xe.Triangles),e.stats.batches++,e.stats.drawCalls++,s=a}}_shaderFor(t){return"sdf"===t?this._sdfShader:"msdf"===t?this._msdfShader:this._colorShader}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*Ar),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(t){if(t<=this._nodeCapacity)return;for(;this._nodeCapacity<t;)this._nodeCapacity*=2;const e=new Float32Array(40*this._nodeCapacity);e.set(this._nodeDataArray),this._nodeDataArray=e}_createNodeDataTexture(t,e){const i=t.createTexture();if(null===i)throw new Error("WebGl2TextRenderer: could not create node data texture.");return t.bindTexture(t.TEXTURE_2D,i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA32F,10,e,0,t.RGBA,t.FLOAT,null),t.bindTexture(t.TEXTURE_2D,null),i}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("WebGl2TextRenderer: could not create buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(n,s)=>{const r=e.get(n),o=n.data;t.bindBuffer(n.type,i),r&&r.dataByteLength>=o.byteLength?(t.bufferSubData(n.type,s,o),r.dataByteLength=o.byteLength):(t.bufferData(n.type,o,n.usage),e.set(n,{handle:i,dataByteLength:o.byteLength}))},destroy:n=>{t.deleteBuffer(i),e.delete(n),n.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:n=>{if(t.bindVertexArray(e),i!==n.version){let e=null;for(const i of n.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,s)=>{e.indexBuffer?t.drawElements(s,i,t.UNSIGNED_SHORT,n):t.drawArrays(s,n,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}class Er{backendType=tr.WebGpu;_backend=null;connect(t){if(null===this._backend){if(t.backendType!==tr.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 kr(t){switch(t){case qe.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case qe.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case qe.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case qe.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 Rr="depth24plus-stencil8",Dr=new Set(["a_position","position"]);class Ir{_matrix=new Le;_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(t){null===this._device&&(this._device=t,this._shaderModule=t.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=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._pipelineLayout=t.createPipelineLayout({bindGroupLayouts:[this._bindGroupLayout]}),this._uniformBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._bindGroup=t.createBindGroup({layout:this._bindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}))}disconnect(){if(null!==this._device){this._uniformBuffer?.destroy(),this._vertexBuffer?.destroy();for(const t of this._stencilTextures.values())t.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(t,e,i){const n=this._device;if(null===n)throw new Error("WebGpuStencilClipper: not connected.");const s=Math.max(1,e),r=Math.max(1,i),o=this._stencilTextures.get(t);if(o?.width===s&&o.height===r)return o.view;o?.texture.destroy();const a=n.createTexture({size:{width:s,height:r},format:Rr,usage:GPUTextureUsage.RENDER_ATTACHMENT}),h={texture:a,view:a.createView(),width:s,height:r};return this._stencilTextures.set(t,h),h.view}releaseAttachment(t){const e=this._stencilTextures.get(t);void 0!==e&&(e.texture.destroy(),this._stencilTextures.delete(t))}draw(t,e,i,n,s,r){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(s).combine(r.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),t.setPipeline(this._getPipeline(e,i,n.topology)),t.setBindGroup(0,this._bindGroup),t.setVertexBuffer(0,this._vertexBuffer),t.draw(a))}_getPipeline(t,e,i){const n=e?this._incrementPipelines:this._decrementPipelines,s=n.get(t);if(void 0!==s)return s;const r={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:e?"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:t,writeMask:0}]},primitive:{topology:"triangle-strip"===i?"triangle-strip":"triangle-list"},depthStencil:{format:Rr,depthWriteEnabled:!1,depthCompare:"always",stencilFront:r,stencilBack:r,stencilReadMask:255,stencilWriteMask:255}});return n.set(t,o),o}_packMatrix(t){const e=this._matrixData;e[0]=t.a,e[1]=t.c,e[2]=0,e[3]=0,e[4]=t.b,e[5]=t.d,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=t.x,e[13]=t.y,e[14]=0,e[15]=t.z}_extractPositions(t){const e=this._resolvePositionAttribute(t.attributes);if("f32"!==e.type)throw new Error(`Stencil clipShape position attribute "${e.name}" must be of type f32 (got "${e.type}").`);const{stride:i,vertexData:n,indices:s}=t,r=n instanceof Float32Array?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),o=null!==s?s.length:t.vertexCount;this._ensurePositionCapacity(o);const a=this._positions;for(let t=0;t<o;t++){const n=(null!==s?s[t]:t)*i+e.offset;a[2*t]=r.getFloat32(n,!0),a[2*t+1]=r.getFloat32(n+4,!0)}return o}_resolvePositionAttribute(t){const e=t.find(t=>Dr.has(t.name));if(e)return e;const i=t.find(t=>t.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensurePositionCapacity(t){const e=2*t;this._positions.length<e&&(this._positions=new Float32Array(Math.max(e,2*this._positions.length)))}_ensureVertexCapacity(t){const e=2*t*Float32Array.BYTES_PER_ELEMENT;e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,2*this._vertexBufferCapacity||512),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}}const Lr={compare:"equal",failOp:"keep",depthFailOp:"keep",passOp:"keep"};function Ur(){return{format:Rr,depthWriteEnabled:!1,depthCompare:"always",stencilFront:Lr,stencilBack:Lr,stencilReadMask:255,stencilWriteMask:0}}const Fr=20;function Gr(t,e,i){return`${t}:${e}:${i?"s":"n"}`}const Nr=256;class Or extends Er{_combinedTransform=new Le;_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 e=this._backend;if(null===e)throw new Error("WebGpuMeshRenderer is not connected to a backend.");const i=t.material;if(null!==i&&null===i.shader.wgsl)throw new Error("Mesh material shader has no `wgsl` source; cannot render through the WebGPU backend.");const n=t.vertexCount;if(0===n)return;const s=null!==i&&t.blendMode===qe.Normal?i.blendMode:t.blendMode;e.setBlendMode(s);const r=t.texture??vi.white,o=e.activeDrawCommand,a=e.shouldPremultiplyTextureSample(r),h=t.indexCount;let l=-1;if(null!==i){const t=this._getOrCreateCustomShaderResources(i);l=t.drawCount,t.drawCount++,t.totalVertices+=n,t.totalIndices+=h}const u={mesh:t,customShader:i,command:o,blendMode:s,texture:r,premultiplySample:a,vertexByteOffset:0,vertexCount:n,indexByteOffset:0,indexCount:h,customDrawIndex:l};this._drawCalls[this._drawCallCount++]=u}drawInstancedBatch(t,e,i){const n=this._backend,s=this._device;if(null===n||null===s||i<=0||0===t.vertexCount)return;if(null!==t.material)throw new Error("RenderBatch custom materials are not supported on the WebGPU backend yet (v1 renders with the default mesh material).");const r=t.geometry;if("static"!==r?.usage)throw new Error('drawInstancedBatch requires a mesh with usage="static" geometry.');const o=t.texture??vi.white,a=n.shouldPremultiplyTextureSample(o);this._ensureInstancedUniformCapacity(1);const h=this._uploadInstancedNodeIndexRange(e,i),l=n.getTransformStorageBuffer(h+1);this._writeInstancedUniformSlot(0,n,a);const u=this._getOrCreateStaticGeometryEntry(t),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:t.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 t=this._backend,e=this._device;if(!t||!e)return;if(0===this._drawCallCount&&!t.clearRequested)return;const i=t.getScissorRect(),n=null!==i&&(i.width<=0||i.height<=0);if(0===this._drawCallCount||n)return t.clearRequested&&(t._passCoordinator.acquirePass(),t._passCoordinator.endPass()),void this._resetFrame();let s=0,r=0;const o=new Map,a=new Map;for(let t=0;t<this._drawCallCount;t++){const e=this._drawCalls[t];if(null===e.customShader)e.vertexByteOffset=s*Fr,e.indexByteOffset=r*Uint16Array.BYTES_PER_ELEMENT,s+=e.vertexCount,r+=e.indexCount;else{const t=o.get(e.customShader)??0,i=a.get(e.customShader)??0;e.vertexByteOffset=t*Fr,e.indexByteOffset=i*Uint16Array.BYTES_PER_ELEMENT,o.set(e.customShader,t+e.vertexCount),a.set(e.customShader,i+e.indexCount)}}this._ensureVertexCapacity(s),this._ensureIndexCapacity(r);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 e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e];if(null===i.customShader){if(this._writeMeshVertices(t,i.mesh,i.vertexByteOffset/Fr,!0),null!==i.mesh.indices)this._packedIndexData.set(i.mesh.indices,i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT);else{const t=i.indexByteOffset/Uint16Array.BYTES_PER_ELEMENT;for(let e=0;e<i.indexCount;e++)this._packedIndexData[t+e]=e}if(null!==c){const t=d*this._uniformAlignment/Float32Array.BYTES_PER_ELEMENT,e=i.mesh.tint;c[t+0]=e.r/255,c[t+1]=e.g/255,c[t+2]=e.b/255,c[t+3]=e.a,c[t+4]=i.premultiplySample?1:0,c[t+5]=0,c[t+6]=0,c[t+7]=0}d++}}for(const[i,n]of this._customShaders){if(0===n.drawCount)continue;this._ensureCustomCapacities(n);let s=0,r=0,o=0;for(let e=0;e<this._drawCallCount;e++){const a=this._drawCalls[e];if(a.customShader===i){if(this._writeMeshVerticesIntoBuffer(a.mesh,s,n.vertexFloatView,n.vertexUintView),null!==a.mesh.indices)n.indexData.set(a.mesh.indices,r);else for(let t=0;t<a.indexCount;t++)n.indexData[r+t]=t;this._writeCustomMeshUniform(i,n,o,a.mesh,t),s+=a.vertexCount,r+=a.indexCount,o++}}e.queue.writeBuffer(n.vertexBuffer,0,n.vertexData,0,n.totalVertices*Fr),e.queue.writeBuffer(n.indexBuffer,0,n.indexData.buffer,n.indexData.byteOffset,n.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4),this._uploadUserUniforms(i,n)}s>0&&(e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,s*Fr),e.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,r*Uint16Array.BYTES_PER_ELEMENT+3&-4)),null!==u&&e.queue.writeBuffer(this._uniformBuffer,0,u,0,l);const _=t._passCoordinator.acquirePass().pass,f=t.renderTargetFormat,p=t._passCoordinator.stencilActive;let m=null,g=null,y=null,w=null,x=0,v=0;const b=new Map;for(let e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e];if(null===i.customShader){const n=this._getStaticBatchLength(e);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 s=this._uploadInstancedNodeIndices(e,n),r=t.getTransformStorageBuffer(s+1);this._writeInstancedUniformSlot(v,t,i.premultiplySample),_.setBindGroup(0,this._getOrCreateInstancedTransformBindGroup(r.buffer),[v*this._uniformAlignment]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getTextureBindGroup(t,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),t.stats.batches++,t.stats.drawCalls++,x+=n,v++,e+=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(t,i.texture))),_.setVertexBuffer(0,this._vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(this._indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),x++}else{const e=this._customShaders.get(i.customShader),n=m!==i.customShader||i.blendMode!==g||f!==y;_.pushDebugGroup("MeshMaterial (custom)"),n&&(_.setPipeline(this._getOrCreateCustomPipeline(e,i.blendMode,f,p)),m=i.customShader,g=i.blendMode,y=f,w=null,_.setBindGroup(2,this._buildUserBindGroup(t,i.customShader,e)));const s=b.get(i.customShader)??0;_.setBindGroup(0,e.meshUniformBindGroup,[s*Nr]),i.texture!==w&&(w=i.texture,_.setBindGroup(1,this._getOrCreateMeshTextureBindGroup(e,t,i.texture))),_.setVertexBuffer(0,e.vertexBuffer,i.vertexByteOffset),_.setIndexBuffer(e.indexBuffer,"uint16",i.indexByteOffset),_.drawIndexed(i.indexCount),_.popDebugGroup(),b.set(i.customShader,s+1)}t.stats.batches++,t.stats.drawCalls++}t._passCoordinator.endPass(),this._resetFrame()}destroy(){this.disconnect(),this._combinedTransform.destroy()}async prewarmPipelines(t){const e=this._device;if(!e||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof e.createRenderPipelineAsync)return;const i=[qe.Normal,qe.Additive,qe.Subtract,qe.Multiply,qe.Screen,qe.Darken,qe.Lighten],n=[];for(const s of i)for(const i of t){const t=Gr(s,i,!1);this._pipelines.has(t)||(n.push(e.createRenderPipelineAsync(this._buildPipelineDescriptor(s,i)).then(e=>{this._pipelines.set(t,e)})),this._instancedPipelines.has(t)||n.push(e.createRenderPipelineAsync(this._buildInstancedPipelineDescriptor(s,i)).then(e=>{this._instancedPipelines.set(t,e)})))}await Promise.all(n)}onConnect(t){this._device||(this._device=t.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 t of this._staticGeometryCache.values())t.vertexBuffer.destroy(),t.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 t of this._customShaders.values())this._releaseCustomShaderResources(t);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(t,e,i,n){const s=e.vertices,r=e.uvs,o=e.colors,a=e.vertexCount;if(n){const n=this._combinedTransform.copy(e.getGlobalTransform()).combine(t.view.getTransform()),h=n.a,l=n.b,u=n.c,c=n.d,d=n.x,_=n.y;for(let t=0;t<a;t++){const e=2*t,n=5*(i+t),a=s[e],f=s[e+1];this._float32View[n+0]=h*a+l*f+d,this._float32View[n+1]=u*a+c*f+_,this._float32View[n+2]=null!==r?r[e]:0,this._float32View[n+3]=null!==r?r[e+1]:0,this._uint32View[n+4]=null!==o?o[t]:4294967295}}else for(let t=0;t<a;t++){const e=2*t,n=5*(i+t);this._float32View[n+0]=s[e],this._float32View[n+1]=s[e+1],this._float32View[n+2]=null!==r?r[e]:0,this._float32View[n+3]=null!==r?r[e+1]:0,this._uint32View[n+4]=null!==o?o[t]:4294967295}}_getPipeline(t){const e=Gr(t.blendMode,t.format,t.stencil);let i=this._pipelines.get(e);return i||(i=this._device.createRenderPipeline(this._buildPipelineDescriptor(t.blendMode,t.format,t.stencil)),this._pipelines.set(e,i)),i}_buildPipelineDescriptor(t,e,i=!1){const n={layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Fr,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:e,blend:kr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(n.depthStencil=Ur()),n}_getTextureBindGroup(t,e){const i=t.getTextureBinding(e),n=this._textureBindGroups.get(e);if(n?.view===i.view)return n.group;const s=this._device.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:i.view},{binding:1,resource:i.sampler}]});return this._textureBindGroups.set(e,{group:s,view:i.view}),s}_getStaticBatchLength(t){const e=this._drawCalls[t];if(!this._isStaticBatchCandidate(e))return 1;let i=1;for(let n=t+1;n<this._drawCallCount;n++){const t=this._drawCalls[n];if(!this._isSameStaticBatch(e,t))break;i++}return i}_isStaticBatchCandidate(t){const e=t.command;return null===t.customShader&&void 0!==e?.groupIndex&&"static"===t.mesh.geometry?.usage}_isSameStaticBatch(t,e){return!(!this._isStaticBatchCandidate(t)||!this._isStaticBatchCandidate(e))&&(t.command.groupIndex===e.command.groupIndex&&t.mesh.geometry===e.mesh.geometry&&t.texture===e.texture&&t.blendMode===e.blendMode&&t.command.material.pipelineKey===e.command.material.pipelineKey&&t.command.material.bindKey===e.command.material.bindKey)}_uploadInstancedNodeIndices(t,e){this._ensureInstancedNodeIndexCapacity(e);let i=0;for(let n=0;n<e;n++){const e=this._drawCalls[t+n].command.nodeIndex>>>0;this._instancedNodeIndexData[n]=e,e>i&&(i=e)}return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,e*Uint32Array.BYTES_PER_ELEMENT),i}_uploadInstancedNodeIndexRange(t,e){this._ensureInstancedNodeIndexCapacity(e);for(let i=0;i<e;i++)this._instancedNodeIndexData[i]=t+i>>>0;return this._device.queue.writeBuffer(this._instancedNodeIndexBuffer,0,this._instancedNodeIndexData.buffer,this._instancedNodeIndexData.byteOffset,e*Uint32Array.BYTES_PER_ELEMENT),t+e-1>>>0}_ensureInstancedNodeIndexCapacity(t){const e=t*Uint32Array.BYTES_PER_ELEMENT;this._instancedNodeIndexData.length<t&&(this._instancedNodeIndexData=new Uint32Array(Math.max(t,2*this._instancedNodeIndexData.length||1))),e>this._instancedNodeIndexBufferCapacity&&(this._instancedNodeIndexBuffer?.destroy(),this._instancedNodeIndexBufferCapacity=Math.max(e,2*this._instancedNodeIndexBufferCapacity||Uint32Array.BYTES_PER_ELEMENT),this._instancedNodeIndexBuffer=this._device.createBuffer({size:this._instancedNodeIndexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureInstancedUniformCapacity(t){if(0===t)return;const e=t*this._uniformAlignment;e>this._instancedUniformBufferCapacity&&(this._instancedUniformBuffer?.destroy(),this._instancedUniformBufferCapacity=Math.max(e,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(t,e,i){const n=this._instancedUniformScratch,s=e.view.getTransform();n.fill(0),n[0]=s.a,n[1]=s.b,n[4]=s.c,n[5]=s.d,n[8]=s.x,n[9]=s.y,n[10]=1,n[12]=i?1:0,this._device.queue.writeBuffer(this._instancedUniformBuffer,t*this._uniformAlignment,n.buffer,n.byteOffset,64)}_getOrCreateInstancedTransformBindGroup(t){return null!==this._instancedTransformBindGroup&&this._instancedTransformStorageBuffer===t||(this._instancedTransformStorageBuffer=t,this._instancedTransformBindGroup=this._device.createBindGroup({layout:this._instancedTransformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._instancedUniformBuffer,size:64}},{binding:1,resource:{buffer:t}}]})),this._instancedTransformBindGroup}_getInstancedPipeline(t){const e=Gr(t.blendMode,t.format,t.stencil);let i=this._instancedPipelines.get(e);return i||(i=this._device.createRenderPipeline(this._buildInstancedPipelineDescriptor(t.blendMode,t.format,t.stencil)),this._instancedPipelines.set(e,i)),i}_buildInstancedPipelineDescriptor(t,e,i=!1){const n={layout:this._instancedPipelineLayout,vertex:{module:this._instancedShaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Fr,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:e,blend:kr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};return i&&(n.depthStencil=Ur()),n}_getOrCreateStaticGeometryEntry(t){const e=t.geometry;if("static"!==e?.usage)throw new Error('Static mesh batching requires Geometry with usage="static".');const i=this._staticGeometryCache.get(e);if(void 0!==i)return i;const n=new ArrayBuffer(t.vertexCount*Fr),s=new Float32Array(n),r=new Uint32Array(n);this._writeMeshVerticesIntoBuffer(t,0,s,r);const o=new Uint16Array(t.indexCount+(1&t.indexCount));if(null!==t.indices)o.set(t.indices,0);else for(let e=0;e<t.indexCount;e++)o[e]=e;const a=t.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 t=this._staticGeometryCache.get(e);void 0!==t&&(t.vertexBuffer.destroy(),t.indexBuffer.destroy(),this._staticGeometryCache.delete(e))};e._onDispose(u);const c={geometry:e,vertexBuffer:h,indexBuffer:l,indexCount:t.indexCount,disposeListener:u};return this._staticGeometryCache.set(e,c),c}_ensureVertexCapacity(t){const e=t*Fr;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?Fr:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(t),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,0===this._vertexBufferCapacity?Fr:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(t){const e=t*Uint16Array.BYTES_PER_ELEMENT+3&-4;this._packedIndexData.length*Uint16Array.BYTES_PER_ELEMENT<e&&(this._packedIndexData=new Uint16Array(Math.max(e/Uint16Array.BYTES_PER_ELEMENT,0===this._packedIndexData.length?2:2*this._packedIndexData.length))),e>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(e,0===this._indexBufferCapacity?4:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_ensureUniformCapacity(t){if(0===t)return;const e=t*this._uniformAlignment;e>this._uniformBufferCapacity&&(this._uniformBuffer?.destroy(),this._uniformBufferCapacity=Math.max(e,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 t=0;for(const e of this._customShaders.values())t+=e.drawCount;return t}_resetFrame(){this._drawCallCount=0;for(const t of this._customShaders.values())t.drawCount=0,t.totalVertices=0,t.totalIndices=0}_getOrCreateCustomShaderResources(t){let e=this._customShaders.get(t);if(void 0!==e)return e;if(null===this._device)throw new Error("WebGpuMeshRenderer is not connected to a backend.");if(null===t.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:t.shader.wgsl}),s=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform",hasDynamicOffset:!0}}]}),r=i.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),o=this._buildUserBindGroupLayout(i,t),a=i.createPipelineLayout({bindGroupLayouts:[s,r,o]}),h=i.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),l=new ArrayBuffer(1280);return e={shaderModule:n,meshUniformLayout:s,meshTextureLayout:r,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(t,e),t._onDispose(()=>{const e=this._customShaders.get(t);void 0!==e&&(this._releaseCustomShaderResources(e),this._customShaders.delete(t))}),e}_ensureCustomCapacities(t){const e=this._device,i=t.totalVertices*Fr;if(i>t.vertexData.byteLength){const e=Math.max(i,2*t.vertexData.byteLength);t.vertexData=new ArrayBuffer(e),t.vertexFloatView=new Float32Array(t.vertexData),t.vertexUintView=new Uint32Array(t.vertexData)}i>t.vertexBufferCapacity&&(t.vertexBuffer?.destroy(),t.vertexBufferCapacity=Math.max(i,2*t.vertexBufferCapacity||Fr),t.vertexBuffer=e.createBuffer({size:t.vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}));const n=t.totalIndices*Uint16Array.BYTES_PER_ELEMENT+3&-4;t.indexData.length*Uint16Array.BYTES_PER_ELEMENT<n&&(t.indexData=new Uint16Array(Math.max(n/Uint16Array.BYTES_PER_ELEMENT,2*t.indexData.length))),n>t.indexBufferCapacity&&(t.indexBuffer?.destroy(),t.indexBufferCapacity=Math.max(n,2*t.indexBufferCapacity||4),t.indexBuffer=e.createBuffer({size:t.indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}));const s=t.drawCount*Nr;s>t.meshUniformBufferCapacity&&(t.meshUniformBuffer?.destroy(),t.meshUniformBufferCapacity=Math.max(s,2*t.meshUniformBufferCapacity||Nr),t.meshUniformBuffer=e.createBuffer({size:t.meshUniformBufferCapacity,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.meshUniformBindGroup=e.createBindGroup({layout:t.meshUniformLayout,entries:[{binding:0,resource:{buffer:t.meshUniformBuffer,size:112}}]}))}_writeMeshVerticesIntoBuffer(t,e,i,n){const s=t.vertices,r=t.uvs,o=t.colors,a=t.vertexCount;for(let t=0;t<a;t++){const a=2*t,h=5*(e+t);i[h+0]=s[a],i[h+1]=s[a+1],i[h+2]=null!==r?r[a]:0,i[h+3]=null!==r?r[a+1]:0,n[h+4]=null!==o?o[t]:4294967295}}_writeCustomMeshUniform(t,e,i,n,s){const r=256/Float32Array.BYTES_PER_ELEMENT,o=new Float32Array(r),a=s.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(e.meshUniformBuffer,256*i,o)}_getOrCreateCustomPipeline(t,e,i,n){const s=`${e}:${i}:${n?"s":"n"}`;let r=t.pipelines.get(s);if(void 0===r){const o={layout:t.pipelineLayout,vertex:{module:t.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:Fr,stepMode:"vertex",attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"}]}]},fragment:{module:t.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:kr(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list",cullMode:"none"}};n&&(o.depthStencil=Ur()),r=this._device.createRenderPipeline(o),t.pipelines.set(s,r)}return r}_getOrCreateMeshTextureBindGroup(t,e,i){const n=e.getTextureBinding(i),s=t.meshTextureBindGroups.get(i);if(s?.view===n.view)return s.group;const r=this._device.createBindGroup({layout:t.meshTextureLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]});return t.meshTextureBindGroups.set(i,{group:r,view:n.view}),r}_buildUserBindGroupLayout(t,e){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const n=zr(e);if(n.length>7)throw new Error("Mesh material requested more than 7 user texture bindings.");let s=1;for(let t=0;t<n.length;t++)i.push({binding:s,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),s++,i.push({binding:s,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),s++;return t.createBindGroupLayout({entries:i})}_uploadUserUniforms(t,e){const i=this._device,n=function(t){const e=[];for(const i of Object.values(t.uniforms))Vr(i)||e.push(i);return e}(t),s=16*Math.max(n.length,1);(null===e.userUniformBuffer||e.userUniformBufferCapacity<s)&&(e.userUniformBuffer?.destroy(),e.userUniformBufferCapacity=s,e.userUniformBuffer=i.createBuffer({size:s,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const r=new Float32Array(s/4);let o=0;for(const t of n){const e=4*o;if("number"==typeof t)r[e]=t;else if(t instanceof Float32Array)r.set(t,e);else if(t instanceof Int32Array)for(let i=0;i<t.length;i++)r[e+i]=t[i];else{const i=t;for(let t=0;t<i.length;t++)r[e+t]=i[t]}o++}i.queue.writeBuffer(e.userUniformBuffer,0,r)}_buildUserBindGroup(t,e,i){const n=this._device,s=[];s.push({binding:0,resource:{buffer:i.userUniformBuffer}});let r=1;for(const i of zr(e)){const e=t.getTextureBinding(i);s.push({binding:r,resource:e.view}),r++,s.push({binding:r,resource:e.sampler}),r++}return n.createBindGroup({layout:i.userLayout,entries:s})}_releaseCustomShaderResources(t){t.vertexBuffer?.destroy(),t.indexBuffer?.destroy(),t.meshUniformBuffer?.destroy(),t.userUniformBuffer?.destroy(),t.pipelines.clear(),t.meshTextureBindGroups=new WeakMap,t.vertexBuffer=null,t.indexBuffer=null,t.meshUniformBuffer=null,t.userUniformBuffer=null,t.meshUniformBindGroup=null,t.vertexBufferCapacity=0,t.indexBufferCapacity=0,t.meshUniformBufferCapacity=0,t.userUniformBufferCapacity=0}}function Vr(t){return!("object"!=typeof t||null===t||!("width"in t)||!("height"in t)||t instanceof Float32Array||t instanceof Int32Array||Array.isArray(t))}function zr(t){const e=[];for(const i of Object.values(t.uniforms))Vr(i)&&e.push(i);for(const i of Object.values(t.textures))e.push(i);return e}const qr=32/Uint32Array.BYTES_PER_ELEMENT,Wr=new Uint16Array([0,1,2,0,2,3]);class Yr extends Er{_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(t){this._device||(this._device=t.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:Wr.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Wr.buffer,Wr.byteOffset,Wr.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(t){const e=this._backend;if(null===e)return;let i=t.quads;if("geometry"===t.pixelSnapMode){const n=e._getSnapPixelSize();i=t.getRenderQuads(e.view,n.width,n.height)}if(0===i.length)return;const n=t.texture;if(0===n.width||0===n.height)return;if(n instanceof vi&&null===n.source)return;const s=t.blendMode,r=e.activeDrawCommand,o=null!==r?r.nodeIndex:e._pushTransform(t),a=null!==this._currentBlendMode&&s!==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=s,this._currentTexture=n,e.setBlendMode(s),this._ensureInstanceCapacity(this._quadIndex+i.length);const u=this._instanceFloat32,c=this._instanceUint32,d=n instanceof vi&&n.flipY;for(const e of i){const i=this._quadIndex*qr;u[i+0]=e.x0,u[i+1]=e.y0,u[i+2]=e.x1,u[i+3]=e.y1;const n=65535*e.u0&65535,s=65535*e.u1&65535,r=65535*e.v0&65535,a=65535*e.v1&65535,h=d?a:r,l=d?r:a;c[i+4]=n|h<<16,c[i+5]=s|l<<16,c[i+6]=t.tint.toRgba(),c[i+7]=o>>>0,this._quadIndex++,o>this._maxNodeIndex&&(this._maxNodeIndex=o)}}flush(){const t=this._backend,e=this._device,i=this._uniformBuffer;if(!t||!e||!i)return;if(0===this._quadIndex&&!t.clearRequested)return;const n=t.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]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const s=t.getScissorRect(),r=null!==s&&(s.width<=0||s.height<=0),o=t._passCoordinator.acquirePass().pass;if(this._quadIndex>0&&!r&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode&&null!==this._currentTexture){e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,32*this._quadIndex);const n=t.getTransformStorageBuffer(this._maxNodeIndex+1),s=this._getOrCreateTransformBindGroup(e,i,n.buffer),r=this._createTextureBindGroup(e,t,this._currentTexture),a=t._passCoordinator.stencilActive,h=this._getPipeline(this._currentBlendMode,t.renderTargetFormat,a);o.setPipeline(h),o.setBindGroup(0,s),o.setBindGroup(1,r),o.setVertexBuffer(0,this._instanceBuffer),o.setIndexBuffer(this._indexBuffer,"uint16"),o.drawIndexed(6,this._quadIndex,0,0,0),t.stats.batches++,t.stats.drawCalls++}t._passCoordinator.endPass(),this._quadIndex=0,this._maxNodeIndex=0,this._currentBlendMode=null,this._currentTexture=null}destroy(){this.disconnect()}_getOrCreateTransformBindGroup(t,e,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=t.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_createTextureBindGroup(t,e,i){const n=e.getTextureBinding(i);return t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:n.view},{binding:1,resource:n.sampler}]})}_getPipeline(t,e,i){const n=`${t}:${e}:${i?"s":"n"}`,s=this._pipelines.get(n);if(s)return s;if(!this._device||!this._shaderModule||!this._pipelineLayout)throw new Error("WebGpuNineSliceSpriteRenderer: renderer must be connected first.");const r={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:e,blend:kr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};i&&(r.depthStencil=Ur());const o=this._device.createRenderPipeline(r);return this._pipelines.set(n,o),o}_ensureInstanceCapacity(t){if(!this._device||t<=this._instanceCapacity)return;let e=Math.max(this._instanceCapacity,32);for(;e<t;)e*=2;const i=this._instanceData,n=Math.min(32*this._quadIndex,i.byteLength),s=new ArrayBuffer(32*e);n>0&&new Uint8Array(s).set(new Uint8Array(i,0,n));const r=this._device.createBuffer({size:s.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=e,this._instanceData=s,this._instanceFloat32=new Float32Array(s),this._instanceUint32=new Uint32Array(s),this._instanceBuffer=r}}const $r=new Uint16Array([0,1,2,0,2,3]);function Xr(t){return"repeat"===t?"repeat":"mirror-repeat"===t?"mirror-repeat":"clamp-to-edge"}class Hr extends Er{_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 te;onConnect(t){if(this._device)return;const e=t.device;this._device=e,this._shaderModule=e.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=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}},{binding:1,visibility:GPUShaderStage.VERTEX,buffer:{type:"read-only-storage"}}]}),this._textureBindGroupLayout=e.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._uniformBuffer=e.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._indexBuffer=e.createBuffer({size:$r.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this._indexBuffer,0,$r.buffer,$r.byteOffset,$r.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(t){const e=this._backend;if(!e)return;const i=t.texture;if(i instanceof vi&&null===i.source)return;if(0===i.width||0===i.height)return;const n=t.resolvedStrategy,s=t.blendMode,r=t.modeX,o=t.modeY;if(this._shaderQuadCount>0||this._geoQuadCount>0){const t=this._currentPath!==n,e=this._currentTexture!==i,a=this._currentBlendMode!==s,h="shader"===n&&(this._currentModeX!==r||this._currentModeY!==o);(t||e||a||h)&&this.flush()}this._currentTexture=i,this._currentBlendMode=s,this._currentPath=n,e.setBlendMode(s);const a=e.activeDrawCommand,h=null!==a?a.nodeIndex:e._pushTransform(t);h>this._maxNodeIndex&&(this._maxNodeIndex=h),"shader"===n?(this._currentModeX=r,this._currentModeY=o,this._writeShaderInstance(t,h)):this._writeGeoQuads(t,h)}_writeShaderInstance(t,e){const i=t.texture,n=t.region.width,s=t.region.height;let r=t.width,o=t.height;const a=i instanceof vi&&i.flipY;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),i=e._getSnapPixelSize(),n=t.getRenderBounds(e.view,i.width,i.height,this._snapBounds);r=n.width,o=n.height}const h=Cs(n,r,t.modeX,t.fitX),l=Cs(s,o,t.modeY,t.fitY),u=t.offsetX/(n>0?n:1),c=t.offsetY/(s>0?s: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]=r,p[f+3]=o,p[f+4]=h,p[f+5]=d,p[f+6]=u,p[f+7]=_,m[f+8]=t.tint.toRgba(),m[f+9]=e>>>0,this._shaderQuadCount++}_writeGeoQuads(t,e){let i=t.quads;if("geometry"===t.pixelSnapMode){const e=this.getBackend(),n=e._getSnapPixelSize();i=t.getRenderQuads(e.view,n.width,n.height)}if(0===i.length)return;const n=t.texture instanceof vi&&t.texture.flipY,s=t.tint.toRgba();this._ensureGeoCapacity(this._geoQuadCount+i.length);const r=this._geoInstF32,o=this._geoInstU32;for(let t=0;t<i.length;t++){const a=i[t],h=8*(this._geoQuadCount+t);r[h+0]=a.x0,r[h+1]=a.y0,r[h+2]=a.x1,r[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]=s,o[h+7]=e>>>0}this._geoQuadCount+=i.length}flush(){const t=this._backend,e=this._device,i=this._uniformBuffer;if(!t||!e||!i)return;if(0===this._shaderQuadCount&&0===this._geoQuadCount&&!t.clearRequested)return;const n=t.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]),e.queue.writeBuffer(i,0,this._projData.buffer,this._projData.byteOffset,this._projData.byteLength);const s=t.getScissorRect(),r=null!==s&&(s.width<=0||s.height<=0),o=t._passCoordinator.acquirePass().pass,a=t._passCoordinator.stencilActive;this._shaderQuadCount>0&&!r&&this._drawShaderBatch(e,t,o,a),this._geoQuadCount>0&&!r&&this._drawGeoBatch(e,t,o,a),t._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(t,e,i,n){if(!this._shaderInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;t.queue.writeBuffer(this._shaderInstBuf,0,this._shaderInstData,0,40*this._shaderQuadCount);const s=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,this._uniformBuffer,s.buffer),o=this._currentModeX??"repeat",a=this._currentModeY??"repeat",h=this._getOrCreateSampler(t,o,a),l=e.getTextureBinding(this._currentTexture).view,u=t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:l},{binding:1,resource:h}]}),c=this._getPipeline("shader",this._currentBlendMode,e.renderTargetFormat,n);i.setPipeline(c),i.setBindGroup(0,r),i.setBindGroup(1,u),i.setVertexBuffer(0,this._shaderInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._shaderQuadCount,0,0,0),e.stats.batches++,e.stats.drawCalls++}_drawGeoBatch(t,e,i,n){if(!this._geoInstBuf||!this._indexBuffer||null===this._currentBlendMode||null===this._currentTexture)return;t.queue.writeBuffer(this._geoInstBuf,0,this._geoInstData,0,32*this._geoQuadCount);const s=e.getTransformStorageBuffer(this._maxNodeIndex+1),r=this._getOrCreateTransformBindGroup(t,this._uniformBuffer,s.buffer),o=e.getTextureBinding(this._currentTexture),a=t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:o.view},{binding:1,resource:o.sampler}]}),h=this._getPipeline("geo",this._currentBlendMode,e.renderTargetFormat,n);i.setPipeline(h),i.setBindGroup(0,r),i.setBindGroup(1,a),i.setVertexBuffer(0,this._geoInstBuf),i.setIndexBuffer(this._indexBuffer,"uint16"),i.drawIndexed(6,this._geoQuadCount,0,0,0),e.stats.batches++,e.stats.drawCalls++}destroy(){this.disconnect()}_getOrCreateSampler(t,e,i){const n=`${e}:${i}`,s=this._samplers.get(n);if(s)return s;const r=t.createSampler({addressModeU:Xr(e),addressModeV:Xr(i),magFilter:"linear",minFilter:"linear"});return this._samplers.set(n,r),r}_getOrCreateTransformBindGroup(t,e,i){return null!==this._transformBindGroup&&this._transformStorageBuf===i||(this._transformStorageBuf=i,this._transformBindGroup=t.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}_getPipeline(t,e,i,n){const s=`${t}:${e}:${i}:${n?"s":"n"}`,r=this._pipelines.get(s);if(r)return r;if(!(this._device&&this._shaderModule&&this._uniformBindGroupLayout&&this._textureBindGroupLayout))throw new Error("WebGpuRepeatingSpriteRenderer: not connected.");const o="shader"===t,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:kr(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};n&&(l.depthStencil=Ur());const u=this._device.createRenderPipeline(l);return this._pipelines.set(s,u),u}_ensureShaderCapacity(t){if(!this._device||t<=this._shaderInstCapacity)return;this._shaderInstCapacity=this._growCapacity(this._shaderInstCapacity,t);const e=this._shaderInstData,i=40*this._shaderQuadCount;this._shaderInstData=new ArrayBuffer(40*this._shaderInstCapacity),i>0&&new Uint8Array(this._shaderInstData).set(new Uint8Array(e,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(t){if(!this._device||t<=this._geoInstCapacity)return;this._geoInstCapacity=this._growCapacity(this._geoInstCapacity,t);const e=this._geoInstData,i=32*this._geoQuadCount;this._geoInstData=new ArrayBuffer(32*this._geoInstCapacity),i>0&&new Uint8Array(this._geoInstData).set(new Uint8Array(e,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(t,e){let i=Math.max(t,32);for(;i<e;)i*=2;return i}}const jr=36,Kr=jr/Uint32Array.BYTES_PER_ELEMENT,Qr=new Uint16Array([0,1,2,0,2,3]);class Zr extends Er{_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 te;_activeBounds=null;onConnect(t){this._device||(this._device=t.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},(t,e)=>({binding:e,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(t,e)=>({binding:8+e,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:Qr.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,Qr.buffer,Qr.byteOffset,Qr.byteLength))}onDisconnect(){this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy();for(const t of this._customMaterials.values())this._releaseCustomResources(t);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(t){const e=this._backend,i=t.texture;if(null===e||!(i instanceof vi)&&!(i instanceof wi)||0===i.width||0===i.height||i instanceof vi&&null===i.source)return;const n=t.material,s=e.activeDrawCommand,r=null!==s?s.nodeIndex:e._pushTransform(t);this._activeBounds=this._resolveBounds(t,e),null===n?this._renderDefault(t,i,e,r):this._renderCustom(t,i,n,e,r)}_resolveBounds(t,e){if("geometry"!==t.pixelSnapMode)return t.getLocalBounds();const i=e._getSnapPixelSize();return t.getRenderBounds(e.view,i.width,i.height,this._snapBounds)}_renderDefault(t,e,i,n){const s=t.blendMode,r=null!==this._currentBlendMode&&s!==this._currentBlendMode,o=!this._textureSlots.has(e)&&this._slotCount>=8,a=null!==this._currentMaterial&&this._instanceCount>0;(r||o||a)&&this.flush(),this._currentBlendMode=s,this._currentMaterial=null,i.setBlendMode(s);let h=this._textureSlots.get(e);void 0===h&&(h=this._slotCount++,this._textureSlots.set(e,h),this._activeTextures[h]=e);const l=h|(i.shouldPremultiplyTextureSample(e)?1:0)<<8;this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(t,e,l,n),this._instanceCount++}_renderCustom(t,e,i,n,s){if(null===i.shader.wgsl)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const r=t.blendMode===qe.Normal?i.blendMode:t.blendMode,o=null!==this._currentBlendMode&&r!==this._currentBlendMode,a=null!==this._currentMaterial&&i!==this._currentMaterial,h=null!==this._currentBaseTexture&&e!==this._currentBaseTexture,l=null===this._currentMaterial&&this._instanceCount>0;(o||a||h||l)&&this.flush(),this._currentBlendMode=r,this._currentMaterial=i,this._currentBaseTexture=e,n.setBlendMode(r),this._ensureInstanceCapacity(this._instanceCount+1),this._packInstance(t,e,0,s),this._instanceCount++}flush(){const t=this._backend,e=this._device,i=this._uniformBuffer;if(!t||!e||!i)return;if(0===this._instanceCount&&!t.clearRequested)return;const n=t.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]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const s=t.getScissorRect(),r=null!==s&&(s.width<=0||s.height<=0),o=t._passCoordinator.acquirePass().pass;if(this._instanceCount>0&&!r&&null!==this._instanceBuffer&&null!==this._indexBuffer&&null!==this._currentBlendMode){e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,this._instanceCount*jr);const n=t.getTransformStorageBuffer(this._maxNodeIndex+1),s=this._getOrCreateTransformBindGroup(e,i,n.buffer),r=this._currentMaterial,a=t._passCoordinator.stencilActive;if(null===r){const i=this._getPipeline(this._currentBlendMode,t.renderTargetFormat,a),n=this._createTextureBindGroup(e,t);o.setPipeline(i),o.setBindGroup(0,s),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,e,t,r,s,a),o.popDebugGroup();t.stats.batches++,t.stats.drawCalls++}t._passCoordinator.endPass(),this._instanceCount=0,this._maxNodeIndex=0,this._resetSlots(),this._currentBlendMode=null,this._currentMaterial=null,this._currentBaseTexture=null}_getOrCreateTransformBindGroup(t,e,i){return null!==this._transformBindGroup&&this._transformStorageBuffer===i||(this._transformStorageBuffer=i,this._transformBindGroup=t.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:i}}]})),this._transformBindGroup}destroy(){this.disconnect()}async prewarmPipelines(t){const e=this._device;if(!e||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof e.createRenderPipelineAsync)return;const i=[qe.Normal,qe.Additive,qe.Subtract,qe.Multiply,qe.Screen,qe.Darken,qe.Lighten],n=[];for(const s of i)for(const i of t){const t=`${s}:${i}`;if(this._pipelines.has(t))continue;const r=e.createRenderPipelineAsync(this._buildPipelineDescriptor(s,i)).then(e=>{this._pipelines.set(t,e)});n.push(r)}await Promise.all(n)}_packInstance(t,e,i,n){const s=this._instanceCount*Kr,r=this._instanceFloat32,o=this._instanceUint32,a=this._activeBounds??t.getLocalBounds();r[s+0]=a.left,r[s+1]=a.top,r[s+2]=a.right,r[s+3]=a.bottom;const h=t.textureFrame,l=e.width,u=e.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=e instanceof vi&&e.flipY,m=p?f:_,g=p?_:f;o[s+4]=c|m<<16,o[s+5]=d|g<<16,o[s+6]=t.tint.toRgba(),o[s+7]=i;const y=n>>>0;o[s+8]=y,y>this._maxNodeIndex&&(this._maxNodeIndex=y)}_ensureInstanceCapacity(t){if(!this._device||t<=this._instanceCapacity)return;let e=Math.max(this._instanceCapacity,32);for(;e<t;)e*=2;const i=this._instanceData,n=Math.min(this._instanceCount*jr,i.byteLength),s=new ArrayBuffer(e*jr);n>0&&new Uint8Array(s).set(new Uint8Array(i,0,n));const r=this._device.createBuffer({size:s.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});this._instanceBuffer?.destroy(),this._instanceCapacity=e,this._instanceData=s,this._instanceFloat32=new Float32Array(s),this._instanceUint32=new Uint32Array(s),this._instanceBuffer=r}_resetSlots(){if(this._slotCount>0){for(let t=0;t<this._slotCount;t++)this._activeTextures[t]=null;this._textureSlots.clear(),this._slotCount=0}}_createTextureBindGroup(t,e){const i=this._activeTextures[0]??vi.empty,n=e.getTextureBinding(i),s=new Array(8);for(let t=0;t<8;t++){const r=this._activeTextures[t]??i;s[t]=r===i?n:e.getTextureBinding(r)}const r=[];for(let t=0;t<8;t++)r.push({binding:t,resource:s[t].view});for(let t=0;t<8;t++)r.push({binding:8+t,resource:s[t].sampler});return t.createBindGroup({layout:this._textureBindGroupLayout,entries:r})}_getPipeline(t,e,i){const n=`${t}:${e}:${i?"s":"n"}`,s=this._pipelines.get(n);if(s)return s;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._backend))throw new Error("Renderer has to be connected first!");const r=this._device.createRenderPipeline(this._buildPipelineDescriptor(t,e,i));return this._pipelines.set(n,r),r}_buildPipelineDescriptor(t,e,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:jr,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:e,blend:kr(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return i&&(n.depthStencil=Ur()),n}_drawCustomBatch(t,e,i,n,s,r){const o=this._getOrCreateCustomResources(n,e),a=this._currentBaseTexture??vi.empty;this._uploadUserUniforms(n,o,e);const h=this._getOrCreateCustomPipeline(o,this._currentBlendMode,i.renderTargetFormat,r,e);t.setPipeline(h),t.setBindGroup(0,s),t.setBindGroup(1,this._getCustomBaseTextureBindGroup(o,i,a,e)),t.setBindGroup(2,this._buildUserBindGroup(n,o,i,e)),t.setVertexBuffer(0,this._instanceBuffer),t.setIndexBuffer(this._indexBuffer,"uint16"),t.drawIndexed(6,this._instanceCount,0,0,0)}_getOrCreateCustomResources(t,e){const i=this._customMaterials.get(t);if(void 0!==i)return i;const n=t.shader.wgsl;if(null===n)throw new Error("SpriteMaterial shader has no `wgsl` source; cannot render through the WebGPU backend.");const s=e.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}`}),r=this._buildUserBindGroupLayout(e,t),o={shaderModule:s,userLayout:r,pipelineLayout:e.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._customBaseTextureLayout,r]}),pipelines:new Map,userUniformBuffer:null,userUniformBufferCapacity:0,baseTextureBindGroups:new WeakMap};return this._customMaterials.set(t,o),t._onDispose(()=>{const e=this._customMaterials.get(t);void 0!==e&&(this._releaseCustomResources(e),this._customMaterials.delete(t))}),o}_getOrCreateCustomPipeline(t,e,i,n,s){const r=`${e}:${i}:${n?"s":"n"}`,o=t.pipelines.get(r);if(void 0!==o)return o;const a={layout:t.pipelineLayout,vertex:{module:t.shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:jr,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:t.shaderModule,entryPoint:"fragmentMain",targets:[{format:i,blend:kr(e),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};n&&(a.depthStencil=Ur());const h=s.createRenderPipeline(a);return t.pipelines.set(r,h),h}_getCustomBaseTextureBindGroup(t,e,i,n){const s=e.getTextureBinding(i),r=t.baseTextureBindGroups.get(i);if(r?.view===s.view)return r.group;const o=n.createBindGroup({layout:this._customBaseTextureLayout,entries:[{binding:0,resource:s.view},{binding:1,resource:s.sampler}]});return t.baseTextureBindGroups.set(i,{group:o,view:s.view}),o}_buildUserBindGroupLayout(t,e){const i=[];i.push({binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});const n=to(e);if(n.length>7)throw new Error("SpriteMaterial requested more than 7 user texture bindings.");let s=1;for(let t=0;t<n.length;t++)i.push({binding:s,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}}),s++,i.push({binding:s,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}),s++;return t.createBindGroupLayout({entries:i})}_uploadUserUniforms(t,e,i){const n=function(t){const e=[];for(const i of Object.values(t.uniforms))Jr(i)||e.push(i);return e}(t),s=16*Math.max(n.length,1);(null===e.userUniformBuffer||e.userUniformBufferCapacity<s)&&(e.userUniformBuffer?.destroy(),e.userUniformBufferCapacity=s,e.userUniformBuffer=i.createBuffer({size:s,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}));const r=new Float32Array(s/4);let o=0;for(const t of n){const e=4*o;if("number"==typeof t)r[e]=t;else if(t instanceof Float32Array)r.set(t,e);else if(t instanceof Int32Array)for(let i=0;i<t.length;i++)r[e+i]=t[i];else{const i=t;for(let t=0;t<i.length;t++)r[e+t]=i[t]}o++}i.queue.writeBuffer(e.userUniformBuffer,0,r)}_buildUserBindGroup(t,e,i,n){const s=[];s.push({binding:0,resource:{buffer:e.userUniformBuffer}});let r=1;for(const e of to(t)){const t=i.getTextureBinding(e);s.push({binding:r,resource:t.view}),r++,s.push({binding:r,resource:t.sampler}),r++}return n.createBindGroup({layout:e.userLayout,entries:s})}_releaseCustomResources(t){t.userUniformBuffer?.destroy(),t.pipelines.clear(),t.userUniformBuffer=null,t.userUniformBufferCapacity=0,t.baseTextureBindGroups=new WeakMap}}function Jr(t){return!("object"!=typeof t||null===t||!("width"in t)||!("height"in t)||t instanceof Float32Array||t instanceof Int32Array||Array.isArray(t))}function to(t){const e=[];for(const i of Object.values(t.uniforms))Jr(i)&&e.push(i);for(const i of Object.values(t.textures))e.push(i);return e}const eo=20;class io extends Er{_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(t){if(!this._device)throw new Error("WebGpuTextRenderer is not connected to a backend.");t instanceof Zs?this._collectText(t):this._collectBitmapText(t)}flush(){if(0===this._pendingQuads.length)return void this._resetFrameState();const t=this.getBackend(),e=this._device;for(const t of this._pendingQuads)this._textureKeyMap.has(t.atlasTexture)||this._textureKeyMap.set(t.atlasTexture,this._textureKeyCounter++);this._pendingQuads.sort((t,e)=>{const i=t.shaderType.localeCompare(e.shaderType);return 0!==i?i:(this._textureKeyMap.get(t.atlasTexture)??0)-(this._textureKeyMap.get(e.atlasTexture)??0)});const i=t.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,e.queue.writeBuffer(this._projBuffer,0,this._projData.buffer,0,48),this._uploadNodeBuffer(e);const n=this._pendingQuads,s=[];let r=0,o=0;for(const t of n)r+=4*t.quads.quadCount,o+=t.quads.indices.length;this._ensureVertexCapacity(r),this._ensureIndexCapacity(o);let a=0,h=0,l=0;for(;l<n.length;){const t=n[l],e=this._textureKeyMap.get(t.atlasTexture);let i=l+1;for(;i<n.length;){const s=n[i];if(s.shaderType!==t.shaderType||this._textureKeyMap.get(s.atlasTexture)!==e)break;i++}const r=h;let o=0;for(let t=l;t<i;t++){const{quads:e,nodeIndex:i}=n[t],s=4*e.quadCount,{vertices:r,uvs:l,indices:u}=e;for(let t=0;t<s;t++){const e=5*(a+t),n=2*t;this._float32View[e+0]=r[n],this._float32View[e+1]=r[n+1],this._float32View[e+2]=l[n],this._float32View[e+3]=l[n+1],this._float32View[e+4]=i}for(let t=0;t<u.length;t++)this._indexData[h+t]=u[t]+a;a+=s,h+=u.length,o+=u.length}s.push({shaderType:t.shaderType,atlasTexture:t.atlasTexture,firstIndex:r,indexCount:o}),l=i}this._ensureGpuVertexBuffer(e,a),this._ensureGpuIndexBuffer(e,h),e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,a*eo),e.queue.writeBuffer(this._indexBuffer,0,this._indexData.buffer,0,2*h);const u=t.renderTargetFormat,c=t._passCoordinator.stencilActive,d=this._getFrameBindGroup(e),_=t._passCoordinator.acquirePass().pass;_.setVertexBuffer(0,this._vertexBuffer),_.setIndexBuffer(this._indexBuffer,"uint16");let f=null,p=null;for(const i of s)i.shaderType!==f&&(_.setPipeline(this._getPipeline(i.shaderType,u,c)),_.setBindGroup(0,d),f=i.shaderType),i.atlasTexture!==p&&(_.setBindGroup(1,this._getTexBindGroup(e,t,i.atlasTexture)),p=i.atlasTexture),_.drawIndexed(i.indexCount,1,i.firstIndex,0,0),t.stats.batches++,t.stats.drawCalls++;t._passCoordinator.endPass(),this._resetFrameState()}destroy(){this.disconnect()}async prewarmPipelines(t){const e=this._device;if(!e||!this._shaderModule||!this._pipelineLayout)return;if("function"!=typeof e.createRenderPipelineAsync)return;const i=["sdf","msdf","color"],n=[];for(const s of i)for(const i of t){const t=`${s}:${i}:n`;this._pipelines.has(t)||n.push(e.createRenderPipelineAsync(this._buildPipelineDescriptor(s,i)).then(e=>{this._pipelines.set(t,e)}))}await Promise.all(n)}onConnect(t){const e=t.device;this._device=e,this._shaderModule=e.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=e.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=e.createBindGroupLayout({label:"WebGpuTextRenderer/texture",entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=e.createPipelineLayout({label:"WebGpuTextRenderer",bindGroupLayouts:[this._frameBindGroupLayout,this._textureBindGroupLayout]}),this._projBuffer=e.createBuffer({label:"WebGpuTextRenderer/proj",size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this._nodeBuffer=e.createBuffer({label:"WebGpuTextRenderer/nodes",size:5120,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=5120;this._vertexBuffer=e.createBuffer({label:"WebGpuTextRenderer/vertices",size:5120,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=5120;this._indexBuffer=e.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(t){t.syncDirty();const{pageQuads:e,atlas:i}=t;if(0===e.length||null===i)return;const n=this._assignNodeIndex(t),s=t.colorGlyphs?"color":"sdf",r=i.pages;for(const t of e){const e=r[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:n,shaderType:s,atlasTexture:e.texture})}}_collectBitmapText(t){const{pageQuads:e,textures:i,msdf:n}=t;if(0===e.length)return;const s=this._assignNodeIndex(t),r=n?"msdf":"color";for(const t of e){const e=i[t.pageIndex];void 0!==e&&this._pendingQuads.push({quads:t,nodeIndex:s,shaderType:r,atlasTexture:e})}}_assignNodeIndex(t){const e=this._nodeIndexMap.get(t);if(void 0!==e)return e;const i=this._nodeCount++;return this._nodeIndexMap.set(t,i),this._ensureNodeCapacity(i+1),this._packNodeData(i,t),i}_packNodeData(t,e){const i=this._nodeDataArray,n=40*t,s=e.style,r=e.getGlobalTransform().toArray(!1);i[n+0]=r[0],i[n+1]=r[1],i[n+2]=r[2],i[n+3]=r[6],i[n+4]=r[3],i[n+5]=r[4],i[n+6]=r[5],i[n+7]=r[7];const o=s.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=s.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=s.outlineWidth>0?Math.max(0,.5-s.outlineWidth):.5;i[n+16]=h,i[n+17]=s.shadowAlpha,i[n+18]=Math.max(.03,.1*s.shadowBlur),i[n+19]=null!==s.gradientColors?1:0;const l=s.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]=s.shadowOffsetX,i[n+25]=s.shadowOffsetY,i[n+26]="vertical"===s.gradientAxis?1:0,i[n+27]=0;const u=s.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=e.textBounds;i[n+36]=0,i[n+37]=0,i[n+38]=c.width,i[n+39]=c.height}_uploadNodeBuffer(t){const e=40*this._nodeCount*4;if(e>this._nodeBufferCapacity){let i=this._nodeBufferCapacity;for(;i<e;)i*=2;this._nodeBuffer?.destroy(),this._nodeBuffer=t.createBuffer({label:"WebGpuTextRenderer/nodes",size:i,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this._nodeBufferCapacity=i,this._frameBindGroupDirty=!0}t.queue.writeBuffer(this._nodeBuffer,0,this._nodeDataArray.buffer,0,e)}_ensureGpuVertexBuffer(t,e){const i=e*eo;if(i<=this._vertexBufferCapacity)return;let n=this._vertexBufferCapacity;for(;n<i;)n*=2;this._vertexBuffer?.destroy(),this._vertexBuffer=t.createBuffer({label:"WebGpuTextRenderer/vertices",size:n,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._vertexBufferCapacity=n}_ensureGpuIndexBuffer(t,e){const i=2*e;if(i<=this._indexBufferCapacity)return;let n=this._indexBufferCapacity;for(;n<i;)n*=2;this._indexBuffer?.destroy(),this._indexBuffer=t.createBuffer({label:"WebGpuTextRenderer/indices",size:n,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._indexBufferCapacity=n}_getFrameBindGroup(t){return this._frameBindGroupDirty||null===this._frameBindGroup?(this._frameBindGroup=t.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(t,e,i){const{view:n,sampler:s}=e.getTextureBinding(i),r=this._texBindGroups.get(i);if(r?.view===n)return r.group;const o=t.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:n},{binding:1,resource:s}]});return this._texBindGroups.set(i,{group:o,view:n}),o}_getPipeline(t,e,i){const n=`${t}:${e}:${i?"s":"n"}`,s=this._pipelines.get(n);if(s)return s;const r=this._device.createRenderPipeline(this._buildPipelineDescriptor(t,e,i));return this._pipelines.set(n,r),r}_buildPipelineDescriptor(t,e,i=!1){let n;n="sdf"===t?"fragmentSdf":"msdf"===t?"fragmentMsdf":"fragmentColor";const s={label:`WebGpuTextRenderer/${t}`,layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:eo,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:n,targets:[{format:e,blend:kr(qe.Normal),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}};return i&&(s.depthStencil=Ur()),s}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(this._vertexCapacity*eo),this._float32View=new Float32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_ensureNodeCapacity(t){if(t<=this._nodeCapacity)return;for(;this._nodeCapacity<t;)this._nodeCapacity*=2;const e=new Float32Array(40*this._nodeCapacity);e.set(this._nodeDataArray),this._nodeDataArray=e}_resetFrameState(){this._pendingQuads.length=0,this._nodeIndexMap.clear(),this._textureKeyMap.clear(),this._textureKeyCounter=0,this._nodeCount=0}}class no extends qn{_rawTransform=null;_sourceGeometry=null;_sourceVersion=-1;constructor(){super({vertices:new Float32Array([0,0,1,0,0,1])})}getGlobalTransform(){return this._rawTransform??super.getGlobalTransform()}configure(t,e,i,n){this._flattenGeometry(t),this._geometry=null,this._material=i,this._rawTransform=e,this.setTint(n??Re.white)}configureBatchSource(t,e){this._flattenGeometry(t),this._geometry=t,this._material=e,this._rawTransform=null,this.setTint(Re.white)}_flattenGeometry(t){if(t===this._sourceGeometry&&t.version===this._sourceVersion)return;const e=Hn(t);this._vertices=e.vertices,this._uvs=e.uvs,this._colors=e.colors,this._indices=e.indices,this._sourceGeometry=t,this._sourceVersion=t.version}}class so{geometry;material;_transforms=[];_tints=[];_count=0;constructor(t,e=null){if("static"!==t.usage)throw new Error(`RenderBatch requires geometry with usage='static' (got '${t.usage}').`);if(null!==e&&"mesh"!==e.target)throw new Error(`RenderBatch material must target 'mesh' (got '${String(e.target)}').`);this.geometry=t,this.material=e}get count(){return this._count}add(t,e=null){let i=this._transforms[this._count];void 0===i&&(i=new Le,this._transforms[this._count]=i),i.copy(t);let n=this._tints[this._count];return void 0===n&&(n=new Re,this._tints[this._count]=n),n.copy(e??Re.white),this._count++,this}clear(){return this._count=0,this}destroy(){for(const t of this._transforms)t.destroy();for(const t of this._tints)t.destroy();this._transforms.length=0,this._tints.length=0,this._count=0}get _instanceTransforms(){return this._transforms}get _instanceTints(){return this._tints}}const ro=()=>({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}),oo=t=>(t.frame++,t.submittedNodes=0,t.culledNodes=0,t.drawCalls=0,t.batches=0,t.renderPasses=0,t.renderTargetChanges=0,t.frameTimeMs=0,t.rawFrameDeltaMs=0,t.textureUploadBytes=0,t.bufferUploadBytes=0,t.downloadBytes=0,t.downloadCount=0,t);class ao{order=500;_backend;_view;_screenView;_immediateMesh=null;_batchMesh=null;_trackedViews=new Set;_renderedViews=new Set;constructor(t){this._backend=t;const e=t.view?.width??0,i=t.view?.height??0,n=t.view?.center?.x??e/2,s=t.view?.center?.y??i/2;this._view=gi.from({center:{x:n,y:s},size:{width:e,height:i}}),this._screenView=new gi(n,s,e,i)}get view(){return this._view}set view(t){const e=this._view;this._view=t,e!==t&&e.destroy()}get screenView(){return this._screenView}trackView(t){this._trackedViews.add(t)}untrackView(t){this._trackedViews.delete(t)}update(t){const e=t.milliseconds;this._view.update(e);for(const t of this._trackedViews)t!==this._view&&t.update(e);for(const t of this._renderedViews)t===this._view||this._trackedViews.has(t)||t.update(e);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(t,e){this._view.resize(t,e),this._screenView.resize(t,e),this._screenView.setCenter(t/2,e/2)}render(t,e={}){const i=e.view??this._view;this._renderedViews.add(i),this._backend.setView(i),Ci(t,this._backend)}capture(t,e){const i=new wi(e.width,e.height),n=new gi(e.width/2,e.height/2,e.width,e.height),s=this._backend._passCoordinator;if(s)return s.withChildPass({target:i,view:n,load:void 0!==e.clearColor?"clear":"load",clearColor:e.clearColor??null,stencil:Ti.None},()=>{Ci(t,this._backend)}),i;const r=this._backend.renderTarget,o=this._backend.view;this._backend.setRenderTarget(i),this._backend.setView(n),void 0!==e.clearColor&&this._backend.clear(e.clearColor);try{Ci(t,this._backend)}finally{this._backend.setRenderTarget(r),this._backend.setView(o)}return i}clear(t){const e=this._backend._passCoordinator;e?e.withChildPass({target:e.activeTarget,view:e.activeView,load:"clear",clearColor:t,stencil:Ti.None},()=>{}):this._backend.clear(t)}renderTo(t,e){const i=e.view??e.target.view;this._renderedViews.add(i);const n=this._backend._passCoordinator;if(n)return void n.withChildPass({target:e.target,view:i,load:void 0!==e.clear?"clear":"load",clearColor:e.clear??null,stencil:Ti.None},()=>{Ci(t,this._backend)});const s=this._backend.renderTarget,r=this._backend.view;this._backend.setRenderTarget(e.target),this._backend.setView(i),void 0!==e.clear&&this._backend.clear(e.clear);try{Ci(t,this._backend)}finally{this._backend.setRenderTarget(s),this._backend.setView(r)}}drawGeometry(t,e,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 s=i.view??this._view;this._renderedViews.add(s);const r=this._immediateMesh??=new no;this._backend.setView(s),r.configure(t,e,n,i.tint??null),this._backend.draw(r),this._backend.flush()}drawBatch(t,e={}){if(null!==t.material)throw new Error("drawBatch custom materials are not supported yet — v1 renders batches with the default mesh material.");if(0===t.count)return;const i=e.view??this._view;this._renderedViews.add(i);const n=this._batchMesh??=new no;this._backend.setView(i),n.configureBatchSource(t.geometry,t.material),this._backend.drawInstanced(n,t._instanceTransforms,t._instanceTints,t.count),this._backend.flush()}get stats(){return this._backend.stats}get backend(){return this._backend}}class ho{_stats;_liveBytes=0;constructor(t){this._stats=t,this._stats.gpuMemoryBytes=0}get liveBytes(){return this._liveBytes}allocate(t){t<=0||(this._liveBytes+=t,this._stats.gpuMemoryBytes=this._liveBytes)}free(t){t<=0||(this._liveBytes=Math.max(0,this._liveBytes-t),this._stats.gpuMemoryBytes=this._liveBytes)}reallocate(t,e){return this.free(t),this.allocate(e),e}recordTextureUpload(t){t<=0||(this._stats.textureUploadBytes+=t)}recordBufferUpload(t){t<=0||(this._stats.bufferUploadBytes+=t)}recordDownload(t){t<=0||(this._stats.downloadBytes+=t,this._stats.downloadCount++)}}const lo=(t,e,i,n=1)=>{const s=Math.max(1,Math.floor(t)),r=Math.max(1,Math.floor(e)),o=Math.max(1,Math.floor(n));let a=0,h=s,l=r;for(let t=0;t<o&&(a+=h*l*i,1!==h||1!==l);t++)h=Math.max(1,h>>1),l=Math.max(1,l>>1);return a},uo=t=>{switch(t){case"r8":return 1;case"r32f":case"rgba8":return 4;case"rgba32f":return 16}};class co{_entries=new Map;_walk;_dispose;constructor(t={}){this._walk=t.walk??null,this._dispose=t.dispose??null}set(t,e){this._entries.set(t,e)}hasOwn(t){return this._entries.has(t)}has(t){return void 0!==this._find(t)}resolve(t){return this._find(t)}values(){return this._entries.values()}destroy(){if(null!==this._dispose){const t=new Set;for(const e of this._entries.values())t.has(e)||(t.add(e),this._dispose(e))}this._entries.clear()}_find(t){let e,i=t;for(;null!==i&&void 0===e;)e=this._entries.get(i),void 0===e&&(i=null!==this._walk?this._walk(i):null);return e}}const _o=t=>{const e=Object.getPrototypeOf(t.prototype);return e?.constructor??null};class fo{_renderers=new co({walk:_o,dispose:t=>{t.disconnect(),"destroy"in t&&"function"==typeof t.destroy&&t.destroy()}});_resolved=new Map;_backend=null;registerRenderer(t,e){if(this._renderers.hasOwn(t))throw new Error(`A renderer is already registered for ${t.name}.`);this._renderers.set(t,e),this._resolved.clear(),null!==this._backend&&e.connect(this._backend)}bindRenderer(t,e){if(0===t.length)throw new Error("A RendererBinding must declare at least one target.");const i=new Set;for(const e of t){if(i.has(e))throw new Error(`A RendererBinding declares the same target ${e.name} more than once.`);i.add(e)}for(const e of t)if(this._renderers.hasOwn(e))throw new Error(`A renderer is already registered for ${e.name}.`);for(const i of t)this._renderers.set(i,e);this._resolved.clear(),null!==this._backend&&e.connect(this._backend)}renderers(){return this._renderers.values()}resolve(t){const e=t.constructor,i=this._resolved.get(e);if(void 0!==i)return i;const n=this._renderers.resolve(e);if(!n)throw new Error(`No renderer registered for ${t.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(e,n),n}connect(t){this._backend=t;for(const e of this._renderers.values())e.connect(t)}disconnect(){for(const t of this._renderers.values())t.disconnect();this._backend=null}destroy(){this._renderers.destroy(),this._resolved.clear(),this._backend=null}}const po=new Float32Array(1),mo=new Uint32Array(po.buffer);class go{_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(t=0){return t>0&&this._ensureCapacity(t),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(t,e){const i=this._count;return this.write(i,t,e),i}rewindTo(t,e){return t>=0&&t<this._count&&(this._count=t,void 0!==e&&(this._frameHash=e>>>0)),this}consumeDirtyRange(t){if(this._dirtyMax<this._dirtyMin)return{firstRow:0,rowCount:0};const e=Math.max(0,this._dirtyMin),i=Math.min(this._dirtyMax,t-1),n=i>=e?i-e+1:0;return this._dirtyMin=0,this._dirtyMax=-1,{firstRow:e,rowCount:n}}write(t,e,i){if(!Number.isInteger(t)||t<0)throw new Error(`TransformBuffer slot must be a non-negative integer (got ${t}).`);this._ensureCapacity(t+1);const n=12*t,s=this._data;s[n+0]=e.a,s[n+1]=e.b,s[n+2]=e.c,s[n+3]=e.d,s[n+4]=e.x,s[n+5]=e.y,s[n+6]=0,s[n+7]=0,s[n+8]=i.r/255,s[n+9]=i.g/255,s[n+10]=i.b/255,s[n+11]=i.a,t>=this._count&&(this._count=t+1),this._dirtyMax<this._dirtyMin?(this._dirtyMin=t,this._dirtyMax=t):(t<this._dirtyMin&&(this._dirtyMin=t),t>this._dirtyMax&&(this._dirtyMax=t)),this._frameHash=this._mix(this._frameHash,t);for(let t=0;t<12;t++)this._frameHash=this._mix(this._frameHash,this._hashFloat(s[n+t]));return this._writeCount++,this}recordSkippedWrite(){return this._skippedWriteCount++,this}recordUpload(t){return this._uploadCount++,this._uploadedRecordCount+=t,this}commitSnapshot(t=0){const e=Math.max(this._count,t),i=this._mix(this._frameHash,e),n=i!==this._lastCommittedHash||e!==this._lastCommittedCount;return n&&(this._version++,this._lastCommittedHash=i,this._lastCommittedCount=e),{count:e,hash:i,changed:n,version:this._version}}_ensureCapacity(t){const e=this.capacity;if(t<=e)return;let i=Math.max(e,16);for(;i<t;)i*=2;const n=new Float32Array(12*i);n.set(this._data),this._data=n}_hashFloat(t){return po[0]=t,mo[0]>>>0}_mix(t,e){return Math.imul((t^e)>>>0,16777619)>>>0}}const yo=new Uint16Array([0,1,2,0,2,3]);class wo{_shader=new Js("#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 e=t.context,i=e.createVertexArray();if(null===i)throw new Error("WebGl2BackdropBlendCompositor: could not create vertex array object.");this._shader.connect(lr(e));const n=new Map,s=new ir(He.ElementArrayBuffer,yo,je.StaticDraw).connect(this._createBufferRuntime(e,n)),r=new ir(He.ArrayBuffer,this._vertexData,je.DynamicDraw).connect(this._createBufferRuntime(e,n));this._shader.sync();const o=(new cr).addIndex(s).addAttribute(r,this._shader.getAttribute("a_position"),e.FLOAT,!1,16,0).addAttribute(r,this._shader.getAttribute("a_texcoord"),e.FLOAT,!1,16,8).connect(this._createVaoRuntime(e,i));this._connection={gl:e,vaoHandle:i,vao:o,indexBuffer:s,vertexBuffer:r,bufferHandles:n}}disconnect(){const t=this._connection;null!==t&&(t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(t,e,i,n,s,r,o){if(null===this._connection)throw new Error("WebGl2BackdropBlendCompositor: not connected.");if(s<=0||r<=0)return;const a=t.context,h=t.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+r)*u)),_=t.acquireRenderTexture(s,r),f=Math.min(_.width,Math.max(0,Math.round(s*l))),p=Math.min(_.height,Math.max(0,Math.round(r*u))),m=h.root&&!a.getContextAttributes()?.alpha;try{a.bindFramebuffer(a.READ_FRAMEBUFFER,t._renderTargetFramebuffer(h)),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,t._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),t._rebindActiveTarget(),this._drawBlend(t,e,_,i,n,s,r,o,m)}finally{t.releaseRenderTexture(_)}}_drawBlend(t,e,i,n,s,r,o,a,h){const l=this._connection;if(null===l)throw new Error("WebGl2BackdropBlendCompositor: not connected.");this._writeQuadVertices(n,s,n+r,s+o),t.bindShader(this._shader);const u=t.view.getTransform().toArray(!1);this._modeValue[0]=a,this._opaqueValue[0]=h?1:0,this._shader.getUniform("u_projection").setValue(u),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(e,0),t.bindTexture(i,1),t.setBlendMode(qe.Normal),t.bindVertexArrayObject(l.vao),l.vertexBuffer.upload(this._float32View),l.vao.draw(6,0),t.stats.batches++,t.stats.drawCalls++,t.bindTexture(null,1)}_writeQuadVertices(t,e,i,n){const s=this._float32View;s[0]=t,s[1]=e,s[2]=0,s[3]=0,s[4]=i,s[5]=e,s[6]=1,s[7]=0,s[8]=i,s[9]=n,s[10]=1,s[11]=1,s[12]=t,s[13]=n,s[14]=0,s[15]=1}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("WebGl2BackdropBlendCompositor: could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:n=>{const s=n.data;t.bindBuffer(n.type,i),t.bufferData(n.type,s,n.usage),e.set(n,i)},destroy:n=>{t.deleteBuffer(i),e.delete(n),n.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:n=>{if(t.bindVertexArray(e),i!==n.version){let e=null;for(const i of n.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,s)=>{e.indexBuffer?t.drawElements(s,i,t.UNSIGNED_SHORT,n):t.drawArrays(s,n,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}const xo=new Uint16Array([0,1,2,0,2,3]);class vo{_shader=new Js("#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 e=t.context,i=e.createVertexArray();if(null===i)throw new Error("WebGl2MaskCompositor: could not create vertex array object.");this._shader.connect(lr(e));const n=new Map,s=new ir(He.ElementArrayBuffer,xo,je.StaticDraw).connect(this._createBufferRuntime(e,n),t.accountant),r=new ir(He.ArrayBuffer,this._vertexData,je.DynamicDraw).connect(this._createBufferRuntime(e,n),t.accountant);this._shader.sync();const o=(new cr).addIndex(s).addAttribute(r,this._shader.getAttribute("a_position"),e.FLOAT,!1,16,0).addAttribute(r,this._shader.getAttribute("a_texcoord"),e.FLOAT,!1,16,8).connect(this._createVaoRuntime(e,i));this._connection={gl:e,vaoHandle:i,vao:o,indexBuffer:s,vertexBuffer:r,bufferHandles:n}}disconnect(){const t=this._connection;null!==t&&(t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._shader.disconnect(),this._connection=null)}compose(t,e,i,n,s,r,o,a){const h=this._connection;if(null===h)throw new Error("WebGl2MaskCompositor: not connected.");this._writeQuadVertices(n,s,n+r,s+o),t.bindShader(this._shader);const l=t.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(),t.bindTexture(e,0),t.bindTexture(i,1),t.setBlendMode(a),t.bindVertexArrayObject(h.vao),h.vertexBuffer.upload(this._float32View),h.vao.draw(6,0),t.stats.batches++,t.stats.drawCalls++,t.bindTexture(null,1)}_writeQuadVertices(t,e,i,n){const s=this._float32View;s[0]=t,s[1]=e,s[2]=0,s[3]=0,s[4]=i,s[5]=e,s[6]=1,s[7]=0,s[8]=i,s[9]=n,s[10]=1,s[11]=1,s[12]=t,s[13]=n,s[14]=0,s[15]=1}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("WebGl2MaskCompositor: could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:n=>{const s=n.data;t.bindBuffer(n.type,i),t.bufferData(n.type,s,n.usage),e.set(n,i)},destroy:n=>{t.deleteBuffer(i),e.delete(n),n.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:n=>{if(t.bindVertexArray(e),i!==n.version){let e=null;for(const i of n.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);n.indexBuffer&&n.indexBuffer.bind(),i=n.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,s)=>{e.indexBuffer?t.drawElements(s,i,t.UNSIGNED_SHORT,n):t.drawArrays(s,n,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}class bo{_backend;_stencilEnabled=!1;constructor(t){this._backend=t}get activeTarget(){return this._backend.renderTarget}get activeView(){return this._backend.view}hasActivePass=!0;beginPass(t){this._backend.setRenderTarget(t.target),this._backend.setView(t.view),this._stencilEnabled=t.stencil===Ti.Enabled,"clear"===t.load&&this._backend.clear(t.clearColor??void 0)}endPass(){this._backend.flush()}withChildPass(t,e){const i=this._backend.renderTarget,n=this._backend.view,s=this._stencilEnabled;this.beginPass(t);try{e()}finally{this._backend.setRenderTarget(i),this._backend.setView(n),this._stencilEnabled=s}}pushScissorRect(t){this._backend.pushScissorRect(t)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(t,e){this._backend.pushStencilClip(t,e)}popStencilClip(){this._backend.popStencilClip()}resolveLoad(t,e){return e?"clear":"load"}}const So=new Set(["a_position","position"]);class Bo{_shader=new Js("#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 Le;_positions=new Float32Array(64);_connection=null;connect(t){if(null!==this._connection)return;const e=t.context,i=e.createVertexArray();if(null===i)throw new Error("WebGl2StencilClipper: could not create vertex array object.");this._shader.connect(lr(e)),this._shader.sync();const n=new ir(He.ArrayBuffer,this._positions,je.DynamicDraw).connect(this._createBufferRuntime(e),t.accountant),s=new cr(Xe.Triangles).addAttribute(n,this._shader.getAttribute("a_position"),e.FLOAT,!1,8,0).connect(this._createVaoRuntime(e,i));this._connection={gl:e,vao:s,vertexBuffer:n}}disconnect(){const t=this._connection;null!==t&&(t.vertexBuffer.destroy(),t.vao.destroy(),this._shader.disconnect(),this._connection=null)}draw(t,e,i){const n=this._connection;if(null===n)throw new Error("WebGl2StencilClipper: not connected.");const s=this._extractPositions(e);if(0===s)return;this._matrix.copy(i).combine(t.view.getTransform()),t.bindShader(this._shader),this._shader.getUniform("u_matrix").setValue(this._matrix.toArray(!1)),this._shader.sync(),t.bindVertexArrayObject(n.vao),n.vertexBuffer.upload(this._positions.subarray(0,2*s));const r="triangle-strip"===e.topology?Xe.TriangleStrip:Xe.Triangles;n.vao.draw(s,0,r),t.stats.drawCalls++}_extractPositions(t){const e=this._resolvePositionAttribute(t.attributes);if("f32"!==e.type)throw new Error(`Stencil clipShape position attribute "${e.name}" must be of type f32 (got "${e.type}").`);const{stride:i,vertexData:n,indices:s}=t,r=n instanceof Float32Array?new DataView(n.buffer,n.byteOffset,n.byteLength):new DataView(n),o=null!==s?s.length:t.vertexCount;this._ensureCapacity(o);const a=this._positions;for(let t=0;t<o;t++){const n=(null!==s?s[t]:t)*i+e.offset;a[2*t]=r.getFloat32(n,!0),a[2*t+1]=r.getFloat32(n+4,!0)}return o}_resolvePositionAttribute(t){const e=t.find(t=>So.has(t.name));if(e)return e;const i=t.find(t=>t.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Stencil clipShape requires a position attribute named `a_position` or `position`.")}_ensureCapacity(t){const e=2*t;this._positions.length<e&&(this._positions=new Float32Array(Math.max(e,2*this._positions.length)))}_createBufferRuntime(t){const e=t.createBuffer();if(null===e)throw new Error("WebGl2StencilClipper: could not create render buffer.");return{bind:i=>{t.bindBuffer(i.type,e)},upload:i=>{t.bindBuffer(i.type,e),t.bufferData(i.type,i.data,i.usage)},destroy:i=>{t.deleteBuffer(e),i.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:n=>{if(t.bindVertexArray(e),i!==n.version){let e=null;for(const i of n.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);i=n.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,s)=>{t.drawArrays(s,n,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}class Co{backendType=tr.WebGl2;rendererRegistry=new fo;onContextLost=new w;onContextRestored=new w;_context;_rootRenderTarget;_onContextLostHandler;_onContextRestoredHandler;_textureStates=new Map;_renderTargetStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_clipBoundsStack=[];_clipPixelStack=[];_clipPointA=new ie;_clipPointB=new ie;_maskCompositor=new vo;_maskCompositorConnected=!1;_backdropBlendCompositor=new wo;_backdropBlendCompositorConnected=!1;_stencilClipper=new Bo;_stencilStates=new Map;_stencilClipperConnected=!1;_passCoordinatorInstance=null;_canvas;_contextLost;_renderTarget;_snapTransform=new Le;_renderer=null;_shader=null;_blendMode=null;_texture=null;_textureUnit=0;_vao=null;_clearColor=new Re;_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 ho(this._stats);_transformBuffer=new go;_transformTexture=null;_transformTextureHash=0;_transformTextureCount=-1;_activeDrawCommand=null;_drawPlanDepth=0;_planBaseStack=[];_planHashStack=[];constructor(t){const e=t.options.canvas??{},i=t.options.rendering??{},n=e.width??800,s=e.height??600,r=t.options.clearColor,o=i.webglAttributes;i.debug,this._canvas=t.canvas;const a=this._createContext(o);if(!a)throw new Error("This browser or hardware does not support WebGL.");this._context=a,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),r&&this.clearColor.copy(r),this._rootRenderTarget=new yi(n,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(qe.Normal),this.resize(n,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 bo(this)}async initialize(){return this}resetStats(){return oo(this._stats),this._transformBuffer.begin(),this}get transformBufferCount(){return this._transformBuffer.count}_beginDrawPlan(t){this._planBaseStack.push(this._transformBuffer.count),this._planHashStack.push(this._transformBuffer.frameHash),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(t,e,i){const n=e+i;for(let i=e;i<n;i++){const e=t[i];if(e.kind!==Qe.Draw)continue;const n=e.command;hi(n,this)?this._writeTransformCommand(n):this._transformBuffer.recordSkippedWrite()}}_prepareDrawCommand(t){this._activeDrawCommand=t}_writeTransformCommand(t){const e=t.drawable;this._transformBuffer.write(t.nodeIndex,this._resolveSnapTransform(e),e.tint)}_resolveSnapTransform(t){const e=this._renderTarget,i=e.root?this._canvas.width:e.width,n=e.root?this._canvas.height:e.height;return On(t,e.view,i,n,this._snapTransform)}_getSnapPixelSize(){const t=this._renderTarget;return{width:t.root?this._canvas.width:t.width,height:t.root?this._canvas.height:t.height}}_pushTransform(t){return this._transformBuffer.push(this._resolveSnapTransform(t),t.tint)}_endDrawPlan(){this._activeDrawCommand=null;const t=this._planBaseStack.pop()??0,e=this._planHashStack.pop()??0;this._drawPlanDepth>0&&this._drawPlanDepth--,this._drawPlanDepth>0&&(this._flushActiveRenderer(),this._transformBuffer.rewindTo(t,e)),0===this._drawPlanDepth&&this._assertBalancedStencil()}_assertBalancedStencil(){let t=0;for(const e of this._stencilStates.values())t+=e.stack.length;if(0===t)return;for(const t of this._stencilStates.values())t.depth=0,t.stack.length=0;const e=this._context;throw e.stencilFunc(e.ALWAYS,0,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.disable(e.STENCIL_TEST),new Error(`Unbalanced stencil clip stack at end of frame (${t} unpopped clip(s)).`)}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(t,e,i,n){if(n<=0||0===t.vertexCount)return this;if(e.length<n||i.length<n)throw new Error(`drawInstanced requires ${n} transforms and tints (got ${e.length}/${i.length}).`);const s=this.rendererRegistry.resolve(t);if(!(s instanceof _r))throw new Error("drawInstanced requires a mesh handled by the WebGL2 mesh renderer.");this._setActiveRenderer(s);const r=this._transformBuffer.push(e[0],i[0]);for(let t=1;t<n;t++)this._transformBuffer.push(e[t],i[t]);return s.drawInstancedBatch(t,r,n),this._activeDrawCommand=null,this._stats.submittedNodes+=n,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setRenderTarget(t){const e=t||this._rootRenderTarget,i=this._renderTarget!==e;return i&&(this._flushActiveRenderer(),this._renderTarget=e,this._stats.renderTargetChanges++),this._bindRenderTarget(e),i&&this._applyStencilState(e),this}pushScissorRect(t){this._flushActiveRenderer(),this._clipBoundsStack.push(t.clone());const e=this._toClipPixels(t),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,n=i?this._intersectClips(i,e):e;return this._clipPixelStack.push(n),this._applyClipState(),this}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const t=this._clipBoundsStack.pop();return t&&t.destroy(),this._clipPixelStack.pop(),this._applyClipState(),this}pushStencilClip(t,e){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 s=this._context,r=n.depth;return 0===r&&(this._ensureTargetStencil(),s.enable(s.STENCIL_TEST),s.disable(s.SCISSOR_TEST),s.clearStencil(0),s.clear(s.STENCIL_BUFFER_BIT),this._applyClipState()),s.colorMask(!1,!1,!1,!1),s.stencilFunc(s.EQUAL,r,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR),this._stencilClipper.draw(this,t,e),s.colorMask(!0,!0,!0,!0),n.depth=r+1,n.stack.push({shape:t,transform:(new Le).copy(e)}),s.stencilFunc(s.EQUAL,n.depth,255),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),this}popStencilClip(){const t=this._renderTarget,e=this._getStencilState(t),i=e.stack.pop();if(void 0===i)return this;this._flushActiveRenderer(),this._setActiveRenderer(null);const n=this._context,s=e.depth;return n.colorMask(!1,!1,!1,!1),n.stencilFunc(n.EQUAL,s,255),n.stencilOp(n.KEEP,n.KEEP,n.DECR),this._stencilClipper.draw(this,i.shape,i.transform),n.colorMask(!0,!0,!0,!0),e.depth=s-1,this._applyStencilState(t),this}composeWithAlphaMask(t,e,i,n,s,r,o){return s<=0||r<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._maskCompositorConnected||(this._maskCompositor.connect(this),this._maskCompositorConnected=!0),this._maskCompositor.compose(this,t,e,i,n,s,r,o)),this}composeWithBackdropBlend(t,e,i,n,s,r){return n<=0||s<=0||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._backdropBlendCompositorConnected||(this._backdropBlendCompositor.connect(this),this._backdropBlendCompositorConnected=!0),this._backdropBlendCompositor.compose(this,t,e,i,n,s,r)),this}_renderTargetFramebuffer(t){return this._prepareRenderTarget(t).framebuffer}_rebindActiveTarget(){this._bindRenderTarget(this._renderTarget)}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const n=this._temporaryRenderTextures[i];if(n.width===t&&n.height===e)return this._temporaryRenderTextures.splice(i,1),n}return new wi(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._renderTarget.view!==t&&this._flushActiveRenderer(),this._renderTarget.setView(t),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(t){return this._vao!==t&&(t?t.bind():this._vao?.unbind(),this._vao=t),this}bindShader(t){return this._shader!==t&&(this._shader&&(this._shader.unbind(),this._shader=null),t&&t.bind(),this._shader=t),this}bindTexture(t,e){if(void 0!==e&&this._setTextureUnit(e),null===t)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(t);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=t,this}setActiveTextureUnit(t){return this._setTextureUnit(t),this}bindTransformBufferTexture(t,e){const i=Math.max(1,e),n=this._transformTexture;n?.height===this._transformBuffer.capacity&&n.buffer===this._transformBuffer.data||(n?.destroy(),this._transformTexture=new Os({width:3,height:this._transformBuffer.capacity,format:"rgba32f",data:this._transformBuffer.data}),this._transformTextureHash=0,this._transformTextureCount=-1);const s=this._transformBuffer.commitSnapshot(i),r=this._transformTexture;if(null===r)throw new Error("Transform texture must be initialized before binding.");if(s.changed||s.count!==this._transformTextureCount||s.hash!==this._transformTextureHash){const{firstRow:t,rowCount:e}=this._transformBuffer.consumeDirtyRange(s.count);e>0&&(r.commitRect(0,t,3,e),this._transformBuffer.recordUpload(e)),this._transformTextureCount=s.count,this._transformTextureHash=s.hash}return this.bindTexture(r,t)}setBlendMode(t){if(t!==this._blendMode){const e=this._context;switch(this._blendMode=t,t){case qe.Additive:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE);break;case qe.Subtract:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ZERO,e.ONE_MINUS_SRC_COLOR);break;case qe.Multiply:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA);break;case qe.Screen:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_COLOR);break;default:e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(t){if(this._textureUnit!==t){const e=this._context;this._textureUnit=t,e.activeTexture(e.TEXTURE0+t)}}setClearColor(t){if(!this._clearColor.equals(t)){const e=this._context;this._clearColor.copy(t),e.clearColor(t.r/255,t.g/255,t.b/255,t.a)}return this}clear(t){const e=this._context;return t&&this.setClearColor(t),this._bindRenderTarget(this._renderTarget),e.clear(e.COLOR_BUFFER_BIT),this}resize(t,e){return this._rootRenderTarget.resize(t,e),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 t of this._clipBoundsStack)t.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(t){try{return this._canvas.getContext("webgl2",{...t,stencil:!0})}catch(t){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const t=this._context,{r:e,g:i,b:n,a:s}=this._clearColor;t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.clearColor(e/255,i/255,n/255,s)}_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 t=this._context.createFramebuffer();if(null===t)throw new Error("Could not create framebuffer.");return t}_createTextureHandle(){const t=this._context.createTexture();if(null===t)throw new Error("Could not create texture.");return t}_bookTextureStorage(t,e,i){const n=lo(e.width,e.height,i,this._textureMipLevelCount(e));t.accountedBytes=this._accountant.reallocate(t.accountedBytes,n)}_textureMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_destroyManagedResources(){for(const t of[...this._renderTargetStates.keys()])this._evictRenderTarget(t,!1);for(const t of[...this._textureStates.keys()])this._evictTexture(t,!1)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(t){let e=this._renderTargetStates.get(t);return e||(this._subscribeToDestroy(t,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(t,!0)}),e={framebuffer:t.root?null:this._createFramebuffer(),version:-1,attachedTexture:null,stencilRenderbuffer:null,stencilWidth:0,stencilHeight:0},this._renderTargetStates.set(t,e)),e}_getTextureState(t){let e=this._textureStates.get(t);return e||(this._subscribeToDestroy(t,this._textureDestroyHandlers,()=>{this._evictTexture(t,!0)}),e={handle:this._createTextureHandle(),version:-1,width:0,height:0,accountedBytes:0},this._textureStates.set(t,e)),e}_subscribeToDestroy(t,e,i){e.has(t)||(t.addDestroyListener(i),e.set(t,i))}_unsubscribeFromDestroy(t,e){const i=e.get(t);i&&(t.removeDestroyListener(i),e.delete(t))}_evictRenderTarget(t,e){const i=this._renderTargetStates.get(t);this._unsubscribeFromDestroy(t,this._renderTargetDestroyHandlers),t instanceof wi&&this._evictTexture(t,!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(t)),this._stencilStates.delete(t),this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget,e&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(t,e){const i=this._textureStates.get(t);this._unsubscribeFromDestroy(t,this._textureDestroyHandlers),i&&(this._texture===t&&(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(t)),this._texture===t&&(this._texture=null),e&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(t){const e=this._prepareRenderTarget(t);if(this._boundFramebuffer!==e.framebuffer||e.version!==t.version){const i=this._context,n=t.getViewport(),s=t.root&&t.width>0?this._canvas.width/t.width:1,r=t.root&&t.height>0?this._canvas.height/t.height:1,o=Math.floor(n.x*s),a=Math.max(0,Math.round(n.width*s)),h=Math.max(0,Math.round(n.height*r)),l=(t.root?this._canvas.height:t.height)-(Math.floor(n.y*r)+h);i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.viewport(o,l,a,h),this._boundFramebuffer=e.framebuffer,e.version=t.version}this._clipPixelStack.length>0&&this._applyClipState()}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(t){const e=this._getRenderTargetState(t);if(t instanceof wi&&e.framebuffer){const i=this._boundFramebuffer,n=this._textureUnit;this._setTextureUnit(15);const s=this._syncTexture(t);if(this._setTextureUnit(n),e.attachedTexture!==s.handle){const t=this._context;t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.handle,0),t.bindFramebuffer(t.FRAMEBUFFER,i),e.attachedTexture=s.handle}this._stencilStates.has(t)||(t.needsStencil=!1),(t.needsStencil||null!==e.stencilRenderbuffer)&&this._syncStencilAttachment(t,e)}return e}_ensureTargetStencil(){const t=this._renderTarget;t.root||(t.needsStencil=!0,this._syncStencilAttachment(t,this._getRenderTargetState(t)))}_syncStencilAttachment(t,e){if(null===e.framebuffer)return;const i=this._context,n=Math.max(1,t.width),s=Math.max(1,t.height);if(null!==e.stencilRenderbuffer&&e.stencilWidth===n&&e.stencilHeight===s)return;null===e.stencilRenderbuffer&&(e.stencilRenderbuffer=i.createRenderbuffer()),i.bindRenderbuffer(i.RENDERBUFFER,e.stencilRenderbuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH24_STENCIL8,n,s),i.bindRenderbuffer(i.RENDERBUFFER,null);const r=this._boundFramebuffer;i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e.stencilRenderbuffer),i.bindFramebuffer(i.FRAMEBUFFER,r),e.stencilWidth=n,e.stencilHeight=s}_getStencilState(t){let e=this._stencilStates.get(t);return void 0===e&&(e={depth:0,stack:[]},this._stencilStates.set(t,e)),e}_applyStencilState(t){const e=this._context,i=this._getStencilState(t).depth;if(0===i)return e.stencilFunc(e.ALWAYS,0,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),void e.disable(e.STENCIL_TEST);e.enable(e.STENCIL_TEST),e.stencilFunc(e.EQUAL,i,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP)}_syncTexture(t){const e=this._context,i=this._getTextureState(t),n=t instanceof wi?t.textureVersion:t.version;if(e.bindTexture(e.TEXTURE_2D,i.handle),i.version!==n){if(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t.wrapMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t.wrapMode),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),t instanceof Os){const n=t.format,s=function(t){const e=WebGL2RenderingContext;switch(t){case"r8":return{internalFormat:e.R8,format:e.RED,type:e.UNSIGNED_BYTE,channels:1};case"r32f":return{internalFormat:e.R32F,format:e.RED,type:e.FLOAT,channels:1};case"rgba8":return{internalFormat:e.RGBA8,format:e.RGBA,type:e.UNSIGNED_BYTE,channels:4};case"rgba32f":return{internalFormat:e.RGBA32F,format:e.RGBA,type:e.FLOAT,channels:4}}}(n),r=t._consumeDirtyRegion(),o=-1===i.version||i.width!==t.width||i.height!==t.height;e.pixelStorei(e.UNPACK_ALIGNMENT,1);const a=uo(n);if(o||null===r||r.full)e.texImage2D(e.TEXTURE_2D,0,s.internalFormat,t.width,t.height,0,s.format,s.type,t.buffer),this._bookTextureStorage(i,t,a),this._accountant.recordTextureUpload(t.width*t.height*a);else{const i=s.channels,n=t.width*i,o=r.width*i,h=t.buffer instanceof Float32Array?new Float32Array(r.width*r.height*i):new Uint8Array(r.width*r.height*i);for(let e=0;e<r.height;e++){const s=(r.y+e)*n+r.x*i,a=e*o;h.set(t.buffer.subarray(s,s+o),a)}e.texSubImage2D(e.TEXTURE_2D,0,r.x,r.y,r.width,r.height,s.format,s.type,h),this._accountant.recordTextureUpload(r.width*r.height*a)}e.pixelStorei(e.UNPACK_ALIGNMENT,4)}else t instanceof wi?-1===i.version||i.width!==t.width||i.height!==t.height||null===t.source?(e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.width,t.height,0,e.RGBA,e.UNSIGNED_BYTE,t.source),this._bookTextureStorage(i,t,To),this._accountant.recordTextureUpload(t.width*t.height*To)):(e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,t.source),this._accountant.recordTextureUpload(t.width*t.height*To)):t.source&&(-1===i.version||i.width!==t.width||i.height!==t.height?(e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source),this._bookTextureStorage(i,t,To)):e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,t.source),this._accountant.recordTextureUpload(t.width*t.height*To));t.generateMipMap&&(t instanceof wi||null!==t.source)&&e.generateMipmap(e.TEXTURE_2D),i.version=n,i.width=t.width,i.height=t.height}return i}_toClipPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(t.right,t.bottom)),n=Math.min(e.x,i.x),s=Math.max(e.x,i.x),r=Math.min(e.y,i.y),o=Math.max(e.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(s))),c=Math.max(0,Math.min(h,Math.floor(r))),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(t,e){const i=Math.max(t.x,e.x),n=Math.max(t.y,e.y),s=Math.min(t.x+t.width,e.x+e.width),r=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:n,width:Math.max(0,s-i),height:Math.max(0,r-n)}}_applyClipState(){const t=this._context;if(0===this._clipPixelStack.length)return void t.disable(t.SCISSOR_TEST);const e=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,s=Math.floor(e.x*i),r=Math.floor(e.y*n),o=Math.max(0,Math.round(e.width*i)),a=Math.max(0,Math.round(e.height*n));t.enable(t.SCISSOR_TEST),t.scissor(s,r,o,a)}}const To=4;class Mo{_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 Le;_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(t){null===this._device&&(this._device=t,this._shaderModule=t.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=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=t.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=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this._pipelineLayout=t.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout,this._blendBindGroupLayout]}),this._vertexBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=t.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._blendBuffer=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._backdropSampler=t.createSampler({magFilter:"nearest",minFilter:"nearest",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this._projectionBindGroup=t.createBindGroup({layout:this._projectionBindGroupLayout,entries:[{binding:0,resource:{buffer:this._projectionBuffer}}]}),this._blendBindGroup=t.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(t,e,i,n,s,r,o){if(null===this._device)throw new Error("WebGpuBackdropBlendCompositor: not connected.");if(s<=0||r<=0)return;const a=this._device,h=t.renderTarget;t.flush();const l=t.renderTargetFormat,u=t._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(s*c),u.width-_)),m=Math.max(0,Math.min(Math.round(r*d),u.height-f));if(p<=0||m<=0)return;const g=this._ensureBackdrop(a,p,m,l),y=a.createCommandEncoder();y.copyTextureToTexture({texture:t._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(t,e,g,i,n,s,r,o,h.root)}_ensureBackdrop(t,e,i,n){return null!==this._backdropTexture&&this._backdropWidth===e&&this._backdropHeight===i&&this._backdropFormat===n||(this._backdropTexture?.destroy(),this._backdropTexture=t.createTexture({size:{width:e,height:i},format:n,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING}),this._backdropView=this._backdropTexture.createView(),this._backdropWidth=e,this._backdropHeight=i,this._backdropFormat=n),this._backdropView}_drawBlend(t,e,i,n,s,r,o,a,h){const l=this._device;this._writeQuadVertices(n,s,n+r,s+o),l.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(t.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=t.getTextureBinding(e),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=t.renderTargetFormat,_=t._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,_),p=t._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),t.stats.batches++,t.stats.drawCalls++,t._passCoordinator.endPass()}_getOrCreatePipeline(t,e){const i=`${t}|${e?"s":"n"}`,n=this._pipelines.get(i);if(void 0!==n)return n;const s=this._device,r={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:kr(qe.Normal)}]},primitive:{topology:"triangle-list"}};e&&(r.depthStencil=Ur());const o=s.createRenderPipeline(r);return this._pipelines.set(i,o),o}_writeQuadVertices(t,e,i,n){const s=this._vertexData;s[0]=t,s[1]=e,s[2]=0,s[3]=0,s[4]=i,s[5]=e,s[6]=1,s[7]=0,s[8]=i,s[9]=n,s[10]=1,s[11]=1,s[12]=t,s[13]=n,s[14]=0,s[15]=1}_writeProjectionMatrix(t){const e=this._projectionMatrix.copy(t),i=this._projectionData;i[0]=e.a,i[1]=e.c,i[2]=0,i[3]=0,i[4]=e.b,i[5]=e.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=0,i[15]=1}}class Ao{_projectionData=new Float32Array(16);_vertexData=new Float32Array(16);_indexData=new Uint16Array([0,1,2,0,2,3]);_projectionMatrix=new Le;_pipelines=new Map;_device=null;_shaderModule=null;_projectionBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_projectionBuffer=null;_projectionBindGroup=null;connect(t){null===this._device&&(this._device=t,this._shaderModule=t.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=t.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=t.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=t.createPipelineLayout({bindGroupLayouts:[this._projectionBindGroupLayout,this._textureBindGroupLayout]}),this._vertexBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._indexBuffer=t.createBuffer({size:6*Uint16Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(this._indexBuffer,0,this._indexData),this._projectionBuffer=t.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._projectionBindGroup=t.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(t,e,i,n,s,r,o,a){if(null===this._device)throw new Error("WebGpuMaskCompositor: not connected.");if(r<=0||o<=0)return;const h=this._device;this._writeQuadVertices(n,s,n+r,s+o),h.queue.writeBuffer(this._vertexBuffer,0,this._vertexData),this._writeProjectionMatrix(t.view.getTransform()),h.queue.writeBuffer(this._projectionBuffer,0,this._projectionData);const l=t.getTextureBinding(e),u=t.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=t.renderTargetFormat,_=t._passCoordinator.stencilActive,f=this._getOrCreatePipeline(d,a,_),p=t._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),t.stats.batches++,t.stats.drawCalls++,t._passCoordinator.endPass()}_getOrCreatePipeline(t,e,i){const n=`${t}|${e}|${i?"s":"n"}`,s=this._pipelines.get(n);if(void 0!==s)return s;const r=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:kr(e)}]},primitive:{topology:"triangle-list"}};i&&(o.depthStencil=Ur());const a=r.createRenderPipeline(o);return this._pipelines.set(n,a),a}_writeQuadVertices(t,e,i,n){const s=this._vertexData;s[0]=t,s[1]=e,s[2]=0,s[3]=0,s[4]=i,s[5]=e,s[6]=1,s[7]=0,s[8]=i,s[9]=n,s[10]=1,s[11]=1,s[12]=t,s[13]=n,s[14]=0,s[15]=1}_writeProjectionMatrix(t){const e=this._projectionMatrix.copy(t),i=this._projectionData;i[0]=e.a,i[1]=e.c,i[2]=0,i[3]=0,i[4]=e.b,i[5]=e.d,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=0,i[15]=1}}class Po{_backend;_stencil=new Ir;_stencilDepths=new Map;_stencilStacks=new Map;_stencilConnected=!1;_stencilWriteInProgress=!1;_stencilLoadOp="load";_stencilRef=0;_active=null;constructor(t){this._backend=t}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 t=this._backend,e=this.stencilActive,i={colorAttachments:[t.createColorAttachment()]};e&&(i.depthStencilAttachment=this._createStencilAttachment(t.renderTarget));const n=t.device.createCommandEncoder(),s=n.beginRenderPass(i);t.stats.renderPasses++;const r=t.getScissorRect();return null!==r&&r.width>0&&r.height>0&&s.setScissorRect(r.x,r.y,r.width,r.height),this._applyViewport(s),e&&s.setStencilReference(this._stencilRef),this._active={encoder:n,pass:s,targetFormat:t.renderTargetFormat,view:t.view,stencilEnabled:e,stencilRef:this._stencilRef},this._active}endPass(){const t=this._active;null!==t&&(this._active=null,t.pass.end(),this._backend.submit(t.encoder.finish()))}beginPass(t){this._backend.setRenderTarget(t.target),this._backend.setView(t.view),"clear"===t.load&&this._backend.clear(t.clearColor??void 0)}withChildPass(t,e){const i=this._backend.renderTarget,n=this._backend.view;this.beginPass(t);try{e()}finally{this._backend.setRenderTarget(i),this._backend.setView(n)}}pushScissorRect(t){this._backend.pushScissorRect(t)}popScissorRect(){this._backend.popScissorRect()}pushStencilClip(t,e){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 s=this.acquirePass();this._stencil.draw(s.pass,s.targetFormat,!0,t,e,s.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(i,n+1),this._stencilRef=n+1,this._getStencilStack(i).push({shape:t,transform:(new Le).copy(e)})}popStencilClip(){const t=this._backend.renderTarget,e=this._stencilStacks.get(t),i=e?.pop();if(void 0===i)return;const n=this._stencilDepths.get(t)??0;this.endPass(),this._stencilWriteInProgress=!0,this._stencilRef=n,this._stencilLoadOp="load";const s=this.acquirePass();this._stencil.draw(s.pass,s.targetFormat,!1,i.shape,i.transform,s.view),this.endPass(),this._stencilWriteInProgress=!1,this._stencilDepths.set(t,n-1),this._stencilRef=n-1}resolveLoad(t,e){return e||!this._backend._targetHasContent(t)?"clear":"load"}releaseStencilTarget(t){this._stencilConnected&&this._stencil.releaseAttachment(t),this._stencilDepths.delete(t),this._stencilStacks.delete(t)}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 t=0;for(const e of this._stencilStacks.values())t+=e.length;return t}_activeTargetDepth(){return this._stencilDepths.get(this._backend.renderTarget)??0}_applyViewport(t){const e=this._backend.view.viewport;if(0===e.x&&0===e.y&&1===e.width&&1===e.height)return;const{width:i,height:n}=this._backend._getAttachmentPixelSize(this._backend.renderTarget),s=Math.floor(e.x*i),r=Math.floor(e.y*n),o=Math.max(1,Math.round(e.width*i)),a=Math.max(1,Math.round(e.height*n));t.setViewport(s,r,o,a,0,1)}_connectStencil(){this._stencilConnected||(this._stencil.connect(this._backend.device),this._stencilConnected=!0)}_getStencilStack(t){let e=this._stencilStacks.get(t);return void 0===e&&(e=[],this._stencilStacks.set(t,e)),e}_createStencilAttachment(t){const{width:e,height:i}=this._backend._getAttachmentPixelSize(t),n=this._stencil.getAttachmentView(t,e,i),s=this._stencilLoadOp;return this._stencilLoadOp="load",{view:n,depthReadOnly:!0,stencilLoadOp:s,stencilStoreOp:"store",stencilClearValue:0}}}class Eo{_buffer=new go;_storageBuffer=null;_storageCapacity=0;_storageHash=0;_storageCount=-1;_needsFullUpload=!1;_accountant=null;_accountedBytes=0;get buffer(){return this._buffer}begin(t=0){this._buffer.begin(t)}writeCommand(t,e){const i=t.drawable;this._buffer.write(t.nodeIndex,e??i.getGlobalTransform(),i.tint)}recordSkippedWrite(){this._buffer.recordSkippedWrite()}push(t,e){return this._buffer.push(e??t.getGlobalTransform(),t.tint)}pushValues(t,e){return this._buffer.push(t,e)}reserve(t,e,i){this._accountant=i??this._accountant;const n=12*Math.max(1,e)*Float32Array.BYTES_PER_ELEMENT;null!==this._storageBuffer&&n<=this._storageCapacity||this._growBuffer(t,n)}getBuffer(t,e,i){this._accountant=i??this._accountant;const n=Math.max(1,e),s=12*n*Float32Array.BYTES_PER_ELEMENT,r=this._buffer.commitSnapshot(n);if((null===this._storageBuffer||s>this._storageCapacity)&&this._growBuffer(t,s),r.changed||r.hash!==this._storageHash||r.count!==this._storageCount){const{firstRow:e,rowCount:i}=this._buffer.consumeDirtyRange(r.count),n=12*Float32Array.BYTES_PER_ELEMENT;this._needsFullUpload?(t.queue.writeBuffer(this._storageBuffer,0,this._buffer.data.buffer,this._buffer.data.byteOffset,r.count*n),this._buffer.recordUpload(r.count),this._accountant?.recordBufferUpload(r.count*n),this._needsFullUpload=!1):i>0&&(t.queue.writeBuffer(this._storageBuffer,e*n,this._buffer.data.buffer,this._buffer.data.byteOffset+e*n,i*n),this._buffer.recordUpload(i),this._accountant?.recordBufferUpload(i*n)),this._storageHash=r.hash,this._storageCount=r.count}return{buffer:this._storageBuffer,count:r.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(t,e){let i=Math.max(this._storageCapacity,12*Float32Array.BYTES_PER_ELEMENT);for(;i<e;)i*=2;this._storageBuffer?.destroy(),this._storageBuffer=t.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 ko="rgba8unorm";class Ro{backendType=tr.WebGpu;rendererRegistry=new fo;onDeviceLost=new w;onDeviceRestored=new w;_canvas;_rootRenderTarget;_clearColor=new Re;_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 ie;_clipPointB=new ie;_maskCompositor=new Ao;_maskCompositorConnected=!1;_backdropBlendCompositor=new Mo;_backdropBlendCompositorConnected=!1;_mipmapShaderModule=null;_mipmapBindGroupLayout=null;_mipmapPipelineLayout=null;_mipmapPipeline=null;_mipmapSampler=null;_context=null;_device=null;_format=null;_initializePromise=null;_renderTarget;_snapTransform=new Le;_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 ho(this._stats);_transformStorage=new Eo;_activeDrawCommand=null;_passCoordinatorInstance=null;_drawPlanDepth=0;_planBaseStack=[];_planHashStack=[];constructor(t){const e=t.options.canvas??{},i=e.width??800,n=e.height??600,s=t.options.clearColor;this._canvas=t.canvas,this._rootRenderTarget=new yi(i,n,!0),this._renderTarget=this._rootRenderTarget,s&&this._clearColor.copy(s),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:ko}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 Po(this)}get clearColor(){return this._clearColor}get deviceLost(){return this._deviceLost}setClearColor(t){return this._clearColor.copy(t),this}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(t=>{throw this._initializePromise=null,t})),this._initializePromise}resetStats(){return oo(this._stats),this._getTransformStorage().buffer.begin(),this}get transformBufferCount(){return this._getTransformStorage().buffer.count}_beginDrawPlan(t){const e=this._getTransformStorage();this._planBaseStack.push(e.buffer.count),this._planHashStack.push(e.buffer.frameHash);const i=e.buffer.count+t;i>0&&null!==this._device&&!this._deviceLost&&e.reserve(this._device,i,this._accountant),this._activeDrawCommand=null,this._drawPlanDepth++}_prepareRenderGroupUpload(t,e,i){const n=this._getTransformStorage(),s=e+i;for(let i=e;i<s;i++){const e=t[i];if(e.kind!==Qe.Draw)continue;const s=e.command;hi(s,this)?n.writeCommand(s,this._resolveSnapTransform(s.drawable)):n.recordSkippedWrite()}}_prepareDrawCommand(t){this._activeDrawCommand=t}_endDrawPlan(){this._activeDrawCommand=null;const t=this._planBaseStack.pop()??0,e=this._planHashStack.pop()??0;if(this._drawPlanDepth>0&&this._drawPlanDepth--,this._drawPlanDepth>0&&(this._flushActiveRenderer(),this._getTransformStorage().buffer.rewindTo(t,e)),0===this._drawPlanDepth&&null!==this._passCoordinatorInstance){const t=this._passCoordinatorInstance.unbalancedStencilClips();if(t>0)throw this._passCoordinatorInstance.resetStencil(),new Error(`Unbalanced stencil clip stack at end of frame (${t} unpopped clip(s)).`)}}draw(t){if(this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._activeDrawCommand=null,this._stats.submittedNodes++,this}drawInstanced(t,e,i,n){if(n<=0||0===t.vertexCount||this._deviceLost||null===this._device)return this._activeDrawCommand=null,this;const s=this.rendererRegistry.resolve(t);if(!(s instanceof Or))throw new Error("drawInstanced requires a mesh handled by the WebGPU mesh renderer.");this._setActiveRenderer(s);const r=this._getTransformStorage(),o=r.pushValues(e[0],i[0]);for(let t=1;t<n;t++)r.pushValues(e[t],i[t]);return s.drawInstancedBatch(t,o,n),this._activeDrawCommand=null,this._stats.submittedNodes+=n,this}execute(t){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this)),this}setBlendMode(t){return this}setRenderTarget(t){const e=t??this._rootRenderTarget;return this._renderTarget!==e&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=e,this._stats.renderTargetChanges++,e!==this._rootRenderTarget&&this._subscribeRenderTarget(e)),this}pushScissorRect(t){this._flushActiveRenderer(),this._clipBoundsStack.push(t.clone());const e=this._toClipPixels(t),i=this._clipPixelStack.length>0?this._clipPixelStack[this._clipPixelStack.length-1]:null,n=i?this._intersectClips(i,e):e;return this._clipPixelStack.push(n),this}composeWithAlphaMask(t,e,i,n,s,r,o){return s<=0||r<=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,t,e,i,n,s,r,o)),this}composeWithBackdropBlend(t,e,i,n,s,r){return n<=0||s<=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,t,e,i,n,s,r)),this}_renderTargetTexture(t){if(t===this._rootRenderTarget)return this.context.getCurrentTexture();if(t instanceof wi)return this._getTextureState(t).texture;throw new Error("WebGpuBackend._renderTargetTexture: unsupported render target type.")}popScissorRect(){if(0===this._clipBoundsStack.length)return this;this._flushActiveRenderer();const t=this._clipBoundsStack.pop();return t&&t.destroy(),this._clipPixelStack.pop(),this}pushStencilClip(t,e){return this._deviceLost||null===this._device||(this._flushActiveRenderer(),this._setActiveRenderer(null),this._passCoordinator.pushStencilClip(t,e)),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 t=this._clipPixelStack[this._clipPixelStack.length-1],e=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(t.x*e),y:Math.floor(t.y*i),width:Math.max(0,Math.round(t.width*e)),height:Math.max(0,Math.round(t.height*i))}}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const n=this._temporaryRenderTextures[i];if(n.width===t&&n.height===e)return this._temporaryRenderTextures.splice(i,1),n}return new wi(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._renderTarget.view!==t&&this._flushActiveRenderer(),this._renderTarget.setView(t),this}clear(t){return t&&this.setClearColor(t),this._clearRequested=!0,this}resize(t,e){return this._rootRenderTarget.resize(t,e),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 t of this._clipBoundsStack)t.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 t of[...this._renderTargetDestroyHandlers.keys()])this._unsubscribeRenderTarget(t);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 t=this._renderTarget;let e;if(t===this._rootRenderTarget)e=this.context.getCurrentTexture().createView();else{if(!(t instanceof wi))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");e=this._syncTexture(t).view}const i=this._passCoordinator.resolveLoad(t,this._clearRequested);return this._clearRequested=!1,{view:e,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(t){if(this.device.queue.submit([t]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof wi){const t=this._syncTexture(this._renderTarget);t.hasContent=!0,t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}}_targetHasContent(t){return t===this._rootRenderTarget?this._hasPresentedFrame:t instanceof wi&&this._getTextureState(t).hasContent}_getAttachmentPixelSize(t){return t===this._rootRenderTarget?{width:this._canvas.width,height:this._canvas.height}:{width:t.width,height:t.height}}getTextureBinding(t){const e=this._syncTexture(t);return{view:e.view,sampler:e.sampler}}getTextureFormat(t){return this._getGpuTextureFormat(t)}shouldPremultiplyTextureSample(t){return!(t instanceof wi)&&t.premultiplyAlpha}getTransformStorageBuffer(t){return this._getTransformStorage().getBuffer(this.device,t,this._accountant)}_pushTransform(t){return this._getTransformStorage().push(t,this._resolveSnapTransform(t))}_resolveSnapTransform(t){const e=this._renderTarget,i=e===this._rootRenderTarget,n=i?this._canvas.width:e.width,s=i?this._canvas.height:e.height;return On(t,e.view,n,s,this._snapTransform)}_getSnapPixelSize(){return this._getAttachmentPixelSize(this._renderTarget)}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer?.flush()}_getTransformStorage(){return null!==this._transformStorage&&void 0!==this._transformStorage||(this._transformStorage=new Eo),this._transformStorage}async _initialize(){const t=this._getGpuNavigator();if(null===t)throw new Error("This browser does not support WebGPU.");if("function"!=typeof t.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof t.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");let e,i;try{e=await t.gpu.requestAdapter()}catch(t){throw this._createInitializationError("Failed to request a WebGPU adapter.",t)}if(null===e)throw new Error("Could not acquire a WebGPU adapter.");if("function"!=typeof e.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");try{i=await e.requestDevice()}catch(t){throw this._createInitializationError("Failed to request a WebGPU device.",t)}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 s=t.gpu.getPreferredCanvasFormat();try{n.configure({device:i,format:s,alphaMode:"opaque",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}this._context=n,this._device=i,this._format=s,this._hasPresentedFrame=!1,this._subscribeToDeviceLoss(),this.rendererRegistry.connect(this),this.resize(this._rootRenderTarget.width,this._rootRenderTarget.height);const r=[s,ko];return await this._prewarmRendererPipelines(r),this}_subscribeToDeviceLoss(){if(!this._device)return;const t=this._device;t.lost.then(e=>{this._destroyed||this._device!==t||this._handleDeviceLoss(e)})}_handleDeviceLoss(t){this._deviceLost=!0,this.onDeviceLost.dispatch(t),"destroyed"!==t.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 t=this._recoveryBackoffMs*Math.pow(2,this._recoveryAttempt-1);await new Promise(e=>{setTimeout(e,t)})}}}finally{this._isRecovering=!1}}}_teardownDeviceState(){for(const[t,e]of this._textureDestroyHandlers)t.removeDestroyListener(e);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(t){const e=[];for(const i of this.rendererRegistry.renderers()){const n=i;"function"==typeof n.prewarmPipelines&&e.push(n.prewarmPipelines(t))}await Promise.all(e)}_getGpuNavigator(){const t=navigator;return t.gpu?t:null}_createInitializationError(t,e){return e instanceof Error&&e.message.length>0?new Error(`${t} ${e.message}`):new Error(t)}_destroyManagedTextures(){for(const t of[...this._textureStates.keys()])this._evictTexture(t)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getTextureState(t){let e=this._textureStates.get(t);if(!e){const i=this.device.createTexture({size:{width:Math.max(t.width,1),height:Math.max(t.height,1)},format:this._getGpuTextureFormat(t),mipLevelCount:this._getMipLevelCount(t),usage:this._getTextureUsage(t)}),n=this._getMipLevelCount(t);e={texture:i,view:i.createView(),sampler:this._createSampler(t),version:-1,width:t.width,height:t.height,mipLevelCount:n,hasContent:!1,accountedBytes:0},e.accountedBytes=this._accountant.reallocate(0,this._estimateTextureBytes(t,n));const s=()=>{this._evictTexture(t)};t.addDestroyListener(s),this._textureDestroyHandlers.set(t,s),this._textureStates.set(t,e)}return e}_syncTexture(t){if(!(t instanceof wi||t instanceof Os||null!==t.source&&0!==t.width&&0!==t.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const e=this._getTextureState(t),i=t instanceof wi?t.textureVersion:t.version,n=this._getMipLevelCount(t);if(e.version!==i){if(e.width!==t.width||e.height!==t.height||e.mipLevelCount!==n){e.texture.destroy();const i=this.device.createTexture({size:{width:t.width,height:t.height},format:this._getGpuTextureFormat(t),mipLevelCount:n,usage:this._getTextureUsage(t)});e.texture=i,e.view=i.createView(),e.width=t.width,e.height=t.height,e.mipLevelCount=n,e.hasContent=!1,e.accountedBytes=this._accountant.reallocate(e.accountedBytes,this._estimateTextureBytes(t,n))}if(e.sampler=this._createSampler(t),t instanceof Os){const i=Do(t.format),n=t._consumeDirtyRegion();if(null===n||n.full||!e.hasContent)this.device.queue.writeTexture({texture:e.texture},t.buffer,{bytesPerRow:t.width*i.bytesPerPixel,rowsPerImage:t.height},{width:t.width,height:t.height}),this._accountant.recordTextureUpload(t.width*t.height*i.bytesPerPixel);else{const s=i.channels,r=i.bytesPerPixel,o=n.width*n.height*r,a=t.buffer instanceof Float32Array?new Float32Array(o/4):new Uint8Array(o),h=t.width*s,l=n.width*s;for(let e=0;e<n.height;e++){const i=(n.y+e)*h+n.x*s,r=e*l;a.set(t.buffer.subarray(i,i+l),r)}this.device.queue.writeTexture({texture:e.texture,origin:{x:n.x,y:n.y}},a,{bytesPerRow:n.width*r,rowsPerImage:n.height},{width:n.width,height:n.height}),this._accountant.recordTextureUpload(n.width*n.height*r)}e.hasContent=!0}else if(!(t instanceof wi)){const i=t.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:e.texture},{width:t.width,height:t.height}),this._accountant.recordTextureUpload(t.width*t.height*4),e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}e.version=i}return e}_evictTexture(t){const e=this._textureStates.get(t),i=this._textureDestroyHandlers.get(t);i&&(t.removeDestroyListener(i),this._textureDestroyHandlers.delete(t)),e&&(e.texture.destroy(),this._accountant.free(e.accountedBytes),e.accountedBytes=0,this._textureStates.delete(t)),this._texture===t&&(this._texture=null)}_subscribeRenderTarget(t){if(!this._renderTargetDestroyHandlers.has(t)){const e=()=>{this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget),this._passCoordinatorInstance?.releaseStencilTarget(t),this._renderTargetDestroyHandlers.delete(t)};t.addDestroyListener(e),this._renderTargetDestroyHandlers.set(t,e)}}_unsubscribeRenderTarget(t){const e=this._renderTargetDestroyHandlers.get(t);e&&(t.removeDestroyListener(e),this._renderTargetDestroyHandlers.delete(t))}_toClipPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._clipPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._clipPointB.set(t.right,t.bottom)),n=Math.min(e.x,i.x),s=Math.max(e.x,i.x),r=Math.min(e.y,i.y),o=Math.max(e.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(s))),c=Math.max(0,Math.min(h,Math.floor(r))),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(t,e){const i=Math.max(t.x,e.x),n=Math.max(t.y,e.y),s=Math.min(t.x+t.width,e.x+e.width),r=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:n,width:Math.max(0,s-i),height:Math.max(0,r-n)}}_createSampler(t){const e=t instanceof Os&&("r32f"===t.format||"rgba32f"===t.format),i=e?"nearest":this._getFilterMode(t.scaleMode);return this.device.createSampler({addressModeU:this._getAddressMode(t.wrapMode),addressModeV:this._getAddressMode(t.wrapMode),magFilter:i,minFilter:i,mipmapFilter:e?"nearest":this._getMipmapFilterMode(t.scaleMode)})}_getGpuTextureFormat(t){if(t instanceof Os){return Do(t.format).gpuFormat}return ko}_getTextureUsage(t){const e=this._getMipLevelCount(t)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return t instanceof wi?GPUTextureUsage.COPY_SRC|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|e:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|e}_getAddressMode(t){switch(t){case $e.Repeat:return"repeat";case $e.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case Ye.Nearest:case Ye.NearestMipmapNearest:case Ye.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case Ye.NearestMipmapLinear:case Ye.LinearMipmapLinear:return"linear";default:return"nearest"}}_textureBytesPerPixel(t){if(t instanceof Os){const e=t.format;return uo(e)}return 4}_estimateTextureBytes(t,e){return lo(t.width,t.height,this._textureBytesPerPixel(t),e)}_getMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_generateMipmaps(t,e){if(e<=1)return;const i=this._getMipmapResources(),n=this.device.createCommandEncoder();for(let s=1;s<e;s++){const e=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:t.createView({baseMipLevel:s-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),r=n.beginRenderPass({colorAttachments:[{view:t.createView({baseMipLevel:s,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});r.setPipeline(i.pipeline),r.setBindGroup(0,e),r.draw(3),r.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:ko,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 Do(t){switch(t){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 Io extends Ps{onStart=new w;onStop=new w;_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=t=>{I.remove(this._onAudioContextReady),this.setupWithAudioContext(t)};constructor(t,e,i){super(new vi(t,i));const{duration:n,volume:s,playbackRate:r,loop:o,muted:a}=t;this._videoElement=t,this._duration=n,this._volume=s,this._playbackRate=r,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)),e&&this.applyOptions(e),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 t=this.currentTime,e=this.duration;return t%e/e}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get paused(){return this._videoElement.paused}set paused(t){t?this.pause():this.play()}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}get bus(){return this._bus}set bus(t){if(this._bus!==t&&(this._audioSetup&&this._audioSetup.gainNode.disconnect(),this._bus=t,this._audioSetup)){const e=t._getInputNode();e?this._audioSetup.gainNode.connect(e):this._audioSetup.gainNode.connect(this._audioSetup.audioContext.destination)}}play(t){return t&&this.applyOptions(t),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:n,time:s,muted:r}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==n&&(this.playbackRate=n),void 0!==s&&(this.currentTime=s),void 0!==r&&(this.muted=r),this}setVolume(t){const e=Y(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,.01)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._videoElement.loop=t),this}setPlaybackRate(t){const e=Y(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._videoElement.playbackRate=e),this}getTime(){return this._videoElement.currentTime}setTime(t){return this._videoElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,.01)}return this}_collect(t,e){this.visible&&(this._markTextureDirtyOnPlaybackAdvance(),this.updateTexture()),super._collect(t,e)}updateTexture(){const t=this.texture;if(!t||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const e=this.textureFrame.width>0&&this.textureFrame.height>0;return t.updateSource(),t.width>0&&t.height>0&&this.setTextureFrame(te.temp.set(0,0,t.width,t.height),!e),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(t,e){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyOnPlaybackAdvance(){const t=this._videoElement.currentTime;this._lastVideoTime!==t&&(this._lastVideoTime=t,this._textureDirty=!0)}_requestVideoFrameCallback(){const t=this._videoElement;t.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=t.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const t=this._videoElement;t.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(t.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext=t=>{const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,.01);const i=this.bus?._getInputNode()??null;i?e.connect(i):e.connect(t.destination);const n=t.createMediaElementSource(this._videoElement);n.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:n}}}class Lo{_objectUrls=[];createObjectUrl(t){const e=URL.createObjectURL(t);return this._objectUrls.push(e),e}revokeObjectUrl(t){URL.revokeObjectURL(t);const e=this._objectUrls.indexOf(t);-1!==e&&this._objectUrls.splice(e,1)}destroy(){for(const t of this._objectUrls)URL.revokeObjectURL(t);this._objectUrls.length=0}}class Uo extends Lo{storageName="binary";async process(t){return t.arrayBuffer()}async create(t){return t}}function Fo(t,e){const i=t.match(new RegExp(`\\b${e}=(-?\\d+)`));return void 0!==i?.[1]?parseInt(i[1],10):0}function Go(t,e){const i=t.match(new RegExp(`\\b${e}="([^"]*)"`));if(void 0!==i?.[1])return i[1];const n=t.match(new RegExp(`\\b${e}=(\\S+)`));return n?.[1]??""}function No(t){const e=t.split(/\r?\n/),i=[],n=new Map,s=new Map;let r=0,o=0;for(const t of e){const e=t.trim();if(0===e.length)continue;switch(e.split(/\s/)[0]??""){case"common":r=Fo(e,"lineHeight"),o=Fo(e,"base");break;case"page":{const t=Fo(e,"id"),n=Go(e,"file");i[t]=n;break}case"char":{const t=Fo(e,"id");n.set(t,{x:Fo(e,"x"),y:Fo(e,"y"),width:Fo(e,"width"),height:Fo(e,"height"),xOffset:Fo(e,"xoffset"),yOffset:Fo(e,"yoffset"),xAdvance:Fo(e,"xadvance"),page:Fo(e,"page")});break}case"kerning":{const t=Fo(e,"first"),i=Fo(e,"second"),n=Fo(e,"amount");s.set(`${t},${i}`,n);break}}}return{pages:i,chars:n,kernings:s,lineHeight:r,base:o}}class Oo extends Lo{storageName="bmfont";_loader;constructor(t){super(),this._loader=t}async process(t){return{text:await t.text(),url:t.url}}async create(t){const{text:e,url:i}=t,n=No(e),s=await Promise.all(n.pages.map(t=>this._loader.load(vi,new URL(t,i).href)));return new ks(n,s)}}class Vo extends Lo{storageName="csv";async process(t){return t.text()}async create(t,e={}){const i=e.delimiter??",",n=[],s=t.replaceAll("\r\n","\n").replaceAll("\r","\n");let r=[],o="",a=!1,h=0;for(;h<s.length;){const t=s[h];a?'"'===t?'"'===s[h+1]?(o+='"',h+=2):(a=!1,h++):(o+=t,h++):'"'===t?(a=!0,h++):t===i?(r.push(o),o="",h++):"\n"===t?(r.push(o),o="",n.push(r),r=[],h++):(o+=t,h++)}return r.push(o),r.some(t=>""!==t)&&n.push(r),n}}class zo extends Lo{storageName="font";_addedFontFaces=[];async process(t){return t.arrayBuffer()}async create(t,e){if(!e?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:n,addToDocument:s}=e;if(t.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${t.byteLength}.`);const r=await new FontFace(i,t,n).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${t.byteLength} bytes).`)});return!1!==s&&(document.fonts.add(r),this._addedFontFaces.push(r)),r}destroy(){for(const t of this._addedFontFaces)document.fonts.delete(t);this._addedFontFaces.length=0,super.destroy()}}const qo=[{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]}],Wo=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of qo)if(!(e.length<t.pattern.length)&&t.pattern.every((i,n)=>((e[n]??0)&(t.mask[n]??0))===i))return t.mimeType;return(t=>{const e=new Uint8Array(t),i=new DataView(t).getUint32(0,!1);return!(e.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...e.subarray(4,11))})(t)?"video/mp4":(t=>{const e=new Uint8Array(t),i=[26,69,223,163].every((t,i)=>t===e[i]),n=e.subarray(4,4100),s=n.findIndex((t,e,i)=>66===i[e]&&130===i[e+1]);return!(!i||-1===s)&&"webm"===String.fromCharCode(...n.subarray(s+3,s+7))})(t)?"video/webm":(t=>{if(t.byteLength<12)return!1;const e=new Uint8Array(t);if("ftyp"!==String.fromCharCode(e[4]??0,e[5]??0,e[6]??0,e[7]??0))return!1;const i=String.fromCharCode(e[8]??0,e[9]??0,e[10]??0,e[11]??0);return"avif"===i||"avis"===i})(t)?"image/avif":"text/plain"};class Yo extends Lo{storageName="image";async process(t){return t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??Wo(t)});if("function"==typeof createImageBitmap)return createImageBitmap(i);const n=this.createObjectUrl(i);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{s(),t(i)},{once:!0}),i.addEventListener("error",()=>{s(),e(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(new Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const $o={once:!0};class Xo extends Lo{storageName="music";_audioElements=[];async process(t){return t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:n,playbackOptions:s,stallTimeout:r}=e,o=new Blob([t],{type:i??Wo(t)}),a=this.createObjectUrl(o);return new Promise((t,e)=>{const i=document.createElement("audio");let o;this._audioElements.push(i);let h=!1;const l=t=>{h||(h=!0,void 0!==o&&(clearTimeout(o),o=void 0),this.revokeObjectUrl(a),t())};i.addEventListener("error",()=>l(()=>e(new Error("Error loading audio source."))),$o),i.addEventListener("abort",()=>l(()=>e(new Error("Audio loading was canceled."))),$o),i.addEventListener("emptied",()=>l(()=>e(new Error("Audio loading was emptied."))),$o),i.addEventListener(n??"canplaythrough",()=>l(()=>t(new me(i,s))),$o),void 0!==r&&i.addEventListener("stalled",()=>{h||(void 0!==o&&clearTimeout(o),o=setTimeout(()=>l(()=>e(new Error("Audio loading stalled."))),r))}),i.preload="auto",i.src=a})}destroy(){for(const t of this._audioElements)t.pause(),t.src="",t.load();this._audioElements.length=0,super.destroy()}}class Ho extends Lo{storageName="sound";async process(t){return t.arrayBuffer()}async create(t,e={}){const i=await G(t);return new le(i,{...e.playbackOptions,...void 0!==e.poolSize&&{poolSize:e.poolSize},...void 0!==e.sprites&&{sprites:e.sprites}})}}const jo=t=>{const e=t.split(":");let i;return i=3===e.length?3600*Number(e[0])+60*Number(e[1])+Number(e[2]):2===e.length?60*Number(e[0])+Number(e[1]):Number(e[0]),i},Ko=new Set(["start","center","end","left","right"]),Qo=new Set(["start","center","end"]),Zo=new Set(["auto","line-left","center","line-right"]),Jo=(t,e)=>{if(e)for(const i of e.split(/\s+/)){const e=i.indexOf(":");if(-1===e)continue;const n=i.slice(0,e),s=i.slice(e+1);switch(n){case"vertical":"rl"!==s&&"lr"!==s&&""!==s||(t.vertical=s);break;case"line":if("auto"===s)t.line="auto";else{const[e="",i]=s.split(","),n=parseFloat(e);Number.isNaN(n)||(t.line=n),void 0!==i&&Qo.has(i)&&(t.lineAlign=i)}break;case"position":{const[e="",i]=s.split(","),n=parseFloat(e);Number.isNaN(n)||(t.position=n),void 0!==i&&Zo.has(i)&&(t.positionAlign=i);break}case"size":{const e=parseFloat(s);Number.isNaN(e)||(t.size=e);break}case"align":Ko.has(s)&&(t.align=s)}}},ta=t=>{const e=t.trim().replace(",",".").split(":");return 3600*Number(e[0])+60*Number(e[1])+Number(e[2])};class ea extends Lo{storageName="subtitle";async process(t){const e=await t.text();return{fmt:(t.url.split("?")[0]??t.url).toLowerCase().endsWith(".srt")?"srt":"vtt",text:e}}async create(t){return"srt"===t.fmt?(t=>{const e=[],i=t.replaceAll("\r\n","\n").replaceAll("\r","\n").split(/\n[ \t]*\n/);for(const t of i){const i=t.trim().split("\n");if(i.length<2)continue;let n=0;/^\d+$/.test((i[0]??"").trim())&&(n=1);const s=i[n];if(!s?.includes("--\x3e"))continue;const r=s.indexOf("--\x3e"),o=ta(s.slice(0,r)),a=ta(s.slice(r+3)),h=i.slice(n+1).join("\n");e.push(new VTTCue(o,a,h))}return e})(t.text):(t=>{const e=[],i=t.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 t=(i[n]??"").trim();if(t.includes("--\x3e")){const s=t.indexOf("--\x3e"),r=t.slice(0,s).trim(),o=t.slice(s+3).trim().split(/\s+/),a=o[0]??"",h=o.slice(1).join(" "),l=jo(r),u=jo(a);n++;const c=[];for(;n<i.length;){const t=i[n];if(void 0===t||""===t.trim())break;c.push(t),n++}const d=new VTTCue(l,u,c.join("\n"));Jo(d,h),e.push(d)}else n++}return e})(t.text)}}class ia extends Lo{storageName="svg";async process(t){return t.text()}async create(t,e={}){const{width:i,height:n}=e;let s=t;if(void 0!==i||void 0!==n){const t=s.indexOf("<svg"),e=s.indexOf(">",t);if(-1!==t&&-1!==e){const r=s.slice(0,t),o=s.slice(t+4,e),a=s.slice(e+1);s=`${r}<svg${String(o).replaceAll(/\s+width=(?:"[^"]*"|'[^']*')/g,"").replaceAll(/\s+height=(?:"[^"]*"|'[^']*')/g,"")}${(void 0!==i?` width="${i}"`:"")+(void 0!==n?` height="${n}"`:"")}>${a}`}}const r=new Blob([s],{type:"image/svg+xml"}),o=this.createObjectUrl(r);return new Promise((t,e)=>{const i=new Image,n=()=>{this.revokeObjectUrl(o)};i.addEventListener("load",()=>{n(),t(i)},{once:!0}),i.addEventListener("error",()=>{n(),e(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{n(),e(new Error("Image loading was canceled."))},{once:!0}),i.src=o})}}class na extends Lo{storageName="texture";async process(t){return t.arrayBuffer()}async create(t,e={}){const{mimeType:i,samplerOptions:n}=e,s=new Blob([t],{type:i??Wo(t)});if("function"==typeof createImageBitmap){const t=await createImageBitmap(s);return new vi(t,n)}const r=this.createObjectUrl(s);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(r)};i.addEventListener("load",()=>{s(),t(new vi(i,n))},{once:!0}),i.addEventListener("error",()=>{s(),e(new Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(new Error("Image loading was canceled."))},{once:!0}),i.src=r})}}const sa={once:!0};class ra extends Lo{storageName="video";_videoElements=[];async process(t){return t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:n,playbackOptions:s,samplerOptions:r,stallTimeout:o}=e,a=new Blob([t],{type:i??Wo(t)}),h=this.createObjectUrl(a);return new Promise((t,e)=>{const i=document.createElement("video");let a;this._videoElements.push(i);let l=!1;const u=t=>{l||(l=!0,void 0!==a&&(clearTimeout(a),a=void 0),this.revokeObjectUrl(h),t())};i.addEventListener("error",()=>u(()=>e(new Error("Video loading error."))),sa),i.addEventListener("abort",()=>u(()=>e(new Error("Video loading error: cancelled."))),sa),i.addEventListener("emptied",()=>u(()=>e(new Error("Video loading error: emptied."))),sa),i.addEventListener(n??"canplaythrough",()=>u(()=>t(new Io(i,s,r))),sa),void 0!==o&&i.addEventListener("stalled",()=>{l||(void 0!==a&&clearTimeout(a),a=setTimeout(()=>u(()=>e(new Error("Video loading stalled."))),o))}),i.preload="auto",i.src=h})}destroy(){for(const t of this._videoElements)t.pause(),t.src="",t.load();this._videoElements.length=0,super.destroy()}}class oa extends Lo{storageName="wasm";async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}class aa extends Lo{storageName="xml";async process(t){return t.text()}async create(t){const e=(new DOMParser).parseFromString(t,"text/xml"),i=e.querySelector("parsererror");if(i)throw new Error(`XML parse error: ${i.textContent.trim()||"unknown error"}`);return e}}class ha{}class la{}class ua{}class ca{}class da{}class _a{}class fa{}class pa{}class ma{}class ga{}function ya(t){return()=>{const e=t();return{async load({source:t,options:i},n){const s=await n.fetchArrayBuffer(t);return e.create(s,i)},createFromBytes:(t,i)=>e.create(t,i),destroy(){e.destroy()}}}}function wa(t){return()=>{const e=t();return{async load({source:t,options:i},n){const s=await n.fetchText(t);return e.create(s,i)},createFromBytes:(t,i)=>e.create((new TextDecoder).decode(t),i),destroy(){e.destroy()}}}}function xa(t,e,i){return{type:t,...e,create:i}}const va=xa(vi,{typeNames:["texture"]},ya(()=>new na)),ba=xa(le,{typeNames:["sound"]},ya(()=>new Ho)),Sa=xa(me,{typeNames:["music"]},ya(()=>new Xo)),Ba=xa(Io,{typeNames:["video"]},ya(()=>new ra)),Ca=xa(ha,{typeNames:["json"]},()=>({load:async({source:t},e)=>e.fetchJson(t),createFromBytes:t=>Promise.resolve(JSON.parse((new TextDecoder).decode(t)))})),Ta=xa(la,{typeNames:["text"]},()=>({load:async({source:t},e)=>e.fetchText(t),createFromBytes:t=>Promise.resolve((new TextDecoder).decode(t))})),Ma=xa(ua,{typeNames:["svg"]},wa(()=>new ia)),Aa=xa(ca,{typeNames:["vtt","srt"]},()=>{const t=new ea;return{async load({source:e},i){const n=await i.fetchText(e),s=(e.split("?")[0]??e).toLowerCase().endsWith(".srt")?"srt":"vtt",r=await t.process({text:()=>Promise.resolve(n),url:e});return t.create({...r,fmt:s})},destroy(){t.destroy()}}}),Pa=xa(da,{typeNames:["xml"]},wa(()=>new aa)),Ea=xa(_a,{typeNames:["csv"]},wa(()=>new Vo)),ka=xa(ma,{typeNames:["binary"]},ya(()=>new Uo)),Ra=xa(ks,{typeNames:["bmFont"],extensions:["fnt"]},t=>({async load({source:e},i){const n=No(await i.fetchText(e)),s=await Promise.all(n.pages.map(i=>t.load(vi,function(t,e){if(/^(?:[a-z][a-z\d+.-]*:|\/\/|\/)/i.test(t))return t;try{return new URL(t,e).href}catch{const i="https://exojs.invalid/",n=new URL(t,i+e.replace(/^\/+/,"")).href.slice(i.length);return e.startsWith("/")?`/${n}`:n}}(i,e))));return new ks(n,s)}})),Da=[];"undefined"!=typeof FontFace&&Da.push(xa(pa,{typeNames:["font"],extensions:["woff","woff2","ttf","otf"]},ya(()=>new zo))),"undefined"!=typeof HTMLImageElement&&Da.push(xa(fa,{typeNames:["image"]},ya(()=>new Yo))),"undefined"!=typeof WebAssembly&&Da.push(xa(ga,{typeNames:["wasm"]},ya(()=>new oa)));const Ia=Object.freeze([va,ba,Sa,Ba,Ca,Ta,Ma,Aa,Pa,Ea,ka,Ra,...Da]);class La{_config;constructor(t){this._config=t}get type(){return this._config.type}get source(){return this._config.source}}const Ua=La,Fa="EXOA";function Ga(t){throw new Error(`Invalid asset container: ${t}.`)}function Na(t){t.byteLength<12&&Ga(`buffer too small for a 12-byte header (got ${t.byteLength})`);const e=new Uint8Array(t),i=new DataView(t);for(let t=0;t<4;t++)e[t]!==Fa.charCodeAt(t)&&Ga(`bad magic (expected "${Fa}")`);const n=i.getUint32(4,!0);n>1&&Ga(`unsupported version ${n} (this build reads up to 1)`);const s=i.getUint32(8,!0),r=12+s;let o;r>t.byteLength&&Ga(`index length ${s} runs past the buffer (size ${t.byteLength})`);try{o=JSON.parse((new TextDecoder).decode(e.subarray(12,r)))}catch{Ga("index is not valid JSON")}Array.isArray(o)||Ga("index is not an array");const a=t.byteLength-r,h=o.map((t,e)=>function(t,e,i){"object"==typeof t&&null!==t||Ga(`index entry ${e} is not an object`);const n=t,{alias:s,type:r,offset:o,length:a,mime:h}=n;return"string"!=typeof s&&Ga(`index entry ${e} has a non-string "alias"`),"string"!=typeof r&&Ga(`index entry ${e} ("${s}") has a non-string "type"`),("number"!=typeof o||!Number.isFinite(o)||o<0)&&Ga(`index entry "${s}" has an invalid "offset"`),("number"!=typeof a||!Number.isFinite(a)||a<0)&&Ga(`index entry "${s}" has an invalid "length"`),o+a>i&&Ga(`index entry "${s}" runs past the data section (offset ${o} + length ${a} > ${i})`),void 0!==h&&"string"!=typeof h&&Ga(`index entry "${s}" has a non-string "mime"`),{alias:s,type:r,offset:o,length:a,..."string"==typeof h&&{mime:h},...void 0!==n.options&&{options:n.options}}}(t,e,a));return{version:n,entries:h,dataStart:r}}class Oa extends Error{bundle;failures;constructor(t,e){super(`Failed to load bundle "${t}" (${e.length} failure${1===e.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=t,this.failures=e}}function Va(t){return function(t){if(!za(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!za(t.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[e,i]of Object.entries(t.bundles)){if(0===e.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 "${e}" must be an array of entries.`);const t=new Map;for(const[n,s]of i.entries()){const i=`bundle "${e}" entry[${n}]`;if(!za(s))throw new Error(`Invalid asset manifest: ${i} must be an object.`);if("function"!=typeof s.type)throw new Error(`Invalid asset manifest: ${i} has an invalid "type" token.`);qa(s.alias,`${i} has an invalid "alias".`),qa(s.path,`${i} has an invalid "path".`);const r=s.type,o=s.alias;t.has(r)||t.set(r,new Set);const a=t.get(r);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${Wa(r)}, "${o}") in bundle "${e}".`);a.add(o)}}}(t),t}function za(t){return"object"==typeof t&&null!==t}function qa(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function Wa(t){return t.name.length>0?t.name:"(anonymous type)"}class Ya{entries;constructor(t){if(Object.hasOwn(t,"entries"))throw new Error('An Assets container may not define an asset named "entries": that name is reserved for the spread-composition helper.');const e={};for(const i of Object.keys(t)){const n=t[i],s=n instanceof La?n:new La(n);e[i]=s,Object.defineProperty(this,i,{value:s,enumerable:!0,configurable:!1,writable:!1})}this.entries=e}}const $a=Ya;class Xa{async resolve(t,e){const{storageName:i,key:n,url:s,requestOptions:r,factory:o,options:a}=t;for(const t of e){const e=await t.load(i,n);if(null!=e)try{return await o.create(e,a)}catch{await t.delete(i,n)}}const h=await fetch(s,r);if(!h.ok)throw new Error(`Failed to fetch "${s}" (${h.status} ${h.statusText}).`);const l=await o.process(h),u=await o.create(l,a);for(const t of e)try{await t.save(i,n,l)}catch{}return u}}const Ha=t=>{const e=Object.getPrototypeOf(t.prototype);return e?.constructor??null};class ja{_factories=new co({walk:Ha,dispose:t=>t.destroy()});register(t,e){this._factories.set(t,e)}resolve(t){const e=this._factories.resolve(t);if(!e)throw new Error(`No factory registered for ${t.name}. Register one with loader.register() before loading.`);return e}has(t){return this._factories.has(t)}destroy(){this._factories.destroy()}}class Ka{onProgress;_progress;_promise;constructor(t,e){this.onProgress=new w,this._progress={total:e,loaded:0,pending:e,failed:0},this._promise=t}get progress(){return this._progress}_notifyItem(t){const e=this._progress,i=e.loaded+(t?1:0),n=e.failed+(t?0:1),s=i+n;this._progress={total:e.total,loaded:i,pending:Math.max(0,e.total-s),failed:n},this.onProgress.dispatch(this._progress)}then(t,e){return this._promise.then(t,e)}catch(t){return this._promise.catch(t)}finally(t){return this._promise.finally(t)}}class Qa{_registry=new ja;_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 w;onBundleProgress=new w;onLoaded=new w;onError=new w;onLoadStart=new w;onLoadProgress=new w;onLoadComplete=new w;onLoadError=new w;constructor(t={}){this._basePath=t.basePath??"",this._fetchOptions=t.fetchOptions??{},this._concurrency=t.concurrency??6,this._stores=t.cache?Array.isArray(t.cache)?t.cache:[t.cache]:[],this._cacheStrategy=t.cacheStrategy??new Xa}register(t,e){return this._registry.register(t,e),this}registerAssetType(t,e,i){if("function"==typeof e)this._assetTypeMap.set(t,e),i&&this._registry.register(e,i);else{const i=class{};Object.defineProperty(i,"name",{value:t}),this._assetTypeMap.set(t,i);const n=e.getIdentityKey?.bind(e);this._handlerFunctions.set(i,{load:(t,i)=>e.load(t,i),...void 0!==n&&{getIdentityKey:n}})}return this}registerExtension(t,e){return this._extensionMap.set(t.replace(/^\./,"").toLowerCase(),e),this}add(t,e){const i=t;if("string"==typeof e)this._addManifestEntry(i,e,e);else if(Array.isArray(e)){const t=e;for(const e of t)this._addManifestEntry(i,e,e)}else for(const[t,n]of Object.entries(e))this._addManifestEntry(i,t,n);return this}registerManifest(t){const e=Va(t),i=new Map,n=new Array;for(const[t,s]of Object.entries(e.bundles)){if(this._bundles.has(t))throw new Error(`Bundle "${t}" is already registered.`);const e=new Array;for(const n of s){const s=n.type,r=this._key(s,n.alias),o=i.get(r)??this._getManifestEntry(s,n.alias);if(o&&!this._isManifestDefinitionEquivalent(o,n.path,n.options))throw new Error(`Conflicting asset definition for (${this._describeType(s)}, "${n.alias}") while registering bundle "${t}".`);i.set(r,{path:n.path,options:n.options}),e.push({type:s,alias:n.alias,path:n.path,options:n.options})}n.push([t,e])}for(const[t,e]of n){for(const t of e)this._addManifestEntry(t.type,t.alias,t.path,t.options);this._bundles.set(t,e)}return this}async loadBundle(t,e={}){const i=this._bundles.get(t);if(!i)throw new Error(`Unknown bundle "${t}".`);const n=i.length;let s=0;const r=new Array;if(0!==n){if(await Promise.all(i.map(async i=>{try{await(e.background?this._loadSingleBackground(i.type,i.alias,i.path,i.options):this._loadSingle(i.type,i.alias,i.options,i.path))}catch(t){r.push({type:i.type,alias:i.alias,error:this._normalizeError(t)})}finally{s++,this._emitBundleProgress(t,s,n,e.onProgress)}})),r.length>0)throw new Oa(t,r)}else this._emitBundleProgress(t,0,0,e.onProgress)}async loadContainer(t){const e=await this._contextFetch(t,"__ctx_binary",t=>t.arrayBuffer()),{entries:i,dataStart:n}=Na(e),s=i.map(e=>{const i=this._assetTypeMap.get(e.type);if(!i)throw new Error(`Container "${t}" references unknown asset type "${e.type}".`);return{entry:e,type:i}});await Promise.all(s.map(({entry:t,type:i})=>{const s=n+t.offset,r=e.slice(s,s+t.length);return this._injectSource(i,t.alias,r,t.options)}))}hasBundle(t){const e=this._bundles.get(t);return!!e&&e.every(t=>this._hasResource(t.type,t.alias))}load(t,e,i){if(t instanceof La){const e=t,i=e._config.source;return this._createLoadingQueue([{alias:i,asset:e}],t=>t.get(i))}if(t instanceof Ya){const e=t,i=Object.entries(e.entries).map(([t,e])=>({alias:t,asset:e}));return this._createLoadingQueue(i,t=>{const e={};for(const{alias:n}of i)e[n]=t.get(n);return e})}if("string"==typeof t&&void 0===e){const e=t,i=e.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 "${e}". Register one via loader.registerExtension().`);const s=n===pa?{family:(e.split("/").pop()?.split(/[?#]/)[0]??"").replace(/\.[^.]+$/,"")}:void 0;this._onFgBatchStart(e,e);let r=null;const o=this._loadSingle(n,e,s).then(t=>(r?.(!0),this._onFgBatchSettled(e,!0),t),t=>{throw r?.(!1),this._onFgBatchSettled(e,!1,this._normalizeError(t)),t}),a=new Ka(o,1);return r=a._notifyItem.bind(a),a}if("function"==typeof t){const n=t,s=e,r=i;if("string"==typeof s){this._onFgBatchStart(s,s);let t=null;const e=this._loadSingle(n,s,r).then(e=>(t?.(!0),this._onFgBatchSettled(s,!0),e),e=>{throw t?.(!1),this._onFgBatchSettled(s,!1,this._normalizeError(e)),e}),i=new Ka(e,1);return t=i._notifyItem.bind(i),i}if(Array.isArray(s)){const t=s;let e=null;const i=new Array(t.length),o=t.map((t,s)=>(this._onFgBatchStart(t,t),this._loadSingle(n,t,r).then(n=>{i[s]=n,e?.(!0),this._onFgBatchSettled(t,!0)},i=>{throw e?.(!1),this._onFgBatchSettled(t,!1,this._normalizeError(i)),i}))),a=Promise.all(o).then(()=>i),h=new Ka(a,t.length);return e=h._notifyItem.bind(h),h}const o=Object.entries(s),a={};let h=null;const l=o.map(([t,e])=>{const i="string"==typeof e?e:e.source,s="string"==typeof e?r:{...e,..."object"==typeof r&&null!==r?r:{}};return this._onFgBatchStart(t,i),this._loadSingle(n,t,s,i).then(e=>{a[t]=e,h?.(!0),this._onFgBatchSettled(t,!0)},e=>{throw h?.(!1),this._onFgBatchSettled(t,!1,this._normalizeError(e)),e})}),u=Promise.all(l).then(()=>a),c=new Ka(u,o.length);return h=c._notifyItem.bind(c),c}const n=t,s=Object.entries(n).map(([t,e])=>({alias:t,asset:e instanceof La?e:new Ua(e)}));return this._createLoadingQueue(s,t=>{const e={};for(const{alias:i}of s)e[i]=t.get(i);return e})}backgroundLoad(){for(const[t,e]of this._manifest)for(const[i,n]of e){if(this._hasResource(t,i))continue;const e=this._key(t,i);this._inFlight.has(e)||this._backgroundQueue.push({type:t,alias:i,path:n.path,options:n.options})}this._backgroundTotal=this._backgroundQueue.length,this._backgroundLoaded=0,this._drainBackground()}loadAll(){return new Promise(t=>{this._backgroundResolve=t,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,t())})}setConcurrency(t){return this._concurrency=t,this}get(t,e){const i=t,n=this._resources.get(i);if(!n?.has(e))throw new Error(`Missing resource "${e}" for type ${i.name}.`);return n.get(e)}peek(t,e){const i=t;return this._resources.get(i)?.get(e)??null}has(t,e){const i=t;return this._resources.get(i)?.has(e)??!1}keyFor(t){return this._resourceKeys.get(t)??null}unload(t,e){if(t instanceof La){const e=t,i=this._assetTypeMap.get(e.type);if(!i)return this;const n=this._resolveAssetIdentityKey(i,e),s=this._identityKeyToAliases.get(n);if(s&&s.size>0)for(const t of[...s])this._unloadOne(i,t);else this._unloadOne(i,e._config.source);return this}if(t instanceof Ya){const e=t;for(const[t,i]of Object.entries(e.entries)){const e=i,n=this._assetTypeMap.get(e.type);if(!n)continue;const s=this._resolveAssetIdentityKey(n,e),r=this._identityKeyToAliases.get(s);if(r?.has(t))for(const t of[...r])this._unloadOne(n,t);else this._unloadOne(n,t)}return this}return this._unloadOne(t,e)}_unloadOne(t,e){const i=t,n=this._key(i,e);this._resources.get(i)?.delete(e);const s=this._aliasKeyToIdentityKey.get(n);if((this._inFlight.has(n)||void 0!==s&&this._inFlightByIdentity.has(s))&&this._preventStoreKeys.add(n),void 0!==s){this._aliasKeyToIdentityKey.delete(n);const t=this._identityKeyToAliases.get(s);t&&(t.delete(e),0===t.size&&this._identityKeyToAliases.delete(s))}return this}unloadAll(t){if(t)this._resources.get(t)?.clear();else for(const t of this._resources.values())t.clear();return this}get basePath(){return this._basePath}set basePath(t){this._basePath=t}get fetchOptions(){return this._fetchOptions}set fetchOptions(t){this._fetchOptions=t}bindAsset(t,e){const i=[],n=void 0!==t.typeNames?[...t.typeNames]:[];for(const e of t.extensions??[])i.push(e.replace(/^\./,"").toLowerCase());const s=new Set;for(const t of i){if(s.has(t))throw new Error(`Duplicate extension key ".${t}" within a single asset binding.`);s.add(t)}if(this._handlerFunctions.has(t.type))throw new Error(`An asset handler is already registered for ${t.type.name}.`);for(const t of n)if(this._assetTypeMap.has(t))throw new Error(`Asset type name "${t}" is already registered.`);for(const t of i)if(this._extensionMap.has(t))throw new Error(`File extension ".${t}" is already mapped to an asset type.`);const r=t=>{const{source:e,...i}=t;return 0===Object.keys(i).length?{source:e}:{source:e,options:i}},o=e.getIdentityKey?.bind(e),a=e.createFromBytes?.bind(e);this._handlerFunctions.set(t.type,{load:(t,i)=>e.load(r(t),i),...o&&{getIdentityKey:t=>o(r(t))},...a&&{createFromBytes:(t,e)=>a(t,e)}});for(const e of n)this._assetTypeMap.set(e,t.type);for(const e of i)this._extensionMap.set(e,t.type);this._boundHandlers.push(e)}hasLoadable(t){return this._handlerFunctions.has(t)||this._registry.has(t)}hasAssetType(t){return this._assetTypeMap.has(t)}hasExtension(t){return this._extensionMap.has(t.replace(/^\./,"").toLowerCase())}destroy(){this._registry.destroy();for(const t of this._stores)t.destroy();const t=new Set;for(const e of this._boundHandlers)t.has(e)||(t.add(e),e.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(t,e,i,n){if(this._hasResource(t,e)){const i=this._resources.get(t);if(!0===i?.has(e))return i.get(e)}const s=this._key(t,e);if(this._inFlight.has(s))return this._inFlight.get(s);if(this._boostFromQueue(t,e),this._inFlight.has(s))return this._inFlight.get(s);const r=this._getManifestEntry(t,e),o=n??r?.path??e,a=i??r?.options,h=this._handlerFunctions.get(t);if(h){const i=this._identityKey(t,o),n={source:o};null!=a&&"object"==typeof a&&Object.assign(n,a);const r=this._buildHandlerContext(i);return this._trackInFlight(s,this._fetchWithHandler(t,e,o,n,h.load,r))}return this._trackInFlight(s,this._fetch(t,e,o,a))}_loadSingleBackground(t,e,i,n){if(this._hasResource(t,e)){const i=this._resources.get(t);if(!0===i?.has(e))return Promise.resolve(i.get(e))}const s=this._key(t,e),r=this._inFlight.get(s);if(r)return r;this._isQueuedInBackground(t,e)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:t,alias:e,path:i,options:n}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(s);return o||this._waitForBackgroundEntry(t,e)}_createLoadingQueue(t,e){const i=new Map;let n=null;const s=t.map(({alias:t,asset:e})=>{this._onFgBatchStart(t,e.source);const s=this._assetTypeMap.get(e.type);return s?this._loadSingleAsset(s,t,e).then(e=>{i.set(t,e),n?.(!0),this._onFgBatchSettled(t,!0)},e=>{throw n?.(!1),this._onFgBatchSettled(t,!1,this._normalizeError(e)),e}):Promise.reject(new Error(`No constructor registered for asset type "${e.type}". Call registerAssetType() first.`)).then(()=>{n?.(!0)},e=>{throw n?.(!1),this._onFgBatchSettled(t,!1,this._normalizeError(e)),e})}),r=Promise.all(s).then(()=>e(i)),o=new Ka(r,t.length);return n=o._notifyItem.bind(o),o}async _loadSingleAsset(t,e,i){if(this._hasResource(t,e))return this._resources.get(t)?.get(e);const n=i.source,s=i._config,{type:r,source:o,...a}=s,h=this._handlerFunctions.get(t),l=h?.getIdentityKey?.(s)??n,u=`id:${this._getTypeId(t)}:${l}`,c=this._key(t,e);this._aliasKeyToIdentityKey.set(c,u);let d=this._identityKeyToAliases.get(u);d||(d=new Set,this._identityKeyToAliases.set(u,d)),d.add(e);const _=this._inFlightByIdentity.get(u);if(_)return _.then(i=>(this._storeResource(t,e,i),i));let f;if(h){const i={source:n,...a},s=this._buildHandlerContext(u);f=this._fetchWithHandler(t,e,n,i,h.load,s)}else{const i=Object.keys(a).length>0?a:void 0;f=this._fetch(t,e,n,i)}const p=f.finally(()=>{this._inFlightByIdentity.delete(u)}).then(t=>t,e=>{const i=this._identityKeyToAliases.get(u);if(i){for(const e of i){const i=this._key(t,e);this._aliasKeyToIdentityKey.delete(i),this._preventStoreKeys.delete(i)}this._identityKeyToAliases.delete(u)}throw e});return this._inFlightByIdentity.set(u,p),p}async _fetchWithHandler(t,e,i,n,s,r){const o=this._resolveUrl(i);try{const i=await s(n,r);return this._storeResource(t,e,i),i}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load "${e}" from "${o}": ${i}`,{cause:t})}}_buildHandlerContext(t){return{loader:this,identityKey:t,fetchText:t=>this._contextFetch(t,"__ctx_text",t=>t.text()),fetchArrayBuffer:t=>this._contextFetch(t,"__ctx_binary",t=>t.arrayBuffer()),fetchJson:t=>this._contextFetch(t,"__ctx_json",t=>t.json())}}_contextFetch(t,e,i){const n=this._resolveUrl(t),s={storageName:e,process:i,create:t=>Promise.resolve(t),destroy(){}};return this._cacheStrategy.resolve({storageName:e,key:t,url:n,requestOptions:this._fetchOptions,factory:s,options:void 0},this._stores)}async _injectSource(t,e,i,n){const s=this._handlerFunctions.get(t);let r;if(s?.createFromBytes)r=await s.createFromBytes(i,n);else{if(!this._registry.has(t))throw new Error(`Asset type "${t.name}" cannot be built from container bytes (no createFromBytes handler).`);r=await this._registry.resolve(t).create(i,n)}this._storeResource(t,e,r)}async _fetch(t,e,i,n){const s=this._registry.resolve(t),r=this._resolveUrl(i);try{const o=await this._cacheStrategy.resolve({storageName:s.storageName,key:i,url:r,requestOptions:this._fetchOptions,factory:s,options:n},this._stores);return this._storeResource(t,e,o),o}catch(t){const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to load "${e}" from "${r}": ${i}`,{cause:t})}}_onFgBatchStart(t,e){0===this._fgBatchActive&&(this._fgBatchLoaded=0),this._fgBatchActive++,this._fgBatchTotal++,1===this._fgBatchActive&&this.onLoadStart.dispatch(t,e)}_onFgBatchSettled(t,e,i){e?this._fgBatchLoaded++:void 0!==i&&this.onLoadError.dispatch(t,i),this._fgBatchActive--,this.onLoadProgress.dispatch(this._fgBatchLoaded,this._fgBatchTotal,t),0===this._fgBatchActive&&(this._fgBatchTotal=0,this.onLoadComplete.dispatch())}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const t=this._backgroundQueue.shift();if(!t)continue;const e=this._key(t.type,t.alias);this._hasResource(t.type,t.alias)||this._inFlight.has(e)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(t)}}_boostFromQueue(t,e){const i=this._backgroundQueue.findIndex(i=>i.type===t&&i.alias===e);if(-1===i)return;const[n]=this._backgroundQueue.splice(i,1);void 0!==n&&this._startBackgroundEntry(n)}_isQueuedInBackground(t,e){return this._backgroundQueue.some(i=>i.type===t&&i.alias===e)}_waitForBackgroundEntry(t,e){if(this._hasResource(t,e)){const i=this._resources.get(t);if(!0===i?.has(e))return Promise.resolve(i.get(e))}const i=this._key(t,e),n=this._inFlight.get(i);return n||new Promise((n,s)=>{const r=(i,s,r)=>{i===t&&s===e&&(a(),n(r))},o=(i,n,r)=>{i===t&&n===e&&(a(),s(r))},a=()=>{this.onLoaded.remove(r),this.onError.remove(o)};this.onLoaded.add(r),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(n,s);if(this._hasResource(t,e)){a();const i=this._resources.get(t);n(i?.get(e))}})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const t=this._backgroundResolve;this._backgroundResolve=null,t()}}_startBackgroundEntry(t){const e=this._key(t.type,t.alias);this._backgroundActive++,this._trackInFlight(e,this._fetch(t.type,t.alias,t.path,t.options)).catch(e=>{const i=e instanceof Error?e:new Error(String(e));this.onError.dispatch(t.type,t.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(t,e){const i=e.finally(()=>{this._inFlight.delete(t),this._preventStoreKeys.delete(t)});return this._inFlight.set(t,i),i}_emitBundleProgress(t,e,i,n){this.onBundleProgress.dispatch(t,e,i),n&&n(e,i)}_addManifestEntry(t,e,i,n){this._manifest.has(t)||this._manifest.set(t,new Map);const s=this._manifest.get(t);s&&s.set(e,{path:i,options:n})}_getManifestEntry(t,e){return this._manifest.get(t)?.get(e)}_isManifestDefinitionEquivalent(t,e,i){return t.path===e&&this._areOptionsEquivalent(t.options,i)}_areOptionsEquivalent(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this._areOptionsEquivalent(t[i],e[i]))return!1;return!0}const i=Object.getPrototypeOf(t);if(i!==Object.getPrototypeOf(e))return!1;if(i!==Object.prototype&&null!==i)return!1;const n=t,s=e,r=Object.keys(n),o=Object.keys(s);if(r.length!==o.length)return!1;for(const t of r){if(!Object.hasOwn(s,t))return!1;if(!this._areOptionsEquivalent(n[t],s[t]))return!1}return!0}_normalizeError(t){return t instanceof Error?t:new Error(String(t))}_describeType(t){return t.name.length>0?t.name:"(anonymous type)"}_hasResource(t,e){return this._resources.get(t)?.has(e)??!1}_storeResource(t,e,i){const n=this._key(t,e);if(this._preventStoreKeys.delete(n))return;let s=this._resources.get(t);s||(s=new Map,this._resources.set(t,s)),s.set(e,i),"object"!=typeof i||null===i||this._resourceKeys.has(i)||this._resourceKeys.set(i,{type:t,source:e}),this.onLoaded.dispatch(t,e,i)}_getTypeId(t){let e=this._typeIds.get(t);return void 0===e&&(e=this._nextTypeId++,this._typeIds.set(t,e)),e}_key(t,e){return`${this._getTypeId(t)}:${e}`}_identityKey(t,e){return`id:${this._getTypeId(t)}:${e}`}_resolveAssetIdentityKey(t,e){const i=e._config,n=this._handlerFunctions.get(t),s=n?.getIdentityKey?.(i)??e.source;return`id:${this._getTypeId(t)}:${s}`}_resolveUrl(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")||t.startsWith("/")?t:`${this._basePath}${t}`}}const Za="undefined"!=typeof window,Ja="undefined"!=typeof document,th="undefined"!=typeof navigator;class eh{static _readyPromise=null;static get ready(){return null===eh._readyPromise&&(eh._readyPromise=eh._detect()),eh._readyPromise}webgl2;webgpu;webgpuAdapter;webgpuVendor;webgpuArchitecture;pointer;keyboard;gamepad;touch;maxTouchPoints;audio;fullscreen;vibration;imageBitmap;deviceMemory;offscreenCanvas;webWorkers;devicePixelRatio;constructor(t){this.webgl2=t.webgl2,this.webgpu=t.webgpu,this.webgpuAdapter=t.webgpuAdapter,this.webgpuVendor=t.webgpuVendor,this.webgpuArchitecture=t.webgpuArchitecture,this.pointer=t.pointer,this.keyboard=t.keyboard,this.gamepad=t.gamepad,this.touch=t.touch,this.maxTouchPoints=t.maxTouchPoints,this.audio=t.audio,this.fullscreen=t.fullscreen,this.vibration=t.vibration,this.imageBitmap=t.imageBitmap,this.deviceMemory=t.deviceMemory,this.offscreenCanvas=t.offscreenCanvas,this.webWorkers=t.webWorkers,this.devicePixelRatio=t.devicePixelRatio,Object.freeze(this)}static async _detect(){const[t,e]=await async function(){if(!nh())return[null,null];const t=navigator.gpu;if(!t||"function"!=typeof t.requestAdapter)return[null,null];try{const e=await t.requestAdapter();if(!e)return[null,null];const i=e;if(i.info)return[e,i.info];if("function"==typeof i.requestAdapterInfo)try{return[e,await i.requestAdapterInfo()]}catch{return[e,null]}return[e,null]}catch{return[null,null]}}();return new eh({webgl2:ih(),webgpu:nh(),webgpuAdapter:t,webgpuVendor:e?.vendor??null,webgpuArchitecture:e?.architecture??null,pointer:Za&&"PointerEvent"in window,keyboard:Za&&"KeyboardEvent"in window,gamepad:th&&"function"==typeof navigator.getGamepads,touch:sh(),maxTouchPoints:rh(),audio:oh(),fullscreen:ah(),vibration:th&&"function"==typeof navigator.vibrate,imageBitmap:"function"==typeof createImageBitmap,deviceMemory:hh(),offscreenCanvas:Za&&void 0!==window.OffscreenCanvas,webWorkers:Za&&"function"==typeof window.Worker,devicePixelRatio:Za?window.devicePixelRatio:1})}}function ih(){if(!Ja)return!1;try{const t=document.createElement("canvas");return null!==t.getContext("webgl2")}catch{return!1}}function nh(){return th&&"gpu"in navigator}function sh(){return!!Za&&("ontouchstart"in window||rh()>0)}function rh(){if(!th)return 0;const t=navigator.maxTouchPoints;return"number"==typeof t?t:0}function oh(){if(!Za)return!1;const t=window;return void 0!==t.AudioContext||void 0!==t.webkitAudioContext}function ah(){if(!Ja)return!1;const t=document.documentElement;return"function"==typeof t.requestFullscreen||"function"==typeof t.webkitRequestFullscreen}function hh(){if(!th)return 0;const t=navigator.deviceMemory;return"number"==typeof t?t:0}class lh{_stepMs;_maxSteps;_accumulatorMs=0;constructor(t,e){if(this._stepMs=t,this._maxSteps=e,!(t>0&&Number.isFinite(t)))throw new RangeError(`FixedTimestep: step must be a positive finite number of ms, received ${t}.`)}get stepMs(){return this._stepMs}get alpha(){return this._accumulatorMs/this._stepMs}advance(t){this._accumulatorMs+=t;const e=1e-9*this._stepMs;let i=0;for(;this._accumulatorMs>=this._stepMs-e&&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 uh;!function(t){t[t.Debug=0]="Debug",t[t.Info=1]="Info",t[t.Warning=2]="Warning",t[t.Error=3]="Error"}(uh||(uh={}));class ch{_handlers=[];_warnedKeys=new Set;log(t,e,i,n){if(t<uh.Error)return;const s={severity:t,channel:e,message:i,...void 0!==n?.data&&{data:n.data},...void 0!==n?.error&&{error:n.error}};for(const t of this._handlers)t(s)}debug(t,e,i){this.log(uh.Debug,t,e,i?{data:i}:void 0)}info(t,e,i){this.log(uh.Info,t,e,i?{data:i}:void 0)}warn(t,e,i){this.log(uh.Warning,t,e,i?{data:i}:void 0)}error(t,e,i){this.log(uh.Error,t,e,i?{error:i}:void 0)}warnOnce(t,e,i){this._warnedKeys.has(t)||(this._warnedKeys.add(t),this.warn(e,i))}addHandler(t){return this._handlers.push(t),()=>{const e=this._handlers.indexOf(t);e>=0&&this._handlers.splice(e,1)}}_resetWarnedKeys(){this._warnedKeys.clear()}}const dh=new ch;class _h extends Ei{onResize=new w;_screenWidth=0;_screenHeight=0;get screenWidth(){return this._screenWidth}get screenHeight(){return this._screenHeight}_render(t){const e=t.screenView;this._screenWidth===e.width&&this._screenHeight===e.height||(this._screenWidth=e.width,this._screenHeight=e.height,this.onResize.dispatch(e.width,e.height)),t.render(this,{view:e})}destroy(){this.onResize.destroy(),super.destroy()}}class fh{_items=new Set;_order=[];_disposed=!1;get disposed(){return this._disposed}get size(){return this._items.size}track(t){return this._disposed||this._items.has(t)||(this._items.add(t),this._order.push(t)),t}has(t){return this._items.has(t)}untrack(t){if(this._disposed||!this._items.delete(t))return!1;const e=this._order.indexOf(t);return-1!==e&&this._order.splice(e,1),!0}destroy(){if(!this._disposed){this._disposed=!0;for(let t=this._order.length-1;t>=0;t--)try{this._order[t].destroy()}catch(t){}this._items.clear(),this._order.length=0}}}function ph(t,e){"number"==typeof e.x&&(t.x=e.x),"number"==typeof e.y&&(t.y=e.y),"number"==typeof e.rotation&&(t.rotation=e.rotation),"number"==typeof e.scaleX&&(t.scale.x=e.scaleX),"number"==typeof e.scaleY&&(t.scale.y=e.scaleY),"number"==typeof e.skewX&&(t.skewX=e.skewX),"number"==typeof e.skewY&&(t.skewY=e.skewY),"number"==typeof e.originX&&(t.origin.x=e.originX),"number"==typeof e.originY&&(t.origin.y=e.originY),!1===e.visible&&(t.visible=!1),"number"==typeof e.zIndex&&(t.zIndex=e.zIndex),!1===e.cullable&&(t.cullable=!1);const i=e.cullArea;if(Array.isArray(i)&&4===i.length&&(t.cullArea=new te(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"string"==typeof e.name&&(t.name=e.name),t instanceof Pi){!0===e.interactive&&(t.interactive=!0),!0===e.draggable&&(t.draggable=!0),!0===e.focusable&&(t.focusable=!0),"number"==typeof e.tabIndex&&(t.tabIndex=e.tabIndex),"string"==typeof e.cursor&&(t.cursor=e.cursor),!0===e.clip&&(t.clip=!0),!0===e.preserveDrawOrder&&(t.preserveDrawOrder=!0),!0===e.cacheAsBitmap&&(t.cacheAsBitmap=!0);const i=e.clipShape;Array.isArray(i)&&4===i.length&&(t.clipShape=new te(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3])))}if(t instanceof zn){const i=e.tint;Array.isArray(i)&&4===i.length&&(t.tint=new Re(Number(i[0]),Number(i[1]),Number(i[2]),Number(i[3]))),"number"==typeof e.blendMode&&(t.blendMode=e.blendMode),"string"==typeof e.pixelSnapMode&&In(e.pixelSnapMode)&&(t.pixelSnapMode=e.pixelSnapMode)}}function mh(t,e,i){const n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:i}function gh(t,e,i,n){const s=t[e];return"string"==typeof s&&i.includes(s)?s:n}function yh(t){return"object"!=typeof t||null===t||Array.isArray(t)?null:t}function wh(t){return"object"==typeof t&&null!==t&&"string"==typeof t.type?t:null}function xh(t){return Array.isArray(t)?t.map(t=>"number"==typeof t&&Number.isFinite(t)?t:0):null}const vh=["normal","bold","100","200","300","400","500","600","700","800","900"],bh=["left","center","right","justify"],Sh=["stretch","repeat","mirror-repeat"],Bh=["clip","round"];function Ch(t,e,i,n,s,r){return(i-t)*(r-e)-(n-e)*(s-t)>0}function Th(t,e,i,n,s,r,o,a){const h=(t-s)*(n-r)-(i-s)*(e-r),l=(t-o)*(r-a)-(s-o)*(e-a),u=(t-i)*(a-n)-(o-i)*(e-n);return!((h<0||l<0||u<0)&&(h>0||l>0||u>0))&&0!==h&&0!==l&&0!==u}function Mh(t,e,i,n,s,r){const o=t[2*n],a=t[2*n+1],h=t[2*s],l=t[2*s+1],u=t[2*r],c=t[2*r+1];let d=i[r];for(;d!==n;){if(d!==s){if(Th(t[2*d],t[2*d+1],o,a,h,l,u,c))return!1}d=i[d]}return!0}const Ah=(t,e,i,n,s)=>{const r=[t,e,i,n],o=s/2,a=new ie(t-i,e-n).perp().normalize().multiply(o),h=new ie(i-t,n-e).perp().normalize().multiply(o),l=new Float32Array([t-a.x,e-a.y,t+a.x,e+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:r}},Ph=(t,e)=>{if(t.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const i=e/2,n=new ie(t[0],t[1]),s=new ie(t[t.length-2],t[t.length-1]),r=t;if(n.x===s.x&&n.y===s.y){(t=[...t]).pop(),t.pop();const[e=0,i=0]=[t[t.length-2],t[t.length-1]];s.set(e,i);const r=s.x+.5*(n.x-s.x),o=s.y+.5*(n.y-s.y);t.unshift(r,o),t.push(r,o)}n.destroy(),s.destroy();const o=t.length/2,a=[];let h,l,u,c,d,_,f=t[0],p=t[1],m=t[2],g=t[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 e=1;e<o-1;e++){f=t[2*(e-1)],p=t[2*(e-1)+1],m=t[2*e],g=t[2*e+1],h=t[2*(e+1)],l=t[2*(e+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),s=-y+m-(-y+f),r=(-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*s;if(Math.abs(S)<.1){a.push(m-y,g-w),a.push(m+y,g+w);continue}const B=(s*b-v*r)/S,C=(o*r-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=t[2*(o-2)],p=t[2*(o-2)+1],m=t[2*(o-1)],g=t[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 t=0;t<S;t++){const e=3*t;1&t?(B[e]=t+1,B[e+1]=t,B[e+2]=t+2):(B[e]=t,B[e+1]=t+1,B[e+2]=t+2)}return{vertices:b,indices:B,points:r}},Eh=(t,e,i)=>{const n=Math.floor(15*Math.sqrt(i+i)),s=2*Math.PI/n,r=[],o=new Float32Array(2*(n+1));o[0]=t,o[1]=e;for(let a=0;a<n;a++){const n=t+Math.sin(s*a)*i,h=e+Math.cos(s*a)*i;r.push(n,h);const l=2*(a+1);o[l]=n,o[l+1]=h}const a=new Uint16Array(3*n);for(let t=0;t<n;t++){const e=3*t;a[e]=0,a[e+1]=t+1,a[e+2]=t+2>n?1:t+2}return{vertices:o,indices:a,points:r}},kh=(t,e,i,n)=>{const s=Math.floor(15*Math.sqrt(i+n)),r=2*Math.PI/s,o=[],a=new Float32Array(2*(s+1));a[0]=t,a[1]=e;for(let h=0;h<s;h++){const s=t+Math.sin(r*h)*i,l=e+Math.cos(r*h)*n;o.push(s,l);const u=2*(h+1);a[u]=s,a[u+1]=l}const h=new Uint16Array(3*s);for(let t=0;t<s;t++){const e=3*t;h[e]=0,h[e+1]=t+1,h[e+2]=t+2>s?1:t+2}return{vertices:a,indices:h,points:o}},Rh=t=>{if(t.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const e=t.length/2,i=function(t){const e=t.length>>1;if(e<3)return new Uint32Array(0);if(3===e)return Ch(t[0],t[1],t[2],t[3],t[4],t[5])?new Uint32Array([0,1,2]):new Uint32Array([2,1,0]);const i=new Uint32Array(e),n=new Uint32Array(e);for(let t=0;t<e;t++)i[t]=(t+e-1)%e,n[t]=(t+1)%e;if(function(t){const e=t.length>>1;let i=0;for(let n=0;n<e;n++){const s=(n+1)%e,r=t[2*n],o=t[2*n+1],a=t[2*s];i+=r*t[2*s+1]-a*o}return i}(t)<0)for(let t=0;t<e;t++){const e=i[t];i[t]=n[t],n[t]=e}const s=new Uint32Array(3*(e-2));let r=0,o=e,a=0;for(;o>3;){let e=!1;const h=a;do{const h=i[a],l=n[a],u=a;if(Ch(t[2*h],t[2*h+1],t[2*u],t[2*u+1],t[2*l],t[2*l+1])&&Mh(t,0,n,h,u,l)){s[r++]=h,s[r++]=u,s[r++]=l,n[h]=l,i[l]=h,o--,e=!0,a=l;break}a=n[a]}while(a!==h);if(!e)break}if(3===o){const e=i[a],o=n[a];Ch(t[2*e],t[2*e+1],t[2*a],t[2*a+1],t[2*o],t[2*o+1])?(s[r++]=e,s[r++]=a,s[r++]=o):(s[r++]=o,s[r++]=a,s[r++]=e)}return s.subarray(0,r)}(t),n=new Float32Array(t.length);for(let i=0;i<e;i++)n[2*i]=t[2*i],n[2*i+1]=t[2*i+1];return{vertices:n,indices:new Uint16Array(i),points:t}},Dh=(t,e,i,n)=>({vertices:new Float32Array([t,e,t+i,e,t,e+n,t+i,e+n]),indices:new Uint16Array([0,1,2,1,3,2]),points:[t,e,t+i,e,t+i,e+n,t,e+n]}),Ih=(t,e,i,n,s)=>{const r=Math.min(Math.abs(s),i/2,n/2);if(r<=0)return Dh(t,e,i,n);const o=Math.max(1,Math.floor(15*Math.sqrt(r+r)/4)),a=Math.PI/2/o,h=[[t+r,e+r,Math.PI],[t+i-r,e+r,1.5*Math.PI],[t+i-r,e+n-r,0],[t+r,e+n-r,.5*Math.PI]],l=[];for(const[t=0,e=0,i=0]of h)for(let n=0;n<=o;n++){const s=i+a*n,o=t+Math.cos(s)*r,h=e+Math.sin(s)*r,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]=t+i/2,c[1]=e+n/2;for(let t=0;t<u;t++){const e=2*(t+1);c[e]=l[2*t],c[e+1]=l[2*t+1]}const d=new Uint16Array(3*u);for(let t=0;t<u;t++){const e=3*t;d[e]=0,d[e+1]=t+1,d[e+2]=t+2>u?1:t+2}return{vertices:c,indices:d,points:[...l,l[0],l[1]]}},Lh=(t,e,i,n,s=n/2,r=0)=>{const o=Math.PI/-2+r,a=2*i,h=N/a,l=[];for(let i=0;i<a;i++){const r=o+i*h,a=i%2?s:n;l.push(t+a*Math.cos(r),e+a*Math.sin(r))}return Rh(l)},Uh={line:Ah,path:Ph,circle:Eh,ellipse:kh,polygon:Rh,rectangle:Dh,roundedRectangle:Ih,star:Lh};class Fh extends Ei{_lineWidth=0;_fillColor=new Re(0,0,0,0);_lineColor=new Re;_fillStyle=this._fillColor;_strokeStyle=this._lineColor;_fillStyleTexture=null;_strokeStyleTexture=null;_ownedTextures=new Set;_currentPoint=new ie(0,0);get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t}get lineColor(){return this._lineColor}set lineColor(t){this.strokeStyle=t}get fillColor(){return this._fillColor}set fillColor(t){this.fillStyle=t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=this._resolveStyle(t,this._fillColor),this._fillStyleTexture=null}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=this._resolveStyle(t,this._lineColor),this._strokeStyleTexture=null}get currentPoint(){return this._currentPoint}getChildAt(t){return super.getChildAt(t)}addChild(t){if(!(t instanceof qn))throw new Error("Graphics can only contain Mesh children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof qn))throw new Error("Graphics can only contain Mesh children.");return super.addChildAt(t,e)}moveTo(t,e){return this._currentPoint.set(t,e),this}lineTo(t,e){const{x:i,y:n}=this._currentPoint;return this.drawPath([i,n,t,e]),this.moveTo(t,e),this}quadraticCurveTo(t,e,i,n){const{x:s,y:r}=this._currentPoint;return this.drawPath(Q(s,r,t,e,i,n)),this.moveTo(i,n),this}bezierCurveTo(t,e,i,n,s,r){const{x:o,y:a}=this._currentPoint;return this.drawPath(K(o,a,t,e,i,n,s,r)),this.moveTo(s,r),this}arcTo(t,e,i,n,s){const{x:r,y:o}=this._currentPoint,a=Math.abs(s);if(0===a||r===t&&o===e||t===i&&e===n)return this.lineTo(t,e);const h=t-r,l=e-o,u=i-t,c=n-e,d=Math.hypot(h,l),_=Math.hypot(u,c);if(0===d||0===_)return this.lineTo(t,e);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(t,e);const x=a/Math.tan(w/2);if(!Number.isFinite(x)||x>d||x>_)return this.lineTo(t,e);const v=t-f*x,b=e-p*x,S=t+m*x,B=e+g*x,C=f*g-p*m>0,T=v+(C?-p:p)*a,M=b+(C?f:-f)*a,A=Math.atan2(b-M,v-T),P=Math.atan2(B-M,S-T);return this.lineTo(v,b),this.drawArc(T,M,a,A,P,C)}drawArc(t,e,i,n,s,r=!1){const o=Math.abs(i);if(0===o)return this;let a=s-n;if(!r&&a<0?a+=N:r&&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 s=n+a*(i/h);l.push(t+Math.cos(s)*o,e+Math.sin(s)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(t,e,i,n){const s=Ah(t,e,i,n,this._lineWidth);return this.addChild(this._createStrokeMesh(s)),this}drawPath(t){const e=Ph(t,this._lineWidth);return this.addChild(this._createStrokeMesh(e)),this}_strokeClosedOutline(t){t.length>=4?this.drawPath([...t,t[0],t[1]]):this.drawPath(t)}drawPolygon(t){const e=Rh(t);return this._appendFill(e),this._lineWidth>0&&this._strokeClosedOutline(e.points),this}drawCircle(t,e,i){const n=Eh(t,e,i);return this._appendFill(n),this._lineWidth>0&&this._strokeClosedOutline(n.points),this}drawEllipse(t,e,i,n){const s=kh(t,e,i,n);return this._appendFill(s),this._lineWidth>0&&this._strokeClosedOutline(s.points),this}drawRectangle(t,e,i,n){const s=Dh(t,e,i,n);return this._appendFill(s),this._lineWidth>0&&this._strokeClosedOutline(s.points),this}drawRoundedRectangle(t,e,i,n,s){const r=Ih(t,e,i,n,s);return this._appendFill(r),this._lineWidth>0&&this._strokeClosedOutline(r.points),this}drawStar(t,e,i,n,s=n/2,r=0){const o=Lh(t,e,i,n,s,r);return this._appendFill(o),this._lineWidth>0&&this._strokeClosedOutline(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._fillColor.copy(Re.transparentBlack),this._lineColor.copy(Re.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(t,e){return null===t?e:t instanceof Re?(e.copy(t),e):t.clone()}_appendFill(t){this._fillStyle instanceof Re&&0===this._fillStyle.a||this.addChild(this._createFillMesh(t))}_createFillMesh(t){return this._fillStyle instanceof Re?this._createSolidMesh(t,this._fillStyle):(this._fillStyleTexture??=this._rasterizeGradient(this._fillStyle),this._createGradientMesh(t,this._fillStyleTexture))}_createStrokeMesh(t){return this._strokeStyle instanceof Re?this._createSolidMesh(t,this._strokeStyle):(this._strokeStyleTexture??=this._rasterizeGradient(this._strokeStyle),this._createGradientMesh(t,this._strokeStyleTexture))}_createSolidMesh(t,e){const i=new qn({vertices:t.vertices,indices:t.indices});return i.tint=e,i}_createGradientMesh(t,e){return new qn({vertices:t.vertices,indices:t.indices,uvs:Gh(t.vertices),texture:e})}_rasterizeGradient(t){const e=t.toTexture(256,256,{samplerOptions:{scaleMode:Ye.Linear}});return this._ownedTextures.add(e),e}_destroyOwnedTextures(){for(const t of this._ownedTextures)t.destroy();this._ownedTextures.clear()}}const Gh=t=>{let e=1/0,i=1/0,n=-1/0,s=-1/0;for(let r=0;r<t.length;r+=2){const o=t[r],a=t[r+1];o<e&&(e=o),o>n&&(n=o),a<i&&(i=a),a>s&&(s=a)}const r=n-e,o=s-i,a=r>0?1/r:0,h=o>0?1/o:0,l=new Float32Array(t.length);for(let n=0;n<t.length;n+=2)l[n]=(t[n]-e)*a,l[n+1]=(t[n+1]-i)*h;return l},Nh=-1;function Oh(t,e){if(!Number.isInteger(e)||e!==Nh&&e<1)throw new Error(`AnimatedSprite ${t} has an invalid repeat value (${e}). Must be -1 (infinite) or a positive integer.`)}class Vh extends Ps{_clips=new Map;_currentClipName=null;_currentFrameIndex=0;_hasAppliedFrame=!1;_playing=!1;_repeatOverride=null;_elapsedFrameTimeMs=0;_completedCycles=0;onComplete=new w;onFrame=new w;constructor(t,e){super(t),e&&this.setClips(e)}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??Nh:Nh}set repeat(t){Oh("repeat",t),this._repeatOverride=t}setClips(t){this._clips.clear();for(const[e,i]of Object.entries(t))this.defineClip(e,i);return this}defineClip(t,e){if(0===t.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");const i=e.frames;if(!Array.isArray(e.frames)||0===i.length)throw new Error(`AnimatedSprite clip "${t}" must define at least one frame.`);const n=e.fps??12;if(!Number.isFinite(n)||n<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid fps value (${n}).`);const s=e.repeat??Nh;Oh(`clip "${t}"`,s);let r=null;if(e.frameDurations){if(e.frameDurations.length!==i.length)throw new Error(`AnimatedSprite clip "${t}" frameDurations length (${e.frameDurations.length}) must match its frame count (${i.length}).`);for(const i of e.frameDurations)if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid frameDurations value (${i}).`);r=[...e.frameDurations]}let o=null;if(e.frameOffsets){if(e.frameOffsets.length!==i.length)throw new Error(`AnimatedSprite clip "${t}" frameOffsets length (${e.frameOffsets.length}) must match its frame count (${i.length}).`);for(const i of e.frameOffsets)if(!Number.isFinite(i.x)||!Number.isFinite(i.y))throw new Error(`AnimatedSprite clip "${t}" has an invalid frameOffsets value (${JSON.stringify(i)}).`);o=e.frameOffsets.map(t=>({x:t.x,y:t.y}))}return this._clips.set(t,{frames:i.map(t=>t.clone()),frameDurationMs:1e3/n,frameDurations:r,frameOffsets:o,repeat:s}),this}_getClipDefinitions(){const t={};for(const[e,i]of this._clips)t[e]={frames:i.frames.map(t=>t.clone()),fps:1e3/i.frameDurationMs,repeat:i.repeat,...i.frameDurations?{frameDurations:[...i.frameDurations]}:{},...i.frameOffsets?{frameOffsets:i.frameOffsets.map(t=>({x:t.x,y:t.y}))}:{}};return t}removeClip(t){return this._currentClipName===t&&this.stop(),this._clips.delete(t),this}play(t,e={}){const i=this._clips.get(t);if(!i)throw new Error(`AnimatedSprite clip "${t}" is not defined.`);void 0!==e.repeat&&Oh("play() options.repeat",e.repeat);const n=this._currentClipName===t,s=e.restart??!0;return n&&!s||(this._currentClipName=t,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._completedCycles=0,this._applyFrame(i,0),this.onFrame.dispatch(t,0)),this._repeatOverride=e.repeat??this._repeatOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const t=this._clips.get(this._currentClipName);return t&&t.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(t,0),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(t){if(!this._playing||null===this._currentClipName)return this;const e=this._clips.get(this._currentClipName);if(!e||e.frames.length<=1)return this;const i="number"==typeof t?t:t.milliseconds;if(i<=0)return this;this._elapsedFrameTimeMs+=i;let n=e.frameDurations?.[this._currentFrameIndex]??e.frameDurationMs;for(;this._elapsedFrameTimeMs>=n;){this._elapsedFrameTimeMs-=n;const t=this._currentFrameIndex+1;if(t>=e.frames.length){const t=this._repeatOverride??e.repeat;let i;if(t===Nh?i=!0:(this._completedCycles++,i=this._completedCycles<t),i){this._currentFrameIndex=0,this._applyFrame(e,0),this.onFrame.dispatch(this._currentClipName,0),n=e.frameDurations?.[this._currentFrameIndex]??e.frameDurationMs;continue}this._currentFrameIndex=e.frames.length-1,this._applyFrame(e,this._currentFrameIndex),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=t,this._applyFrame(e,this._currentFrameIndex),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex),n=e.frameDurations?.[this._currentFrameIndex]??e.frameDurationMs}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const t of this._clips.values())for(const e of t.frames)e.destroy();this._clips.clear()}static fromSpritesheet(t){const e={};for(const[i,n]of t.animations)e[i]={frames:n.map(e=>t.getFrame(e))};return new Vh(t.texture,e)}_applyFrame(t,e){if(this._hasAppliedFrame)this.setTextureFrame(t.frames[e],!1);else{const i=this.scale.x,n=this.scale.y;this.setTextureFrame(t.frames[e],!0),this.scale.set(i,n),this._hasAppliedFrame=!0}const i=t.frameOffsets?.[e];i&&(this.getLocalBounds().setPosition(i.x,i.y),this._invalidateBoundsCascade())}}function zh(t){const e={};for(const[i,n]of Object.entries(t))void 0!==n&&(e[i]=n);return e}const qh=t=>[t.r,t.g,t.b,t.a],Wh=t=>Array.isArray(t)&&4===t.length?new Re(Number(t[0]),Number(t[1]),Number(t[2]),Number(t[3])):void 0,Yh=(t,e,i,n,s)=>t.r===e&&t.g===i&&t.b===n&&t.a===s;function $h(t){const e={};return"Arial"!==t.fontFamily&&(e.fontFamily=t.fontFamily),"normal"!==t.fontWeight&&(e.fontWeight=t.fontWeight),"normal"!==t.fontStyle&&(e.fontStyle=t.fontStyle),20!==t.fontSize&&(e.fontSize=t.fontSize),Yh(t.fillColor,255,255,255,1)||(e.fillColor=qh(t.fillColor)),Yh(t.outlineColor,0,0,0,1)||(e.outlineColor=qh(t.outlineColor)),0!==t.outlineWidth&&(e.outlineWidth=t.outlineWidth),"left"!==t.align&&(e.align=t.align),1.2!==t.lineHeight&&(e.lineHeight=t.lineHeight),0!==t.leading&&(e.leading=t.leading),Yh(t.shadowColor,0,0,0,1)||(e.shadowColor=qh(t.shadowColor)),0!==t.shadowOffsetX&&(e.shadowOffsetX=t.shadowOffsetX),0!==t.shadowOffsetY&&(e.shadowOffsetY=t.shadowOffsetY),0!==t.shadowAlpha&&(e.shadowAlpha=t.shadowAlpha),0!==t.shadowBlur&&(e.shadowBlur=t.shadowBlur),null!==t.gradientColors&&(e.gradientColors=[qh(t.gradientColors[0]),qh(t.gradientColors[1])]),"vertical"!==t.gradientAxis&&(e.gradientAxis=t.gradientAxis),Object.keys(e).length>0?e:void 0}function Xh(t){if("object"!=typeof t||null===t)return;const e=t,i={};"string"==typeof e.fontFamily&&(i.fontFamily=e.fontFamily);const n=gh(e,"fontWeight",vh);void 0!==n&&(i.fontWeight=n),"italic"!==e.fontStyle&&"normal"!==e.fontStyle||(i.fontStyle=e.fontStyle),"number"==typeof e.fontSize&&(i.fontSize=e.fontSize);const s=Wh(e.fillColor);void 0!==s&&(i.fillColor=s);const r=Wh(e.outlineColor);void 0!==r&&(i.outlineColor=r),"number"==typeof e.outlineWidth&&(i.outlineWidth=e.outlineWidth);const o=gh(e,"align",bh);void 0!==o&&(i.align=o),"number"==typeof e.lineHeight&&(i.lineHeight=e.lineHeight),"number"==typeof e.leading&&(i.leading=e.leading);const a=Wh(e.shadowColor);if(void 0!==a&&(i.shadowColor=a),"number"==typeof e.shadowOffsetX&&(i.shadowOffsetX=e.shadowOffsetX),"number"==typeof e.shadowOffsetY&&(i.shadowOffsetY=e.shadowOffsetY),"number"==typeof e.shadowAlpha&&(i.shadowAlpha=e.shadowAlpha),"number"==typeof e.shadowBlur&&(i.shadowBlur=e.shadowBlur),Array.isArray(e.gradientColors)&&2===e.gradientColors.length){const t=Wh(e.gradientColors[0]),n=Wh(e.gradientColors[1]);void 0!==t&&void 0!==n&&(i.gradientColors=[t,n])}return"horizontal"!==e.gradientAxis&&"vertical"!==e.gradientAxis||(i.gradientAxis=e.gradientAxis),i}const Hh=["visible","clip","ellipsis"],jh=["ltr","rtl"],Kh=["normal","pre","pre-line"];function Qh(t){if("object"!=typeof t||null===t)return;const e=t,i={},n=mh(e,"maxWidth");void 0!==n&&(i.maxWidth=n);const s=mh(e,"maxHeight");void 0!==s&&(i.maxHeight=s);const r=gh(e,"overflow",Hh);void 0!==r&&(i.overflow=r);const o=mh(e,"letterSpacing");void 0!==o&&(i.letterSpacing=o);const a=gh(e,"direction",jh);void 0!==a&&(i.direction=a);const h=function(t,e,i){const n=t[e];return"boolean"==typeof n?n:i}(e,"breakWords");void 0!==h&&(i.breakWords=h);const l=gh(e,"whiteSpace",Kh);return void 0!==l&&(i.whiteSpace=l),Object.keys(i).length>0?i:void 0}const Zh=t=>Array.isArray(t)?new Float32Array(t.map(Number)):new Float32Array,Jh=t=>Array.isArray(t)?new Uint32Array(t.map(Number)):new Uint32Array,tl=t=>"number"==typeof t&&Number.isFinite(t)?t:void 0,el=t=>{const e=yh(t);return{left:tl(e?.left)??0,top:tl(e?.top)??0,right:tl(e?.right)??0,bottom:tl(e?.bottom)??0}},il=t=>{const e=yh(t);if(null===e)return;const i={},n=gh(e,"edges",Sh);void 0!==n&&(i.edges=n);const s=gh(e,"center",Sh);void 0!==s&&(i.center=s);const r=gh(e,"top",Sh);void 0!==r&&(i.top=r);const o=gh(e,"right",Sh);void 0!==o&&(i.right=o);const a=gh(e,"bottom",Sh);void 0!==a&&(i.bottom=a);const h=gh(e,"left",Sh);void 0!==h&&(i.left=h);const l=gh(e,"edgeFit",Bh);void 0!==l&&(i.edgeFit=l);const u=gh(e,"centerFit",Bh);return void 0!==u&&(i.centerFit=u),i},nl={write(t,e){const i={vertices:[...t.vertices]};null!==t.indices&&(i.indices=[...t.indices]),null!==t.uvs&&(i.uvs=[...t.uvs]),null!==t.colors&&(i.colors=[...t.colors]);const n=e.keyFor(t.texture);return null!==n&&(i.texture=n),t.material,i},read(t,e){return new qn(zh({vertices:Zh(t.vertices),indices:void 0!==t.indices?(i=t.indices,Array.isArray(i)?new Uint16Array(i.map(Number)):new Uint16Array):void 0,uvs:void 0!==t.uvs?Zh(t.uvs):void 0,colors:void 0!==t.colors?Jh(t.colors):void 0,texture:e.resolveAsset("string"==typeof t.texture?t.texture:null,vi)}));var i}},sl={write:(t,e)=>0===t.children.length?{}:{children:t.children.map(t=>e.writeNode(t))},read(t,e){const i=new Fh,n=t.children;if(Array.isArray(n))for(const t of n){const n=wh(t);null!==n&&i.addChild(e.readNode(n))}return i}},rl={write(t,e){const i={slices:{...t.slices},border:{...t.border},modes:{...t.modes},width:t.width,height:t.height},n=e.keyFor(t.texture);return null!==n&&(i.texture=n),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,vi);if(null===i)throw new Error("NineSliceSprite deserialize requires its texture to be pre-loaded into the Loader.");return new ys(i,zh({slices:el(t.slices),border:null!==yh(t.border)?el(t.border):void 0,modes:il(t.modes),width:tl(t.width),height:tl(t.height)}))}},ol={write(t,e){const i={width:t.width,height:t.height,modeX:t.modeX,modeY:t.modeY,fitX:t.fitX,fitY:t.fitY,offsetX:t.offsetX,offsetY:t.offsetY},n=e.keyFor(t.texture);return null!==n&&(i.texture=n),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,vi);if(null===i)throw new Error("RepeatingSprite deserialize requires its texture to be pre-loaded into the Loader.");return new Ms(i,zh({width:tl(t.width),height:tl(t.height),modeX:gh(t,"modeX",Sh),modeY:gh(t,"modeY",Sh),fitX:gh(t,"fitX",Bh),fitY:gh(t,"fitY",Bh),offsetX:tl(t.offsetX),offsetY:tl(t.offsetY)}))}},al={write(t,e){const i={},n=e.keyFor(t.texture);null!==n&&(i.texture=n);const s={};for(const[e,i]of Object.entries(t._getClipDefinitions()))s[e]=zh({frames:i.frames.map(t=>[t.x,t.y,t.width,t.height]),fps:i.fps,repeat:i.repeat,frameDurations:i.frameDurations?[...i.frameDurations]:void 0,frameOffsets:i.frameOffsets?i.frameOffsets.map(t=>[t.x,t.y]):void 0});return i.clips=s,null!==t.currentClip&&(i.currentClip=t.currentClip),t.playing&&(i.playing=!0),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,vi),n={},s=yh(t.clips);if(null!==s)for(const[t,e]of Object.entries(s)){const i=yh(e);if(null===i)continue;const s=Array.isArray(i.frames)?i.frames.map(t=>{const e=xh(t)??[];return new te(e[0]??0,e[1]??0,e[2]??0,e[3]??0)}):[],r=Array.isArray(i.frameDurations)?xh(i.frameDurations)??void 0:void 0,o=Array.isArray(i.frameOffsets)?i.frameOffsets.map(t=>{const e=xh(t)??[];return{x:e[0]??0,y:e[1]??0}}):void 0;n[t]=zh({frames:s,fps:tl(i.fps),repeat:tl(i.repeat),frameDurations:r,frameOffsets:o})}const r=new Vh(i,n);return"string"==typeof t.currentClip&&t.currentClip in n&&(r.play(t.currentClip),!0!==t.playing&&r.pause()),r}},hl={write(t,e){const i={text:t.text},n=e.keyFor(t.font);null!==n&&(i.font=n),t.msdf&&(i.msdf=!0),1!==t.fontScale&&(i.scale=t.fontScale);const s=$h(t.style);return void 0!==s&&(i.style=s),Object.keys(t.layout).length>0&&(i.layout={...t.layout}),i},read(t,e){const i=e.resolveAsset("string"==typeof t.font?t.font:null,ks);if(null===i)throw new Error("BitmapText deserialize requires its BmFont to be pre-loaded into the Loader.");const n=Qh(t.layout);return new Fs("string"==typeof t.text?t.text:"",i,zh({...Xh(t.style),msdf:!0===t.msdf,scale:tl(t.scale),layout:n}))}},ll={write(t){const e={src:t.videoElement.src};return 1!==t.volume&&(e.volume=t.volume),t.loop&&(e.loop=!0),1!==t.playbackRate&&(e.playbackRate=t.playbackRate),t.muted&&(e.muted=!0),t.currentTime>0&&(e.time=t.currentTime),e},read(t){const e=document.createElement("video");return"string"==typeof t.src&&(e.src=t.src),new Io(e,zh({volume:tl(t.volume),loop:!0===t.loop||void 0,playbackRate:tl(t.playbackRate),muted:!0===t.muted||void 0,time:tl(t.time)}))}};class ul extends Ei{_uiWidth=0;_uiHeight=0;_enabled=!0;_uiAnchor=null;_uiAnchorOffsetX=0;_uiAnchorOffsetY=0;_uiAnchorRoot=null;_onAnchorResize=(t,e)=>{this._applyAnchor(t,e)};get uiWidth(){return this._uiWidth}get uiHeight(){return this._uiHeight}setSize(t,e){const i=Math.max(0,t),n=Math.max(0,e);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(t){this._enabled!==t&&(this._enabled=t,this._onEnabledChanged(t))}anchorIn(t,e,i=0,n=0){return this._uiAnchor=e,this._uiAnchorOffsetX=i,this._uiAnchorOffsetY=n,this._uiAnchorRoot!==t&&(this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=t,t.onResize.add(this._onAnchorResize)),this._applyAnchor(t.screenWidth,t.screenHeight),this}_applyAnchor(t,e){if(null===this._uiAnchor)return;const[i,n]=(t=>{let e=.5,i=.5;return t.endsWith("left")?e=0:t.endsWith("right")&&(e=1),t.startsWith("top")?i=0:t.startsWith("bottom")&&(i=1),[e,i]})(this._uiAnchor);this.setPosition(i*(t-this._uiWidth)+this._uiAnchorOffsetX,n*(e-this._uiHeight)+this._uiAnchorOffsetY)}_relayout(){}_onEnabledChanged(t){}destroy(){this._uiAnchorRoot?.onResize.remove(this._onAnchorResize),this._uiAnchorRoot=null,super.destroy()}}class cl extends ul{onClick=new w;_background=new Fh;_label;_colors;_cornerRadius;_state="normal";_pointerInside=!1;constructor(t={}){super(),this._colors={normal:(t.color??new Re(54,120,220,1)).clone(),hover:(t.hoverColor??new Re(74,140,240,1)).clone(),pressed:(t.pressedColor??new Re(40,96,180,1)).clone(),disabled:(t.disabledColor??new Re(70,76,90,1)).clone()},this._cornerRadius=t.cornerRadius??8,this._label=new Zs(t.label??"",{fillColor:t.textColor??Re.white,fontSize:t.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(t.width??120,t.height??40)}get label(){return this._label.text}set label(t){this._label.text=t,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 e=t.channel;!this.enabled||e!==Ui.Enter&&e!==Ui.Space||(t.preventDefault(),this.onClick.dispatch(this))};_refreshState(){let t="normal";this.enabled?this._pointerInside&&(t="hover"):t="disabled",this._state=t,this._draw()}_onEnabledChanged(t){this.interactive=t,this._refreshState()}_relayout(){this._draw(),this._positionLabel()}_draw(){const t=this._background;t.clear(),this._uiWidth<=0||this._uiHeight<=0||(t.fillColor=this._colors[this._state],t.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_positionLabel(){const t=this._label.getLocalBounds();this._label.setPosition((this._uiWidth-t.width)/2,(this._uiHeight-t.height)/2)}}class dl extends ul{_text;constructor(t="",e={}){super(),this._text=new Zs(t,{fillColor:Re.white,fontSize:16,...e}),this.addChild(this._text),this._syncSize()}get text(){return this._text.text}set text(t){this._text.text!==t&&(this._text.text=t,this._syncSize())}get textNode(){return this._text}_syncSize(){const t=this._text.getLocalBounds();this.setSize(t.width,t.height)}}class _l extends ul{_background=new Fh;_color;_borderColor;_borderWidth;_cornerRadius;constructor(t={}){super(),this._color=(t.color??new Re(30,34,45,.92)).clone(),this._borderColor=(t.borderColor??new Re(255,255,255,.12)).clone(),this._borderWidth=t.borderWidth??0,this._cornerRadius=t.cornerRadius??8,this.addChild(this._background),this.setSize(t.width??0,t.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 t=this._background;t.clear(),this._uiWidth<=0||this._uiHeight<=0||(this._borderWidth>0&&(t.lineWidth=this._borderWidth,t.lineColor=this._borderColor),t.fillColor=this._color,t.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}}class fl extends ul{_track=new Fh;_fill=new Fh;_trackColor;_fillColor;_cornerRadius;_value;constructor(t={}){super(),this._value=Y(t.value??0,0,1),this._trackColor=(t.trackColor??new Re(255,255,255,.16)).clone(),this._fillColor=(t.fillColor??new Re(80,220,120,1)).clone(),this._cornerRadius=t.cornerRadius??4,this.addChild(this._track),this.addChild(this._fill),this.setSize(t.width??200,t.height??12)}get value(){return this._value}set value(t){const e=Y(t,0,1);this._value!==e&&(this._value=e,this._drawFill())}get trackColor(){return this._trackColor}get fillColor(){return this._fillColor}get cornerRadius(){return this._cornerRadius}_relayout(){this._drawTrack(),this._drawFill()}_drawTrack(){const t=this._track;t.clear(),this._uiWidth<=0||this._uiHeight<=0||(t.fillColor=this._trackColor,t.drawRoundedRectangle(0,0,this._uiWidth,this._uiHeight,this._cornerRadius))}_drawFill(){const t=this._fill;t.clear();const e=this._uiWidth*this._value;e<=0||this._uiHeight<=0||(t.fillColor=this._fillColor,t.drawRoundedRectangle(0,0,e,this._uiHeight,Math.min(this._cornerRadius,e/2)))}}class pl extends ul{_direction;_spacing;_padding;constructor(t={}){super(),this._direction=t.direction??"column",this._spacing=t.spacing??8,this._padding=t.padding??0}get direction(){return this._direction}get spacing(){return this._spacing}get padding(){return this._padding}addItem(t){return this.addChild(t),this.layout()}layout(){const t="row"===this._direction;let e=this._padding,i=0,n=!0;for(const s of this.children){const r=s instanceof ul?s.uiWidth:s.getLocalBounds().width,o=s instanceof ul?s.uiHeight:s.getLocalBounds().height;n||(e+=this._spacing),n=!1,t?(s.setPosition(e,this._padding),e+=r,i=Math.max(i,o)):(s.setPosition(this._padding,e),e+=o,i=Math.max(i,r))}const s=e+this._padding,r=i+2*this._padding;return this.setSize(t?s:r,t?r:s),this}}const ml=t=>"number"==typeof t&&Number.isFinite(t)?t:void 0,gl={write(t){const e={text:t.text},i=$h(t.textNode.style);return void 0!==i&&(e.style=i),t.enabled||(e.enabled=!1),e},read(t){const e=new dl("string"==typeof t.text?t.text:"",Xh(t.style));return!1===t.enabled&&(e.enabled=!1),e}},yl={write(t,e){const i={width:t.uiWidth,height:t.uiHeight,color:qh(t.color),borderColor:qh(t.borderColor),borderWidth:t.borderWidth,cornerRadius:t.cornerRadius};t.enabled||(i.enabled=!1);const n=t.children.filter(e=>e!==t.background);return n.length>0&&(i.children=n.map(t=>e.writeNode(t))),i},read(t,e){const i=new _l(zh({width:ml(t.width),height:ml(t.height),color:Wh(t.color),borderColor:Wh(t.borderColor),borderWidth:ml(t.borderWidth),cornerRadius:ml(t.cornerRadius)}));!1===t.enabled&&(i.enabled=!1);const n=t.children;if(Array.isArray(n))for(const t of n){const n=wh(t);null!==n&&i.addChild(e.readNode(n))}return i}},wl={write(t){const e={width:t.uiWidth,height:t.uiHeight,label:t.label,cornerRadius:t.cornerRadius,color:qh(t.colors.normal),hoverColor:qh(t.colors.hover),pressedColor:qh(t.colors.pressed),disabledColor:qh(t.colors.disabled),textColor:qh(t.textColor),fontSize:t.fontSize};return t.enabled||(e.enabled=!1),e},read(t){const e=new cl(zh({width:ml(t.width),height:ml(t.height),label:"string"==typeof t.label?t.label:void 0,cornerRadius:ml(t.cornerRadius),color:Wh(t.color),hoverColor:Wh(t.hoverColor),pressedColor:Wh(t.pressedColor),disabledColor:Wh(t.disabledColor),textColor:Wh(t.textColor),fontSize:ml(t.fontSize)}));return!1===t.enabled&&(e.enabled=!1),e}},xl={write(t){const e={width:t.uiWidth,height:t.uiHeight,value:t.value,trackColor:qh(t.trackColor),fillColor:qh(t.fillColor),cornerRadius:t.cornerRadius};return t.enabled||(e.enabled=!1),e},read(t){const e=new fl(zh({width:ml(t.width),height:ml(t.height),value:ml(t.value),trackColor:Wh(t.trackColor),fillColor:Wh(t.fillColor),cornerRadius:ml(t.cornerRadius)}));return!1===t.enabled&&(e.enabled=!1),e}},vl={write(t,e){const i={direction:t.direction,spacing:t.spacing,padding:t.padding};return t.enabled||(i.enabled=!1),t.children.length>0&&(i.children=t.children.map(t=>e.writeNode(t))),i},read(t,e){const i=new pl(zh({direction:"row"===t.direction||"column"===t.direction?t.direction:void 0,spacing:ml(t.spacing),padding:ml(t.padding)}));!1===t.enabled&&(i.enabled=!1);const n=t.children;if(Array.isArray(n)){for(const t of n){const n=wh(t);null!==n&&i.addChild(e.readNode(n))}i.layout()}return i}},bl={write:(t,e)=>t.children.length>0?{children:t.children.map(t=>e.writeNode(t))}:{},read(t,e){const i=new _h,n=t.children;if(Array.isArray(n))for(const t of n){const n=wh(t);null!==n&&i.addChild(e.readNode(n))}return i}};const Sl={write:(t,e)=>0===t.children.length?{}:{children:t.children.map(t=>e.writeNode(t))},read(t,e){const i=new Ei,n=t.children;if(Array.isArray(n))for(const t of n){const n=wh(t);null!==n&&i.addChild(e.readNode(n))}return i}},Bl={write(t,e){const i={},n=e.keyFor(t.texture);null!==n&&(i.texture=n),t.material;const s=t.texture,r=t.textureFrame;return null===s||0===r.x&&0===r.y&&r.width===s.width&&r.height===s.height||(i.frame=[r.x,r.y,r.width,r.height]),i},read(t,e){const i=e.resolveAsset("string"==typeof t.texture?t.texture:null,vi),n=new Ps(i),s=t.frame;return null!==i&&Array.isArray(s)&&4===s.length&&n.setTextureFrame(te.temp.set(Number(s[0]),Number(s[1]),Number(s[2]),Number(s[3]))),n}},Cl={write(t){const e={text:t.text},i=$h(t.style);return void 0!==i&&(e.style=i),Object.keys(t.layout).length>0&&(e.layout={...t.layout}),t.colorGlyphs&&(e.colorGlyphs=!0),8!==t.sdfRadius&&(e.sdfRadius=t.sdfRadius),e},read(t){const e=Qh(t.layout);return new Zs("string"==typeof t.text?t.text:"",zh({...Xh(t.style),...e,colorGlyphs:!0===t.colorGlyphs,sdfRadius:"number"==typeof t.sdfRadius?t.sdfRadius:void 0}))}};function Tl(t){t.register("Container",Ei,Sl),t.register("Sprite",Ps,Bl),t.register("Text",Zs,Cl),function(t){t.register("Mesh",qn,nl),t.register("Graphics",Fh,sl),t.register("NineSliceSprite",ys,rl),t.register("RepeatingSprite",Ms,ol),t.register("AnimatedSprite",Vh,al),t.register("BitmapText",Fs,hl),t.register("Video",Io,ll)}(t),function(t){t.register("Label",dl,gl),t.register("Panel",_l,yl),t.register("Button",cl,wl),t.register("ProgressBar",fl,xl),t.register("Stack",pl,vl),t.register("UIRoot",_h,bl)}(t)}const Ml=t=>{const e=Object.getPrototypeOf(t);return"function"==typeof e&&e!==Function.prototype?e:null};class Al{_fallback;_byCtor=new co({walk:Ml});_byName=new Map;constructor(t=null){this._fallback=t}register(t,e,i){const n=this._byName.get(t);if(void 0!==n&&n.ctor!==e)throw new Error(`A serializer for type name "${t}" is already registered for a different constructor.`);const s={typeName:t,ctor:e,serializer:i};this._byCtor.set(e,s),this._byName.set(t,s)}resolveByNode(t){return this._byCtor.resolve(t.constructor)??this._fallback?.resolveByNode(t)}resolveByName(t){return this._byName.get(t)??this._fallback?.resolveByName(t)}hasType(t){return this._byName.has(t)||(this._fallback?.hasType(t)??!1)}clear(){this._byName.clear(),this._byCtor.destroy()}}const Pl=new Al;function El(t,e,i,n=Pl){n.register(t,e,i)}const kl=1;let Rl=!1;function Dl(){Rl||(Rl=!0,Tl(Pl))}function Il(t,e,i){const n={version:e,loader:t,readNode:t=>Ul(t,n,i),resolveAsset:(e,i)=>{if(null==e||null===t)return null;return t.peek(i,e)}};return n}function Ll(t,e,i){const n=i.resolveByNode(t);if(void 0===n)throw new Error(`No serializer registered for node type "${t.constructor.name}". Register one via registerSerializer().`);const s={type:n.typeName};return function(t,e){if(0!==t.x&&(e.x=t.x),0!==t.y&&(e.y=t.y),0!==t.rotation&&(e.rotation=t.rotation),1!==t.scale.x&&(e.scaleX=t.scale.x),1!==t.scale.y&&(e.scaleY=t.scale.y),0!==t.skewX&&(e.skewX=t.skewX),0!==t.skewY&&(e.skewY=t.skewY),0!==t.origin.x&&(e.originX=t.origin.x),0!==t.origin.y&&(e.originY=t.origin.y),t.visible||(e.visible=!1),0!==t.zIndex&&(e.zIndex=t.zIndex),t.cullable||(e.cullable=!1),null!==t.cullArea&&(e.cullArea=[t.cullArea.x,t.cullArea.y,t.cullArea.width,t.cullArea.height]),null!==t.name&&(e.name=t.name),t instanceof Pi){t.interactive&&(e.interactive=!0),t.draggable&&(e.draggable=!0),t.focusable&&(e.focusable=!0),0!==t.tabIndex&&(e.tabIndex=t.tabIndex),null!==t.cursor&&(e.cursor=t.cursor),t.clip&&(e.clip=!0),t.preserveDrawOrder&&(e.preserveDrawOrder=!0),t.cacheAsBitmap&&(e.cacheAsBitmap=!0);const i=t.clipShape;i instanceof te&&(e.clipShape=[i.x,i.y,i.width,i.height])}if(t instanceof zn){const i=t.tint;255===i.r&&255===i.g&&255===i.b&&1===i.a||(e.tint=[i.r,i.g,i.b,i.a]),t.blendMode!==qe.Normal&&(e.blendMode=t.blendMode),"none"!==t.pixelSnapMode&&(e.pixelSnapMode=t.pixelSnapMode)}}(t,s),Object.assign(s,n.serializer.write(t,e)),s}function Ul(t,e,i){const n=i.resolveByName(t.type);if(void 0===n)throw new Error(`No serializer registered for type "${t.type}". Register one via registerSerializer().`);const s=n.serializer.read(t,e);return ph(s,t),s}function Fl(t,e=null,i=Pl){return Dl(),Ll(t,function(t,e){const i={version:1,loader:t,writeNode:t=>Ll(t,i,e),keyFor:e=>{if(null==e||"object"!=typeof e||null===t)return null;const i=t.keyFor(e);return null===i?null:i.source}};return i}(e,i),i)}function Gl(t,e,i=null,n=Pl){Dl();const s=Il(i,1,n);t.removeChildren(),ph(t,e);const r=e.children;if(Array.isArray(r))for(const e of r){const i=wh(e);null!==i&&t.addChild(s.readNode(i))}}class Nl{_systems=[];_set=new Set;_pending=[];_ticking=!1;_sorted=!0;onAdd=new w;onRemove=new w;add(t){return this._ticking?this._pending.push({add:!0,system:t}):this._insert(t),t}remove(t){return this._ticking?!!this._set.has(t)&&(this._pending.push({add:!1,system:t}),!0):this._delete(t)}has(t){return this._set.has(t)}get size(){return this._set.size}_tick(t){if(0!==this._systems.length){this._sorted||(this._systems.sort((t,e)=>(t.order??0)-(e.order??0)),this._sorted=!0),this._ticking=!0;for(const e of this._systems)e.update(t);this._ticking=!1,this._drainPending()}}destroy(){for(let t=this._systems.length-1;t>=0;t--)this._systems[t].destroy();this._systems.length=0,this._set.clear(),this._pending.length=0,this.onAdd.destroy(),this.onRemove.destroy()}_insert(t){this._set.has(t)||(this._set.add(t),this._systems.push(t),this._sorted=!1,this.onAdd.dispatch(t))}_delete(t){if(!this._set.delete(t))return!1;const e=this._systems.indexOf(t);return-1!==e&&this._systems.splice(e,1),this.onRemove.dispatch(t),!0}_drainPending(){if(0!==this._pending.length){for(const{add:t,system:e}of this._pending)t?this._insert(e):this._delete(e);this._pending.length=0}}}class Ol{_scene;_bindings=new Set;constructor(t){this._scene=t}onStart(t,e,i){return this._track(this._scene.app.input.onStart(t,e,i))}onActive(t,e,i){return this._track(this._scene.app.input.onActive(t,e,i))}onStop(t,e,i){return this._track(this._scene.app.input.onStop(t,e,i))}onTrigger(t,e,i){return this._track(this._scene.app.input.onTrigger(t,e,i))}destroy(){for(const t of this._bindings)t.unbind();this._bindings.clear()}_track(t){return this._bindings.add(t),t}}class Vl{_scene;_tweens=new Set;constructor(t){this._scene=t}create(t){const e=this._scene.app.tweens.create(t);return this._tweens.add(e),e}add(t){return this._scene.app.tweens.add(t),this._tweens.add(t),this}destroy(){for(const t of this._tweens)t.stop();this._tweens.clear()}}class zl{_app=null;_root=new Ei;paused=!1;onLoad=new w;onUnload=new w;_inputs=null;_tweens=null;_systems=null;_disposal=new fh;get app(){return this._app}set app(t){this._app=t}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 Ol(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 Vl(this))}return this._tweens}track(t){return this._disposal.track(t)}get systems(){return null===this._systems&&(this._systems=this._disposal.track(new Nl)),this._systems}_tickSystems(t){this._systems?._tick(t)}_ui=null;get ui(){return null===this._ui&&(this._ui=this._disposal.track(new _h),null!==this._root._getStage()&&this._app?.interaction.attachUIRoot(this._ui)),this._ui}_peekUI(){return this._ui}addChild(t){return this._root.addChild(t),this}removeChild(t){return this._root.removeChild(t),this}serialize(){const t=this._app?.loader??null,e=this._app?.serializers,i={version:1,root:Fl(this._root,t,e)},n=this._peekUI();return null!==n&&(i.ui=Fl(n,t,e)),i}deserialize(t){const e=function(t){const e=yh(t);if(null===e)throw new Error("Cannot deserialize scene: the document is not an object.");const i="number"==typeof e.version?e.version:0;if(i>1)throw new Error(`Cannot deserialize scene: data version ${i} is newer than the supported version 1.`);const n=wh(e.root);if(null===n)throw new Error("Cannot deserialize scene: the document has no valid root node.");const s=wh(e.ui);return null!==s?{version:i,root:n,ui:s}:{version:i,root:n}}(t),i=this._app?.loader??null,n=this._app?.serializers;return Gl(this._root,e.root,i,n),void 0!==e.ui&&Gl(this.ui,e.ui,i,n),this}load(t){}init(t){}update(t){}fixedUpdate(t){}draw(t){}unload(t){}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 ql extends qn{render(t){return this.visible&&t.draw(this),this}}class Wl{_app;_activeScene=null;_transitionOverlay=(()=>new ql({vertices:new Float32Array([0,0,1,0,0,1,1,1]),indices:new Uint16Array([0,1,2,1,3,2])}))();_transition=null;onChangeScene=new w;onStartScene=new w;onUpdateScene=new w;onStopScene=new w;_asyncUpdateWarned=new WeakSet;_asyncDrawWarned=new WeakSet;constructor(t){this._app=t}get currentScene(){return this._activeScene}set currentScene(t){this.setScene(t)}async setScene(t,e={}){return await this._runWithTransition(async()=>{if(t===this._activeScene)return;null!==t&&await this._prepareScene(t);const e=this._activeScene;this._activeScene=t,null!==e&&await this._disposeScene(e),this.onChangeScene.dispatch(t),null!==t&&this.onStartScene.dispatch(t)},e.transition),this}update(t){this._advanceTransition(t.milliseconds);const e=this._activeScene;if(null!==e){if(!e.paused){const i=e.update(t);!this._asyncUpdateWarned.has(e)&&i instanceof Promise&&(this._asyncUpdateWarned.add(e),dh.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.")),e._tickSystems(t)}const i=e.draw(this._app.rendering);!this._asyncDrawWarned.has(e)&&i instanceof Promise&&(this._asyncDrawWarned.add(e),dh.warn("scene","Scene.draw() returned a Promise. draw() must be synchronous — an async draw() produces incomplete frames and silently drops errors.")),e._peekUI()?._render(this._app.rendering)}const i=this._getTransitionAlpha();return i>0&&this._renderTransitionOverlay(i),null!==e&&this.onUpdateScene.dispatch(e),this}fixedUpdate(t){const e=this._activeScene;return null===e||e.paused||e.fixedUpdate(t),this}destroy(){if(this._transition){const t=this._transition;this._transition=null,t.color.destroy(),t.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(t){t.app=this._app;try{await t.load(this._app.loader),await t.init(this._app.loader),t.root.children.length>0&&t.draw===zl.prototype.draw&&dh.warn("scene",`Scene.root has ${t.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(t.root);const e=t._peekUI();null!==e&&this._app.interaction.attachUIRoot(e),t.onLoad.dispatch()}catch(e){let i=null;try{await t.unload(this._app.loader)}catch(t){i=t}if(t.destroy(),t.app=null,i){const t=e instanceof Error?e.message:String(e);let n="unknown cleanup error";throw i instanceof Error?n=i.message:"string"==typeof i&&(n=i),new Error(`Failed to initialize scene: ${t}. Cleanup also failed: ${n}.`,{cause:e})}throw e}}async _disposeScene(t){t.onUnload.dispatch(),this.onStopScene.dispatch(t),await t.unload(this._app.loader);const e=t._peekUI();null!==e&&this._app.interaction.detachUIRoot(e),this._app.interaction.detachRoot(t.root),t.destroy(),t.app=null}async _unloadActiveSceneOnDestroy(){const t=this._activeScene;if(null!==t){this._activeScene=null;try{await this._disposeScene(t)}catch(t){dh.error("scene","SceneManager.destroy() failed to unload the active scene.",t instanceof Error?t:void 0)}}}async _runWithTransition(t,e){if("fade"!==e?.type)return void await t();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,e.duration??220);0!==i?await new Promise((n,s)=>{this._transition={type:"fade",durationMs:i,action:t,resolve:n,reject:s,color:(e.color??Re.black).clone(),elapsedMs:0,phase:"out"}}):await t()}_advanceTransition(t){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),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,t)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const t=this._transition;if("switching"===t?.phase){try{await t.action()}catch(e){return void(this._transition===t&&(this._transition=null,t.color.destroy(),t.reject(e)))}this._transition===t&&(t.phase="in",t.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const t=this._transition;this._transition=null,t.color.destroy(),t.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const t=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?t:1-t}_renderTransitionOverlay(t){const e=this._transition,i=e?e.color:Re.black,n=this._app.backend,s=n.view.getBounds(),r=this._transitionOverlay,o=r.vertices;o[0]=s.left,o[1]=s.top,o[2]=s.right,o[3]=s.top,o[4]=s.left,o[5]=s.bottom,o[6]=s.right,o[7]=s.bottom,r.tint.set(i.r,i.g,i.b,Math.max(0,Math.min(1,t))),r.render(n)}}var Yl;!function(t){t[t.Loading=1]="Loading",t[t.Running=2]="Running",t[t.Halting=3]="Halting",t[t.Stopped=4]="Stopped"}(Yl||(Yl={}));const $l=1e3/60,Xl={type:"auto"},Hl=800,jl=600,Kl=1,Ql=-1,Zl={method:"GET",mode:"cors",cache:"default"},Jl={debug:!1,spriteRendererBatchSize:4096,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1}},tu={gamepadDefinitions:[],gamepadSlotStrategy:"sticky",pointerDistanceThreshold:10};class eu{options;canvas;loader;input;focus;interaction;scene;random;tweens=new o;systems=new Nl;serializers=new Al(Pl);onResize=new w;onFrame=new w;onFixedFrame=new w;onCanvasFocusChange=new w;onVisibilityChange=new w;onBackendLost=new w;onBackendRestored=new w;onError=new w;pauseOnHidden=!1;_updateHandler;_startupClock=new Oi;_activeClock=new Oi;_frameClock=new Oi;_fixed;_fixedTime;_frameAlpha=0;_status=Yl.Stopped;_pixelRatio=Kl;_designWidth=Hl;_designHeight=jl;_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 fe;constructor(t={}){const e=t.canvas??{},i=t.loader??{},n=t.rendering??{},s=t.input??{},r=e.element??document.createElement("canvas"),o=e.width??Hl,a=e.height??jl;this._pixelRatio=e.pixelRatio??(()=>{const t=globalThis.devicePixelRatio;return"number"==typeof t&&t>0?Math.min(t,2):1})(),this._designWidth=o,this._designHeight=a,this.canvas=r,this._applyCanvasSize(o,a),void 0!==e.tabIndex?this.canvas.tabIndex=e.tabIndex:this.canvas.hasAttribute("tabindex")||(this.canvas.tabIndex=Ql),void 0!==e.imageRendering&&(this.canvas.style.imageRendering=e.imageRendering),this._mountCanvas(e.mount),this._sizingMode=e.sizingMode??"fixed",this._applySizingMode(this._sizingMode),this.options={clearColor:t.clearColor??Re.cornflowerBlue,backend:t.backend??Xl,canvas:{element:this.canvas,width:o,height:a,pixelRatio:this._pixelRatio,tabIndex:this.canvas.tabIndex,...void 0!==e.imageRendering&&{imageRendering:e.imageRendering}},loader:{basePath:i.basePath??"",fetchOptions:i.fetchOptions??{...Zl},...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??Jl.debug,webglAttributes:n.webglAttributes??Jl.webglAttributes,spriteRendererBatchSize:n.spriteRendererBatchSize??Jl.spriteRendererBatchSize},input:{gamepadDefinitions:s.gamepadDefinitions??[...tu.gamepadDefinitions],gamepadSlotStrategy:s.gamepadSlotStrategy??tu.gamepadSlotStrategy,pointerDistanceThreshold:s.pointerDistanceThreshold??tu.pointerDistanceThreshold}},this._snapshot=void 0===t.extensions?function(){if(0===Ae?.revision)return Ae.snapshot;const t=Me([...Pe.values()]);return Ae={revision:0,snapshot:t},t}():Me([...t.extensions??[]]),this.loader=new Qa(this.options.loader);try{!function(t,e){const i=new Set,n=new Set,s=new Set;for(const r of e){if(i.has(r.type)||t.hasLoadable(r.type))throw new Error(`An asset handler is already registered for ${r.type.name}.`);for(const e of r.typeNames??[]){if(n.has(e)||t.hasAssetType(e))throw new Error(`Asset type name "${e}" is already registered. Remove the conflicting binding.`);n.add(e)}for(const e of r.extensions??[]){const i=e.replace(/^\./,"").toLowerCase();if(s.has(i)||t.hasExtension(i))throw new Error(`File extension ".${i}" is already mapped to an asset type. Remove the conflicting binding.`);s.add(i)}i.add(r.type)}for(const i of e){const e=i.create(t);t.bindAsset({type:i.type,...void 0!==i.typeNames&&{typeNames:i.typeNames},...void 0!==i.extensions&&{extensions:i.extensions}},e)}}(this.loader,[...Ia,...this._snapshot.assets]),function(t,e){for(const i of e)t.register(i.typeName,i.target,i.serializer)}(this.serializers,this._snapshot.serializers)}catch(t){try{this.loader.destroy()}catch{}throw t}this._backendType=this.resolveInitialBackendType(),this._backend=this.createBackend(this._backendType,this._snapshot),this._rendering=new ao(this._backend),this.input=new Tn(this),this.focus=new Fi(this),this.interaction=new Pn(this),this.scene=new Wl(this),this.random=new Rn(this.options.seed),this._updateHandler=this.update.bind(this);const h=void 0!==this.options.fixedTimeStep?1e3*this.options.fixedTimeStep:$l;this._fixed=new lh(h,5),this._fixedTime=new Ni(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(t=>{this.onCanvasFocusChange.dispatch(t)}),this.onVisibilityChange.add(t=>{this._audio._applyVisibility(t)})}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(t){this.setCursor(t)}get sizingMode(){return this._sizingMode}set sizingMode(t){t!==this._sizingMode&&(this._resizeObserver?.disconnect(),this._resizeObserver=null,this._sizingMode=t,this._applySizingMode(t))}get clearColor(){return this._backend.clearColor}set clearColor(t){this._backend.clearColor.copy(t)}get audio(){return this._audio}get width(){return this._designWidth}get height(){return this._designHeight}get pixelRatio(){return this._pixelRatio}screenToWorld(t,e){return this._rendering.view.screenToWorld(t,e)}_backingStoreToDesign(t,e){const i=this.canvas.width||1,n=this.canvas.height||1;return{x:t/i*this._designWidth,y:e/n*this._designHeight}}async start(t){if(this._status===Yl.Stopped){this._status=Yl.Loading;const e=eh.ready;try{await this.initializeBackend(),this._capabilities=await e,await this.scene.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._fixed.reset(),this._activeClock.start(),this._status=Yl.Running}catch(t){throw this._status=Yl.Stopped,t}}return this}update(){if(this._status===Yl.Running){if(this.pauseOnHidden&&!this._documentVisible)return this._frameClock.restart(),this._fixed.reset(),this._frameRequest=requestAnimationFrame(this._updateHandler),this;const t=this._frameClock.elapsedTime.milliseconds,e=Math.min(t,100),i=Ni.temp.set(e),n=performance.now();this.backend.resetStats(),this.backend.stats.rawFrameDeltaMs=t,this.systems._tick(i);const s=this._fixed.advance(e);for(let t=0;t<s;t++)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===Yl.Running&&(this._status=Yl.Halting,cancelAnimationFrame(this._frameRequest),this.scene.setScene(null).catch(t=>{dh.error("core","Application.stop() failed to unload the active scene.",t instanceof Error?t:void 0),this.onError?.dispatch(t instanceof Error?t:new Error(String(t)))}),this._activeClock.stop(),this._frameClock.stop(),this._status=Yl.Stopped),this}resize(t,e){return this._designWidth=t,this._designHeight=e,this._applyCanvasSize(t,e),this.options.canvas={...this.options.canvas??{},width:t,height:e,pixelRatio:this._pixelRatio},this.backend.resize(t,e),this._rendering.resize(t,e),this.onResize.dispatch(t,e,this),this}_mountCanvas(t){if(void 0===t||"undefined"==typeof document)return;const e="string"==typeof t?document.querySelector(t):t;e?.append(this.canvas)}_applySizingMode(t){const e=this.canvas.style;switch(t){case"fill":{const t=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!t)break;this._resizeObserver=new ResizeObserver(()=>{const e=t.clientWidth,i=t.clientHeight;e>0&&i>0&&this.resize(e,i)}),this._resizeObserver.observe(t);break}case"letterbox":{const t=this.canvas.parentElement;if("undefined"==typeof ResizeObserver||!t)break;const e=t.style;e.display="flex",e.alignItems="center",e.justifyContent="center",e.overflow="hidden",e.background="#000",this._resizeObserver=new ResizeObserver(()=>{const e=t.clientWidth,i=t.clientHeight;e>0&&i>0&&this._applyLetterboxLayout(e,i)}),this._resizeObserver.observe(t);break}case"fit":e.width="100%",e.height="100%",e.objectFit="contain";break;case"shrink":e.maxWidth="100%",e.maxHeight="100%",e.objectFit="contain"}}_applyLetterboxLayout(t,e){const i=((t,e,i,n,s)=>{const r=Math.min(t/i,e/n),o=i*r,a=n*r;return{contentWidthCss:o,contentHeightCss:a,backingWidth:Math.max(1,Math.round(o*s)),backingHeight:Math.max(1,Math.round(a*s))}})(t,e,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(t){const e=t instanceof vi?t.source:t;if(null===e)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof e?e:`url(${y(e)}), auto`,this.canvas.style.cursor=this._cursor,this}capture(t,e){return this._rendering.capture(t,e)}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 t="visible"===document.visibilityState;t!==this._documentVisible&&(this._documentVisible=t,this.onVisibilityChange.dispatch(t))}resolveInitialBackendType(){const t=this.options.backend?.type;return"webgl2"===t?"webgl2":"webgpu"===t||this.canUseWebGpu()?"webgpu":"webgl2"}createBackend(t,e){const i=function(t){const e=t.spriteRendererBatchSize??4096,i={[tr.WebGl2]:()=>new Tr(e),[tr.WebGpu]:()=>new Zr},n={[tr.WebGl2]:()=>new _r,[tr.WebGpu]:()=>new Or},s={[tr.WebGl2]:()=>new Pr,[tr.WebGpu]:()=>new io},r={[tr.WebGl2]:()=>new mr(e),[tr.WebGpu]:()=>new Yr},o={[tr.WebGl2]:()=>new Sr(e),[tr.WebGpu]:()=>new Hr};return[{targets:[Ps],create:t=>i[t.backendType]?.()},{targets:[qn],create:t=>n[t.backendType]?.()},{targets:[Zs,Fs],create:t=>s[t.backendType]?.()},{targets:[ys],create:t=>r[t.backendType]?.()},{targets:[Ms],create:t=>o[t.backendType]?.()}]}(this.options.rendering??{}),n=[...i,...e.renderers];if("webgpu"===t){const t=new Ro(this);t.onDeviceLost.add(()=>{this.onBackendLost.dispatch()}),t.onDeviceRestored.add(()=>{this.onBackendRestored.dispatch()});try{Ee(t,n)}catch(e){try{t.destroy()}catch{}throw e}return t}const s=new Co(this);s.onContextLost.add(()=>{this.onBackendLost.dispatch()}),s.onContextRestored.add(()=>{this.onBackendRestored.dispatch()});try{Ee(s,n)}catch(t){try{s.destroy()}catch{}throw t}return s}async initializeBackend(){try{await this._backend.initialize()}catch(t){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw t;this._backend.destroy(),this._backendType="webgl2",this._backend=this.createBackend(this._backendType,this._snapshot);const e=this._rendering;this.systems.remove(e),e.destroy(),this._rendering=new ao(this._backend),this.systems.add(this._rendering),await this._backend.initialize()}}canUseWebGpu(){return!!navigator.gpu}_applyCanvasSize(t,e){const i=Math.round(t*this._pixelRatio),n=Math.round(e*this._pixelRatio);this.canvas.width=i,this.canvas.height=n,this.canvas.style.width=`${t}px`,this.canvas.style.height=`${e}px`}}const iu=Object.freeze({version:"0.15.1",revision:"6f825a8",development:!1});const nu={decodeBase64:function(t){const e=t.replaceAll(/\s+/g,""),i=atob(e),n=i.length,s=new Uint8Array(n);for(let t=0;t<n;t++)s[t]=i.charCodeAt(t);return s},decompress:async function(t,e){if("undefined"==typeof DecompressionStream)throw new Error("Codec.decompress requires the native DecompressionStream API.");const i=new ReadableStream({start(e){e.enqueue(t),e.close()}}).pipeThrough(new DecompressionStream(e)).getReader(),n=[];let s=0;for(;;){const{done:t,value:e}=await i.read();if(t)break;n.push(e),s+=e.length}const r=new Uint8Array(s);let o=0;for(const t of n)r.set(t,o),o+=t.length;return r}},su="undefined"!=typeof performance,ru={mark:t=>{su&&"function"==typeof performance.mark&&performance.mark(t)},measure:(t,e,i)=>{if(su&&"function"==typeof performance.measure)try{return performance.measure(t,e,i)}catch{return}},clearMarks:t=>{su&&"function"==typeof performance.clearMarks&&performance.clearMarks(t)},clearMeasures:t=>{su&&"function"==typeof performance.clearMeasures&&performance.clearMeasures(t)}};class ou{_descriptor;constructor(t){this._descriptor=t}static from(t,e=null,i){return new ou(Fl(t,e,i))}static fromJSON(t){return new ou(t)}instantiate(t=null,e){return function(t,e=null,i=Pl){return Dl(),Ul(t,Il(e,1,i),i)}(this._descriptor,t,e)}toJSON(){return this._descriptor}}const au=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]]]),hu=new Map([["ButtonNorth",Wi.North],["ButtonWest",Wi.West],["ButtonEast",Wi.East],["ButtonSouth",Wi.South],["LeftShoulder",Wi.LeftShoulder],["RightShoulder",Wi.RightShoulder],["LeftTrigger",Wi.LeftTrigger],["RightTrigger",Wi.RightTrigger],["Select",Wi.Select],["Start",Wi.Start],["LeftStick",Wi.LeftStick],["RightStick",Wi.RightStick],["DPadUp",Wi.DPadUp],["DPadDown",Wi.DPadDown],["DPadLeft",Wi.DPadLeft],["DPadRight",Wi.DPadRight]]),lu=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"]]),uu=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"]]),cu=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"]]),du=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"]]),_u=new Map([[$i.GenericDualAnalog,lu],[$i.Xbox,uu],[$i.PlayStation,cu],[$i.SwitchPro,du],[$i.JoyConLeft,du],[$i.JoyConRight,du],[$i.GameCube,lu],[$i.SteamController,lu],[$i.SteamDeck,lu],[$i.ArcadeStick,lu]]);class fu{static controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];static getControlPosition(t){return au.get(t)??[.5,.5]}static getControlLabels(t){return _u.get(t)??lu}static getControlChannelMap(){return hu}}let pu=null;class mu{static collisionSegments=32;collisionType=it.Circle;_position;_collisionVertices=null;_verticesDirty=!0;_normals=null;_normalsDirty=!0;_radius;constructor(t=0,e=0,i=0){this._position=new ie(t,e),this._radius=i}get position(){return this._position}set position(t){this._position.copy(t),this._verticesDirty=!0,this._normalsDirty=!0}get x(){return this._position.x}set x(t){this._position.x!==t&&(this._position.x=t,this._verticesDirty=!0,this._normalsDirty=!0)}get y(){return this._position.y}set y(t){this._position.y!==t&&(this._position.y=t,this._verticesDirty=!0,this._normalsDirty=!0)}get radius(){return this._radius}set radius(t){this._radius!==t&&(this._radius=t,this._verticesDirty=!0,this._normalsDirty=!0)}setPosition(t,e){return this._position.set(t,e),this._verticesDirty=!0,this._normalsDirty=!0,this}setRadius(t){return this._radius!==t&&(this._radius=t,this._verticesDirty=!0,this._normalsDirty=!0),this}set(t,e,i){return this._position.set(t,e),this._radius=i,this._verticesDirty=!0,this._normalsDirty=!0,this}copy(t){return this._position.copy(t.position),this._radius=t.radius,this._verticesDirty=!0,this._normalsDirty=!0,this}clone(){return new mu(this.x,this.y,this.radius)}equals({x:t,y:e,radius:i}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.radius!==i)}getBounds(){return new te(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){if(this._normalsDirty){const t=this.getCollisionVertices();null===this._normals&&(this._normals=t.map(()=>new ie));for(let e=0;e<t.length;e++){const i=t[e],n=t[(e+1)%t.length];this._normals[e].set(n.x-i.x,n.y-i.y).rperp().normalize()}this._normalsDirty=!1}return this._normals}project(t,e=new mt){const i=t.dot(this.x,this.y),n=this.radius*t.length;return e.set(i-n,i+n)}contains(t,e){return vt(ie.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case it.SceneNode:return Et(t.getBounds(),this);case it.Rectangle:return Et(t,this);case it.Polygon:return Gt(this,t);case it.Circle:return Dt(this,t);case it.Ellipse:return It(this,t);case it.Line:return Tt(t,this);case it.Point:return vt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case it.SceneNode:return Wt(this,t.getBounds());case it.Rectangle:return Wt(this,t);case it.Polygon:return Xt(t,this,!0);case it.Circle:return qt(this,t);case it.Ellipse:return $t(t,this,!0);default:return null}}destroy(){if(this._position.destroy(),null!==this._collisionVertices){for(const t of this._collisionVertices)t.destroy();this._collisionVertices=null}if(null!==this._normals){for(const t of this._normals)t.destroy();this._normals=null}}getCollisionVertices(){if(this._verticesDirty){const t=mu.collisionSegments;if(null===this._collisionVertices){this._collisionVertices=new Array(t);for(let e=0;e<t;e++)this._collisionVertices[e]=new ie}for(let e=0;e<t;e++){const i=2*e*Math.PI/t-Math.PI/2,n=Math.cos(i)*this._radius,s=Math.sin(i)*this._radius;this._collisionVertices[e].set(this._radius+n,this._radius+s)}this._verticesDirty=!1}return this._collisionVertices}static get temp(){return null===pu&&(pu=new mu),pu}}class gu{collisionType=it.Ellipse;_position;_radius;constructor(t=0,e=0,i=0,n=i){this._position=new ie(t,e),this._radius=new ie(i,n)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius.copy(t)}get rx(){return this._radius.x}set rx(t){this._radius.x=t}get ry(){return this._radius.y}set ry(t){this._radius.y=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t,e=t){return this._radius.set(t,e),this}set(t,e,i,n){return this._position.set(t,e),this._radius.set(i,n),this}copy(t){return this._position.copy(t.position),this._radius.copy(t.radius),this}clone(){return new gu(this.x,this.y,this.rx,this.ry)}getBounds(){return new te(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new mt){const i=this.x*t.x+this.y*t.y,n=Math.sqrt((this.rx*t.x)**2+(this.ry*t.y)**2);return e.set(i-n,i+n)}intersectsWith(t){switch(t.collisionType){case it.SceneNode:return kt(t.getBounds(),this);case it.Rectangle:return kt(t,this);case it.Polygon:return Ot(this,t);case it.Circle:return It(t,this);case it.Ellipse:return Nt(this,t);case it.Line:return Mt(t,this);case it.Point:return bt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case it.SceneNode:return Yt(this,t.getBounds());case it.Rectangle:return Yt(this,t);case it.Circle:return $t(this,t);case it.Polygon:return jt(this,t);case it.Ellipse:return Ht(this,t);default:return null}}contains(t,e){return bt(ie.temp.set(t,e),this)}equals({x:t,y:e,rx:i,ry:n}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.rx!==i||void 0!==n&&this.ry!==n)}destroy(){this._position.destroy(),this._radius.destroy()}}let yu=null;class wu{collisionType=it.Line;_fromPosition;_toPosition;constructor(t=0,e=0,i=0,n=0){this._fromPosition=new ie(t,e),this._toPosition=new ie(i,n)}get fromPosition(){return this._fromPosition}set fromPosition(t){this._fromPosition.copy(t)}get fromX(){return this._fromPosition.x}set fromX(t){this._fromPosition.x=t}get fromY(){return this._fromPosition.y}set fromY(t){this._fromPosition.y=t}get toPosition(){return this._toPosition}set toPosition(t){this._toPosition.copy(t)}get toX(){return this._toPosition.x}set toX(t){this._toPosition.x=t}get toY(){return this._toPosition.y}set toY(t){this._toPosition.y=t}set(t,e,i,n){return this._fromPosition.set(t,e),this._toPosition.set(i,n),this}copy(t){return this._fromPosition.copy(t.fromPosition),this.toPosition.copy(t.toPosition),this}clone(){return new wu(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:t,fromY:e,toX:i,toY:n}=this,s=Math.min(t,i),r=Math.min(e,n);return new te(s,r,Math.max(t,i)-s,Math.max(e,n)-r)}getNormals(){return[]}project(t,e=new mt){return e}intersectsWith(t){switch(t.collisionType){case it.SceneNode:return Ct(this,t.getBounds());case it.Rectangle:return Ct(this,t);case it.Polygon:return At(this,t);case it.Circle:return Tt(this,t);case it.Ellipse:return Mt(this,t);case it.Line:return Bt(this,t);case it.Point:return wt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return wt(ie.temp.set(t,e),this,i)}equals({fromX:t,fromY:e,toX:i,toY:n}={}){return!(void 0!==t&&this.fromX!==t||void 0!==e&&this.fromY!==e||void 0!==i&&this.toX!==i||void 0!==n&&this.toY!==n)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===yu&&(yu=new wu),yu}}class xu{radius;phi;constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new xu(t.length,t.angle)}toVector(){return ie.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}let vu=null;class bu{_startPoint;_endPoint;constructor(t=0,e=0,i=0,n=0){this._startPoint=new ie(t,e),this._endPoint=new ie(i,n)}get startPoint(){return this._startPoint}set startPoint(t){this._startPoint.copy(t)}get startX(){return this._startPoint.x}set startX(t){this._startPoint.x=t}get startY(){return this._startPoint.y}set startY(t){this._startPoint.y=t}get endPoint(){return this._endPoint}set endPoint(t){this._endPoint.copy(t)}get endX(){return this._endPoint.x}set endX(t){this._endPoint.x=t}get endY(){return this._endPoint.y}set endY(t){this._endPoint.y=t}set(t,e,i,n){return this._startPoint.set(t,e),this._endPoint.set(i,n),this}copy(t){return this._startPoint.copy(t.startPoint),this._endPoint.copy(t.endPoint),this}clone(){return new bu(this.startX,this.startY,this.endX,this.endY)}equals({startX:t,startY:e,endX:i,endY:n}={}){return!(void 0!==t&&this.startX!==t||void 0!==e&&this.startY!==e||void 0!==i&&this.endX!==i||void 0!==n&&this.endY!==n)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===vu&&(vu=new bu),vu}}function Su(t,e,i,n){const s=t.x,r=t.x+t.width,o=t.y,a=t.y+t.height,h=n.x,l=n.x+n.width,u=n.y,c=n.y+n.height;let d=-1/0,_=1/0;if(e>0)d=(h-r)/e,_=(l-s)/e;else if(e<0)d=(l-s)/e,_=(h-r)/e;else if(r<=h||s>=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=t.x+e*y,x=t.y+i*y;let v=0,b=0;if(m<=0){Math.min(r-h,l-s)<Math.min(a-u,c-o)?v=s<h?-1:1:b=o<u?-1:1}else d>f?v=e>0?-1:1:b=i>0?-1:1;return{t:y,x:w,y:x,normalX:v,normalY:b}}function Bu(t,e,i,n){const s=t.x-n.x,r=t.y-n.y,o=t.radius+n.radius,a=e*e+i*i,h=2*(s*e+r*i),l=s*s+r*r-o*o;if(l<=0){const e=Math.sqrt(s*s+r*r),i=e>0?s/e:1,n=e>0?r/e:0;return{t:0,x:t.x,y:t.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=t.x+e*c,_=t.y+i*c;return{t:c,x:d,y:_,normalX:(d-n.x)/o,normalY:(_-n.y)/o}}const Cu={rectangle:Su,circleVsRectangle:function(t,e,i,n){const s=t.radius,r=t.x,o=t.y,a=n.x,h=n.x+n.width,l=n.y,u=n.y+n.height,c=r-Math.max(a,Math.min(r,h)),d=o-Math.max(l,Math.min(o,u));if(c*c+d*d<=s*s){const t=Math.sqrt(c*c+d*d);if(t>0)return{t:0,x:r,y:o,normalX:c/t,normalY:d/t};const e=r-a,i=h-r,n=o-l,s=u-o;return Math.min(e,i)<=Math.min(n,s)?{t:0,x:r,y:o,normalX:e<i?-1:1,normalY:0}:{t:0,x:r,y:o,normalX:0,normalY:n<s?-1:1}}if(0===e&&0===i)return null;let _=1/0,f=0,p=0;const m=(t,e,i)=>{t>=0&&t<=1&&t<_&&(_=t,f=e,p=i)};if(0!==e){const t=(a-s-r)/e;if(t>=0&&t<=1){const e=o+i*t;e>=l&&e<=u&&m(t,-1,0)}const n=(h+s-r)/e;if(n>=0&&n<=1){const t=o+i*n;t>=l&&t<=u&&m(n,1,0)}}if(0!==i){const t=(l-s-o)/i;if(t>=0&&t<=1){const i=r+e*t;i>=a&&i<=h&&m(t,0,-1)}const n=(u+s-o)/i;if(n>=0&&n<=1){const t=r+e*n;t>=a&&t<=h&&m(n,0,1)}}const g=e*e+i*i,y=[a,h,a,h],w=[l,l,u,u];for(let t=0;t<4;t++){const n=y[t],a=w[t],h=r-n,l=o-a,u=2*(h*e+l*i),c=u*u-4*g*(h*h+l*l-s*s);if(c<0)continue;const d=(-u-Math.sqrt(c))/(2*g);if(d<0||d>1)continue;m(d,(r+e*d-n)/s,(o+i*d-a)/s)}return _>1?null:{t:_,x:r+e*_,y:o+i*_,normalX:f,normalY:p}},circleVsCircle:Bu,rectangleAgainst:function(t,e,i,n){if(0===n.length)return null;const s=Math.min(t.x,t.x+e),r=Math.max(t.x+t.width,t.x+t.width+e),o=Math.min(t.y,t.y+i),a=Math.max(t.y+t.height,t.y+t.height+i);let h=null;for(const l of n){if(r<=l.x||s>=l.x+l.width||a<=l.y||o>=l.y+l.height)continue;const n=Su(t,e,i,l);null!==n&&(null===h||n.t<h.t)&&(h=n)}return h},circleAgainst:function(t,e,i,n){if(0===n.length)return null;const s=Math.min(t.x,t.x+e)-t.radius,r=Math.max(t.x,t.x+e)+t.radius,o=Math.min(t.y,t.y+i)-t.radius,a=Math.max(t.y,t.y+i)+t.radius;let h=null;for(const l of n){if(r<=l.x-l.radius||s>=l.x+l.radius||a<=l.y-l.radius||o>=l.y+l.radius)continue;const n=Bu(t,e,i,l);null!==n&&(null===h||n.t<h.t)&&(h=n)}return h},substep:function*(t,e,i,n,s){const r=Math.hypot(i,n),o=Math.max(1,Math.ceil(r/s));for(let s=0;s<=o;s++){const r=s/o;yield{x:t+i*r,y:e+n*r,t:r}}}};class Tu{_context;target;view;constructor(t,e,i){this._context=t,this.target=e,this.view=i}get backend(){return this._context.backend}clear(t){this._context.clear(t)}render(t,e){this._context.render(t,{view:e?.view??this.view})}renderTo(t,e){this._context.renderTo(t,e)}drawGeometry(t,e,i){this._context.drawGeometry(t,e,{...i,view:i?.view??this.view})}drawBatch(t,e){this._context.drawBatch(t,{...e,view:e?.view??this.view})}}class Mu{enabled;label;_pipelineOwner=null;constructor(t){this.enabled=t?.enabled??!0,this.label=t?.label??new.target.name}resize(t,e){}destroy(){}}class Au extends Mu{_callback;_clear;_target;_view;_redirect;_activeContext=null;_executing=!1;constructor(t,e){super(e),this._callback=t,this._clear=e?.clear??null,this._target=e?.target??null,this._view=e?.view??null,this._redirect=null!==this._target?new Mi(()=>this._runCallback(),{target:this._target,view:this._view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(t){if(this._executing)throw new Error("CallbackRenderPass.execute is not re-entrant.");this._executing=!0;try{if(null!==this._redirect){this._activeContext=t;try{t.backend.execute(this._redirect)}finally{this._activeContext=null}return}null!==this._clear&&t.backend.clear(this._clear),this._callback(new Tu(t,t.backend.renderTarget,t.backend.view))}finally{this._executing=!1}}_runCallback(){null!==this._activeContext&&null!==this._target&&this._callback(new Tu(this._activeContext,this._target,this._view??this._target.view))}}class Pu extends Mu{_node;_target;_clear;_renderOptions;_redirect;constructor(t,e){super(e),this._node=t,this._target=e?.target??null,this._clear=e?.clear??null,this._renderOptions=void 0!==e?.view?{view:e.view}:{},this._redirect=null!==this._target?new Mi(t=>Ci(this._node,t),{target:this._target,view:e?.view??this._target.view,...null!==this._clear&&{clearColor:this._clear}}):null}execute(t){null===this._redirect?(null!==this._clear&&t.backend.clear(this._clear),t.render(this._node,this._renderOptions)):t.backend.execute(this._redirect)}}class Eu extends Mu{_passes=[];_executing=!1;_destroyed=!1;constructor(t){super(t)}get size(){return this._passes.length}addPass(t){return this._admit(t),this._passes.push(t),t._pipelineOwner=this,this}insertPass(t,e){this._admit(t);const i=Math.max(0,Math.min(e,this._passes.length));return this._passes.splice(i,0,t),t._pipelineOwner=this,this}removePass(t){this._assertLive(),this._assertNotExecuting();const e=this._passes.indexOf(t);return-1!==e&&(this._passes.splice(e,1),t._pipelineOwner=null,!0)}clear(){this._assertLive(),this._assertNotExecuting();for(const t of this._passes)t._pipelineOwner=null;return this._passes.length=0,this}hasPass(t){return t._pipelineOwner===this}indexOf(t){return this._passes.indexOf(t)}at(t){return this._passes[t]}[Symbol.iterator](){return this._passes[Symbol.iterator]()}execute(t){if(this.enabled){if(this._assertLive(),this._executing)throw new Error("RenderPipeline.execute is not re-entrant.");this._executing=!0;try{for(const e of this._passes)e.enabled&&e.execute(t)}finally{this._executing=!1}}}resize(t,e){for(const i of this._passes)i.resize(t,e)}destroy(){if(this._destroyed)return;this._assertNotExecuting(),this._destroyed=!0;const t=this._passes.splice(0,this._passes.length),e=[];for(const i of t){i._pipelineOwner=null;try{i.destroy()}catch(t){e.push(t)}}if(e.length>0)throw e[0]}_admit(t){if(this._assertLive(),this._assertNotExecuting(),null!==t._pipelineOwner)throw new Error("RenderPass already belongs to a RenderPipeline; remove it from its current pipeline first.");if(t instanceof Eu&&t._reaches(this))throw new Error("RenderPipeline cannot contain itself, directly or indirectly (cycle).")}_reaches(t){if(this===t)return!0;for(const e of this._passes)if(e instanceof Eu&&e._reaches(t))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 ku{destroy(){}}class Ru extends ku{_sprite=new Ps(null);_sampleTint=Re.white.clone();_radius=2;_quality=1;constructor(t={}){super(),this._radius=Math.max(0,t.radius??2),this._quality=Math.max(1,Math.floor(t.quality??1))}get radius(){return this._radius}set radius(t){this._radius=Math.max(0,t)}get quality(){return this._quality}set quality(t){this._quality=Math.max(1,Math.floor(t))}apply(t,e,i){const n=this._radius,s=this._quality,r=Math.max(1,2*s+1),o=1/(n<=0?1:2*r);this._sampleTint.set(255,255,255,o),this._sprite.setTexture(e).setBlendMode(qe.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new Mi(()=>{if(n<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<r;e++){const i=(2*(1===r?0:e/(r-1))-1)*n;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:i,view:i.view,clearColor:Re.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}}class Du extends ku{_color;_sprite=new Ps(null);constructor(t=Re.white){super(),this._color=t.clone()}get color(){return this._color}apply(t,e,i){this._sprite.setTexture(e).setBlendMode(qe.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new Mi(()=>{this._sprite.render(t)},{target:i,view:i.view,clearColor:Re.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}}const Iu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);class Lu extends ku{uniforms;_fragmentSource;_vertexSource;_shader=null;_connection=null;constructor(t){if(super(),!t.fragmentSource)throw new Error("WebGl2ShaderFilter requires fragmentSource for the WebGL2 backend.");const e=!1!==t.autoUpgrade;var i;this._fragmentSource=e?(i=t.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")):t.fragmentSource,this._vertexSource=t.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={...t.uniforms??{}}}apply(t,e,i){if(t.backendType===tr.WebGpu)throw new Error("WebGl2ShaderFilter requires the WebGL2 backend. Use WebGpuShaderFilter on WebGPU.");const n=t;this._ensureConnected(n);const s=this._shader;t.execute(new Mi(t=>{const n=t;n.bindShader(s),n.bindTexture(e,0),s.uniforms.has("uTexture")&&s.getUniform("uTexture").setValue(new Int32Array([0])),s.uniforms.has("uResolution")&&s.getUniform("uResolution").setValue(new Float32Array([i.width,i.height]));let r=1;for(const[t,e]of Object.entries(this.uniforms)){if(!s.uniforms.has(t))continue;const i=s.getUniform(t);e instanceof vi?(n.bindTexture(e,r),i.setValue(new Int32Array([r])),r++):i.setValue(this._marshalValue(e))}s.sync();const o=this._connection;n.bindVertexArrayObject(o.vao),o.vao.draw(4,0,Xe.TriangleStrip)},{target:i,view:i.view,clearColor:Re.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 t of Object.keys(this.uniforms))delete this.uniforms[t]}_ensureConnected(t){if(null!==this._shader)return;const e=t.context,i=new Js(this._vertexSource,this._fragmentSource);i.connect(lr(e)),i.sync();const n=e.createVertexArray();if(null===n)throw new Error("WebGl2ShaderFilter: could not create vertex array object.");const s=this._createVertexBuffer(e),r=this._createVao(e,n,i,s);this._shader=i,this._connection={gl:e,vertexBuffer:s,vao:r}}_createVertexBuffer(t){const e=t.createBuffer();if(null===e)throw new Error("WebGl2ShaderFilter: could not create vertex buffer.");const i=new ir(He.ArrayBuffer,Iu,je.StaticDraw);return i.connect({bind:()=>{t.bindBuffer(t.ARRAY_BUFFER,e)},upload:(i,n)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,i.data,i.usage)},destroy:i=>{t.deleteBuffer(e),i.disconnect()}}),i}_createVao(t,e,i,n){let s=-1;const r=new cr(Xe.TriangleStrip);return i.attributes.has("aPosition")&&r.addAttribute(n,i.getAttribute("aPosition"),t.FLOAT,!1,16,0),i.attributes.has("aUv")&&r.addAttribute(n,i.getAttribute("aUv"),t.FLOAT,!1,16,8),r.connect({bind:i=>{if(t.bindVertexArray(e),s!==i.version){let e=null;for(const n of i.attributes){const i=n.buffer;e!==i&&(i.bind(),e=i),t.vertexAttribPointer(n.location,n.size,n.type,n.normalized,n.stride,n.start),t.enableVertexAttribArray(n.location)}s=i.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,n,s)=>{t.drawArrays(s,n,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}),r}_marshalValue(t){return t instanceof Float32Array||t instanceof Int32Array?t:"number"==typeof t?new Float32Array([t]):new Float32Array(t)}}const Uu=new Float32Array([-1,-1,0,0,1,-1,1,0,-1,1,0,1,1,1,1,1]);function Fu(t){return t instanceof vi||"object"==typeof t&&null!==t&&"width"in t&&"height"in t&&!(t instanceof Float32Array)&&!(t instanceof Int32Array)&&!Array.isArray(t)}class Gu extends ku{uniforms;_fragmentSource;_vertexSource;_connection=null;constructor(t){if(super(),!t.fragmentSource)throw new Error("WebGpuShaderFilter requires fragmentSource.");this._fragmentSource=t.fragmentSource,this._vertexSource=t.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={...t.uniforms??{}}}apply(t,e,i){if(t.backendType!==tr.WebGpu)throw new Error("WebGpuShaderFilter requires the WebGPU backend. Use WebGl2ShaderFilter on WebGL2.");const n=t;this._ensureConnected(n,i);const s=this._connection;t.execute(new Mi(t=>{const n=t,r=s.device,o=new Float32Array([i.width,i.height,0,0]);r.queue.writeBuffer(s.resolutionBuffer,0,o);const a=n.getTextureBinding(e),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(n,s),u=n._passCoordinator.acquirePass().pass;u.setPipeline(s.pipeline),u.setVertexBuffer(0,s.vertexBuffer),u.setBindGroup(0,h),u.setBindGroup(1,l),u.draw(4),n.stats.drawCalls++,n._passCoordinator.endPass()},{target:i,view:i.view,clearColor:Re.transparentBlack}))}destroy(){null!==this._connection&&(this._connection.vertexBuffer.destroy(),this._connection.resolutionBuffer.destroy(),this._connection.userUniformBuffer?.destroy(),this._connection=null);for(const t of Object.keys(this.uniforms))delete this.uniforms[t]}_ensureConnected(t,e){if(null!==this._connection)return;const i=t.device,n=i.createShaderModule({code:this._vertexSource}),s=i.createShaderModule({code:this._fragmentSource}),r=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:[r,o]}),h=t.getTextureFormat(e),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:s,entryPoint:"main",targets:[{format:h}]},primitive:{topology:"triangle-strip"}}),u=i.createBuffer({size:Uu.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});i.queue.writeBuffer(u,0,Uu);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:r,userBindGroupLayout:o,pipelineLayout:a,pipeline:l,sampler:d,userUniformBuffer:null}}_buildUserBindGroupLayout(t){const e=[];Object.values(this.uniforms).some(t=>!Fu(t))&&e.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}});let i=1;for(const t of Object.values(this.uniforms))Fu(t)&&(e.push({binding:i,visibility:GPUShaderStage.FRAGMENT,texture:{}}),i++,e.push({binding:i,visibility:GPUShaderStage.FRAGMENT,sampler:{}}),i++);return 0===e.length&&e.push({binding:0,visibility:GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}),t.createBindGroupLayout({entries:e})}_buildUserBindGroup(t,e){const i=e.device,n=[],s=Object.entries(this.uniforms).filter(([,t])=>!Fu(t));if(s.length>0){const t=16*s.length,r=new Float32Array(t/4);let o=0;for(const[,t]of s){const e=4*o;if("number"==typeof t)r[e]=t;else if(t instanceof Float32Array)r.set(t,e);else if(t instanceof Int32Array)for(let i=0;i<t.length;i++)r[e+i]=t[i];else{const i=t;for(let t=0;t<i.length;t++)r[e+t]=i[t]}o++}(null===e.userUniformBuffer||e.userUniformBuffer.size<t)&&(e.userUniformBuffer?.destroy(),e.userUniformBuffer=i.createBuffer({size:t,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),i.queue.writeBuffer(e.userUniformBuffer,0,r),n.push({binding:0,resource:{buffer:e.userUniformBuffer}})}else null===e.userUniformBuffer&&(e.userUniformBuffer=i.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),n.push({binding:0,resource:{buffer:e.userUniformBuffer}});let r=1;for(const[,e]of Object.entries(this.uniforms)){if(!Fu(e))continue;const i=t.getTextureBinding(e);n.push({binding:r,resource:i.view}),r++,n.push({binding:r,resource:i.sampler}),r++}return i.createBindGroup({layout:e.userBindGroupLayout,entries:n})}}class Nu extends ku{static identityLut1D(t=256){const e=document.createElement("canvas");e.width=t,e.height=1;const i=e.getContext("2d");if(null===i)throw new Error("LutFilter.identityLut1D: 2D canvas context unavailable.");const n=i.createImageData(t,1);for(let e=0;e<t;e++){const i=Math.round(e/(t-1)*255),s=4*e;n.data[s]=i,n.data[s+1]=i,n.data[s+2]=i,n.data[s+3]=255}return i.putImageData(n,0,0),new vi(e,{scaleMode:Ye.Linear,wrapMode:$e.ClampToEdge,generateMipMap:!1})}static identityLut3D(t=17){const e=t*t,i=document.createElement("canvas");i.width=e,i.height=t;const n=i.getContext("2d");if(null===n)throw new Error("LutFilter.identityLut3D: 2D canvas context unavailable.");const s=n.createImageData(e,t),r=t-1;for(let i=0;i<t;i++){const n=Math.round(i/r*255);for(let o=0;o<t;o++){const a=Math.round(o/r*255);for(let h=0;h<t;h++){const l=Math.round(h/r*255),u=4*(o*e+(i*t+h));s.data[u]=l,s.data[u+1]=a,s.data[u+2]=n,s.data[u+3]=255}}}return n.putImageData(s,0,0),new vi(i,{scaleMode:Ye.Linear,wrapMode:$e.ClampToEdge,generateMipMap:!1})}static fromImage(t){return new vi(t,{scaleMode:Ye.Linear,wrapMode:$e.ClampToEdge,generateMipMap:!1})}_mode;_size;_lut;_backendFilter=null;constructor(t={}){super(),this._mode=t.mode??"3d",this._size=Math.max(2,Math.floor(t.size??17)),this._lut="1d"===this._mode?Nu.identityLut1D():Nu.identityLut3D(this._size)}get mode(){return this._mode}get size(){return this._size}get lut(){return this._lut}setLut(t){return this._lut=t,null!==this._backendFilter&&(this._backendFilter.uniforms.uLut=t),this}apply(t,e,i){null===this._backendFilter&&(this._backendFilter=this._createBackendFilter(t)),this._backendFilter.apply(t,e,i)}destroy(){null!==this._backendFilter&&(this._backendFilter.destroy(),this._backendFilter=null)}_createBackendFilter(t){const e="3d"===this._mode,i={uLut:this._lut};return e&&(i.uLutSize=this._size),t.backendType===tr.WebGpu?new Gu({fragmentSource:e?"\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:i}):new Lu({fragmentSource:e?"#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:i})}}const Ou={f32:4,u8:1,u16:2,u32:4,i32:4},Vu=new Set(["triangle-list","triangle-strip"]),zu=new Set(["static","dynamic","stream"]),qu=new Set(["a_position","position"]),Wu=new WeakMap;let Yu=1;const $u=(t,e)=>{const{byteLength:i}=t;if(i%e!==0)throw new Error(`Geometry vertexData byteLength ${i} must be divisible by stride ${e}.`);return i/e},Xu=(t,e,i,n)=>{switch(e){case"f32":return t.getFloat32(i,!0);case"u8":{const e=t.getUint8(i);return n?e/255:e}case"u16":{const e=t.getUint16(i,!0);return n?e/65535:e}case"u32":{const e=t.getUint32(i,!0);return n?e/4294967295:e}case"i32":{const e=t.getInt32(i,!0);return n?Math.max(e/2147483647,-1):e}default:return 0}};class Hu{attributes;stride;topology;usage;indices;vertexData;_version=0;_localBounds=new te;_localBoundsDirty=!0;_positionAttribute;_disposeCallbacks=new Set;constructor(t){const{attributes:e,vertexData:i,stride:n,indices:s=null,topology:r="triangle-list",usage:o="static"}=t;if(0===e.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(!Vu.has(r))throw new Error(`Geometry topology must be one of: triangle-list, triangle-strip (got ${String(r)}).`);if(!zu.has(o))throw new Error(`Geometry usage must be one of: static, dynamic, stream (got ${String(o)}).`);const a=[],h=new Set;for(const t of e){if("string"!=typeof t.name||0===t.name.length)throw new Error("Geometry attribute name must be a non-empty string.");if(h.has(t.name))throw new Error(`Geometry attribute "${t.name}" is declared more than once.`);if(h.add(t.name),!Number.isInteger(t.size)||t.size<1||t.size>4)throw new Error(`Geometry attribute "${t.name}" size must be an integer in [1..4] (got ${t.size}).`);if(!Number.isInteger(t.offset)||t.offset<0)throw new Error(`Geometry attribute "${t.name}" offset must be a non-negative integer (got ${t.offset}).`);const e=Ou[t.type],i=t.offset+e*t.size;if(i>n)throw new Error(`Geometry attribute "${t.name}" range [${t.offset}, ${i}) exceeds stride ${n}.`);for(const e of a)if(t.offset<e.end&&i>e.start)throw new Error(`Geometry attribute "${t.name}" overlaps attribute "${e.name}" in the interleaved layout.`);a.push({name:t.name,start:t.offset,end:i})}const l=(t=>{const e=t.find(t=>qu.has(t.name));if(e)return e;const i=t.find(t=>t.name.toLowerCase().includes("position"));if(i)return i;throw new Error("Geometry requires a position attribute named `a_position` or `position`.")})(e);if(l.size<2)throw new Error(`Geometry position attribute "${l.name}" must declare at least 2 components.`);const u=$u(i,n);if(null!==s)for(let t=0;t<s.length;t++){const e=s[t];if(e>=u)throw new Error(`Geometry index ${e} at position ${t} is out of range for vertex count ${u}.`)}this.attributes=(t=>t.map(t=>({...t})))(e),this.vertexData=i,this.stride=n,this.indices=s,this.topology=r,this.usage=o,this._positionAttribute={...l}}get vertexCount(){return $u(this.vertexData,this.stride)}get indexCount(){return this.indices?.length??this.vertexCount}get version(){return this._version}get id(){return(t=>{const e=Wu.get(t);if(void 0!==e)return e;const i=Yu++;return Wu.set(t,i),i})(this)}invalidate(){return this._version++,this._localBoundsDirty=!0,this}getLocalBounds(t=this._localBounds){return this._localBoundsDirty&&this.recomputeLocalBounds(),t===this._localBounds?this._localBounds:t.copy(this._localBounds)}recomputeLocalBounds(){const t=this.vertexCount;if(0===t)return this._localBounds.set(0,0,0,0),this._localBoundsDirty=!1,this;const e=this.vertexData instanceof Float32Array?new DataView(this.vertexData.buffer,this.vertexData.byteOffset,this.vertexData.byteLength):new DataView(this.vertexData),i=Ou[this._positionAttribute.type];let n=1/0,s=1/0,r=-1/0,o=-1/0;for(let a=0;a<t;a++){const t=a*this.stride+this._positionAttribute.offset,h=Xu(e,this._positionAttribute.type,t,this._positionAttribute.normalized),l=Xu(e,this._positionAttribute.type,t+i,this._positionAttribute.normalized);h<n&&(n=h),h>r&&(r=h),l<s&&(s=l),l>o&&(o=l)}return this._localBounds.set(n,s,r-n,o-s),this._localBoundsDirty=!1,this}destroy(){for(const t of this._disposeCallbacks)t();this._disposeCallbacks.clear()}_onDispose(t){this._disposeCallbacks.add(t)}}const ju=(t,e)=>t.offset-e.offset;class Ku{_stops;_sample=new Float32Array(4);constructor(t){this._stops=Ku._normalizeStops(t)}get stops(){return this._stops}copy(t){return this._stops=t._stops.map(t=>({offset:t.offset,color:t.color.clone()})),this._copyGeometry(t),this}equals(t){if(this===t)return!0;if(this.type!==t.type||this._stops.length!==t._stops.length)return!1;for(let e=0;e<this._stops.length;e++){const i=this._stops[e],n=t._stops[e];if(i.offset!==n.offset||!i.color.equals(n.color))return!1}return this._geometryEquals(t)}toTexture(t,e,i={}){if(!Number.isInteger(t)||!Number.isInteger(e)||t<=0||e<=0)throw new Error("Gradient.toTexture() width/height must be positive integers.");return"rgba32f"===i.format?this._toRgba32fTexture(t,e,i):this._toRgba8Texture(t,e,i)}destroy(){for(const t of this._stops)t.color.destroy();this._stops=[]}sampleAt(t,e){const i=Y(t,0,1),n=this._stops[0];let s=n.offset,r=n.color;for(let t=1;t<this._stops.length;t++){const n=this._stops[t];if(i<=n.offset){const t=Math.max(n.offset-s,1e-6),o=Y((i-s)/t,0,1);return e[0]=r.r/255+(n.color.r/255-r.r/255)*o,e[1]=r.g/255+(n.color.g/255-r.g/255)*o,e[2]=r.b/255+(n.color.b/255-r.b/255)*o,void(e[3]=r.a+(n.color.a-r.a)*o)}s=n.offset,r=n.color}e[0]=r.r/255,e[1]=r.g/255,e[2]=r.b/255,e[3]=r.a}static _normalizeStops(t){if(t.length<2)throw new Error("Gradient requires at least 2 color stops.");return t.map(t=>{if(!Number.isFinite(t.offset))throw new Error("Gradient stop offset must be a finite number.");return{offset:Y(t.offset,0,1),color:t.color.clone()}}).sort(ju)}_toRgba8Texture(t,e,i){const n=new Os({width:t,height:e,format:"rgba8",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),s=n.buffer;let r=0;for(let i=0;i<e;i++){const n=1===e?0:i/(e-1);for(let e=0;e<t;e++){const i=1===t?0:e/(t-1);this.sampleAt(this.resolveT(i,n),this._sample),s[r]=Qu(this._sample[0]),s[r+1]=Qu(this._sample[1]),s[r+2]=Qu(this._sample[2]),s[r+3]=Qu(this._sample[3]),r+=4}}return n.commit(),n}_toRgba32fTexture(t,e,i){const n=new Os({width:t,height:e,format:"rgba32f",...void 0!==i.samplerOptions&&{samplerOptions:i.samplerOptions}}),s=n.buffer;let r=0;for(let i=0;i<e;i++){const n=1===e?0:i/(e-1);for(let e=0;e<t;e++){const i=1===t?0:e/(t-1);this.sampleAt(this.resolveT(i,n),this._sample),s[r]=this._sample[0],s[r+1]=this._sample[1],s[r+2]=this._sample[2],s[r+3]=this._sample[3],r+=4}}return n.commit(),n}}const Qu=t=>255*Y(t,0,1)+.5|0;class Zu extends Ku{type="linear";_start;_end;constructor(t,e=[0,0],i=[1,0]){super(t),this._start=[e[0],e[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 Zu(this.stops,this._start,this._end)}resolveT(t,e){const i=this._end[0]-this._start[0],n=this._end[1]-this._start[1],s=i*i+n*n;return s<=1e-6?0:((t-this._start[0])*i+(e-this._start[1])*n)/s}_copyGeometry(t){this._start=[t._start[0],t._start[1]],this._end=[t._end[0],t._end[1]]}_geometryEquals(t){return t instanceof Zu&&this._start[0]===t._start[0]&&this._start[1]===t._start[1]&&this._end[0]===t._end[0]&&this._end[1]===t._end[1]}}class Ju extends Ku{type="radial";_center;_radius;constructor(t,e=[.5,.5],i=.5){super(t),this._center=[e[0],e[1]],this._radius=Math.max(0,i)}get center(){return[this._center[0],this._center[1]]}get radius(){return this._radius}clone(){return new Ju(this.stops,this._center,this._radius)}resolveT(t,e){if(this._radius<=1e-6)return 1;const i=t-this._center[0],n=e-this._center[1];return Math.sqrt(i*i+n*n)/this._radius}_copyGeometry(t){this._center=[t._center[0],t._center[1]],this._radius=t._radius}_geometryEquals(t){return t instanceof Ju&&this._center[0]===t._center[0]&&this._center[1]===t._center[1]&&this._radius===t._radius}}const tc=new WeakMap;let ec=1;const ic=t=>{const e=tc.get(t);if(void 0!==e)return e;const i=ec++;return tc.set(t,i),i},nc=new Map;let sc=1;const rc=new Map;let oc=1;const ac=(t,e,i)=>{const n=t.get(e);if(void 0!==n)return n;const s=i();return t.set(e,s),s},hc=t=>"object"==typeof t&&null!==t&&!Array.isArray(t)&&!ArrayBuffer.isView(t);let lc=1;class uc{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??qe.Normal,this.sampler=t.sampler??null,this._id=lc++}get pipelineKey(){return((t,e,i)=>{const n=`${t}|${e}|${(t=>null===t?"-":[t.scaleMode,t.wrapMode,t.premultiplyAlpha?1:0,t.generateMipMap?1:0,t.flipY?1:0].join(":"))(i)}`;return ac(nc,n,()=>sc++)})(this.shader.id,this.blendMode,this.sampler)}get bindKey(){return((t,e,i)=>{const n=[];for(const t of Object.keys(i))n.push(`t:${t}=${ic(i[t])}`);for(const t of Object.keys(e)){const i=e[t];hc(i)&&n.push(`u:${t}=${ic(i)}`)}n.sort();const s=`${t}|${n.join(",")}`;return ac(rc,s,()=>oc++)})(this._id,this.uniforms,this.textures)}setUniform(t,e){return this.uniforms[t]=e,this}setTexture(t,e){return this.textures[t]=e,this}destroy(){for(const t of this._disposeCallbacks)t();this._disposeCallbacks.clear()}_onDispose(t){this._disposeCallbacks.add(t)}}let cc=1;class dc{glsl;wgsl;_id;constructor(t){if(void 0===t.glsl&&void 0===t.wgsl)throw new Error("ShaderSource requires at least one of `glsl` or `wgsl`.");if(void 0!==t.glsl){if("string"!=typeof t.glsl.vertex||0===t.glsl.vertex.length)throw new Error("ShaderSource.glsl.vertex must be a non-empty string.");if("string"!=typeof t.glsl.fragment||0===t.glsl.fragment.length)throw new Error("ShaderSource.glsl.fragment must be a non-empty string.")}if(void 0!==t.wgsl&&("string"!=typeof t.wgsl||0===t.wgsl.length))throw new Error("ShaderSource.wgsl must be a non-empty string.");this.glsl=t.glsl??null,this.wgsl=t.wgsl??null,this._id=cc++}get id(){return this._id}getDeclaredUniforms(){return{glsl:null!==this.glsl?gc(this.glsl.vertex,this.glsl.fragment):{},wgsl:null!==this.wgsl?yc(this.wgsl):{}}}detectUniformDrift(){if(null===this.glsl||null===this.wgsl)return{onlyInGlsl:[],onlyInWgsl:[]};const t=this.getDeclaredUniforms(),e=new Set(Object.keys(t.glsl).filter(t=>!_c.has(t))),i=new Set(Object.keys(t.wgsl).filter(t=>!_c.has(t))),n=[],s=[];for(const t of e)i.has(t)||n.push(t);for(const t of i)e.has(t)||s.push(t);return{onlyInGlsl:n,onlyInWgsl:s}}}const _c=new Set(["u_projection","u_translation","u_tint","u_texture","u_mesh"]),fc=/\buniform\s+(?:mediump\s+|highp\s+|lowp\s+|)(\w+)\s+(\w+)[^;]*;/g,pc=/@group\(\s*2\s*\)\s*@binding\(\s*\d+\s*\)\s*var(?:<[^>]+>|)\s+(\w+)\s*:\s*([^;]+);/g;function mc(t){return t.replaceAll(/\/\*[\s\S]*?\*\//g,"").replaceAll(/\/\/[^\n]*/g,"")}function gc(t,e){const i={};for(const n of[t,e]){const t=mc(n);let e;for(fc.lastIndex=0;null!==(e=fc.exec(t));){const[,t,n]=e;void 0!==t&&void 0!==n&&(i[n]=t)}}return i}function yc(t){const e={},i=mc(t);let n;for(pc.lastIndex=0;null!==(n=pc.exec(i));){const[,t,i]=n;void 0!==t&&void 0!==i&&(e[t]=i.trim())}return e}class wc extends uc{target="mesh";constructor(t){super(t)}static from(t,e,i){if(t instanceof dc){return new wc({shader:t,...void 0!==e?e:{}})}const n=new dc({glsl:{vertex:t,fragment:e},...void 0!==i?.wgsl?{wgsl:i.wgsl}:{}});return new wc({shader:n,...void 0!==i?.uniforms?{uniforms:i.uniforms}:{},...void 0!==i?.blendMode?{blendMode:i.blendMode}:{},...void 0!==i?.sampler?{sampler:i.sampler}:{}})}}class xc extends uc{target="sprite";constructor(t){super(t)}static from(t,e,i){if(t instanceof dc){return new xc({shader:t,...void 0!==e?e:{}})}const n=new dc({glsl:{vertex:t,fragment:e},...void 0!==i?.wgsl?{wgsl:i.wgsl}:{}});return new xc({shader:n,...void 0!==i?.uniforms?{uniforms:i.uniforms}:{},...void 0!==i?.blendMode?{blendMode:i.blendMode}:{},...void 0!==i?.sampler?{sampler:i.sampler}:{}})}}class vc{texture;frames=new Map;sprites=new Map;animations=new Map;constructor(t,e){this.texture=t,this.parse(e)}parse(t,e=!1){e||this.clear();for(const[e,i]of Object.entries(t.frames))this.addFrame(e,i);if(t.animations)for(const[e,i]of Object.entries(t.animations))this.defineAnimation(e,i)}addFrame(t,e){const{x:i,y:n,w:s,h:r}=e.frame,o=new te(i,n,s,r),a=new Ps(this.texture);a.setTextureFrame(o),this.frames.set(t,o),this.sprites.set(t,a)}defineAnimation(t,e){if(0===t.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(0===e.length)throw new Error(`Spritesheet animation "${t}" must reference at least one frame.`);for(const i of e)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${t}" references missing frame "${i}".`);return this.animations.set(t,[...e]),this}getFrame(t){const e=this.frames.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}getAnimationFrameNames(t){const e=this.animations.get(t);if(!e)throw new Error(`Spritesheet animation named ${t} is not available!`);return e}getFrameSprite(t){const e=this.sprites.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}clear(){for(const t of this.frames.values())t.destroy();this.frames.clear();for(const t of this.sprites.values())t.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}}const bc={woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};class Sc extends Ei{_html;_css;_width;_height;_resolution;_canvas;_ctx;_texture;_mesh;_destroyed=!1;_renderVersion=0;_activeRender=null;_fonts=[];constructor(t,e={}){super(),this._html=t,this._css=e.css??"",this._width=e.width??256,this._height=e.height??128,this._resolution=e.resolution??1;const[i,n]=Sc._makeCanvas(Math.ceil(this._width*this._resolution),Math.ceil(this._height*this._resolution));this._canvas=i,this._ctx=n,this._texture=new vi(i),this._texture.setSize(this._width,this._height),this._mesh=this._buildMesh(),this.addChild(this._mesh),t.length>0&&this._schedule()}get html(){return this._html}set html(t){this._html!==t&&(this._html=t,this._schedule())}get css(){return this._css}set css(t){this._css!==t&&(this._css=t,this._schedule())}get width(){return this._width}set width(t){this.resize(t,this._height)}get height(){return this._height}set height(t){this.resize(this._width,t)}get resolution(){return this._resolution}set resolution(t){this._resolution!==t&&(this._resolution=t,this._resizeCanvas(),this._schedule())}get ready(){return this._activeRender??Promise.resolve()}addFont(t,e,i="woff2"){const n=`data:${bc[i]};base64,${Sc._toBase64(e)}`,s=this._fonts.findIndex(e=>e.family===t);return s>=0?this._fonts[s]={family:t,dataUri:n}:this._fonts.push({family:t,dataUri:n}),this._schedule(),this}removeFont(t){const e=this._fonts.findIndex(e=>e.family===t);return e>=0&&(this._fonts.splice(e,1),this._schedule()),this}resize(t,e){return this._width===t&&this._height===e||(this._width=t,this._height=e,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=>{dh.log(uh.Warning,"rendering","HTMLText render failed.",t instanceof Error?{error:t}:void 0)})}async _render(t){if("undefined"==typeof Blob||"undefined"==typeof Image)return;const e=new Blob([this._buildSvg()],{type:"image/svg+xml;charset=utf-8"}),i=URL.createObjectURL(e),n=new Image;try{await new Promise((t,e)=>{n.onload=()=>t(),n.onerror=()=>e(new Error("HTMLText: SVG render failed")),n.src=i})}finally{URL.revokeObjectURL(i)}if(this._destroyed||t!==this._renderVersion)return;const s=Math.ceil(this._width*this._resolution),r=Math.ceil(this._height*this._resolution);this._ctx.clearRect(0,0,s,r),this._ctx.drawImage(n,0,0,s,r),this._texture.updateSource()}_buildSvg(){const t=this._width,e=this._height,i=this._fonts.map(({family:t,dataUri:e})=>`@font-face{font-family:'${t.replaceAll("\\","\\\\").replaceAll("'","\\'")}';src:url('${e}');}`).join(""),n=this._css.replaceAll(/<\/style>/gi,"<\\/style>");return`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${e}"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="width:${t}px;height:${e}px;overflow:hidden;box-sizing:border-box;">${i||n?`<style>${i}${n}</style>`:""}${this._html}</div></foreignObject></svg>`}_buildMesh(){const t=this._width,e=this._height;return new qn({vertices:new Float32Array([0,0,t,0,t,e,0,e]),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 t=Math.ceil(this._width*this._resolution),e=Math.ceil(this._height*this._resolution);this._canvas.width=t,this._canvas.height=e,this._texture.updateSource()}static _toBase64(t){const e=new Uint8Array(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}static _makeCanvas(t,e){if("undefined"!=typeof OffscreenCanvas){const i=new OffscreenCanvas(t,e),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=t,i.height=e;const n=i.getContext("2d");if(!n)throw new Error("HTMLText: could not obtain 2D context.");return[i,n]}}class Bc{_context;_sampler;_scaleMode;_wrapMode;constructor(t,e){const{scaleMode:i,wrapMode:n}=e;this._context=t,this._sampler=t.createSampler(),this._scaleMode=i,this._wrapMode=n,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this.updateScaleModeParameters()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this.updateWrapModeParameters()),this}bind(t){return this._context.bindSampler(t,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 t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_MAG_FILTER,this._scaleMode),t.samplerParameteri(this._sampler,t.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_S,this._wrapMode),t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_T,this._wrapMode)}}const Cc=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"];class Tc{name;version;_storeNames;_migrations;_onCloseHandler=this.disconnect.bind(this);_connected=!1;_database=null;get connected(){return this._connected}constructor(t,e=1,i=Cc,n){if(!_)throw new Error("This browser does not support indexedDB!");this.name=t,this.version=e,this._storeNames=i,this._migrations=n}async getObjectStore(t,e="readonly"){return await this.connect(),this._database.transaction([t],e).objectStore(t)}async connect(){return!(!this._connected||!this._database)||new Promise((t,e)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",t=>{const n=i.result,s=i.transaction,r=[...s.objectStoreNames],{oldVersion:o,newVersion:a}=t;if(n.addEventListener("error",()=>e(new Error("An error occurred while opening the database."))),n.addEventListener("abort",()=>e(new Error("The database opening was aborted."))),this._migrations){const t=Object.keys(this._migrations).map(Number).filter(t=>t>o&&t<=(a??this.version)).sort((t,e)=>t-e);for(const e of t){const t=this._migrations[e];if(void 0===t)continue;if(!t(n,s))return void s.abort()}}else{for(const t of r)this._storeNames.includes(t)||n.deleteObjectStore(t);for(const t of this._storeNames)r.includes(t)||n.createObjectStore(t,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,t(!0)}),i.addEventListener("error",()=>e(new Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>e(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(t,e){const i=await this.getObjectStore(t);return new Promise((t,n)=>{const s=i.get(e);s.addEventListener("success",()=>t(s.result?.data??null)),s.addEventListener("error",()=>n(new Error("An error occurred while loading an item.")))})}async save(t,e,i){const n=await this.getObjectStore(t,"readwrite");return new Promise((t,s)=>{const r=n.put({name:e,data:i});r.addEventListener("success",()=>t()),r.addEventListener("error",()=>s(new Error("An error occurred while saving an item.")))})}async delete(t,e){const i=await this.getObjectStore(t,"readwrite");return new Promise((t,n)=>{const s=i.delete(e);s.addEventListener("success",()=>t(!0)),s.addEventListener("error",()=>n(new Error("An error occurred while deleting an item.")))})}async clearStorage(t){const e=await this.getObjectStore(t,"readwrite");return new Promise((t,i)=>{const n=e.clear();n.addEventListener("success",()=>t(!0)),n.addEventListener("error",()=>i(new Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((t,e)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>t(!0)),i.addEventListener("error",()=>e(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 Mc{_db;constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new Tc(e.name,e.version??1,e.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt","__ctx_text","__ctx_json","__ctx_binary"],e.migrations)}async load(t,e){return this._db.load(t,e)}async save(t,e,i){return this._db.save(t,e,i)}async delete(t,e){return this._db.delete(t,e)}async clear(t){return this._db.clearStorage(t)}destroy(){this._db.destroy()}}class Ac{_storeName;_store;constructor(t="exojs-kv-store"){const e="string"==typeof t?{name:t}:t,i=e.storeName??"__kv_store";this._storeName=i,this._store=new Mc({name:e.name,...void 0!==e.version&&{version:e.version},...void 0!==e.migrations&&{migrations:e.migrations},storeNames:[i]})}async get(t){return await this._store.load(this._storeName,t)}async set(t,e){await this._store.save(this._storeName,t,e)}async has(t){return null!==await this._store.load(this._storeName,t)}async delete(t){return this._store.delete(this._storeName,t)}async clear(){return this._store.clear(this._storeName)}destroy(){this._store.destroy()}}class Pc{_map=new Map;get(t){return Promise.resolve(this._map.has(t)?this._map.get(t):null)}set(t,e){return this._map.set(t,e),Promise.resolve()}has(t){return Promise.resolve(this._map.has(t))}delete(t){return Promise.resolve(this._map.delete(t))}clear(){return this._map.clear(),Promise.resolve(!0)}}class Ec{async resolve(t,e){const{url:i,requestOptions:n,factory:s,options:r}=t,o=await fetch(i,n);if(!o.ok)throw new Error(`Failed to fetch "${i}" (${o.status} ${o.statusText}).`);const a=await s.process(o);return s.create(a,r)}}class kc{_storage;_prefix;constructor(t,e={}){this._storage=t,this._prefix=e.prefix??""}get(t){const e=this._storage.getItem(this._prefix+t);if(null===e)return Promise.resolve(null);try{return Promise.resolve(JSON.parse(e))}catch{return Promise.reject(new Error(`WebStorageStore.get() failed: stored value for key "${t}" is not valid JSON.`))}}set(t,e){let i;try{i=JSON.stringify(e)}catch{return Promise.reject(new Error("WebStorageStore.set() failed: value is not JSON-serializable."))}return this._storage.setItem(this._prefix+t,i),Promise.resolve()}has(t){return Promise.resolve(null!==this._storage.getItem(this._prefix+t))}delete(t){const e=this._prefix+t,i=null!==this._storage.getItem(e);return this._storage.removeItem(e),Promise.resolve(i)}clear(){if(""===this._prefix)return this._storage.clear(),Promise.resolve(!0);const t=[];for(let e=0;e<this._storage.length;e++){const i=this._storage.key(e);!0===i?.startsWith(this._prefix)&&t.push(i)}for(const e of t)this._storage.removeItem(e);return Promise.resolve(!0)}}class Rc extends Lo{storageName="json";async process(t){return t.json()}async create(t){return t}}class Dc extends Lo{storageName="text";async process(t){return t.text()}async create(t){return t}}class Ic extends ul{content;_direction;_scrollX=0;_scrollY=0;_onWheel=t=>{const e=this._stage?.app?.input.getPrimaryPointerPosition();if(null==e)return;this.getBounds().contains(e.x,e.y)&&this.scrollBy("vertical"!==this._direction?t.x:0,"horizontal"!==this._direction?t.y:0)};constructor(t){super(),this._direction=t.direction??"vertical",this.content=new Ei,this.clip=!0,this.interactive=!0,this.addChild(this.content),this.setSize(t.width,t.height)}get scrollX(){return this._scrollX}get scrollY(){return this._scrollY}scrollBy(t,e){this.scrollTo(this._scrollX+t,this._scrollY+e)}scrollTo(t,e){const i=this.content.getBounds(),n=Math.max(0,i.width-this._uiWidth),s=Math.max(0,i.height-this._uiHeight);this._scrollX=Math.max(0,Math.min(t,n)),this._scrollY=Math.max(0,Math.min(e,s)),this.content.setPosition(-this._scrollX,-this._scrollY)}_relayout(){this.scrollTo(this._scrollX,this._scrollY)}_setStage(t){const e=this._stage?.app,i=t?.app;super._setStage(t),e!==i&&(e?.input.onMouseWheel.remove(this._onWheel),i?.input.onMouseWheel.add(this._onWheel))}destroy(){this._stage?.app?.input.onMouseWheel.remove(this._onWheel),super.destroy()}}class Lc{_target;_offsetX;_offsetY;_delayMs;_background;_textColor;_padding;_fontSize;_text;_node=null;_timer=null;_onPointerOver=t=>{this._scheduleShow(t.worldX,t.worldY)};_onPointerOut=()=>{this._hide()};constructor(t,e){this._target=t,this._text=e.text,this._offsetX=e.offsetX??12,this._offsetY=e.offsetY??-28,this._delayMs=1e3*(e.delay??.3),this._background=e.background??2236962,this._textColor=e.textColor??16777215,this._padding=e.padding??6,this._fontSize=e.fontSize??12,t.onPointerOver.add(this._onPointerOver),t.onPointerOut.add(this._onPointerOut)}destroy(){this._hide(),this._target.onPointerOver.remove(this._onPointerOver),this._target.onPointerOut.remove(this._onPointerOut)}_scheduleShow(t,e){this._cancelTimer(),this._timer=setTimeout(()=>{this._show(t,e)},this._delayMs)}_show(t,e){this._removeNode();const i=this._findUIRoot();if(null===i)return;const n=t=>new Re(t>>16&255,t>>8&255,255&t,1),s=new Zs(this._text,{fillColor:n(this._textColor),fontSize:this._fontSize}),r=s.getLocalBounds(),o=r.width+2*this._padding,a=r.height+2*this._padding,h=new Fh;h.fillColor=n(this._background),h.drawRoundedRectangle(0,0,o,a,4),s.setPosition(this._padding,this._padding);const l=new Ei;l.addChild(h),l.addChild(s),l.setPosition(t+this._offsetX,e+this._offsetY),this._node=l,i.addChild(l)}_hide(){this._cancelTimer(),this._removeNode()}_removeNode(){if(null!==this._node){const t=this._node.parent;null!==t&&t.removeChild(this._node),this._node=null}}_cancelTimer(){null!==this._timer&&(clearTimeout(this._timer),this._timer=null)}_findUIRoot(){let t=this._target.parent;for(;null!==t;){if(t instanceof _h)return t;t=t.parent}return null}}export{Lo as AbstractAssetFactory,Es as AbstractText,Vh as AnimatedSprite,eu as Application,Yl as ApplicationStatus,Hi as ArcadeStickGamepadMapping,Ua as Asset,$a as Assets,J as AudioBus,tt as AudioEffect,ue as AudioGenerator,ce as AudioInput,de as AudioListener,fe as AudioManager,me as AudioStream,ma as BinaryAsset,Uo as BinaryFactory,ge as BiquadEffect,Fs as BitmapText,qe as BlendModes,Ru as BlurFilter,ks as BmFont,Us as BmFontAdapter,Oo as BmFontLoaderFactory,Ge as Bounds,He as BufferTypes,je as BufferUsage,Oa as BundleLoadError,cl as Button,Xa as CacheFirstStrategy,Au as CallbackRenderPass,eh as Capabilities,Di as ChannelOffset,Ri as ChannelSize,mu as Circle,Oi as Clock,nu as Codec,Kt as Collision,it as CollisionType,Re as Color,Du as ColorFilter,Ei as Container,_a as CsvAsset,Vo as CsvFactory,Os as DataTexture,fh as DisposalScope,zn as Drawable,e as Ease,gu as Ellipse,we as Envelope,ku as Filter,De as Flags,Fi as FocusManager,pa as FontAsset,zo as FontFactory,Zi as GameCubeGamepadMapping,qi as Gamepad,ji as GamepadAxis,Wi as GamepadButton,Xi as GamepadMapping,$i as GamepadMappingFamily,fu as GamepadPromptLayouts,Qi as GenericDualAnalogGamepadMapping,Hu as Geometry,Hs as GlyphAtlas,Ku as Gradient,Fh as Graphics,Sc as HTMLText,xe as HighpassFilter,fa as ImageAsset,Yo as ImageFactory,Tc as IndexedDbDatabase,Ac as IndexedDbKeyValueStore,Mc as IndexedDbStore,zi as InputBinding,Tn as InputManager,An as InteractionEvent,Pn as InteractionManager,mt as Interval,Ji as JoyConLeftGamepadMapping,tn as JoyConRightGamepadMapping,ha as Json,Rc as JsonFactory,ki as KeyEvent,Ui as Keyboard,dl as Label,wu as Line,Zu as LinearGradient,Qa as Loader,Ka as LoadingQueue,uh as LogSeverity,ch as Logger,ve as LowpassFilter,Nu as LutFilter,uc as Material,Z as MathUtils,Le as Matrix,Pc as MemoryStore,qn as Mesh,Uh as MeshBuilder,wc as MeshMaterial,Xo as MusicFactory,Ec as NetworkOnlyStrategy,ys as NineSliceSprite,pi as ObservableSize,Qt as ObservableVector,_l as Panel,Tu as PassContext,ru as Perf,en as PlayStationGamepadMapping,Sn as Pointer,bn as PointerState,vn as PointerStateFlag,xu as PolarVector,Fe as Polygon,ou as Prefab,fl as ProgressBar,Mn as Quadtree,Ju as RadialGradient,Rn as Random,te as Rectangle,tr as RenderBackendType,so as RenderBatch,Pi as RenderNode,Pu as RenderNodePass,Mu as RenderPass,Eu as RenderPipeline,yi as RenderTarget,wi as RenderTexture,ao as RenderingContext,Xe as RenderingPrimitives,Ms as RepeatingSprite,kl as SERIALIZATION_VERSION,Bc as Sampler,Ye as ScaleModes,zl as Scene,Wl as SceneManager,ze as SceneNode,Ic as ScrollContainer,bu as Segment,Al as SerializationRegistry,Js as Shader,rr as ShaderAttribute,Ke as ShaderPrimitives,dc as ShaderSource,or as ShaderUniform,w as Signal,h as Size,le as Sound,Ho as SoundFactory,he as SoundPoolStrategy,Ps as Sprite,As as SpriteFlags,xc as SpriteMaterial,vc as Spritesheet,pl as Stack,nn as SteamControllerGamepadMapping,sn as SteamDeckGamepadMapping,ca as SubtitleAsset,ea as SubtitleFactory,ua as SvgAsset,ia as SvgFactory,Cu as Sweep,rn as SwitchProGamepadMapping,Nl as SystemRegistry,Zs as Text,la as TextAsset,Dc as TextFactory,Ls as TextStyle,vi as Texture,na as TextureFactory,Zn as TextureRegion,Ni as Time,Vi as Timer,Lc as Tooltip,s as Tween,o as TweenManager,r as TweenSequencer,n as TweenSequencerState,i as TweenState,_h as UIRoot,ie as Vector,Io as Video,ra as VideoFactory,gi as View,mi as ViewFlags,ga as WasmAsset,oa as WasmFactory,Lu as WebGl2ShaderFilter,Gu as WebGpuShaderFilter,kc as WebStorageStore,ul as Widget,Ce as WorkletEffect,$e as WrapModes,on as XboxGamepadMapping,da as XmlAsset,aa as XmlFactory,iu as buildInfo,ro as createRenderStats,ye as crossFade,G as decodeAudioData,Va as defineAssetManifest,L as getAudioContext,F as getOfflineAudioContext,We as isAdvancedBlendMode,U as isAudioContextReady,dh as logger,Ii as maxPointers,I as onAudioContextReady,Li as pointerSlotSize,Be as registerAudioWorkletProcessor,El as registerSerializer,oo as resetRenderStats};
|
|
2
2
|
//# sourceMappingURL=exo.esm.js.map
|