@codexo/exojs 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +163 -0
- package/README.md +141 -0
- package/dist/esm/audio/AbstractMedia.d.ts +45 -0
- package/dist/esm/audio/AbstractMedia.js +103 -0
- package/dist/esm/audio/AbstractMedia.js.map +1 -0
- package/dist/esm/audio/AudioAnalyser.d.ts +30 -0
- package/dist/esm/audio/AudioAnalyser.js +92 -0
- package/dist/esm/audio/AudioAnalyser.js.map +1 -0
- package/dist/esm/audio/Media.d.ts +25 -0
- package/dist/esm/audio/Music.d.ts +20 -0
- package/dist/esm/audio/Music.js +119 -0
- package/dist/esm/audio/Music.js.map +1 -0
- package/dist/esm/audio/Sound.d.ts +56 -0
- package/dist/esm/audio/Sound.js +394 -0
- package/dist/esm/audio/Sound.js.map +1 -0
- package/dist/esm/audio/audio-context.d.ts +11 -0
- package/dist/esm/audio/audio-context.js +115 -0
- package/dist/esm/audio/audio-context.js.map +1 -0
- package/dist/esm/audio/index.d.ts +6 -0
- package/dist/esm/core/Application.d.ts +76 -0
- package/dist/esm/core/Application.js +206 -0
- package/dist/esm/core/Application.js.map +1 -0
- package/dist/esm/core/Bounds.d.ts +19 -0
- package/dist/esm/core/Bounds.js +59 -0
- package/dist/esm/core/Bounds.js.map +1 -0
- package/dist/esm/core/Clock.d.ts +18 -0
- package/dist/esm/core/Clock.js +68 -0
- package/dist/esm/core/Clock.js.map +1 -0
- package/dist/esm/core/Color.d.ts +176 -0
- package/dist/esm/core/Color.js +265 -0
- package/dist/esm/core/Color.js.map +1 -0
- package/dist/esm/core/Quadtree.d.ts +20 -0
- package/dist/esm/core/Quadtree.js +86 -0
- package/dist/esm/core/Quadtree.js.map +1 -0
- package/dist/esm/core/Scene.d.ts +83 -0
- package/dist/esm/core/Scene.js +81 -0
- package/dist/esm/core/Scene.js.map +1 -0
- package/dist/esm/core/SceneManager.d.ts +66 -0
- package/dist/esm/core/SceneManager.js +396 -0
- package/dist/esm/core/SceneManager.js.map +1 -0
- package/dist/esm/core/SceneNode.d.ts +58 -0
- package/dist/esm/core/SceneNode.js +174 -0
- package/dist/esm/core/SceneNode.js.map +1 -0
- package/dist/esm/core/Signal.d.ts +18 -0
- package/dist/esm/core/Signal.js +63 -0
- package/dist/esm/core/Signal.js.map +1 -0
- package/dist/esm/core/Time.d.ts +38 -0
- package/dist/esm/core/Time.js +107 -0
- package/dist/esm/core/Time.js.map +1 -0
- package/dist/esm/core/Timer.d.ts +12 -0
- package/dist/esm/core/Timer.js +34 -0
- package/dist/esm/core/Timer.js.map +1 -0
- package/dist/esm/core/index.d.ts +13 -0
- package/dist/esm/core/types.d.ts +29 -0
- package/dist/esm/core/utils.d.ts +22 -0
- package/dist/esm/core/utils.js +136 -0
- package/dist/esm/core/utils.js.map +1 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +135 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/input/ArcadeStickGamepadMapping.d.ts +5 -0
- package/dist/esm/input/ArcadeStickGamepadMapping.js +29 -0
- package/dist/esm/input/ArcadeStickGamepadMapping.js.map +1 -0
- package/dist/esm/input/GameCubeGamepadMapping.d.ts +5 -0
- package/dist/esm/input/GameCubeGamepadMapping.js +9 -0
- package/dist/esm/input/GameCubeGamepadMapping.js.map +1 -0
- package/dist/esm/input/Gamepad.d.ts +45 -0
- package/dist/esm/input/Gamepad.js +154 -0
- package/dist/esm/input/Gamepad.js.map +1 -0
- package/dist/esm/input/GamepadChannels.d.ts +39 -0
- package/dist/esm/input/GamepadChannels.js +45 -0
- package/dist/esm/input/GamepadChannels.js.map +1 -0
- package/dist/esm/input/GamepadControl.d.ts +15 -0
- package/dist/esm/input/GamepadControl.js +29 -0
- package/dist/esm/input/GamepadControl.js.map +1 -0
- package/dist/esm/input/GamepadDefinitions.d.ts +31 -0
- package/dist/esm/input/GamepadDefinitions.js +175 -0
- package/dist/esm/input/GamepadDefinitions.js.map +1 -0
- package/dist/esm/input/GamepadMapping.d.ts +23 -0
- package/dist/esm/input/GamepadMapping.js +32 -0
- package/dist/esm/input/GamepadMapping.js.map +1 -0
- package/dist/esm/input/GamepadPromptLayouts.d.ts +9 -0
- package/dist/esm/input/GamepadPromptLayouts.js +140 -0
- package/dist/esm/input/GamepadPromptLayouts.js.map +1 -0
- package/dist/esm/input/GenericDualAnalogGamepadMapping.d.ts +5 -0
- package/dist/esm/input/GenericDualAnalogGamepadMapping.js +53 -0
- package/dist/esm/input/GenericDualAnalogGamepadMapping.js.map +1 -0
- package/dist/esm/input/Input.d.ts +28 -0
- package/dist/esm/input/Input.js +68 -0
- package/dist/esm/input/Input.js.map +1 -0
- package/dist/esm/input/InputManager.d.ts +76 -0
- package/dist/esm/input/InputManager.js +346 -0
- package/dist/esm/input/InputManager.js.map +1 -0
- package/dist/esm/input/JoyConLeftGamepadMapping.d.ts +5 -0
- package/dist/esm/input/JoyConLeftGamepadMapping.js +9 -0
- package/dist/esm/input/JoyConLeftGamepadMapping.js.map +1 -0
- package/dist/esm/input/JoyConRightGamepadMapping.d.ts +5 -0
- package/dist/esm/input/JoyConRightGamepadMapping.js +9 -0
- package/dist/esm/input/JoyConRightGamepadMapping.js.map +1 -0
- package/dist/esm/input/PlayStationGamepadMapping.d.ts +5 -0
- package/dist/esm/input/PlayStationGamepadMapping.js +9 -0
- package/dist/esm/input/PlayStationGamepadMapping.js.map +1 -0
- package/dist/esm/input/Pointer.d.ts +52 -0
- package/dist/esm/input/Pointer.js +127 -0
- package/dist/esm/input/Pointer.js.map +1 -0
- package/dist/esm/input/SteamControllerGamepadMapping.d.ts +5 -0
- package/dist/esm/input/SteamControllerGamepadMapping.js +9 -0
- package/dist/esm/input/SteamControllerGamepadMapping.js.map +1 -0
- package/dist/esm/input/SwitchProGamepadMapping.d.ts +5 -0
- package/dist/esm/input/SwitchProGamepadMapping.js +9 -0
- package/dist/esm/input/SwitchProGamepadMapping.js.map +1 -0
- package/dist/esm/input/XboxGamepadMapping.d.ts +5 -0
- package/dist/esm/input/XboxGamepadMapping.js +9 -0
- package/dist/esm/input/XboxGamepadMapping.js.map +1 -0
- package/dist/esm/input/index.d.ts +19 -0
- package/dist/esm/input/types.d.ts +111 -0
- package/dist/esm/input/types.js +117 -0
- package/dist/esm/input/types.js.map +1 -0
- package/dist/esm/math/AbstractVector.d.ts +33 -0
- package/dist/esm/math/AbstractVector.js +106 -0
- package/dist/esm/math/AbstractVector.js.map +1 -0
- package/dist/esm/math/Circle.d.ts +41 -0
- package/dist/esm/math/Circle.js +137 -0
- package/dist/esm/math/Circle.js.map +1 -0
- package/dist/esm/math/CircleLike.d.ts +5 -0
- package/dist/esm/math/Collision.d.ts +28 -0
- package/dist/esm/math/Collision.js +13 -0
- package/dist/esm/math/Collision.js.map +1 -0
- package/dist/esm/math/Ellipse.d.ts +37 -0
- package/dist/esm/math/Ellipse.js +112 -0
- package/dist/esm/math/Ellipse.js.map +1 -0
- package/dist/esm/math/EllipseLike.d.ts +6 -0
- package/dist/esm/math/Flags.d.ts +12 -0
- package/dist/esm/math/Flags.js +41 -0
- package/dist/esm/math/Flags.js.map +1 -0
- package/dist/esm/math/Interval.d.ts +16 -0
- package/dist/esm/math/Interval.js +45 -0
- package/dist/esm/math/Interval.js.map +1 -0
- package/dist/esm/math/Line.d.ts +36 -0
- package/dist/esm/math/Line.js +114 -0
- package/dist/esm/math/Line.js.map +1 -0
- package/dist/esm/math/LineLike.d.ts +6 -0
- package/dist/esm/math/Matrix.d.ts +32 -0
- package/dist/esm/math/Matrix.js +134 -0
- package/dist/esm/math/Matrix.js.map +1 -0
- package/dist/esm/math/ObservableSize.d.ts +16 -0
- package/dist/esm/math/ObservableSize.js +56 -0
- package/dist/esm/math/ObservableSize.js.map +1 -0
- package/dist/esm/math/ObservableVector.d.ts +21 -0
- package/dist/esm/math/ObservableVector.js +74 -0
- package/dist/esm/math/ObservableVector.js.map +1 -0
- package/dist/esm/math/PointLike.d.ts +4 -0
- package/dist/esm/math/PolarVector.d.ts +8 -0
- package/dist/esm/math/PolarVector.js +19 -0
- package/dist/esm/math/PolarVector.js.map +1 -0
- package/dist/esm/math/Polygon.d.ts +38 -0
- package/dist/esm/math/Polygon.js +163 -0
- package/dist/esm/math/Polygon.js.map +1 -0
- package/dist/esm/math/PolygonLike.d.ts +6 -0
- package/dist/esm/math/Random.d.ts +15 -0
- package/dist/esm/math/Random.js +72 -0
- package/dist/esm/math/Random.js.map +1 -0
- package/dist/esm/math/Rectangle.d.ts +48 -0
- package/dist/esm/math/Rectangle.js +208 -0
- package/dist/esm/math/Rectangle.js.map +1 -0
- package/dist/esm/math/RectangleLike.d.ts +6 -0
- package/dist/esm/math/Segment.d.ts +25 -0
- package/dist/esm/math/Segment.js +79 -0
- package/dist/esm/math/Segment.js.map +1 -0
- package/dist/esm/math/ShapeLike.d.ts +4 -0
- package/dist/esm/math/Size.d.ts +24 -0
- package/dist/esm/math/Size.js +71 -0
- package/dist/esm/math/Size.js.map +1 -0
- package/dist/esm/math/Transformable.d.ts +47 -0
- package/dist/esm/math/Transformable.js +140 -0
- package/dist/esm/math/Transformable.js.map +1 -0
- package/dist/esm/math/Vector.d.ts +28 -0
- package/dist/esm/math/Vector.js +80 -0
- package/dist/esm/math/Vector.js.map +1 -0
- package/dist/esm/math/collision-detection.d.ts +41 -0
- package/dist/esm/math/collision-detection.js +394 -0
- package/dist/esm/math/collision-detection.js.map +1 -0
- package/dist/esm/math/collision-primitives.d.ts +39 -0
- package/dist/esm/math/collision-primitives.js +164 -0
- package/dist/esm/math/collision-primitives.js.map +1 -0
- package/dist/esm/math/geometry.d.ts +8 -0
- package/dist/esm/math/geometry.js +195 -0
- package/dist/esm/math/geometry.js.map +1 -0
- package/dist/esm/math/index.d.ts +27 -0
- package/dist/esm/math/utils.d.ts +21 -0
- package/dist/esm/math/utils.js +60 -0
- package/dist/esm/math/utils.js.map +1 -0
- package/dist/esm/particles/Particle.d.ts +40 -0
- package/dist/esm/particles/Particle.js +106 -0
- package/dist/esm/particles/Particle.js.map +1 -0
- package/dist/esm/particles/ParticleProperties.d.ts +14 -0
- package/dist/esm/particles/ParticleSystem.d.ts +43 -0
- package/dist/esm/particles/ParticleSystem.js +186 -0
- package/dist/esm/particles/ParticleSystem.js.map +1 -0
- package/dist/esm/particles/affectors/ColorAffector.d.ts +17 -0
- package/dist/esm/particles/affectors/ColorAffector.js +42 -0
- package/dist/esm/particles/affectors/ColorAffector.js.map +1 -0
- package/dist/esm/particles/affectors/ForceAffector.d.ts +13 -0
- package/dist/esm/particles/affectors/ForceAffector.js +28 -0
- package/dist/esm/particles/affectors/ForceAffector.js.map +1 -0
- package/dist/esm/particles/affectors/ParticleAffector.d.ts +6 -0
- package/dist/esm/particles/affectors/ScaleAffector.d.ts +13 -0
- package/dist/esm/particles/affectors/ScaleAffector.js +28 -0
- package/dist/esm/particles/affectors/ScaleAffector.js.map +1 -0
- package/dist/esm/particles/affectors/TorqueAffector.d.ts +12 -0
- package/dist/esm/particles/affectors/TorqueAffector.js +26 -0
- package/dist/esm/particles/affectors/TorqueAffector.js.map +1 -0
- package/dist/esm/particles/emitters/ParticleEmitter.d.ts +6 -0
- package/dist/esm/particles/emitters/ParticleOptions.d.ts +46 -0
- package/dist/esm/particles/emitters/ParticleOptions.js +104 -0
- package/dist/esm/particles/emitters/ParticleOptions.js.map +1 -0
- package/dist/esm/particles/emitters/UniversalEmitter.d.ts +17 -0
- package/dist/esm/particles/emitters/UniversalEmitter.js +45 -0
- package/dist/esm/particles/emitters/UniversalEmitter.js.map +1 -0
- package/dist/esm/particles/index.d.ts +11 -0
- package/dist/esm/physics/RapierPhysicsWorld.d.ts +136 -0
- package/dist/esm/physics/RapierPhysicsWorld.js +475 -0
- package/dist/esm/physics/RapierPhysicsWorld.js.map +1 -0
- package/dist/esm/physics/index.d.ts +1 -0
- package/dist/esm/rendering/CallbackRenderPass.d.ts +7 -0
- package/dist/esm/rendering/CallbackRenderPass.js +12 -0
- package/dist/esm/rendering/CallbackRenderPass.js.map +1 -0
- package/dist/esm/rendering/Container.d.ts +36 -0
- package/dist/esm/rendering/Container.js +197 -0
- package/dist/esm/rendering/Container.js.map +1 -0
- package/dist/esm/rendering/Drawable.d.ts +16 -0
- package/dist/esm/rendering/Drawable.js +54 -0
- package/dist/esm/rendering/Drawable.js.map +1 -0
- package/dist/esm/rendering/RenderBackendType.d.ts +4 -0
- package/dist/esm/rendering/RenderBackendType.js +8 -0
- package/dist/esm/rendering/RenderBackendType.js.map +1 -0
- package/dist/esm/rendering/RenderNode.d.ts +51 -0
- package/dist/esm/rendering/RenderNode.js +235 -0
- package/dist/esm/rendering/RenderNode.js.map +1 -0
- package/dist/esm/rendering/RenderPass.d.ts +4 -0
- package/dist/esm/rendering/RenderStats.d.ts +12 -0
- package/dist/esm/rendering/RenderStats.js +24 -0
- package/dist/esm/rendering/RenderStats.js.map +1 -0
- package/dist/esm/rendering/RenderTarget.d.ts +34 -0
- package/dist/esm/rendering/RenderTarget.js +109 -0
- package/dist/esm/rendering/RenderTarget.js.map +1 -0
- package/dist/esm/rendering/RenderTargetPass.d.ts +18 -0
- package/dist/esm/rendering/RenderTargetPass.js +31 -0
- package/dist/esm/rendering/RenderTargetPass.js.map +1 -0
- package/dist/esm/rendering/Renderer.d.ts +15 -0
- package/dist/esm/rendering/RendererRegistry.d.ts +43 -0
- package/dist/esm/rendering/RendererRegistry.js +86 -0
- package/dist/esm/rendering/RendererRegistry.js.map +1 -0
- package/dist/esm/rendering/SceneRenderRuntime.d.ts +29 -0
- package/dist/esm/rendering/View.d.ts +102 -0
- package/dist/esm/rendering/View.js +364 -0
- package/dist/esm/rendering/View.js.map +1 -0
- package/dist/esm/rendering/filters/BlurFilter.d.ts +20 -0
- package/dist/esm/rendering/filters/BlurFilter.js +68 -0
- package/dist/esm/rendering/filters/BlurFilter.js.map +1 -0
- package/dist/esm/rendering/filters/ColorFilter.d.ts +12 -0
- package/dist/esm/rendering/filters/ColorFilter.js +42 -0
- package/dist/esm/rendering/filters/ColorFilter.js.map +1 -0
- package/dist/esm/rendering/filters/Filter.d.ts +5 -0
- package/dist/esm/rendering/filters/Filter.js +5 -0
- package/dist/esm/rendering/filters/Filter.js.map +1 -0
- package/dist/esm/rendering/index.d.ts +52 -0
- package/dist/esm/rendering/primitives/CircleGeometry.d.ts +4 -0
- package/dist/esm/rendering/primitives/CircleGeometry.js +21 -0
- package/dist/esm/rendering/primitives/CircleGeometry.js.map +1 -0
- package/dist/esm/rendering/primitives/DrawableShape.d.ts +11 -0
- package/dist/esm/rendering/primitives/DrawableShape.js +21 -0
- package/dist/esm/rendering/primitives/DrawableShape.js.map +1 -0
- package/dist/esm/rendering/primitives/Geometry.d.ts +13 -0
- package/dist/esm/rendering/primitives/Geometry.js +16 -0
- package/dist/esm/rendering/primitives/Geometry.js.map +1 -0
- package/dist/esm/rendering/primitives/Graphics.d.ts +36 -0
- package/dist/esm/rendering/primitives/Graphics.js +208 -0
- package/dist/esm/rendering/primitives/Graphics.js.map +1 -0
- package/dist/esm/rendering/shader/Shader.d.ts +27 -0
- package/dist/esm/rendering/shader/Shader.js +63 -0
- package/dist/esm/rendering/shader/Shader.js.map +1 -0
- package/dist/esm/rendering/shader/ShaderAttribute.d.ts +9 -0
- package/dist/esm/rendering/shader/ShaderAttribute.js +21 -0
- package/dist/esm/rendering/shader/ShaderAttribute.js.map +1 -0
- package/dist/esm/rendering/shader/ShaderUniform.d.ts +16 -0
- package/dist/esm/rendering/shader/ShaderUniform.js +38 -0
- package/dist/esm/rendering/shader/ShaderUniform.js.map +1 -0
- package/dist/esm/rendering/sprite/AnimatedSprite.d.ts +43 -0
- package/dist/esm/rendering/sprite/AnimatedSprite.js +177 -0
- package/dist/esm/rendering/sprite/AnimatedSprite.js.map +1 -0
- package/dist/esm/rendering/sprite/Sprite.d.ts +43 -0
- package/dist/esm/rendering/sprite/Sprite.js +169 -0
- package/dist/esm/rendering/sprite/Sprite.js.map +1 -0
- package/dist/esm/rendering/sprite/Spritesheet.d.ts +34 -0
- package/dist/esm/rendering/sprite/Spritesheet.js +88 -0
- package/dist/esm/rendering/sprite/Spritesheet.js.map +1 -0
- package/dist/esm/rendering/text/Text.d.ts +26 -0
- package/dist/esm/rendering/text/Text.js +130 -0
- package/dist/esm/rendering/text/Text.js.map +1 -0
- package/dist/esm/rendering/text/TextStyle.d.ts +65 -0
- package/dist/esm/rendering/text/TextStyle.js +192 -0
- package/dist/esm/rendering/text/TextStyle.js.map +1 -0
- package/dist/esm/rendering/texture/RenderTexture.d.ts +36 -0
- package/dist/esm/rendering/texture/RenderTexture.js +123 -0
- package/dist/esm/rendering/texture/RenderTexture.js.map +1 -0
- package/dist/esm/rendering/texture/Sampler.d.ts +29 -0
- package/dist/esm/rendering/texture/Sampler.js +76 -0
- package/dist/esm/rendering/texture/Sampler.js.map +1 -0
- package/dist/esm/rendering/texture/Texture.d.ts +52 -0
- package/dist/esm/rendering/texture/Texture.js +173 -0
- package/dist/esm/rendering/texture/Texture.js.map +1 -0
- package/dist/esm/rendering/types.d.ts +68 -0
- package/dist/esm/rendering/types.js +79 -0
- package/dist/esm/rendering/types.js.map +1 -0
- package/dist/esm/rendering/utils.d.ts +9 -0
- package/dist/esm/rendering/utils.js +39 -0
- package/dist/esm/rendering/utils.js.map +1 -0
- package/dist/esm/rendering/video/Video.d.ts +62 -0
- package/dist/esm/rendering/video/Video.js +293 -0
- package/dist/esm/rendering/video/Video.js.map +1 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.d.ts +49 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.js +175 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2BatchedRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.d.ts +44 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.js +57 -0
- package/dist/esm/rendering/webgl2/AbstractWebGl2Renderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.d.ts +11 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.js +110 -0
- package/dist/esm/rendering/webgl2/WebGl2ParticleRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.d.ts +26 -0
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.js +217 -0
- package/dist/esm/rendering/webgl2/WebGl2PrimitiveRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderBuffer.d.ts +26 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderBuffer.js +54 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderBuffer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.d.ts +99 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.js +600 -0
- package/dist/esm/rendering/webgl2/WebGl2RenderManager.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2RendererRuntime.d.ts +15 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderBlock.d.ts +17 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderBlock.js +63 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderBlock.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.d.ts +3 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.js +59 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderMappings.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.d.ts +2 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js +161 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.d.ts +11 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.js +82 -0
- package/dist/esm/rendering/webgl2/WebGl2SpriteRenderer.js.map +1 -0
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.d.ts +40 -0
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.js +69 -0
- package/dist/esm/rendering/webgl2/WebGl2VertexArrayObject.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/particle.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/particle.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/particle.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/particle.vert.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/primitive.vert.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.frag.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.frag.js.map +1 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.vert.js +4 -0
- package/dist/esm/rendering/webgl2/glsl/sprite.vert.js.map +1 -0
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.d.ts +28 -0
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.js +50 -0
- package/dist/esm/rendering/webgpu/AbstractWebGpuRenderer.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuBlendState.d.ts +6 -0
- package/dist/esm/rendering/webgpu/WebGpuBlendState.js +79 -0
- package/dist/esm/rendering/webgpu/WebGpuBlendState.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.d.ts +33 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js +443 -0
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.d.ts +39 -0
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js +489 -0
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.d.ts +111 -0
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js +777 -0
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js.map +1 -0
- package/dist/esm/rendering/webgpu/WebGpuRendererRuntime.d.ts +8 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.d.ts +33 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js +528 -0
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js.map +1 -0
- package/dist/esm/resources/AbstractAssetFactory.d.ts +10 -0
- package/dist/esm/resources/AbstractAssetFactory.js +24 -0
- package/dist/esm/resources/AbstractAssetFactory.js.map +1 -0
- package/dist/esm/resources/AssetFactory.d.ts +6 -0
- package/dist/esm/resources/AssetManifest.d.ts +28 -0
- package/dist/esm/resources/AssetManifest.js +66 -0
- package/dist/esm/resources/AssetManifest.js.map +1 -0
- package/dist/esm/resources/CacheFirstStrategy.d.ts +5 -0
- package/dist/esm/resources/CacheFirstStrategy.js +34 -0
- package/dist/esm/resources/CacheFirstStrategy.js.map +1 -0
- package/dist/esm/resources/CacheStore.d.ts +7 -0
- package/dist/esm/resources/CacheStrategy.d.ts +12 -0
- package/dist/esm/resources/Database.d.ts +13 -0
- package/dist/esm/resources/FactoryRegistry.d.ts +9 -0
- package/dist/esm/resources/FactoryRegistry.js +42 -0
- package/dist/esm/resources/FactoryRegistry.js.map +1 -0
- package/dist/esm/resources/IndexedDbDatabase.d.ts +21 -0
- package/dist/esm/resources/IndexedDbDatabase.js +143 -0
- package/dist/esm/resources/IndexedDbDatabase.js.map +1 -0
- package/dist/esm/resources/IndexedDbStore.d.ts +16 -0
- package/dist/esm/resources/IndexedDbStore.js +32 -0
- package/dist/esm/resources/IndexedDbStore.js.map +1 -0
- package/dist/esm/resources/Loader.d.ts +88 -0
- package/dist/esm/resources/Loader.js +601 -0
- package/dist/esm/resources/Loader.js.map +1 -0
- package/dist/esm/resources/NetworkOnlyStrategy.d.ts +5 -0
- package/dist/esm/resources/NetworkOnlyStrategy.js +12 -0
- package/dist/esm/resources/NetworkOnlyStrategy.js.map +1 -0
- package/dist/esm/resources/factories/BinaryFactory.d.ts +6 -0
- package/dist/esm/resources/factories/BinaryFactory.js +14 -0
- package/dist/esm/resources/factories/BinaryFactory.js.map +1 -0
- package/dist/esm/resources/factories/FontFactory.d.ts +13 -0
- package/dist/esm/resources/factories/FontFactory.js +36 -0
- package/dist/esm/resources/factories/FontFactory.js.map +1 -0
- package/dist/esm/resources/factories/ImageFactory.d.ts +10 -0
- package/dist/esm/resources/factories/ImageFactory.js +35 -0
- package/dist/esm/resources/factories/ImageFactory.js.map +1 -0
- package/dist/esm/resources/factories/JsonFactory.d.ts +6 -0
- package/dist/esm/resources/factories/JsonFactory.js +14 -0
- package/dist/esm/resources/factories/JsonFactory.js.map +1 -0
- package/dist/esm/resources/factories/MusicFactory.d.ts +16 -0
- package/dist/esm/resources/factories/MusicFactory.js +37 -0
- package/dist/esm/resources/factories/MusicFactory.js.map +1 -0
- package/dist/esm/resources/factories/SoundFactory.d.ts +14 -0
- package/dist/esm/resources/factories/SoundFactory.js +22 -0
- package/dist/esm/resources/factories/SoundFactory.js.map +1 -0
- package/dist/esm/resources/factories/SvgFactory.d.ts +6 -0
- package/dist/esm/resources/factories/SvgFactory.js +34 -0
- package/dist/esm/resources/factories/SvgFactory.js.map +1 -0
- package/dist/esm/resources/factories/TextFactory.d.ts +6 -0
- package/dist/esm/resources/factories/TextFactory.js +14 -0
- package/dist/esm/resources/factories/TextFactory.js.map +1 -0
- package/dist/esm/resources/factories/TextureFactory.d.ts +13 -0
- package/dist/esm/resources/factories/TextureFactory.js +37 -0
- package/dist/esm/resources/factories/TextureFactory.js.map +1 -0
- package/dist/esm/resources/factories/VideoFactory.d.ts +18 -0
- package/dist/esm/resources/factories/VideoFactory.js +40 -0
- package/dist/esm/resources/factories/VideoFactory.js.map +1 -0
- package/dist/esm/resources/factories/VttFactory.d.ts +6 -0
- package/dist/esm/resources/factories/VttFactory.js +57 -0
- package/dist/esm/resources/factories/VttFactory.js.map +1 -0
- package/dist/esm/resources/factories/WasmFactory.d.ts +6 -0
- package/dist/esm/resources/factories/WasmFactory.js +14 -0
- package/dist/esm/resources/factories/WasmFactory.js.map +1 -0
- package/dist/esm/resources/index.d.ts +26 -0
- package/dist/esm/resources/tokens.d.ts +30 -0
- package/dist/esm/resources/tokens.js +33 -0
- package/dist/esm/resources/tokens.js.map +1 -0
- package/dist/esm/resources/utils.d.ts +1 -0
- package/dist/esm/resources/utils.js +129 -0
- package/dist/esm/resources/utils.js.map +1 -0
- package/dist/esm/vendor/webgl-debug.js +1160 -0
- package/dist/esm/vendor/webgl-debug.js.map +1 -0
- package/dist/exo.esm.js +17111 -0
- package/dist/exo.esm.js.map +1 -0
- package/dist/exo.esm.min.js +2 -0
- package/dist/exo.esm.min.js.map +1 -0
- package/dist/exo.global.js +17328 -0
- package/dist/exo.global.js.map +1 -0
- package/dist/exo.global.min.js +2 -0
- package/dist/exo.global.min.js.map +1 -0
- package/package.json +96 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let t=null;class e{_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 e(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 e(0,0);static get temp(){return null===t&&(t=new e),t}}class i{_state=new Uint32Array(624);_iteration=0;_seed=0;_value=0;constructor(t=Date.now()){this.setSeed(t),this._twist()}get seed(){return this._seed}get value(){return this._value}get iteration(){return this._iteration}setSeed(t){return this._seed=t,this.reset(),this}reset(){this._state[0]=this._seed;for(let t=1;t<624;t++){const e=this._state[t-1]^this._state[t-1]>>>30;this._state[t]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+t,this._state[t]|=0}return this._iteration=0,this}next(t=0,e=1){return this._iteration>=624&&this._twist(),this._value=this._state[this._iteration++],this._value^=this._value>>>11,this._value^=this._value<<7&2636928640,this._value^=this._value<<15&4022730752,this._value^=this._value>>>18,this._value=(this._value>>>0)/4294967295*(e-t)+t,this._value}destroy(){}_twist(){const t=this._state;for(let e=0;e<227;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e+397]^i>>>1^2567483615*(1&i)}for(let e=227;e<623;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e-227]^i>>>1^2567483615*(1&i)}const e=2147483648&t[623]|2147483647&t[0];t[623]=t[396]^e>>>1^2567483615*(1&e),this._iteration=0,this._value=0}}let r=null;class s{_milliseconds;constructor(t=0,e=s.milliseconds){this._milliseconds=t*e}get milliseconds(){return this._milliseconds}set milliseconds(t){this._milliseconds=t}get seconds(){return this._milliseconds/s.seconds}set seconds(t){this._milliseconds=t*s.seconds}get minutes(){return this._milliseconds/s.minutes}set minutes(t){this._milliseconds=t*s.minutes}get hours(){return this._milliseconds/s.hours}set hours(t){this._milliseconds=t*s.hours}set(t=0,e=s.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:r}={}){return!(void 0!==t&&this.milliseconds!==t||void 0!==e&&this.seconds!==e||void 0!==i&&this.minutes!==i||void 0!==r&&this.hours!==r)}greaterThan(t){return this._milliseconds>t.milliseconds}lessThan(t){return this._milliseconds<t.milliseconds}clone(){return new s(this._milliseconds)}copy(t){return this._milliseconds=t.milliseconds,this}add(t=0,e=s.milliseconds){return this._milliseconds+=t*e,this}addTime(t){return this._milliseconds+=t.milliseconds,this}subtract(t=0,e=s.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 zero=new s(0);static oneMillisecond=new s(1);static oneSecond=new s(1,s.seconds);static oneMinute=new s(1,s.minutes);static oneHour=new s(1,s.hours);static get temp(){return null===r&&(r=new s),r}}const n=/^no$/;let o=null,a=null,h=null,l=null,u=null;const c=()=>"undefined"!=typeof document,d=()=>"undefined"!=typeof window,_=()=>{if(!c())throw new Error("Canvas operations require a document context.");return null===a&&(a=document.createElement("canvas")),a},p=(t,e)=>(null===l&&(l=new i),l).next(t,e),f=()=>{},m=t=>{t.preventDefault(),t.stopImmediatePropagation()},g="undefined"!=typeof AudioContext,y="undefined"!=typeof indexedDB,x=d()&&"ontouchstart"in window,w="undefined"!=typeof PointerEvent,v=()=>{if(null!==u)return u;if(!d())return u=!1,u;let t=!1;try{window.addEventListener("test",f,{get passive(){return t=!0,!1}}),window.removeEventListener("test",f)}catch(t){}return u=t,u},b=()=>performance.now(),T=t=>new s(t,s.milliseconds),S=t=>new s(t,s.seconds),C=t=>new s(t,s.minutes),M=t=>new s(t,s.hours),P=new ArrayBuffer(0),B=(t,e,i)=>{if(e<t.length&&i>0){const r=e+i>t.length?t.length-e:i,s=t.length-r;for(let i=e;i<s;i++)t[i]=t[i+r];t.length=s}return t},E=(...t)=>t.some(t=>(()=>{if(!c())throw new Error("Audio codec detection requires a document context.");return null===o&&(o=document.createElement("audio")),o})().canPlayType(t).replace(n,"")),R=t=>{const i=t;return t instanceof HTMLImageElement?e.temp.set(t.naturalWidth,t.naturalHeight):t instanceof HTMLVideoElement?e.temp.set(t.videoWidth,t.videoHeight):t instanceof SVGElement?e.temp.copy(t.getBoundingClientRect()):"number"==typeof i.displayWidth&&"number"==typeof i.displayHeight?e.temp.set(i.displayWidth,i.displayHeight):"number"==typeof i.width&&"number"==typeof i.height?e.temp.set(i.width,i.height):e.zero},k=t=>null===t?e.zero:R(t),A=t=>{const{width:e,height:i}=R(t),r=_();return r.width=e,r.height=i,(()=>{if(null===h){const t=_().getContext("2d");if(!t)throw new Error("Could not create a 2D canvas context.");h=t}return h})().drawImage(t,0,0,e,i),r.toDataURL()};class L{_startTime;_elapsedTime=new s(0);_running=!1;constructor(t=s.zero,e=!1){this._startTime=t.clone(),e&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const t=b();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=b()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(b()-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 F{_bindings=new Array;get bindings(){return this._bindings}has(t,e){return this._bindings.some(i=>i.handler===t&&i.context===e)}add(t,e){return this.has(t,e)||this._bindings.push({handler:t,context:e}),this}once(t,e){const i=(...r)=>{this.remove(i,e),t.call(e,...r)};return this.add(i,e),this}remove(t,e){const i=this._bindings.findIndex(i=>i.handler===t&&i.context===e);return-1!==i&&B(this._bindings,i,1),this}clearByContext(t){const e=this._bindings.filter(e=>e.context===t);for(const t of e)B(this._bindings,this._bindings.indexOf(t),1);return this}clear(){return this._bindings.length=0,this}dispatch(...t){if(this._bindings.length){const e=this._bindings.slice();for(const i of e)if(!1===i.handler.call(i.context,...t))break}return this}destroy(){this.clear()}}const D=2*Math.PI,N=Math.PI/180,I=180/Math.PI;var U;!function(t){t[t.left=-1]="left",t[t.middle=0]="middle",t[t.right=1]="right"}(U||(U={}));const V=t=>{const e=t%360;return e<0?e+360:e},O=t=>t*N,G=t=>t*I,z=(t,e,i)=>Math.min(i,Math.max(e,t)),W=t=>t&&(t<0?-1:1),q=(t,e,i)=>(1-i)*t+i*e,H=t=>0!==t&&!(t&t-1),Y=(t,e,i)=>t>=Math.min(e,i)&&t<=Math.max(e,i),X=(t,e,i,r)=>{const s=t-i,n=e-r;return Math.sqrt(s*s+n*n)},j=(t,e,i,r,s,n,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,p=_*d,f=c*c,m=f*c;h.push(p*t+3*_*c*i+3*d*f*s+m*o,p*e+3*_*c*r+3*d*f*n+m*a)}return h},$=(t,e,i,r,s,n,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push(q(q(t,i,l),q(i,s,l),l),q(q(e,r,l),q(r,n,l),l))}return o},K=(t,e)=>{const i=e.dot(t.x,t.y);return i<0?U.left:i>t.lengthSq?U.right:U.middle};class Q{_r;_g;_b;_a;_rgba=null;_array=null;constructor(t=0,e=0,i=0,r=1){this._r=255&t,this._g=255&e,this._b=255&i,this._a=z(r,0,1)}get r(){return this._r}set r(t){this._r=255&t,this._rgba=null}get g(){return this._g}set g(t){this._g=255&t,this._rgba=null}get b(){return this._b}set b(t){this._b=255&t,this._rgba=null}get a(){return this._a}set a(t){this._a=z(t,0,1),this._rgba=null}get red(){return this.r}set red(t){this.r=t}get green(){return this.g}set green(t){this.g=t}get blue(){return this.b}set blue(t){this.b=t}get alpha(){return this.a}set alpha(t){this.a=t}set(t=this._r,e=this._g,i=this._b,r=this._a){return this._r=255&t,this._g=255&e,this._b=255&i,this._a=z(r,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new Q(this._r,this._g,this._b,this._a)}equals({r:t,g:e,b:i,a:r}={}){return!(void 0!==t&&this.r!==t||void 0!==e&&this.g!==e||void 0!==i&&this.b!==i||void 0!==r&&this.a!==r)}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=this._a&&(255*this._a<<24)+(this._b<<16)+(this._g<<8)+this._r>>>0),this._rgba}destroy(){this._array&&(this._array=null)}static aliceBlue=new Q(240,248,255,1);static antiqueWhite=new Q(250,235,215,1);static aqua=new Q(0,255,255,1);static aquamarine=new Q(127,255,212,1);static azure=new Q(240,255,255,1);static beige=new Q(245,245,220,1);static bisque=new Q(255,228,196,1);static black=new Q(0,0,0,1);static blanchedAlmond=new Q(255,235,205,1);static blue=new Q(0,0,255,1);static blueViolet=new Q(138,43,226,1);static brown=new Q(165,42,42,1);static burlyWood=new Q(222,184,135,1);static cadetBlue=new Q(95,158,160,1);static chartreuse=new Q(127,255,0,1);static chocolate=new Q(210,105,30,1);static coral=new Q(255,127,80,1);static cornflowerBlue=new Q(100,149,237,1);static cornsilk=new Q(255,248,220,1);static crimson=new Q(220,20,60,1);static cyan=new Q(0,255,255,1);static darkBlue=new Q(0,0,139,1);static darkCyan=new Q(0,139,139,1);static darkGoldenrod=new Q(184,134,11,1);static darkGray=new Q(169,169,169,1);static darkGreen=new Q(0,100,0,1);static darkKhaki=new Q(189,183,107,1);static darkMagenta=new Q(139,0,139,1);static darkOliveGreen=new Q(85,107,47,1);static darkOrange=new Q(255,140,0,1);static darkOrchid=new Q(153,50,204,1);static darkRed=new Q(139,0,0,1);static darkSalmon=new Q(233,150,122,1);static darkSeaGreen=new Q(143,188,139,1);static darkSlateBlue=new Q(72,61,139,1);static darkSlateGray=new Q(47,79,79,1);static darkTurquoise=new Q(0,206,209,1);static darkViolet=new Q(148,0,211,1);static deepPink=new Q(255,20,147,1);static deepSkyBlue=new Q(0,191,255,1);static dimGray=new Q(105,105,105,1);static dodgerBlue=new Q(30,144,255,1);static firebrick=new Q(178,34,34,1);static floralWhite=new Q(255,250,240,1);static forestGreen=new Q(34,139,34,1);static fuchsia=new Q(255,0,255,1);static gainsboro=new Q(220,220,220,1);static ghostWhite=new Q(248,248,255,1);static gold=new Q(255,215,0,1);static goldenrod=new Q(218,165,32,1);static gray=new Q(128,128,128,1);static green=new Q(0,128,0,1);static greenYellow=new Q(173,255,47,1);static honeydew=new Q(240,255,240,1);static hotPink=new Q(255,105,180,1);static indianRed=new Q(205,92,92,1);static indigo=new Q(75,0,130,1);static ivory=new Q(255,255,240,1);static khaki=new Q(240,230,140,1);static lavender=new Q(230,230,250,1);static lavenderBlush=new Q(255,240,245,1);static lawnGreen=new Q(124,252,0,1);static lemonChiffon=new Q(255,250,205,1);static lightBlue=new Q(173,216,230,1);static lightCoral=new Q(240,128,128,1);static lightCyan=new Q(224,255,255,1);static lightGoldenrodYellow=new Q(250,250,210,1);static lightGray=new Q(211,211,211,1);static lightGreen=new Q(144,238,144,1);static lightPink=new Q(255,182,193,1);static lightSalmon=new Q(255,160,122,1);static lightSeaGreen=new Q(32,178,170,1);static lightSkyBlue=new Q(135,206,250,1);static lightSlateGray=new Q(119,136,153,1);static lightSteelBlue=new Q(176,196,222,1);static lightYellow=new Q(255,255,224,1);static lime=new Q(0,255,0,1);static limeGreen=new Q(50,205,50,1);static linen=new Q(250,240,230,1);static magenta=new Q(255,0,255,1);static maroon=new Q(128,0,0,1);static mediumAquamarine=new Q(102,205,170,1);static mediumBlue=new Q(0,0,205,1);static mediumOrchid=new Q(186,85,211,1);static mediumPurple=new Q(147,112,219,1);static mediumSeaGreen=new Q(60,179,113,1);static mediumSlateBlue=new Q(123,104,238,1);static mediumSpringGreen=new Q(0,250,154,1);static mediumTurquoise=new Q(72,209,204,1);static mediumVioletRed=new Q(199,21,133,1);static midnightBlue=new Q(25,25,112,1);static mintCream=new Q(245,255,250,1);static mistyRose=new Q(255,228,225,1);static moccasin=new Q(255,228,181,1);static navajoWhite=new Q(255,222,173,1);static navy=new Q(0,0,128,1);static oldLace=new Q(253,245,230,1);static olive=new Q(128,128,0,1);static oliveDrab=new Q(107,142,35,1);static orange=new Q(255,165,0,1);static orangeRed=new Q(255,69,0,1);static orchid=new Q(218,112,214,1);static paleGoldenrod=new Q(238,232,170,1);static paleGreen=new Q(152,251,152,1);static paleTurquoise=new Q(175,238,238,1);static paleVioletRed=new Q(219,112,147,1);static papayaWhip=new Q(255,239,213,1);static peachPuff=new Q(255,218,185,1);static peru=new Q(205,133,63,1);static pink=new Q(255,192,203,1);static plum=new Q(221,160,221,1);static powderBlue=new Q(176,224,230,1);static purple=new Q(128,0,128,1);static red=new Q(255,0,0,1);static rosyBrown=new Q(188,143,143,1);static royalBlue=new Q(65,105,225,1);static saddleBrown=new Q(139,69,19,1);static salmon=new Q(250,128,114,1);static sandyBrown=new Q(244,164,96,1);static seaGreen=new Q(46,139,87,1);static seaShell=new Q(255,245,238,1);static sienna=new Q(160,82,45,1);static silver=new Q(192,192,192,1);static skyBlue=new Q(135,206,235,1);static slateBlue=new Q(106,90,205,1);static slateGray=new Q(112,128,144,1);static snow=new Q(255,250,250,1);static springGreen=new Q(0,255,127,1);static steelBlue=new Q(70,130,180,1);static tan=new Q(210,180,140,1);static teal=new Q(0,128,128,1);static thistle=new Q(216,191,216,1);static tomato=new Q(255,99,71,1);static transparentBlack=new Q(0,0,0,0);static transparentWhite=new Q(255,255,255,0);static turquoise=new Q(64,224,208,1);static violet=new Q(238,130,238,1);static wheat=new Q(245,222,179,1);static white=new Q(255,255,255,1);static whiteSmoke=new Q(245,245,245,1);static yellow=new Q(255,255,0,1);static yellowGreen=new Q(154,205,50,1)}var Z,J,tt,et,it,rt,st;!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"}(Z||(Z={})),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"}(J||(J={})),function(t){t[t.Repeat=10497]="Repeat",t[t.ClampToEdge=33071]="ClampToEdge",t[t.MirroredRepeat=33648]="MirroredRepeat"}(tt||(tt={})),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"}(et||(et={})),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"}(it||(it={})),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"}(rt||(rt={})),function(t){t[t.Int=5124]="Int",t[t.IntVec2=35667]="IntVec2",t[t.IntVec3=35668]="IntVec3",t[t.IntVec4=35669]="IntVec4",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"}(st||(st={}));class nt{get direction(){return Math.atan2(this.x,this.y)}set direction(t){const e=this.length;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get angle(){return this.direction}set angle(t){this.direction=t}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(t){const e=this.direction;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)}get magnitude(){return this.length}set magnitude(t){this.length=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=1/(t.a*t.d+t.c*-t.b);return this.set(this.x*t.d*e+this.y*-t.c*e+(t.y*t.c-t.x*t.d)*e,this.y*t.a*e+this.x*-t.b*e+(-t.y*t.a+t.x*t.b)*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)}}class ot extends nt{_x;_y;_callback;constructor(t,e=0,i=0){super(),this._x=e,this._y=i,this._callback=t}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._callback?.())}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._callback?.())}set direction(t){const e=this.length;this.set(Math.cos(t)*e,Math.sin(t)*e)}set length(t){const e=this.direction;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._callback?.()),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 ot(this._callback,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){}}let at=null;class ht{a;b;x;c;d;y;e;f;z;_array=null;constructor(t=1,e=0,i=0,r=0,s=1,n=0,o=0,a=0,h=1){this.a=t,this.b=e,this.x=i,this.c=r,this.d=s,this.y=n,this.e=o,this.f=a,this.z=h}set(t=this.a,e=this.b,i=this.x,r=this.c,s=this.d,n=this.y,o=this.e,a=this.f,h=this.z){return this.a=t,this.b=e,this.x=i,this.c=r,this.d=s,this.y=n,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 ht(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:r,d:s,y:n,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!==r&&this.c!==r||void 0!==s&&this.d!==s||void 0!==n&&this.y!==n||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(ht.identity):t.set((this.z*this.d-this.y*this.f)/e,(this.z*this.c-this.y*this.e)/-e,(this.f*this.c-this.d*this.e)/e,(this.z*this.b-this.x*this.f)/-e,(this.z*this.a-this.x*this.e)/e,(this.f*this.a-this.b*this.e)/-e,(this.y*this.b-this.x*this.d)/e,(this.y*this.a-this.x*this.c)/-e,(this.d*this.a-this.b*this.c)/e)}translate(t,e=t){return this.combine(ht.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const r=O(t),s=Math.cos(r),n=Math.sin(r);return this.combine(ht.temp.set(s,-n,e*(1-s)+i*n,n,s,i*(1-s)-e*n,0,0,1))}scale(t,e=t,i=0,r=i){return this.combine(ht.temp.set(t,0,i*(1-t),0,e,r*(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 ht(1,0,0,0,1,0,0,0,1);static get temp(){return null===at&&(at=new ht),at}}class lt{_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()}}var ut;!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"}(ut||(ut={}));class ct{flags=new lt(ut.Transform);_transform=new ht;_position=new ot(this._setPositionDirty.bind(this),0,0);_scale=new ot(this._setScalingDirty.bind(this),1,1);_origin=new ot(this._setOriginDirty.bind(this),0,0);_rotation=0;_sin=0;_cos=1;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)}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}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(ut.Transform)&&(this.updateTransform(),this.flags.remove(ut.Transform)),this._transform}updateTransform(){if(this.flags.has(ut.Rotation)){const t=O(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}if(this.flags.has(ut.Rotation|ut.Scaling)){const{x:t,y:e}=this._scale;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){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}destroy(){this._transform.destroy(),this._position.destroy(),this._scale.destroy(),this._origin.destroy(),this.flags.destroy()}_setPositionDirty(){this.flags.push(ut.Translation)}_setRotationDirty(){this.flags.push(ut.Rotation)}_setScalingDirty(){this.flags.push(ut.Scaling)}_setOriginDirty(){this.flags.push(ut.Origin)}}let dt=null;class _t{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 _t(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 _t(0,0);static get temp(){return null===dt&&(dt=new _t),dt}}var pt;!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"}(pt||(pt={}));const ft=1e-10,mt=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),gt=({x:t,y:e,rx:i,ry:r})=>{if(i<=0||r<=0)return[];const s=mt(i,r),n=2*Math.PI/s,o=[];for(let a=0;a<s;a++){const s=a*n;o.push({x:t+Math.cos(s)*i,y:e+Math.sin(s)*r})}return o},yt=({x:t,y:e},{x:i,y:r},{x:s,y:n})=>t<=Math.max(i,s)+ft&&t>=Math.min(i,s)-ft&&e<=Math.max(r,n)+ft&&e>=Math.min(r,n)-ft,xt=({x:t,y:e},{x:i,y:r},{x:s,y:n})=>{const o=(r-e)*(s-i)-(i-t)*(n-r);return Math.abs(o)<=ft?0:o>0?1:2},wt=(t,e,i,r)=>{const s=xt(t,e,i),n=xt(t,e,r),o=xt(i,r,t),a=xt(i,r,e);return s!==n&&o!==a||(!(0!==s||!yt(i,t,e))||(!(0!==n||!yt(r,t,e))||(!(0!==o||!yt(t,i,r))||!(0!==a||!yt(e,i,r)))))},vt=({x:t,y:e},i)=>{const r=i.length;if(r<3)return!1;let s=!1;for(let n=0,o=r-1;n<r;o=n++){const r=i[o],a=i[n];a.y>e!=r.y>e&&t<(r.x-a.x)*((e-a.y)/(r.y-a.y))+a.x&&(s=!s)}return s},bt=(t,e)=>{if(0===t.length||0===e.length)return!1;for(let i=0;i<t.length;i++){const r=t[i],s=t[(i+1)%t.length];for(let t=0;t<e.length;t++){const i=e[t],n=e[(t+1)%e.length];if(wt(r,s,i,n))return!0}}return vt(t[0],e)||vt(e[0],t)},Tt=({x:t,y:e},{x:i,y:r},{x:s,y:n},o=.1)=>{const a=X(t,e,i,r),h=X(t,e,s,n),l=X(i,r,s,n);return a+h>=l-o&&a+h<=l+o},St=(t,e,i,r)=>{const s=(e.x-t.x)*(r.y-i.y)-(r.x-i.x)*(e.y-t.y);if(Math.abs(s)<=ft)return!1;const n=((r.x-i.x)*(t.y-i.y)-(r.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 n>=0&&n<=1&&o>=0&&o<=1},Ct=(t,e)=>Math.sqrt(t*t+e*e),Mt=(t,e,i,r)=>{const s=i*t+r*e;const n=(o=t)*o+(a=e)*a;var o,a;return s<0?U.left:s>n?U.right:U.middle},Pt=(t,e)=>{const i=t.getNormals(),r=e.getNormals(),s=new _t,n=new _t;for(const r of i)if(t.project(r,s),e.project(r,n),!s.overlaps(n))return!1;for(const i of r)if(t.project(i,s),e.project(i,n),!s.overlaps(n))return!1;return!0},Bt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:r},s=0)=>X(t,e,i,r)<=s)(t,e,i),Et=(t,e,i=.1)=>Tt(t,e.fromPosition,e.toPosition,i),Rt=(t,e)=>(({x:t,y:e},{x:i,y:r,width:s,height:n})=>Y(t,i,i+s)&&Y(e,r,r+n))(t,e),kt=(t,e)=>(({x:t,y:e},{x:i,y:r,radius:s})=>s>0&&X(t,e,i,r)<=s)(t,e),At=(t,e)=>(({x:t,y:e},{x:i,y:r,rx:s,ry:n})=>{if(s<=0||n<=0)return!1;const o=(t-i)/s,a=(e-r)/n;return o*o+a*a<=1})(t,e),Lt=(t,e)=>((t,{points:e})=>vt(t,e))(t,e),Ft=(t,e)=>St(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),Dt=(t,e)=>{const{x:i,y:r,width:s,height:n}=e,o={x:i,y:r},a={x:i+s,y:r},h={x:i,y:r+n},l={x:i+s,y:r+n};return St(t.fromPosition,t.toPosition,o,h)||St(t.fromPosition,t.toPosition,a,l)||St(t.fromPosition,t.toPosition,o,a)||St(t.fromPosition,t.toPosition,h,l)},Nt=(t,e)=>{if(kt(t.fromPosition,e)||kt(t.toPosition,e))return!0;const{fromX:i,fromY:r,toX:s,toY:n}=t,{x:o,y:a,radius:h}=e,l=X(i,r,s,n);if(0===l)return!1;const u=((o-i)*(s-i)+(a-r)*(n-r))/(l*l),c=i+u*(s-i),d=r+u*(n-r);return!!Tt({x:c,y:d},t.fromPosition,t.toPosition)&&X(c,d,o,a)<=h},It=(t,e)=>{const{x:i,y:r,rx:s,ry:n}=e;if(s<=0||n<=0)return!1;const o=(t.fromX-i)/s,a=(t.fromY-r)/n,h=(t.toX-i)/s-o,l=(t.toY-r)/n-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 p=Math.sqrt(_),f=(-c-p)/(2*u),m=(-c+p)/(2*u);return f>=0&&f<=1||m>=0&&m<=1},Ut=(t,e)=>{const{x:i,y:r,points:s}=e,n=s.length;for(let e=0;e<n;e++){const o=s[e],a=s[(e+1)%n];if(St(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+r},{x:a.x+i,y:a.y+r}))return!0}return!1},Vt=(t,e)=>(({x:t,y:e,width:i,height:r},{x:s,y:n,width:o,height:a})=>!(s>t+i||n>e+r||t>s+o||e>n+a))(t,e),Ot=({x:t,y:e,width:i,height:r},{x:s,y:n,radius:o})=>{const a=z(s,t,t+i),h=z(n,e,e+r);return X(s,n,a,h)<=o},Gt=(t,e)=>bt((({x:t,y:e,width:i,height:r})=>[{x:t,y:e},{x:t+i,y:e},{x:t+i,y:e+r},{x:t,y:e+r}])(t),gt(e)),zt=(t,e)=>Pt(t,e),Wt=({x:t,y:e,radius:i},{x:r,y:s,radius:n})=>X(t,e,r,s)<=i+n,qt=(t,e)=>bt((({x:t,y:e,radius:i})=>{if(i<=0)return[];const r=mt(i),s=2*Math.PI/r,n=[];for(let o=0;o<r;o++){const r=o*s;n.push({x:t+Math.cos(r)*i,y:e+Math.sin(r)*i})}return n})(t),gt(e)),Ht=(t,e,i,r,s,n,o,a,h)=>{if(Mt(a,h,s,n)!==U.left)return!1;return Mt(r.x,r.y,t-i.x,e-i.y)===U.right&&Ct(s,n)>o},Yt=(t,e,i,r,s,n,o,a,h)=>{if(Mt(a,h,s,n)!==U.right)return!1;return Mt(r.x,r.y,t-i.x,e-i.y)===U.left&&Ct(s,n)>o},Xt=(t,e,i,r,s)=>{const n=s,o=-r,a=Ct(n,o);if(0===a)return!1;const h=(t*n+e*o)/a;return h>0&&Math.abs(h)>i},jt=({x:t,y:e,radius:i},{x:r,y:s,points:n,edges:o})=>{const a=r-t,h=s-e,l=n.length;for(let t=0;t<l;t++){const e=n[t],r=a-e.x,s=h-e.y,u=0===t?l-1:t-1,c=(t+1)%l,d=o[t];if(Ht(a,h,n[u],o[u],r,s,i,d.x,d.y))return!1;if(Yt(a,h,n[c],o[c],r,s,i,d.x,d.y))return!1;if(Xt(r,s,i,d.x,d.y))return!1}return!0},$t=(t,e)=>bt(gt(t),gt(e)),Kt=(t,e)=>bt(gt(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:r})=>({x:i+t,y:r+e})))(e)),Qt=(t,e)=>Pt(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=t.position.clone().set(0,0),r=t.position.clone().set(0,0);return{shapeA:t,shapeB:e,overlap:0,shapeAinB:e.containsRect(t),shapeBinA:t.containsRect(e),projectionN:i,projectionV:r}},Jt=(t,e)=>{const i=e.position.clone().subtract(t.x,t.y),r=i.length,s=t.radius+e.radius-r;if(s<0)return i.destroy(),null;const n=i.clone().normalize(),o=i.multiply(s);return{shapeA:t,shapeB:e,overlap:s,shapeAinB:t.radius<=e.radius&&r<=e.radius-t.radius,shapeBinA:e.radius<=t.radius&&r<=t.radius-e.radius,projectionN:n,projectionV:o}},te=(t,e,i=!1)=>{const r=t.radius,s=e.width/2,n=e.height/2,o=X(t.x,t.y,e.x-s,e.y-n),a=r<=Math.min(s,n)&&o<=Math.min(s,n)-r,h=Math.max(s,n)<=r&&o<=r-Math.max(s,n);if(o>t.radius)return null;const l=t.position.clone().set(0,0),u=t.position.clone().set(0,0);return{shapeA:i?e:t,shapeB:i?t:e,overlap:r-o,shapeAinB:i?h:a,shapeBinA:i?a:h,projectionN:l,projectionV:u}},ee=(t,e,i=!1)=>{const r=e.radius,s=t.points,n=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,p=n-e.x,f=o-e.y,m=Mt(d,_,p,f),g=Ct(p,f);if(g>r&&(l=!1),m===U.left){const i=s[0===t?h-1:t-1],l=e.x-i.x,d=e.y-i.y,_=n-i.x,m=o-i.y;if(Mt(l,d,_,m)===U.right){if(g>r)return a.destroy(),null;const t=r-g;Math.abs(t)<Math.abs(c)&&(c=t,a.set(p,f).normalize()),u=!1}}else if(m===U.right){const e=s[(t+2)%h],l=e.x-i.x,d=e.y-i.y,_=n-i.x,p=o-i.y,f=Ct(_,p);if(Mt(l,d,_,p)===U.left){if(f>r)return a.destroy(),null;const t=r-f;Math.abs(t)<Math.abs(c)&&(c=t,a.set(_,p).normalize()),u=!1}}else{const t=_,e=-d,i=Ct(t,e),s=0===i?0:(p*t+f*e)/i;if(s>0&&Math.abs(s)>r)return a.destroy(),null;(s>=0||r-s<2*r)&&(u=!1);const n=r-s;Math.abs(n)<Math.abs(c)&&(c=n,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}},ie=(t,e)=>{const i=t.getNormals(),r=e.getNormals(),s=(i[0]||r[0]).clone(),n=new _t,o=new _t;let a=1/0,h=!0,l=!0,u=!1,c=!1,d=0;for(const r of i){if(t.project(r,n),e.project(r,o),!n.overlaps(o))return s.destroy(),null;d=n.getOverlap(o),u=o.containsInterval(n),c=n.containsInterval(o),!u&&h&&(h=!1),!c&&l&&(l=!1),(u||c)&&(d+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),d<a&&(a=d,s.copy(r))}for(const i of r){if(t.project(i,n),e.project(i,o),!n.overlaps(o))return s.destroy(),null;d=n.getOverlap(o),u=o.containsInterval(n),c=n.containsInterval(o),!u&&h&&(h=!1),!c&&l&&(l=!1),(u||c)&&(d+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),d<a&&(a=d,s.copy(i))}const _=s.clone().multiply(a,a);return{shapeA:t,shapeB:e,overlap:a,shapeAinB:h,shapeBinA:l,projectionN:s,projectionV:_}};let re=null;const se=()=>{},ne=new ot(se);class oe{collisionType=pt.Rectangle;_position;_size;_normals=null;_normalsDirty=!1;constructor(t=0,i=t,r=0,s=r){this._position=new ot(()=>{this._normalsDirty=!0},t,i),this._size=new e(r,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,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,r){return this.setPosition(t,e),this.setSize(i,r),this}copy(t){return this.position=t.position,this.size=t.size,this}clone(){return new oe(this.x,this.y,this.width,this.height)}equals({x:t,y:e,width:i,height:r}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.width!==i||void 0!==r&&this.height!==r)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new ot(se),new ot(se),new ot(se),new ot(se)])),this._normalsDirty=!1),this._normals}project(t,e=new _t){const i=t.dot(this.left,this.top),r=t.dot(this.right,this.top),s=t.dot(this.right,this.bottom),n=t.dot(this.left,this.bottom);return e.set(Math.min(i,r,s,n),Math.max(i,r,s,n))}transform(t,e=this){const i=ne.set(this.left,this.top).transform(t);let r=i.x,s=i.x,n=i.y,o=i.y;return i.set(this.left,this.bottom).transform(t),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(t),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(t),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y),e.set(r,n,s-r,o-n)}contains(t,e){return Rt(ne.set(t,e),this)}containsRect(t){return Y(t.left,this.left,this.right)&&Y(t.right,this.left,this.right)&&Y(t.top,this.top,this.bottom)&&Y(t.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case pt.SceneNode:return t.isAlignedBox?Vt(this,t.getBounds()):Pt(this,t);case pt.Rectangle:return Vt(this,t);case pt.Polygon:return zt(this,t);case pt.Circle:return Ot(this,t);case pt.Ellipse:return Gt(this,t);case pt.Line:return Dt(t,this);case pt.Point:return Rt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case pt.SceneNode:return t.isAlignedBox?Zt(this,t.getBounds()):ie(this,t);case pt.Rectangle:return Zt(this,t);case pt.Polygon:return ie(this,t);case pt.Circle:return te(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===re&&(re=new oe),re}}class ae{_minX=1/0;_minY=1/0;_maxX=-1/0;_maxY=-1/0;_dirty=!0;_rect=new oe;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,oe.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()}}class he extends ct{collisionType=pt.SceneNode;_bounds=new ae;_visible=!0;_globalTransform=new ht;_localBounds=new oe;_anchor=new ot(this._updateOrigin.bind(this),0,0);_parentNode=null;_zIndex=0;_childOrder=0;_cullable=!0;get anchor(){return this._anchor}set anchor(t){this._anchor.copy(t)}get parent(){return this._parentNode}set parent(t){this._parentNode=t}get parentNode(){return this._parentNode}set parentNode(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,this._parentNode?.markSortDirty())}get childOrder(){return this._childOrder}get cullable(){return this._cullable}set cullable(t){this._cullable=t}get globalTransform(){return this.getGlobalTransform()}get localBounds(){return this.getLocalBounds()}get bounds(){return this.getBounds()}get isAlignedBox(){return this.rotation%90==0}setAnchor(t,e=t){return this._anchor.set(t,e),this}setChildOrder(t){return this._childOrder=t,this}setCullable(t){return this._cullable=t,this}getLocalBounds(){return this._localBounds}getBounds(){return this.updateParentTransform(),this.updateBounds(),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._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this._globalTransform}getNormals(){return this.getBounds().getNormals()}project(t,e=new _t){return this.getBounds().project(t,e)}intersectsWith(t){if(this.isAlignedBox)return this.getBounds().intersectsWith(t);switch(t.collisionType){case pt.SceneNode:case pt.Rectangle:case pt.Polygon:return Pt(this,t);case pt.Circle:return Ot(this.getBounds(),t);case pt.Ellipse:return Gt(this.getBounds(),t);case pt.Line:return Dt(t,this.getBounds());case pt.Point:return Rt(t,this.getBounds());default:return!1}}collidesWith(t){if(this.isAlignedBox)return this.getBounds().collidesWith(t);switch(t.collisionType){case pt.SceneNode:case pt.Rectangle:case pt.Polygon:case pt.Circle:return ie(this,t);default:return null}}contains(t,e){return this.getBounds().contains(t,e)}inView(t){return!this._cullable||t.getBounds().intersectsWith(this.getBounds())}render(t){return this}destroy(){super.destroy(),this._globalTransform.destroy(),this._localBounds.destroy(),this._bounds.destroy(),this._anchor.destroy()}_updateOrigin(){const{x:t,y:e}=this._anchor,{width:i,height:r}=this.getBounds();this.setOrigin(i*t,r*e)}}class le extends e{_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 le(this._callback,this._width,this._height)}}var ue;!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"}(ue||(ue={}));class ce{_center;_size;_viewport=new oe(0,0,1,1);_transform=new ht;_inverseTransform=new ht;_bounds=new ae;_flags=new lt;_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,r){this._center=new ot(this._setPositionDirty.bind(this),t,e),this._size=new le(this._setScalingDirty.bind(this),i,r),this._zoomBaseWidth=i,this._zoomBaseHeight=r,this._flags.push(ue.Transform,ue.TransformInverse,ue.BoundingBox)}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=z(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,r){return this._zoomBaseWidth=i,this._zoomBaseHeight=r,this._zoomLevel=1,this._size.set(i,r),this._center.set(t,e),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(ue.Transform),this}getTransform(){return this._flags.has(ue.Transform)&&(this.updateTransform(),this._flags.remove(ue.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=2/this.width,r=-2/this.height;if(this._flags.has(ue.Rotation)){const t=O(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}return this._flags.has(ue.Rotation|ue.Scaling)&&(this._transform.a=i*this._cos,this._transform.b=i*this._sin,this._transform.c=-r*this._sin,this._transform.d=r*this._cos),this._transform.x=i*-this._transform.a-r*this._transform.b+-i*t,this._transform.y=i*-this._transform.c-r*this._transform.d+-r*e,this}getInverseTransform(){return this._flags.has(ue.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(ue.TransformInverse)),this._inverseTransform}getBounds(){return this._flags.has(ue.BoundingBox)&&(this.updateBounds(),this._flags.remove(ue.BoundingBox)),this._bounds.getRect()}updateBounds(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=this.width/2,r=this.height/2;return this._bounds.reset().addCoords(t-i,e-r).addCoords(t+i,e+r),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(ue.TransformInverse,ue.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(ue.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(ue.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(ue.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;const 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,r=t.left+e,s=t.right-e,n=t.top+i,o=t.bottom-i,a=r>s?(t.left+t.right)/2:z(this._center.x,r,s),h=n>o?(t.top+t.bottom)/2:z(this._center.y,n,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 r=Math.sin(1.7*this._shakePhase)*i,s=Math.cos(1.3*this._shakePhase)*i;r===this._shakeOffsetX&&s===this._shakeOffsetY||(this._shakeOffsetX=r,this._shakeOffsetY=s,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}let de=null;class _e extends nt{collisionType=pt.Point;x;y;constructor(t=0,e=0){super(),this.x=t,this.y=e}clone(){return new _e(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(t){switch(t.collisionType){case pt.SceneNode:return Rt(this,t.getBounds());case pt.Rectangle:return Rt(this,t);case pt.Polygon:return Lt(this,t);case pt.Circle:return kt(this,t);case pt.Ellipse:return At(this,t);case pt.Line:return Et(this,t);case pt.Point:return Bt(this,t);default:return!1}}collidesWith(t){return null}getBounds(){return oe.temp.set(this.x,this.y,0,0)}contains(t,e){return Bt(_e.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new _t){return e}destroy(){}static get temp(){return null===de&&(de=new _e),de}static zero=new _e(0,0);static one=new _e(1,1);static add(t,e){return new _e(t.x+e.x,t.y+e.y)}static subtract(t,e){return new _e(t.x-e.x,t.y-e.y)}static multiply(t,e){return new _e(t.x*e.x,t.y*e.y)}static divide(t,e){return new _e(t.x/e.x,t.y/e.y)}}class pe{_root;_destroyListeners=new Set;_version=0;_size;_viewport=new oe;_defaultView;_view;constructor(t,i,r=!1){this._size=new e(t,i),this._root=r,this._defaultView=new ce(t/2,i/2,t,i),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:r,height:s}=t.viewport;return this._viewport.set(Math.round(e*this.width),Math.round(i*this.height),Math.round(r*this.width),Math.round(s*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(t,e=this._view){const i=this.getViewport(e);return new _e(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),r=t.clone().transform(e.getTransform());return r.set((r.x+1)/2*i.width+i.left|0,(1-r.y)/2*i.height+i.top|0)}destroy(){for(const t of Array.from(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 fe extends pe{static defaultSamplerOptions={scaleMode:J.Linear,wrapMode:tt.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:r,wrapMode:s,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...fe.defaultSamplerOptions,...i};this._scaleMode=r,this._wrapMode=s,this._premultiplyAlpha=n,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 H(this.width)&&H(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++}}class me{_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.renderTarget,i=t.view;t.setRenderTarget(this._target),t.setView(this._view),null!==this._clearColor&&t.clear(this._clearColor);try{this._callback(t)}finally{t.setRenderTarget(e),t.setView(i)}}}const ge=t=>"destroy"in t&&"function"==typeof t.destroy;class ye extends he{static _spriteFactory=null;_filters=[];_cacheBounds=new oe;_cacheSprite=null;_captureView=null;_mask=null;_cacheAsBitmap=!1;_cacheDirty=!0;_cacheTexture=null;get filters(){return this._filters}set filters(t){this.setFilters(t)}get mask(){return this._mask}set mask(t){this._mask!==t&&(this._mask=t,this.invalidateCache())}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(t){this.setCacheAsBitmap(t)}setFilters(t){return this._filters.length=0,this._filters.push(...t),this.invalidateCache()}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){ye._spriteFactory=t}clearFilters(){return this._filters.length>0&&(this._filters.length=0,this.invalidateCache()),this}setCacheAsBitmap(t){return this._cacheAsBitmap!==t&&(this._cacheAsBitmap=t,this.invalidateCache(),t||this._destroyCacheTexture()),this}invalidateCache(){return this._cacheDirty=!0,this}renderVisualContent(t,e,i=Z.Normal){const r=this._filters.length>0,s=this._cacheAsBitmap;if(!r&&!s)return void this._withMask(t,e);const n=this.getBounds();if(n.width<=0||n.height<=0)return;const o=Math.floor(n.left),a=Math.floor(n.top),h=Math.max(1,Math.ceil(n.width)),l=Math.max(1,Math.ceil(n.height)),u=!this._cacheBounds.equals({x:o,y:a,width:h,height:l}),c=s&&(this._cacheDirty||null===this._cacheTexture||u);if(s&&!c&&null!==this._cacheTexture)return void this._withMask(t,()=>{this._drawTexture(t,this._cacheTexture,o,a,h,l,i)});const d=[],_=s?this._ensureCacheTexture(h,l):null;try{const n=s&&!r?_:t.acquireRenderTexture(h,l);n!==_&&d.push(n),this._renderContentToTexture(t,n,o,a,h,l,e);let u=n;if(r)for(let e=0;e<this._filters.length;e++){const i=e===this._filters.length-1&&s?_:t.acquireRenderTexture(h,l);i!==_&&d.push(i),this._filters[e].apply(t,u,i),u=i}s&&(this._cacheTexture=_,this._cacheBounds.set(o,a,h,l),this._cacheDirty=!1),this._withMask(t,()=>{this._drawTexture(t,u,o,a,h,l,i)})}finally{for(const e of d)t.releaseRenderTexture(e)}}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)ge(t)&&t.destroy();this._filters.length=0,this._mask=null}_withMask(t,e){if(null===this._mask)return void e();const i=this._mask.getBounds();if(!(i.width<=0||i.height<=0)){t.pushMask(i);try{e()}finally{t.popMask()}}}_renderContentToTexture(t,e,i,r,s,n,o){null===this._captureView?this._captureView=new ce(i+s/2,r+n/2,s,n):this._captureView.reset(i+s/2,r+n/2,s,n),t.execute(new me(()=>{o()},{target:e,view:this._captureView,clearColor:Q.transparentBlack}))}_drawTexture(t,e,i,r,s,n,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(Q.white).setPosition(i,r).setRotation(0).setScale(1,1),a.width=s,a.height=n,a.render(t)}_ensureCacheTexture(t,e){return null===this._cacheTexture?this._cacheTexture=new fe(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===ye._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=ye._spriteFactory()}return this._cacheSprite}}class xe extends ye{_tint=Q.white.clone();_blendMode=Z.Normal;get tint(){return this._tint}set tint(t){this.setTint(t)}get blendMode(){return this._blendMode}set blendMode(t){this.setBlendMode(t)}setTint(t){return t&&(this._tint.copy(t),this.invalidateCache()),this}setBlendMode(t){return this._blendMode!==t&&(this._blendMode=t,this.invalidateCache()),this}render(t){return this.visible?this.inView(t.view)?(this.renderVisualContent(t,()=>{t.draw(this)},this._blendMode),this):(t.stats.culledNodes++,this):this}destroy(){super.destroy(),this._tint.destroy()}}class we extends xe{geometry;drawMode;color;constructor(t,e,i=et.Triangles){super(),this.geometry=t,this.color=e.clone(),this.drawMode=i}destroy(){super.destroy(),this.color.destroy()}}class ve{vertices;indices;points;constructor({vertices:t=[],indices:e=[],points:i=[]}={}){this.vertices=new Float32Array(t),this.indices=new Uint16Array(e),this.points=i}destroy(){}}class be extends we{render(t){return this.visible&&t.draw(this),this}}class Te{_app;_stack=[];_transitionOverlay=new be((()=>new ve({vertices:[0,0,1,0,0,1,1,1],indices:[0,1,2,3],points:[0,0,1,0,0,1,1,1]}))(),Q.black,et.TriangleStrip);_transition=null;onChangeScene=new F;onStartScene=new F;onUpdateScene=new F;onStopScene=new F;constructor(t){this._app=t,this._subscribeInputRouting()}get scene(){return this._stack.length>0?this._stack[this._stack.length-1].scene:null}set scene(t){this.setScene(t)}get scenes(){return this._stack.map(t=>t.scene)}async setScene(t,e={}){return await this._runWithTransition(async()=>{if(null===t)return await this._unloadAllScenes(),void this.onChangeScene.dispatch(null);if(this.scene===t)return void(this._stack.length>1&&await this._unloadCoveredScenes());if(this._stack.some(e=>e.scene===t))throw new Error("Cannot set a scene that is already present in the scene stack.");const e=this._resolveParticipationPolicy(t);await this._prepareScene(t),await this._unloadAllScenes(),this._stack.push({scene:t,policy:e}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async pushScene(t,e={}){return await this._runWithTransition(async()=>{if(this._stack.some(e=>e.scene===t))throw new Error("Cannot push a scene instance that is already present in the stack.");const i=this._resolveParticipationPolicy(t,e);await this._prepareScene(t),this._stack.push({scene:t,policy:i}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async popScene(t={}){return await this._runWithTransition(async()=>{if(0===this._stack.length)return;const t=this._stack[this._stack.length-1];await this._disposeScene(t.scene),this._stack.pop(),this.onChangeScene.dispatch(this.scene)},t.transition),this}update(t){this._advanceTransition(t.milliseconds);const{updateScenes:e,drawScenes:i}=this._resolveParticipants();for(const i of e)i.update(t);for(const t of i)t.draw(this._app.renderManager);const r=this._getTransitionAlpha();return r>0&&this._renderTransitionOverlay(r),null!==this.scene&&this.onUpdateScene.dispatch(this.scene),this}destroy(){if(this._unsubscribeInputRouting(),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._unloadAllScenesOnDestroy(),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)}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),r=i instanceof Error?i.message:String(i);throw new Error(`Failed to initialize scene: ${t}. Cleanup also failed: ${r}.`,{cause:e})}throw e}}async _disposeScene(t){this.onStopScene.dispatch(t),await t.unload(this._app.loader),t.destroy(),t.app=null}async _unloadAllScenes(){for(let t=this._stack.length-1;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0}async _unloadCoveredScenes(){if(this._stack.length<=1)return;const t=this._stack[this._stack.length-1];for(let t=this._stack.length-2;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0,this._stack.push(t)}async _unloadAllScenesOnDestroy(){for(let t=this._stack.length-1;t>=0;t--)try{await this._disposeScene(this._stack[t].scene)}catch(t){console.error("SceneManager.destroy() failed to unload the active scene.",t)}this._stack.length=0}_resolveParticipationPolicy(t,e={}){const i=t.getParticipationPolicy(),r=e.mode??i.mode??"overlay";return{mode:r,input:e.input??i.input??("overlay"===r?"passthrough":"capture")}}_resolveParticipants(){const t=new Array,e=new Array;let i=!0,r=!0;for(let s=this._stack.length-1;s>=0;s--){const n=this._stack[s];i&&t.push(n.scene),r&&e.push(n.scene),"opaque"===n.policy.mode?(i=!1,r=!1):"modal"===n.policy.mode&&(i=!1)}return t.reverse(),e.reverse(),{updateScenes:t,drawScenes:e}}_subscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.add?.(this._handleKeyDown),t?.onKeyUp?.add?.(this._handleKeyUp),t?.onPointerEnter?.add?.(this._handlePointerEnter),t?.onPointerLeave?.add?.(this._handlePointerLeave),t?.onPointerDown?.add?.(this._handlePointerDown),t?.onPointerMove?.add?.(this._handlePointerMove),t?.onPointerUp?.add?.(this._handlePointerUp),t?.onPointerTap?.add?.(this._handlePointerTap),t?.onPointerSwipe?.add?.(this._handlePointerSwipe),t?.onPointerCancel?.add?.(this._handlePointerCancel),t?.onMouseWheel?.add?.(this._handleMouseWheel)}_unsubscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.remove?.(this._handleKeyDown),t?.onKeyUp?.remove?.(this._handleKeyUp),t?.onPointerEnter?.remove?.(this._handlePointerEnter),t?.onPointerLeave?.remove?.(this._handlePointerLeave),t?.onPointerDown?.remove?.(this._handlePointerDown),t?.onPointerMove?.remove?.(this._handlePointerMove),t?.onPointerUp?.remove?.(this._handlePointerUp),t?.onPointerTap?.remove?.(this._handlePointerTap),t?.onPointerSwipe?.remove?.(this._handlePointerSwipe),t?.onPointerCancel?.remove?.(this._handlePointerCancel),t?.onMouseWheel?.remove?.(this._handleMouseWheel)}_dispatchInput(t){for(let e=this._stack.length-1;e>=0;e--){const i=this._stack[e];if("transparent"===i.policy.input)continue;if(!1===i.scene.handleInput(t)||"capture"===i.policy.input)break}}_handleKeyDown=t=>{this._dispatchInput({type:"keyDown",channel:t})};_handleKeyUp=t=>{this._dispatchInput({type:"keyUp",channel:t})};_handlePointerEnter=t=>{this._dispatchInput({type:"pointerEnter",pointer:t})};_handlePointerLeave=t=>{this._dispatchInput({type:"pointerLeave",pointer:t})};_handlePointerDown=t=>{this._dispatchInput({type:"pointerDown",pointer:t})};_handlePointerMove=t=>{this._dispatchInput({type:"pointerMove",pointer:t})};_handlePointerUp=t=>{this._dispatchInput({type:"pointerUp",pointer:t})};_handlePointerTap=t=>{this._dispatchInput({type:"pointerTap",pointer:t})};_handlePointerSwipe=t=>{this._dispatchInput({type:"pointerSwipe",pointer:t})};_handlePointerCancel=t=>{this._dispatchInput({type:"pointerCancel",pointer:t})};_handleMouseWheel=t=>{this._dispatchInput({type:"mouseWheel",wheel:t})};async _runWithTransition(t,e){if(!e||"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((r,s)=>{this._transition={type:"fade",durationMs:i,action:t,resolve:r,reject:s,color:(e.color??Q.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(t&&"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:Q.black,r=this._app.renderManager,s=r.view.getBounds(),n=this._transitionOverlay.geometry.vertices;n[0]=s.left,n[1]=s.top,n[2]=s.right,n[3]=s.top,n[4]=s.left,n[5]=s.bottom,n[6]=s.right,n[7]=s.bottom,this._transitionOverlay.color.set(i.r,i.g,i.b,Math.max(0,Math.min(1,t))),this._transitionOverlay.render(r)}}const Se=function(){var t=function(t){window.console&&window.console.error?window.console.error(t):function(t){window.console&&window.console.log&&window.console.log(t)}(t)},e={enable:{1:{0:!0}},disable:{1:{0:!0}},getParameter:{1:{0:!0}},drawArrays:{3:{0:!0}},drawElements:{4:{0:!0,2:!0}},createShader:{1:{0:!0}},getShaderParameter:{2:{1:!0}},getProgramParameter:{2:{1:!0}},getShaderPrecisionFormat:{2:{0:!0,1:!0}},getVertexAttrib:{2:{1:!0}},vertexAttribPointer:{6:{2:!0}},bindTexture:{2:{0:!0}},activeTexture:{1:{0:!0}},getTexParameter:{2:{0:!0,1:!0}},texParameterf:{3:{0:!0,1:!0}},texParameteri:{3:{0:!0,1:!0,2:!0}},copyTexImage2D:{8:{0:!0,2:!0}},copyTexSubImage2D:{8:{0:!0}},generateMipmap:{1:{0:!0}},bindBuffer:{2:{0:!0}},getBufferParameter:{2:{0:!0,1:!0}},pixelStorei:{2:{0:!0,1:!0}},bindRenderbuffer:{2:{0:!0}},bindFramebuffer:{2:{0:!0}},checkFramebufferStatus:{1:{0:!0}},framebufferRenderbuffer:{4:{0:!0,1:!0,2:!0}},framebufferTexture2D:{5:{0:!0,1:!0,2:!0}},getFramebufferAttachmentParameter:{3:{0:!0,1:!0,2:!0}},getRenderbufferParameter:{2:{0:!0,1:!0}},renderbufferStorage:{4:{0:!0,1:!0}},clear:{1:{0:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]}}},depthFunc:{1:{0:!0}},blendFunc:{2:{0:!0,1:!0}},blendFuncSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},blendEquation:{1:{0:!0}},blendEquationSeparate:{2:{0:!0,1:!0}},stencilFunc:{3:{0:!0}},stencilFuncSeparate:{4:{0:!0,1:!0}},stencilMaskSeparate:{2:{0:!0}},stencilOp:{3:{0:!0,1:!0,2:!0}},stencilOpSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},cullFace:{1:{0:!0}},frontFace:{1:{0:!0}},drawArraysInstancedANGLE:{4:{0:!0}},drawElementsInstancedANGLE:{5:{0:!0,2:!0}},blendEquationEXT:{1:{0:!0}},bufferData:{3:{0:!0,2:!0},4:{0:!0,2:!0},5:{0:!0,2:!0}},bufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},copyBufferSubData:{5:{0:!0,1:!0}},getBufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},blitFramebuffer:{10:{8:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]},9:!0}},framebufferTextureLayer:{5:{0:!0,1:!0}},invalidateFramebuffer:{2:{0:!0}},invalidateSubFramebuffer:{6:{0:!0}},readBuffer:{1:{0:!0}},getInternalformatParameter:{3:{0:!0,1:!0,2:!0}},renderbufferStorageMultisample:{5:{0:!0,2:!0}},texStorage2D:{5:{0:!0,2:!0}},texStorage3D:{6:{0:!0,2:!0}},texImage2D:{9:{0:!0,2:!0,6:!0,7:!0},6:{0:!0,2:!0,3:!0,4:!0},10:{0:!0,2:!0,6:!0,7:!0}},texImage3D:{10:{0:!0,2:!0,7:!0,8:!0},11:{0:!0,2:!0,7:!0,8:!0}},texSubImage2D:{9:{0:!0,6:!0,7:!0},7:{0:!0,4:!0,5:!0},10:{0:!0,6:!0,7:!0}},texSubImage3D:{11:{0:!0,8:!0,9:!0},12:{0:!0,8:!0,9:!0}},copyTexSubImage3D:{9:{0:!0}},compressedTexImage2D:{7:{0:!0,2:!0},8:{0:!0,2:!0},9:{0:!0,2:!0}},compressedTexImage3D:{8:{0:!0,2:!0},9:{0:!0,2:!0},10:{0:!0,2:!0}},compressedTexSubImage2D:{8:{0:!0,6:!0},9:{0:!0,6:!0},10:{0:!0,6:!0}},compressedTexSubImage3D:{10:{0:!0,8:!0},11:{0:!0,8:!0},12:{0:!0,8:!0}},vertexAttribIPointer:{5:{2:!0}},drawArraysInstanced:{4:{0:!0}},drawElementsInstanced:{5:{0:!0,2:!0}},drawRangeElements:{6:{0:!0,4:!0}},readPixels:{7:{4:!0,5:!0},8:{4:!0,5:!0}},clearBufferfv:{3:{0:!0},4:{0:!0}},clearBufferiv:{3:{0:!0},4:{0:!0}},clearBufferuiv:{3:{0:!0},4:{0:!0}},clearBufferfi:{4:{0:!0}},beginQuery:{2:{0:!0}},endQuery:{1:{0:!0}},getQuery:{2:{0:!0,1:!0}},getQueryParameter:{2:{1:!0}},samplerParameteri:{3:{1:!0,2:!0}},samplerParameterf:{3:{1:!0}},getSamplerParameter:{2:{1:!0}},fenceSync:{2:{0:!0,1:{enumBitwiseOr:[]}}},clientWaitSync:{3:{1:{enumBitwiseOr:["SYNC_FLUSH_COMMANDS_BIT"]}}},waitSync:{3:{1:{enumBitwiseOr:[]}}},getSyncParameter:{2:{1:!0}},bindTransformFeedback:{2:{0:!0}},beginTransformFeedback:{1:{0:!0}},transformFeedbackVaryings:{3:{2:!0}},bindBufferBase:{3:{0:!0}},bindBufferRange:{5:{0:!0}},getIndexedParameter:{2:{0:!0}},getActiveUniforms:{3:{2:!0}},getActiveUniformBlockParameter:{3:{2:!0}}},i=null,r=null;function s(t){if(null==i)for(var e in i={},r={},t)"number"==typeof t[e]&&(i[t[e]]=e,r[e]=t[e])}function n(){if(null==i)throw"WebGLDebugUtils.init(ctx) not called"}function o(t){n();var e=i[t];return void 0!==e?"gl."+e:"/*UNKNOWN WebGL ENUM*/ 0x"+t.toString(16)}function a(t,i,s,n){var a;if(void 0!==(a=e[t])&&(void 0!==(a=a[i])&&a[s])){if("object"==typeof a[s]&&void 0!==a[s].enumBitwiseOr){for(var h=a[s].enumBitwiseOr,l=0,u=[],c=0;c<h.length;++c){var d=r[h[c]];0!==(n&d)&&(l|=d,u.push(o(d)))}return l===n?u.join(" | "):o(n)}return o(n)}return null===n?"null":void 0===n?"undefined":n.toString()}function h(t,e,i){t.__defineGetter__(i,function(){return e[i]}),t.__defineSetter__(i,function(t){e[i]=t})}function l(t){var e=!!t.createTransformFeedback;e&&t.bindVertexArray(null);var i=t.getParameter(t.MAX_VERTEX_ATTRIBS),r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r);for(var s=0;s<i;++s)t.disableVertexAttribArray(s),t.vertexAttribPointer(s,4,t.FLOAT,!1,0,0),t.vertexAttrib1f(s,0),e&&t.vertexAttribDivisor(s,0);t.deleteBuffer(r);var n=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(s=0;s<n;++s)t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_CUBE_MAP,null),t.bindTexture(t.TEXTURE_2D,null),e&&(t.bindTexture(t.TEXTURE_2D_ARRAY,null),t.bindTexture(t.TEXTURE_3D,null),t.bindSampler(s,null));if(t.activeTexture(t.TEXTURE0),t.useProgram(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindRenderbuffer(t.RENDERBUFFER,null),t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.DITHER),t.disable(t.SCISSOR_TEST),t.blendColor(0,0,0,0),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.clearColor(0,0,0,0),t.clearDepth(1),t.clearStencil(-1),t.colorMask(!0,!0,!0,!0),t.cullFace(t.BACK),t.depthFunc(t.LESS),t.depthMask(!0),t.depthRange(0,1),t.frontFace(t.CCW),t.hint(t.GENERATE_MIPMAP_HINT,t.DONT_CARE),t.lineWidth(1),t.pixelStorei(t.PACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.UNPACK_COLORSPACE_CONVERSION_WEBGL&&t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.BROWSER_DEFAULT_WEBGL),t.polygonOffset(0,0),t.sampleCoverage(1,!1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilMask(4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),e){t.drawBuffers([t.BACK]),t.readBuffer(t.BACK),t.bindBuffer(t.COPY_READ_BUFFER,null),t.bindBuffer(t.COPY_WRITE_BUFFER,null),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.bindBuffer(t.PIXEL_UNPACK_BUFFER,null);var o=t.getParameter(t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);for(s=0;s<o;++s)t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,s,null);var a=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);for(s=0;s<a;++s)t.bindBufferBase(t.UNIFORM_BUFFER,s,null);t.disable(t.RASTERIZER_DISCARD),t.pixelStorei(t.UNPACK_IMAGE_HEIGHT,0),t.pixelStorei(t.UNPACK_SKIP_IMAGES,0),t.pixelStorei(t.UNPACK_ROW_LENGTH,0),t.pixelStorei(t.UNPACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_SKIP_PIXELS,0),t.pixelStorei(t.PACK_ROW_LENGTH,0),t.pixelStorei(t.PACK_SKIP_ROWS,0),t.pixelStorei(t.PACK_SKIP_PIXELS,0),t.hint(t.FRAGMENT_SHADER_DERIVATIVE_HINT,t.DONT_CARE)}for(;t.getError(););}return{init:s,mightBeEnum:function(t){return n(),void 0!==i[t]},glEnumToString:o,glFunctionArgToString:a,glFunctionArgsToString:function(t,e){for(var i="",r=e.length,s=0;s<r;++s)i+=(0==s?"":", ")+a(t,r,s,e[s]);return i},makeDebugContext:function e(i,r,n,l){l=l||i,s(i),r=r||function(e,i,r){for(var s="",n=r.length,h=0;h<n;++h)s+=(0==h?"":", ")+a(i,n,h,r[h]);t("WebGL error "+o(e)+" in "+i+"("+s+")")};var u={};function c(t,e){return function(){n&&n(e,arguments);var i=t[e].apply(t,arguments),s=l.getError();return 0!=s&&(u[s]=!0,r(s,e,arguments)),i}}var d={};for(var _ in i)if("function"==typeof i[_])if("getExtension"!=_)d[_]=c(i,_);else{var p=c(i,_);d[_]=function(){var t=p.apply(i,arguments);return t?e(t,r,n,l):null}}else h(d,i,_);return d.getError=function(){for(var t in u)if(u.hasOwnProperty(t)&&u[t])return u[t]=!1,t;return i.NO_ERROR},d},makeLostContextSimulatingCanvas:function(t){var e,i,r,s=[],n=[],o={},a=1,u=!1,c=[],d=0,_=0,p=!1,f=0,m={};function g(t){return"function"==typeof t?t:function(e){t.handleEvent(e)}}function y(){++_,u||d==_&&t.loseContext()}function x(t,e){var i=t[e];return function(){if(y(),!u)return i.apply(t,arguments)}}function w(t){return{statusMessage:t,preventDefault:function(){p=!0}}}return t.getContext=(r=t.getContext,function(){var s=r.apply(t,arguments);if(s instanceof WebGLRenderingContext||window.WebGL2RenderingContext&&s instanceof WebGL2RenderingContext){if(s!=e){if(e)throw"got different context";i=window.WebGL2RenderingContext&&s instanceof WebGL2RenderingContext,o=function(t){for(var r in t)"function"==typeof t[r]?o[r]=x(t,r):h(o,t,r);o.getError=function(){if(y(),!u)for(;t=e.getError();)m[t]=!0;for(var t in m)if(m[t])return delete m[t],t;return o.NO_ERROR};var s=["createBuffer","createFramebuffer","createProgram","createRenderbuffer","createShader","createTexture"];i&&s.push("createQuery","createSampler","fenceSync","createTransformFeedback","createVertexArray");for(var n=0;n<s.length;++n){var l=s[n];o[l]=function(e){return function(){if(y(),u)return null;var i=e.apply(t,arguments);return i.__webglDebugContextLostId__=a,c.push(i),i}}(t[l])}var d=["getActiveAttrib","getActiveUniform","getBufferParameter","getContextAttributes","getAttachedShaders","getFramebufferAttachmentParameter","getParameter","getProgramParameter","getProgramInfoLog","getRenderbufferParameter","getShaderParameter","getShaderInfoLog","getShaderSource","getTexParameter","getUniform","getUniformLocation","getVertexAttrib"];for(i&&d.push("getInternalformatParameter","getQuery","getQueryParameter","getSamplerParameter","getSyncParameter","getTransformFeedbackVarying","getIndexedParameter","getUniformIndices","getActiveUniforms","getActiveUniformBlockParameter","getActiveUniformBlockName"),n=0;n<d.length;++n)l=d[n],o[l]=function(e){return function(){return y(),u?null:e.apply(t,arguments)}}(o[l]);var _=["isBuffer","isEnabled","isFramebuffer","isProgram","isRenderbuffer","isShader","isTexture"];for(i&&_.push("isQuery","isSampler","isSync","isTransformFeedback","isVertexArray"),n=0;n<_.length;++n)l=_[n],o[l]=function(e){return function(){return y(),!u&&e.apply(t,arguments)}}(o[l]);return o.checkFramebufferStatus=function(e){return function(){return y(),u?o.FRAMEBUFFER_UNSUPPORTED:e.apply(t,arguments)}}(o.checkFramebufferStatus),o.getAttribLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getAttribLocation),o.getVertexAttribOffset=function(e){return function(){return y(),u?0:e.apply(t,arguments)}}(o.getVertexAttribOffset),o.isContextLost=function(){return u},i&&(o.getFragDataLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getFragDataLocation),o.clientWaitSync=function(e){return function(){return y(),u?o.WAIT_FAILED:e.apply(t,arguments)}}(o.clientWaitSync),o.getUniformBlockIndex=function(e){return function(){return y(),u?o.INVALID_INDEX:e.apply(t,arguments)}}(o.getUniformBlockIndex)),o}(e=s)}return o}return s}),function(t){var e=t.addEventListener;t.addEventListener=function(i,r,o){switch(i){case"webglcontextlost":!function(t){s.push(g(t))}(r);break;case"webglcontextrestored":!function(t){n.push(g(t))}(r);break;default:e.apply(t,arguments)}}}(t),t.loseContext=function(){if(!u){for(u=!0,d=0,++a;e.getError(););!function(){for(var t=Object.keys(m),e=0;e<t.length;++e)delete m[t[e]]}(),m[e.CONTEXT_LOST_WEBGL]=!0;var i=w("context lost"),r=s.slice();setTimeout(function(){for(var e=0;e<r.length;++e)r[e](i);f>=0&&setTimeout(function(){t.restoreContext()},f)},0)}},t.restoreContext=function(){u&&n.length&&setTimeout(function(){if(!p)throw"can not restore. webglcontestlost listener did not call event.preventDefault";!function(){for(var t=0;t<c.length;++t){var r=c[t];r instanceof WebGLBuffer?e.deleteBuffer(r):r instanceof WebGLFramebuffer?e.deleteFramebuffer(r):r instanceof WebGLProgram?e.deleteProgram(r):r instanceof WebGLRenderbuffer?e.deleteRenderbuffer(r):r instanceof WebGLShader?e.deleteShader(r):r instanceof WebGLTexture?e.deleteTexture(r):i&&(r instanceof WebGLQuery?e.deleteQuery(r):r instanceof WebGLSampler?e.deleteSampler(r):r instanceof WebGLSync?e.deleteSync(r):r instanceof WebGLTransformFeedback?e.deleteTransformFeedback(r):r instanceof WebGLVertexArrayObject&&e.deleteVertexArray(r))}}(),l(e),u=!1,_=0,p=!1;for(var t=n.slice(),r=w("context restored"),s=0;s<t.length;++s)t[s](r)},0)},t.loseContextInNCalls=function(t){if(u)throw"You can not ask a lost contet to be lost";d=_+t},t.getNumCalls=function(){return _},t.setRestoreTimeout=function(t){f=t},t},resetToInitialState:l}}();class Ce{_attributes=[];_indexBuffer=null;_drawMode;_runtime=null;_version=0;constructor(t=et.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=st.Float,r=!1,s=0,n=0){const{location:o,size:a}=e;return this._attributes.push({buffer:t,location:o,size:a,type:i,normalized:r,stride:s,start:n}),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}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}var Me;!function(t){t[t.WebGl2=0]="WebGl2",t[t.WebGpu=1]="WebGpu"}(Me||(Me={}));class Pe{backendType=Me.WebGl2;_runtime=null;connect(t){if(null===this._runtime){if(t.backendType!==Me.WebGl2)throw new Error(`${this.constructor.name} requires a WebGL2 runtime, but received backendType ${String(t.backendType)}.`);this._runtime=t,this.onConnect(t)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}class Be{attributes=new Map;uniforms=new Map;_vertexSource;_fragmentSource;_runtime=null;constructor(t,e){this._vertexSource=t,this._fragmentSource=e}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(t){return this._runtime=t,t.initialize(this),this}disconnect(){return this._runtime=null,this.attributes.clear(),this.uniforms.clear(),this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}sync(){return this._runtime?.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._runtime?.destroy(this),this._runtime=null,this.attributes.clear(),this.uniforms.clear()}}const Ee={[st.Float]:1,[st.FloatVec2]:2,[st.FloatVec3]:3,[st.FloatVec4]:4,[st.Int]:1,[st.IntVec2]:2,[st.IntVec3]:3,[st.IntVec4]:4,[st.Bool]:1,[st.BoolVec2]:2,[st.BoolVec3]:3,[st.BoolVec4]:4,[st.FloatMat2]:4,[st.FloatMat3]:9,[st.FloatMat4]:16,[st.Sampler2D]:1},Re={[st.Float]:Float32Array,[st.FloatVec2]:Float32Array,[st.FloatVec3]:Float32Array,[st.FloatVec4]:Float32Array,[st.Int]:Int32Array,[st.IntVec2]:Int32Array,[st.IntVec3]:Int32Array,[st.IntVec4]:Int32Array,[st.Bool]:Uint8Array,[st.BoolVec2]:Uint8Array,[st.BoolVec3]:Uint8Array,[st.BoolVec4]:Uint8Array,[st.FloatMat2]:Float32Array,[st.FloatMat3]:Float32Array,[st.FloatMat4]:Float32Array,[st.Sampler2D]:Uint8Array},ke={[st.Float]:"FLOAT",[st.FloatVec2]:"FLOAT_VEC2",[st.FloatVec3]:"FLOAT_VEC3",[st.FloatVec4]:"FLOAT_VEC4",[st.Int]:"INT",[st.IntVec2]:"INT_VEC2",[st.IntVec3]:"INT_VEC3",[st.IntVec4]:"INT_VEC4",[st.Bool]:"BOOL",[st.BoolVec2]:"BOOL_VEC2",[st.BoolVec3]:"BOOL_VEC3",[st.BoolVec4]:"BOOL_VEC4",[st.FloatMat2]:"FLOAT_MAT2",[st.FloatMat3]:"FLOAT_MAT3",[st.FloatMat4]:"FLOAT_MAT4",[st.Sampler2D]:"SAMPLER_2D"};class Ae{index;name;type;size;location=-1;constructor(t,e,i){this.index=t,this.name=e,this.type=i,this.size=Ee[i]}destroy(){}}class Le{index;type;size;name;_value;_dirty=!0;constructor(t,e,i,r,s){this.name=r.replace(/\[.*?]/,""),this.index=t,this.type=e,this.size=i,this._value=s}get propName(){return this.name.substr(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 Fe{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,r=t.getActiveUniformBlockParameter(e,this.index,t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),s=t.getActiveUniforms(e,r,t.UNIFORM_OFFSET),n=r.length;for(let o=0;o<n;o++){const{type:n,size:a,name:h}=t.getActiveUniform(e,r[o]),l=new Re[n](i,s[o],Ee[n]*a),u=new Le(r[o],n,a,h,l);this._uniforms.set(u.propName,u)}}}const De={[st.Float]:(t,e,i)=>{t.uniform1f(e,i[0])},[st.FloatVec2]:(t,e,i)=>{t.uniform2fv(e,i)},[st.FloatVec3]:(t,e,i)=>{t.uniform3fv(e,i)},[st.FloatVec4]:(t,e,i)=>{t.uniform4fv(e,i)},[st.Int]:(t,e,i)=>{t.uniform1i(e,i[0])},[st.IntVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[st.IntVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[st.IntVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[st.Bool]:(t,e,i)=>{t.uniform1i(e,i[0])},[st.BoolVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[st.BoolVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[st.BoolVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[st.FloatMat2]:(t,e,i)=>{t.uniformMatrix2fv(e,!1,i)},[st.FloatMat3]:(t,e,i)=>{t.uniformMatrix3fv(e,!1,i)},[st.FloatMat4]:(t,e,i)=>{t.uniformMatrix4fv(e,!1,i)},[st.Sampler2D]:(t,e,i)=>{t.uniform1i(e,i[0])}};function Ne(t){let e=null,i=null,r=null;const s=[],n=[];function o(o){e||(i=Ie(t,t.VERTEX_SHADER,o.vertexSource),r=Ie(t,t.FRAGMENT_SHADER,o.fragmentSource),e=function(t,e,i){const r=t.createProgram();if(!r)throw new Error("Could not create shader program.");if(t.attachShader(r,e),t.attachShader(r,i),t.linkProgram(r),!t.getProgramParameter(r,t.LINK_STATUS)){const s=t.getProgramInfoLog(r);throw t.detachShader(r,e),t.detachShader(r,i),t.deleteProgram(r),new Error(`Shader program linking failed: ${s}`)}return r}(t,i,r),function(t,e,i){const r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let s=0;s<r;s++){const r=t.getActiveAttrib(e,s);if(!r)continue;const n=new Ae(s,r.name,r.type);n.location=t.getAttribLocation(e,r.name),i.attributes.set(r.name,n)}}(t,e,o),function(t,e,i,r){const s=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),n=new Uint8Array(s).map((t,e)=>e),o=t.getActiveUniforms(e,n,t.UNIFORM_BLOCK_INDEX),a=n.filter(t=>-1===o[t]);for(const s of a){const n=t.getActiveUniform(e,s);if(!n)continue;const o=new Re[n.type](Ee[n.type]*n.size),a=new Le(s,n.type,n.size,n.name,o),h=t.getUniformLocation(e,a.name),l=De[n.type];i.uniforms.set(a.name,a),h&&r.push({location:h,uploadFn:l,uniform:a})}}(t,e,o,s),function(t,e,i){const r=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let s=0;s<r;s++){const r=new Fe(t,e,s);i.push(r)}}(t,e,n))}function a(){for(const e of s)e.uniform.dirty&&(e.uploadFn(t,e.location,e.uniform.value),e.uniform.markClean());for(const t of n)t.upload()}return{initialize:o,bind:i=>{o(i),t.useProgram(e),a()},unbind:()=>{t.useProgram(null)},sync:()=>{t.useProgram(e),a()},destroy:o=>{t.deleteShader(i),t.deleteShader(r),t.deleteProgram(e);for(const t of n)t.destroy();i=null,r=null,e=null,s.length=0,n.length=0,o.disconnect()}}}function Ie(t,e,i){const r=t.createShader(e);if(!r)throw new Error("Could not create shader.");if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(r);throw t.deleteShader(r),new Error(`Shader compilation failed: ${e}`)}return r}class Ue{_type;_usage;_runtime=null;_data=P;_version=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){return this._runtime=t,this._data.byteLength>0&&t.upload(this,0),this}disconnect(){return this._runtime=null,this}upload(t,e=0){this._data=t,this._version++,this._runtime?.upload(this,e)}bind(){this._runtime?.bind(this)}destroy(){this._runtime?.destroy(this),this._runtime=null}}const Ve=(t={})=>{const{canvas:e,fillStyle:i,width:r,height:s}=t,n=e??document.createElement("canvas"),o=n.getContext("2d");return n.width=r??10,n.height=s??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,n.width,n.height),n},Oe=new Map;class Ge extends Pe{attributeCount;batchSize;indexData;vertexData;float32View;uint32View;shader;batchIndex=0;currentTexture=null;currentBlendMode=null;currentView=null;currentViewId=-1;vao=null;indexBuffer=null;vertexBuffer=null;connection=null;constructor(t,e,i,r){super(),this.batchSize=t,this.attributeCount=e,this.vertexData=new ArrayBuffer(t*e*4),this.float32View=new Float32Array(this.vertexData),this.uint32View=new Uint32Array(this.vertexData),this.indexData=(t=>{const e=new Uint16Array(6*t),i=e.length;for(let t=0,r=0;t<i;t+=6,r+=4)e[t]=r,e[t+1]=r+1,e[t+2]=r+2,e[t+3]=r,e[t+4]=r+2,e[t+5]=r+3;return e})(t),this.shader=new Be(i,r)}flush(){const t=this.getRuntimeOrNull(),e=this.vertexBuffer,i=this.vao;if(0===this.batchIndex||null===t||null===e||null===i)return;const r=t.view;this.currentView===r&&this.currentViewId===r.updateId||(this.currentView=r,this.currentViewId=r.updateId,this.updateView(r)),this.shader.sync(),t.bindVertexArrayObject(i),e.upload(this.float32View.subarray(0,this.batchIndex*this.attributeCount)),i.draw(6*this.batchIndex,0),t.stats.batches++,t.stats.drawCalls++,this.batchIndex=0}destroy(){this.disconnect(),this.shader.destroy(),this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.connection=null}onConnect(t){const e=t.context;this.shader.connect(Ne(e)),this.connection=this.createConnection(e),this.indexBuffer=new Ue(it.ElementArrayBuffer,this.indexData,rt.StaticDraw).connect(this.createBufferRuntime(this.connection)),this.vertexBuffer=new Ue(it.ArrayBuffer,this.vertexData,rt.DynamicDraw).connect(this.createBufferRuntime(this.connection)),this.vao=this.createVao(e,this.indexBuffer,this.vertexBuffer).connect(this.createVaoRuntime(this.connection))}onDisconnect(){this.flush(),this.shader.disconnect(),this.indexBuffer?.destroy(),this.indexBuffer=null,this.vertexBuffer?.destroy(),this.vertexBuffer=null,this.vao?.destroy(),this.vao=null,this.connection=null,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.batchIndex=0}createConnection(t){const e=t.createVertexArray();if(null===e)throw new Error("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("Could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,r)=>{const s=t.gl,n=i.data,o=t.buffers.get(i);s.bindBuffer(i.type,e),o&&o.dataByteLength>=n.byteLength?(s.bufferSubData(i.type,r,n),o.dataByteLength=n.byteLength):(s.bufferData(i.type,n,i.usage),t.buffers.set(i,{handle:e,dataByteLength:n.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}createVaoRuntime(t){let e=-1;return{bind:i=>{const r=t.gl;if(r.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),r.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),r.enableVertexAttribArray(e.location);i.indexBuffer&&i.indexBuffer.bind(),e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,r,s)=>{const n=t.gl;e.indexBuffer?n.drawElements(s,i,n.UNSIGNED_SHORT,r):n.drawArrays(s,r,i)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}class ze extends Ge{constructor(t){super(t,16,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,blendMode:i,tint:r,vertices:s,texCoords:n}=t,o=this.batchIndex>=this.batchSize,a=e!==this.currentTexture,h=i!==this.currentBlendMode,l=o||a||h,u=l?0:this.batchIndex*this.attributeCount,c=this.float32View,d=this.uint32View,_=this.getRuntime();return l&&(this.flush(),a&&(this.currentTexture=e),h&&(this.currentBlendMode=i,_.setBlendMode(i))),a&&e&&_.bindTexture(e),c[u+0]=s[0],c[u+1]=s[1],c[u+4]=s[2],c[u+5]=s[3],c[u+8]=s[4],c[u+9]=s[5],c[u+12]=s[6],c[u+13]=s[7],d[u+2]=n[0],d[u+6]=n[1],d[u+10]=n[2],d[u+14]=n[3],d[u+3]=d[u+7]=d[u+11]=d[u+15]=r.toRgba(),this.batchIndex++,this}createVao(t,e,i){return(new Ce).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,12)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class We extends Ge{constructor(t){super(t,36,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec2 a_translation;\r\nlayout(location = 3) in vec2 a_scale;\r\nlayout(location = 4) in float a_rotation;\r\nlayout(location = 5) in vec4 a_color;\n\nuniform mat3 u_projection;\nuniform mat3 u_translation;\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\n vec2 rotation = vec2(sin(radians(a_rotation)), cos(radians(a_rotation)));\n vec3 position = vec3(\n (a_position.x * (a_scale.x * rotation.y)) + (a_position.y * (a_scale.y * rotation.x)) + a_translation.x,\n (a_position.x * (a_scale.x * -rotation.x)) + (a_position.y * (a_scale.y * rotation.y)) + a_translation.y,\n 1.0\n );\n\n gl_Position = vec4((u_projection * u_translation * position).xy, 0.0, 1.0);\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,vertices:i,texCoords:r,particles:s,blendMode:n}=t,o=e!==this.currentTexture,a=n!==this.currentBlendMode,h=this.float32View,l=this.uint32View,u=this.getRuntime();this.flush(),(o||a)&&(o&&(this.currentTexture=e),a&&(this.currentBlendMode=n,u.setBlendMode(n))),o&&u.bindTexture(e),this.shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));for(const t of s){this.batchIndex>=this.batchSize&&this.flush();const{position:e,scale:s,rotation:n,tint:o}=t,a=this.batchIndex*this.attributeCount;h[a+0]=h[a+27]=i[0],h[a+1]=h[a+10]=i[1],h[a+9]=h[a+18]=i[2],h[a+19]=h[a+28]=i[3],l[a+2]=r[0],l[a+11]=r[1],l[a+20]=r[2],l[a+29]=r[3],h[a+3]=h[a+12]=h[a+21]=h[a+30]=e.x,h[a+4]=h[a+13]=h[a+22]=h[a+31]=e.y,h[a+5]=h[a+14]=h[a+23]=h[a+32]=s.x,h[a+6]=h[a+15]=h[a+24]=h[a+33]=s.y,h[a+7]=h[a+16]=h[a+25]=h[a+34]=n,l[a+8]=l[a+17]=l[a+26]=l[a+35]=o.toRgba(),this.batchIndex++}return this}createVao(t,e,i){return(new Ce).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_translation"),t.FLOAT,!1,this.attributeCount,12).addAttribute(i,this.shader.getAttribute("a_scale"),t.FLOAT,!1,this.attributeCount,20).addAttribute(i,this.shader.getAttribute("a_rotation"),t.FLOAT,!1,this.attributeCount,28).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,32)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class qe extends Pe{_vertexCapacity;_indexCapacity;_vertexData;_indexData;_float32View;_uint32View;_shader=new Be("#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\nuniform mat3 u_translation;\r\n\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * u_translation * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nin vec4 v_color;\r\n\r\nvoid main(void) {\r\n fragColor = v_color;\r\n}\r\n");_connection=null;_currentBlendMode=null;_currentView=null;_viewId=-1;constructor(t){super(),this._vertexCapacity=Math.max(4,t),this._indexCapacity=Math.max(6,3*this._vertexCapacity),this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._indexData=new Uint16Array(this._indexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}render(t){const e=this._connection;if(!e)throw new Error("Renderer not connected");const i=this.getRuntime(),{geometry:r,drawMode:s,color:n,blendMode:o}=t,a=r.vertices,h=r.indices,l=a.length/2,u=h.length>0?h.length:l;if(0===l||0===u)return;this._ensureVertexCapacity(l),this._ensureIndexCapacity(u),o!==this._currentBlendMode&&(this._currentBlendMode=o,i.setBlendMode(o));const c=i.view;this._currentView===c&&this._viewId===c.updateId||(this._currentView=c,this._viewId=c.updateId,this._shader.getUniform("u_projection").setValue(c.getTransform().toArray(!1))),this._shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));const d=n.toRgba();for(let t=0;t<l;t++){const e=2*t,i=3*t;this._float32View[i]=a[e],this._float32View[i+1]=a[e+1],this._uint32View[i+2]=d}if(h.length>0)this._indexData.set(h,0);else for(let t=0;t<l;t++)this._indexData[t]=t;this._shader.sync(),i.bindVertexArrayObject(e.vao),e.vertexBuffer.upload(this._float32View.subarray(0,3*l)),e.indexBuffer.upload(this._indexData.subarray(0,u)),e.vao.draw(u,0,s),i.stats.batches++,i.stats.drawCalls++}flush(){}destroy(){this.disconnect(),this._shader.destroy(),this._currentBlendMode=null,this._currentView=null}onConnect(t){const e=t.context,i=e.createVertexArray();if(this._shader.connect(Ne(e)),null===i)throw new Error("Could not create vertex array object.");const r=new Map,s=new Ue(it.ElementArrayBuffer,this._indexData,rt.DynamicDraw).connect(this._createBufferRuntime(e,r)),n=new Ue(it.ArrayBuffer,this._vertexData,rt.DynamicDraw).connect(this._createBufferRuntime(e,r)),o=(new Ce).addIndex(s).addAttribute(n,this._shader.getAttribute("a_position"),e.FLOAT,!1,12,0).addAttribute(n,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,12,8).connect(this._createVaoRuntime(e,i));this._connection={gl:e,buffers:r,vaoHandle:i,vao:o,indexBuffer:s,vertexBuffer:n}}onDisconnect(){const t=this._connection;t&&(this._shader.disconnect(),t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1)}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(12*this._vertexCapacity),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)}}_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:(r,s)=>{const n=e.get(r),o=r.data;t.bindBuffer(r.type,i),n&&n.dataByteLength>=o.byteLength?(t.bufferSubData(r.type,s,o),n.dataByteLength=o.byteLength):(t.bufferData(r.type,o,r.usage),e.set(r,{handle:i,dataByteLength:o.byteLength}))},destroy:r=>{t.deleteBuffer(i),e.delete(r),r.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:r=>{if(t.bindVertexArray(e),i!==r.version){let e=null;for(const i of r.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);r.indexBuffer&&r.indexBuffer.bind(),i=r.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,r,s)=>{e.indexBuffer?t.drawElements(s,i,t.UNSIGNED_SHORT,r):t.drawArrays(s,r,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}var He;!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"}(He||(He={}));class Ye extends xe{_texture=null;_textureFrame=new oe;_vertices=new Float32Array(8);_texCoords=new Uint32Array(4);constructor(t){super(),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 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(){const{left:t,top:e,right:i,bottom:r}=this.getLocalBounds(),{a:s,b:n,x:o,c:a,d:h,y:l}=this.getGlobalTransform();return this._vertices[0]=t*s+e*n+o,this._vertices[1]=t*a+e*h+l,this._vertices[2]=i*s+e*n+o,this._vertices[3]=i*a+e*h+l,this._vertices[4]=i*s+r*n+o,this._vertices[5]=i*a+r*h+l,this._vertices[6]=t*s+r*n+o,this._vertices[7]=t*a+r*h+l,this._vertices}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(He.TextureCoords)){const{width:t,height:e}=this._texture,{left:i,top:r,right:s,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(r/e*65535&65535)<<16,h=s/t*65535&65535,l=(n/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,this.updateTexture(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,e=!0){const i=this.width,r=this.height;return this._textureFrame.copy(t),this.flags.push(He.TextureCoords),this.localBounds.set(0,0,t.width,t.height),e?(this.width=t.width,this.height=t.height):(this.width=i,this.height=r),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(oe.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){const[t,e,i,r,s,n,o,a]=this.vertices;return[new _e(i-t,r-e).rperp().normalize(),new _e(s-i,n-r).rperp().normalize(),new _e(o-s,a-n).rperp().normalize(),new _e(t-o,e-a).rperp().normalize()]}project(t,e=new _t){const[i,r,s,n,o,a,h,l]=this.vertices,u=t.dot(i,r),c=t.dot(s,n),d=t.dot(o,a),_=t.dot(h,l);return e.set(Math.min(u,c,d,_),Math.max(u,c,d,_))}contains(t,e){if(this.rotation%90==0)return this.getBounds().contains(t,e);const[i,r,s,n,o,a]=this.vertices,h=_e.temp,l=h.set(s-i,n-r),u=l.dot(t-i,e-r),c=l.lengthSq,d=h.set(o-s,a-n),_=d.dot(t-s,e-n),p=d.lengthSq;return u>0&&u<=c&&_>0&&_<=p}destroy(){super.destroy(),this._textureFrame.destroy(),this._texture=null}}ye.setInternalSpriteFactory(()=>new Ye(null));class Xe{_totalLifetime=s.oneSecond.clone();_elapsedLifetime=s.zero.clone();_position=_e.zero.clone();_velocity=_e.zero.clone();_scale=_e.one.clone();_rotation=0;_rotationSpeed=0;_textureIndex=0;_tint=Q.white.clone();get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get tint(){return this._tint}set tint(t){this._tint.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=V(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get remainingLifetime(){return s.temp.set(this._totalLifetime.milliseconds-this._elapsedLifetime.milliseconds)}get elapsedRatio(){return this._elapsedLifetime.milliseconds/this._totalLifetime.milliseconds}get remainingRatio(){return this.remainingLifetime.milliseconds/this._totalLifetime.milliseconds}get expired(){return this._elapsedLifetime.greaterThan(this._totalLifetime)}applyOptions(t){const{totalLifetime:e,elapsedLifetime:i,position:r,velocity:s,scale:n,tint:o,rotation:a,rotationSpeed:h,textureIndex:l}=t;return this._totalLifetime.copy(e),this._elapsedLifetime.copy(i),this._position.copy(r),this._velocity.copy(s),this._scale.copy(n),this._tint.copy(o),this._rotation=a,this._rotationSpeed=h,this._textureIndex=l,this}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class je extends xe{_emitters=[];_affectors=[];_particles=[];_graveyard=[];_texture;_textureFrame=new oe;_vertices=new Float32Array(4);_texCoords=new Uint32Array(4);_updateTexCoords=!0;_updateVertices=!0;constructor(t){super(),this._texture=t,this.resetTextureFrame()}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get vertices(){if(this._updateVertices){const{x:t,y:e,width:i,height:r}=this._textureFrame,s=i/2,n=r/2;this._vertices[0]=t-s,this._vertices[1]=e-n,this._vertices[2]=i-s,this._vertices[3]=r-n,this._updateVertices=!1}return this._vertices}get texCoords(){if(this._updateTexCoords){const{width:t,height:e}=this._texture,{left:i,top:r,right:s,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(r/e*65535&65535)<<16,h=s/t*65535&65535,l=(n/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),this._updateTexCoords=!1}return this._texCoords}get emitters(){return this._emitters}get affectors(){return this._affectors}get particles(){return this._particles}get graveyard(){return this._graveyard}setTexture(t){return this._texture!==t&&(this._texture=t,this.resetTextureFrame()),this}setTextureFrame(t){return this._textureFrame.copy(t),this._updateTexCoords=!0,this._updateVertices=!0,this.localBounds.set(0,0,t.width,t.height),this}resetTextureFrame(){return this.setTextureFrame(oe.temp.set(0,0,this._texture.width,this._texture.height))}addEmitter(t){return this._emitters.push(t),this}clearEmitters(){for(const t of this._emitters)t.destroy();return this._emitters.length=0,this}addAffector(t){return this._affectors.push(t),this}clearAffectors(){for(const t of this._affectors)t.destroy();return this._affectors.length=0,this}requestParticle(){return this._graveyard.pop()||new Xe}emitParticle(t){return this._particles.push(t),this}updateParticle(t,e){const i=e.seconds;return t.elapsedLifetime.addTime(e),t.position.add(i*t.velocity.x,i*t.velocity.y),t.rotation+=i*t.rotationSpeed,this}clearParticles(){for(const t of this._particles)t.destroy();for(const t of this._graveyard)t.destroy();return this._particles.length=0,this._graveyard.length=0,this}update(t){const e=this._emitters,i=this._affectors,r=this._particles,s=this._graveyard,n=r.length;for(const i of e)i.apply(this,t);let o=0;for(let e=n-1;e>=0;e--)if(this.updateParticle(r[e],t),r[e].expired)s.push(r[e]),o++;else{o>0&&(r.splice(e+1,o),o=0);for(const s of i)s.apply(r[e],t)}return o>0&&r.splice(0,o),this}destroy(){super.destroy(),this.clearEmitters(),this.clearAffectors(),this.clearParticles(),this._textureFrame.destroy()}}class $e{static _black=null;static _white=null;static defaultSamplerOptions={scaleMode:J.Linear,wrapMode:tt.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1};static empty=new $e(null);static get black(){return null===$e._black&&($e._black=new $e(Ve({fillStyle:"#000"}))),$e._black}static get white(){return null===$e._white&&($e._white=new $e(Ve({fillStyle:"#fff"}))),$e._white}_version=0;_source=null;_size=new e(0,0);_destroyListeners=new Set;_scaleMode;_wrapMode;_premultiplyAlpha=!1;_generateMipMap=!1;_flipY=!1;constructor(t=null,e){const{scaleMode:i,wrapMode:r,premultiplyAlpha:s,generateMipMap:n,flipY:o}={...$e.defaultSamplerOptions,...e};this._scaleMode=i,this._wrapMode=r,this._premultiplyAlpha=s,this._generateMipMap=n,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 H(this.width)&&H(this.height)}get version(){return 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}=k(this._source);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 Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}class Ke{_renderers=new Map;_runtime=null;registerRenderer(t,e){if(this._renderers.has(t))throw new Error(`A renderer is already registered for ${t.name}.`);this._renderers.set(t,e),null!==this._runtime&&e.connect(this._runtime)}resolve(t){let e,i=t.constructor;for(;null!==i&&!e;)if(e=this._renderers.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No renderer registered for ${t.constructor.name}. Register one with registry.registerRenderer() before the first draw call.`);return e}connect(t){this._runtime=t;for(const e of this._renderers.values())e.connect(t)}disconnect(){for(const t of this._renderers.values())t.disconnect();this._runtime=null}destroy(){this.disconnect();for(const t of this._renderers.values())"destroy"in t&&"function"==typeof t.destroy&&t.destroy();this._renderers.clear()}}const Qe=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0}),Ze=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),Je=(t,e)=>{throw`${Se.glEnumToString(t)} was caused by call to: ${e}`},ti=(t,e)=>{((t,e)=>{console.log(`gl.${t}(${Se.glFunctionArgsToString(t,e)})`)})(t,e),((t,e)=>{for(const i of e)void 0===i&&console.error(`undefined passed to gl.${t}(${Se.glFunctionArgsToString(t,e)})`)})(t,e)};class ei{backendType=Me.WebGl2;rendererRegistry=new Ke;_context;_rootRenderTarget;_onContextLostHandler;_onContextRestoredHandler;_textureStates=new Map;_renderTargetStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_maskStack=[];_maskPixelStack=[];_maskPointA=new _e;_maskPointB=new _e;_canvas;_contextLost;_renderTarget;_renderer=null;_shader=null;_blendMode=null;_texture=null;_textureUnit=0;_vao=null;_clearColor=new Q;_cursor;_boundFramebuffer=null;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};constructor(t){const{width:e,height:i,clearColor:r,webglAttributes:s,debug:n,spriteRendererBatchSize:o,particleRendererBatchSize:a,primitiveRendererBatchSize:h}=t.options;this._canvas=t.canvas;const l=this._createContext(s);if(!l)throw new Error("This browser or hardware does not support WebGL.");this._context=n?Se.makeDebugContext(l,Je,ti,l):l,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),r&&this.clearColor.copy(r),this._rootRenderTarget=new pe(e,i,!0),this._renderTarget=this._rootRenderTarget,this._cursor=this._canvas.style.cursor,this._onContextLostHandler=this._onContextLost.bind(this),this._onContextRestoredHandler=this._onContextRestored.bind(this),this._setupContext(),this._addEvents(),this.rendererRegistry.registerRenderer(Ye,new ze(o)),this.rendererRegistry.registerRenderer(je,new We(a)),this.rendererRegistry.registerRenderer(we,new qe(h)),this.rendererRegistry.connect(this),this._bindRenderTarget(this._renderTarget),this.setBlendMode(Z.Normal),this.resize(e,i)}get context(){return this._context}get renderTarget(){return this._renderTarget}get view(){return this._renderTarget.view}get clearColor(){return this._clearColor}get cursor(){return this._cursor}get stats(){return this._stats}async initialize(){return this}resetStats(){return Ze(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setRenderTarget(t){const e=t||this._rootRenderTarget;return this._renderTarget!==e&&(this._renderTarget=e,this._stats.renderTargetChanges++),this._bindRenderTarget(e),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,r=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(r),this._applyMaskState(),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this._applyMaskState(),this}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const r=this._temporaryRenderTextures[i];if(r.width===t&&r.height===e)return this._temporaryRenderTextures.splice(i,1),r}return new fe(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&&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}setBlendMode(t){if(t!==this._blendMode){const e=this._context;switch(this._blendMode=t,t){case Z.Additive:e.blendFunc(e.ONE,e.ONE);break;case Z.Subtract:e.blendFunc(e.ZERO,e.ONE_MINUS_SRC_COLOR);break;case Z.Multiply:e.blendFunc(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA);break;case Z.Screen:e.blendFunc(e.ONE,e.ONE_MINUS_SRC_COLOR);break;default: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}setCursor(t){const e=t instanceof $e?t.source:t;if(null===e)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof e?e:`url(${A(e)})`,this._canvas.style.cursor=this._cursor,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._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._bindRenderTarget(this._renderTarget),this}flush(){return this._flushActiveRenderer(),this}destroy(){this._removeEvents(),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._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy(),this._rootRenderTarget.destroy(),this._vao=null,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._boundFramebuffer=null}_createContext(t){try{return this._canvas.getContext("webgl2",t)}catch(t){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const t=this._context,{r:e,g:i,b:r,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,r/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._restoreContext()}_onContextRestored(){this._contextLost=!1}_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}_destroyManagedResources(){for(const t of Array.from(this._renderTargetStates.keys()))this._evictRenderTarget(t,!1);for(const t of Array.from(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},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},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 fe&&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),this._renderTargetStates.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._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,{x:r,y:s,width:n,height:o}=t.getViewport();i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.viewport(r,s,n,o),this._boundFramebuffer=e.framebuffer,e.version=t.version}this._maskPixelStack.length>0&&this._applyMaskState()}_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 fe&&e.framebuffer){const i=this._boundFramebuffer,r=this._syncTexture(t);if(e.attachedTexture!==r.handle){const t=this._context;t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.handle,0),t.bindFramebuffer(t.FRAMEBUFFER,i),e.attachedTexture=r.handle}}return e}_syncTexture(t){const e=this._context,i=this._getTextureState(t),r=t instanceof fe?t.textureVersion:t.version;return e.bindTexture(e.TEXTURE_2D,i.handle),i.version!==r&&(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 fe?-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):e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,t.source):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):e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,t.source)),t.generateMipMap&&(t instanceof fe||null!==t.source)&&e.generateMipmap(e.TEXTURE_2D),i.version=r,i.width=t.width,i.height=t.height),i}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),r=Math.min(e.x,i.x),s=Math.max(e.x,i.x),n=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(r))),u=Math.max(0,Math.min(a,Math.ceil(s))),c=Math.max(0,Math.min(h,Math.floor(n))),d=Math.max(0,Math.min(h,Math.ceil(o))),_=Math.max(0,u-l),p=Math.max(0,d-c);return{x:l,y:Math.max(0,h-d),width:_,height:p}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),r=Math.max(t.y,e.y),s=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:r,width:Math.max(0,s-i),height:Math.max(0,n-r)}}_applyMaskState(){const t=this._context;if(0===this._maskPixelStack.length)return void t.disable(t.SCISSOR_TEST);const e=this._maskPixelStack[this._maskPixelStack.length-1];t.enable(t.SCISSOR_TEST),t.scissor(e.x,e.y,e.width,e.height)}}class ii{backendType=Me.WebGpu;_runtime=null;connect(t){if(null===this._runtime){if(t.backendType!==Me.WebGpu)throw new Error(`${this.constructor.name} requires a WebGPU runtime, but received backendType ${String(t.backendType)}.`);this._runtime=t,this.onConnect(t)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}function ri(t){switch(t){case Z.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case Z.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case Z.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case Z.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 si=20,ni=si/Uint32Array.BYTES_PER_ELEMENT;class oi extends ii{_combinedTransform=new ht;_drawCalls=[];_drawCallCount=0;_pipelines=new Map;_renderManager=null;_device=null;_shaderModule=null;_pipelineLayout=null;_vertexBuffer=null;_indexBuffer=null;_vertexBufferCapacity=0;_indexBufferCapacity=0;_vertexData=new ArrayBuffer(0);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_packedIndexData=new Uint16Array(0);_generatedIndexData=new Uint16Array(0);_sequentialIndexData=new Uint16Array(0);render(t){const e=this._renderManager;if(null===e)throw new Error("Renderer not connected");if(t.drawMode!==et.Points&&t.drawMode!==et.Lines&&t.drawMode!==et.LineLoop&&t.drawMode!==et.LineStrip&&t.drawMode!==et.Triangles&&t.drawMode!==et.TriangleFan&&t.drawMode!==et.TriangleStrip)throw new Error(`WebGPU primitive renderer does not support draw mode "${t.drawMode}" yet.`);if(e.setBlendMode(t.blendMode),0===t.geometry.vertices.length)return;const i=this._drawCallCount++,r=this._drawCalls[i];r?(r.shape=t,r.blendMode=t.blendMode):this._drawCalls.push({shape:t,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device;if(!t||!e)return;if(0===this._drawCallCount&&!t.clearRequested)return;const i=t.getScissorRect(),r=null!==i&&(i.width<=0||i.height<=0),s=[],n=[];let o=0,a=0;if(this._drawCallCount>0&&!r)for(let e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e],r=i.shape,h=this._resolveDrawCall(r);if(n.push(h),null===h)continue;const l=this._getPipeline({topology:h.topology,usesStripIndex:h.usesStripIndex,blendMode:i.blendMode,format:t.renderTargetFormat});s.push({pipeline:l,vertexByteOffset:o*si,vertexCount:h.vertexCount,indexByteOffset:a*Uint16Array.BYTES_PER_ELEMENT,indexCount:h.indexCount}),o+=h.vertexCount,a+=h.indexCount}if(0===s.length){if(t.clearRequested){const i=e.createCommandEncoder(),r=i.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,r.end(),t.submit(i.finish())}return void(this._drawCallCount=0)}this._ensureVertexCapacity(o),a>0&&(this._ensureIndexCapacity(a),this._packedIndexData.length<a&&(this._packedIndexData=new Uint16Array(Math.max(a,0===this._packedIndexData.length?1:2*this._packedIndexData.length))));{let e=0,i=0;for(let r=0;r<this._drawCallCount;r++){const s=n[r];if(null===s)continue;const o=this._drawCalls[r].shape;this._writeShapeVertices(t,o,e),null!==s.indices&&s.indexCount>0&&(this._packedIndexData.set(s.indices.subarray(0,s.indexCount),i),i+=s.indexCount),e+=s.vertexCount}}e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,o*si),a>0&&e.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,a*Uint16Array.BYTES_PER_ELEMENT);const h=e.createCommandEncoder(),l=h.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,null!==i&&l.setScissorRect(i.x,i.y,i.width,i.height);for(const e of s)l.setPipeline(e.pipeline),l.setVertexBuffer(0,this._vertexBuffer,e.vertexByteOffset),e.indexCount>0?(l.setIndexBuffer(this._indexBuffer,"uint16",e.indexByteOffset),l.drawIndexed(e.indexCount)):l.draw(e.vertexCount),t.stats.batches++,t.stats.drawCalls++;l.end(),t.submit(h.finish()),this._drawCallCount=0}destroy(){this.disconnect(),this._combinedTransform.destroy()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct VertexInput {\n @location(0) position: vec4<f32>,\n @location(1) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = input.position;\n output.color = vec4<f32>(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 return input.color;\n}\n"}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[]})}onDisconnect(){this.flush(),this._destroyBuffers(),this._pipelines.clear(),this._pipelineLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._drawCallCount=0}_writeShapeVertices(t,e,i){const r=this._combinedTransform.copy(e.getGlobalTransform()).combine(t.view.getTransform()),s=r.a,n=r.b,o=r.c,a=r.d,h=r.x,l=r.y,u=r.z,c=e.color.toRgba(),d=e.geometry.vertices,_=d.length/2;for(let t=0;t<_;t++){const e=2*t,r=(i+t)*ni,_=d[e],p=d[e+1];this._float32View[r+0]=s*_+n*p+h,this._float32View[r+1]=o*_+a*p+l,this._float32View[r+2]=0,this._float32View[r+3]=u,this._uint32View[r+4]=c}}_ensureVertexCapacity(t){const e=t*si;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?si: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?si: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;e>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(e,0===this._indexBufferCapacity?Uint16Array.BYTES_PER_ELEMENT:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_getPipeline(t){const e=`${t.topology}:${t.usesStripIndex?1:0}:${t.blendMode}:${t.format}`,i=this._pipelines.get(e);if(i)return i;const r=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:si,attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t.format,blend:ri(t.blendMode),writeMask:GPUColorWrite.ALL}]},primitive:{topology:t.topology,stripIndexFormat:t.usesStripIndex?"uint16":void 0}});return this._pipelines.set(e,r),r}_getTopology(t){switch(t){case et.Points:return"point-list";case et.Lines:return"line-list";case et.LineLoop:case et.LineStrip:return"line-strip";case et.Triangles:case et.TriangleFan:return"triangle-list";case et.TriangleStrip:return"triangle-strip";default:throw new Error(`WebGPU primitive renderer does not support draw mode "${t}" yet.`)}}_resolveDrawCall(t){const e=t.geometry.vertices.length/2;if(0===e)return null;switch(t.drawMode){case et.LineLoop:return this._resolveLineLoopDrawCall(t.geometry.indices,e);case et.TriangleFan:return this._resolveTriangleFanDrawCall(t.geometry.indices,e);default:{const i=t.geometry.indices,r=this._getTopology(t.drawMode),s=i.length,n=s>0&&(t.drawMode===et.LineStrip||t.drawMode===et.TriangleStrip);return s>0?{topology:r,usesStripIndex:n,vertexCount:e,indices:i,indexCount:s}:{topology:r,usesStripIndex:n,vertexCount:e,indices:null,indexCount:0}}}}_resolveLineLoopDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),r=i.length;if(r<2)return null;const s=r+1,n=this._ensureGeneratedIndexCapacity(s);return n.set(i.subarray(0,r),0),n[r]=i[0],{topology:"line-strip",usesStripIndex:!0,vertexCount:e,indices:n,indexCount:s}}_resolveTriangleFanDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),r=i.length;if(r<3)return null;const s=3*(r-2),n=this._ensureGeneratedIndexCapacity(s);let o=0;for(let t=1;t<r-1;t++)n[o++]=i[0],n[o++]=i[t],n[o++]=i[t+1];return{topology:"triangle-list",usesStripIndex:!1,vertexCount:e,indices:n,indexCount:s}}_getSequentialIndices(t){if(t>this._sequentialIndexData.length){let e=Math.max(1,this._sequentialIndexData.length);for(;e<t;)e*=2;this._sequentialIndexData=new Uint16Array(e)}for(let e=0;e<t;e++)this._sequentialIndexData[e]=e;return this._sequentialIndexData.subarray(0,t)}_ensureGeneratedIndexCapacity(t){if(t>this._generatedIndexData.length){let e=Math.max(1,this._generatedIndexData.length);for(;e<t;)e*=2;this._generatedIndexData=new Uint16Array(e)}return this._generatedIndexData.subarray(0,t)}_destroyBuffers(){this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0}}const ai=28/Uint32Array.BYTES_PER_ELEMENT;class hi extends ii{_drawCalls=[];_drawCallCount=0;_projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT);_renderManager=null;_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_uniformBindGroup=null;_vertexBuffer=null;_indexBuffer=null;_vertexCapacity=0;_vertexData=new ArrayBuffer(0);_float32View=new Float32Array(this._vertexData);_uint32View=new Uint32Array(this._vertexData);_pipelines=new Map;onConnect(t){this._renderManager||(this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.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 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\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n @location(3) premultiplySample: u32,\n @location(4) textureSlot: 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) @interpolate(flat) premultiplySample: u32,\n @location(3) @interpolate(flat) textureSlot: u32,\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 output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n output.premultiplySample = input.premultiplySample;\n output.textureSlot = input.textureSlot;\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"}}]}),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._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._ensureBatchCapacity(32))}onDisconnect(){this.flush(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._vertexBuffer=null,this._indexBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._drawCallCount=0}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof $e)&&!(i instanceof fe)||0===i.width||0===i.height||i instanceof $e&&null===i.source)return;e.setBlendMode(t.blendMode);const r=this._drawCallCount++,s=this._drawCalls[r];s?(s.sprite=t,s.texture=i,s.color=t.tint.toRgba(),s.blendMode=t.blendMode):this._drawCalls.push({sprite:t,texture:i,color:t.tint.toRgba(),blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,r=this._uniformBindGroup,s=this._vertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&r&&s&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;this._drawCallCount>0&&this._ensureBatchCapacity(this._drawCallCount);const o=[];let a=0;for(let t=0;t<this._drawCallCount;){const e=this._getBatchRange(t),i=e.end-e.start;this._writeBatchVertexData(e,a),o.push({firstSprite:a,spriteCount:i,blendMode:e.blendMode,textures:e.textures}),a+=i,t=e.end}const h=t.view.getTransform();this._projectionData.set([h.a,h.c,0,0,h.b,h.d,0,0,0,0,1,0,h.x,h.y,0,h.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const l=e.createCommandEncoder(),u=l.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const c=t.getScissorRect(),d=null!==c&&(c.width<=0||c.height<=0);if(null===c||d||u.setScissorRect(c.x,c.y,c.width,c.height),this._drawCallCount>0&&!d){e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,4*a*28),u.setBindGroup(0,r),u.setVertexBuffer(0,this._vertexBuffer),u.setIndexBuffer(this._indexBuffer,"uint32");for(const i of o){const r=this._getPipeline(i.blendMode,t.renderTargetFormat),s=this._createTextureBindGroup(e,t,i.textures);u.setPipeline(r),u.setBindGroup(1,s),u.drawIndexed(6*i.spriteCount,1,6*i.firstSprite,0,0),t.stats.batches++,t.stats.drawCalls++}}u.end(),t.submit(l.finish()),this._drawCallCount=0}destroy(){this.disconnect()}_ensureBatchCapacity(t){if(!this._device||t<=this._vertexCapacity)return;let e=Math.max(this._vertexCapacity,32);for(;e<t;)e*=2;const i=new ArrayBuffer(4*e*28),r=this._device.createBuffer({size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),s=new Uint32Array(6*e),n=this._device.createBuffer({size:s.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});for(let t=0;t<e;t++){const e=4*t,i=6*t;s[i]=e,s[i+1]=e+1,s[i+2]=e+2,s[i+3]=e,s[i+4]=e+2,s[i+5]=e+3}this._device.queue.writeBuffer(n,0,s.buffer,s.byteOffset,s.byteLength),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexCapacity=e,this._vertexData=i,this._float32View=new Float32Array(i),this._uint32View=new Uint32Array(i),this._vertexBuffer=r,this._indexBuffer=n}_writeBatchVertexData(t,e){const i=this._renderManager;if(!i)return;let r=4*e*ai;for(let e=t.start;e<t.end;e++){const s=this._drawCalls[e],n=t.textureSlots.get(s.texture)??0,o=i.shouldPremultiplyTextureSample(s.texture)?1:0,a=s.sprite.vertices,h=s.sprite.texCoords;for(let t=0;t<4;t++){const e=2*t,i=h[t];this._float32View[r]=a[e],this._float32View[r+1]=a[e+1],this._float32View[r+2]=(65535&i)/65535,this._float32View[r+3]=(i>>>16&65535)/65535,this._uint32View[r+4]=s.color,this._uint32View[r+5]=o,this._uint32View[r+6]=n,r+=ai}}}_getBatchRange(t){const e=this._drawCalls[t],i=new Map,r=new Array;let s=t+1;for(i.set(e.texture,0),r.push(e.texture);s<this._drawCallCount;){const t=this._drawCalls[s];if(t.blendMode!==e.blendMode)break;if(!i.has(t.texture)){if(r.length>=8)break;i.set(t.texture,r.length),r.push(t.texture)}if(i.size>8)break;s++}return{start:t,end:s,spriteCount:s-t,blendMode:e.blendMode,textures:r,textureSlots:i}}_createTextureBindGroup(t,e,i){const r=i[0],s=e.getTextureBinding(r),n=[],o=new Array(8);for(let t=0;t<8;t++){const n=i[t]??r,a=n===r?s:e.getTextureBinding(n);o[t]=a}for(let t=0;t<8;t++)n.push({binding:t,resource:o[t].view});for(let t=0;t<8;t++)n.push({binding:8+t,resource:o[t].sampler});return t.createBindGroup({layout:this._textureBindGroupLayout,entries:n})}_getPipeline(t,e){const i=`${t}:${e}`,r=this._pipelines.get(i);if(r)return r;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._renderManager))throw new Error("Renderer has to be connected first!");const s=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"},{shaderLocation:3,offset:20,format:"uint32"},{shaderLocation:4,offset:24,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:ri(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,s),s}}const li=56,ui=new Float32Array([0,0,1,0,1,1,0,1]),ci=new Uint16Array([0,1,2,0,2,3]);class di extends ii{_drawCalls=[];_drawCallCount=0;_uniformData=new Float32Array(144/Float32Array.BYTES_PER_ELEMENT);_renderManager=null;_device=null;_shaderModule=null;_uniformBindGroupLayout=null;_textureBindGroupLayout=null;_pipelineLayout=null;_uniformBuffer=null;_uniformBindGroup=null;_staticVertexBuffer=null;_instanceBuffer=null;_indexBuffer=null;_instanceBufferByteLength=0;_instanceData=new ArrayBuffer(56);_float32View=new Float32Array(this._instanceData);_uint32View=new Uint32Array(this._instanceData);_pipelines=new Map;render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof $e)||null===i.source||0===i.width||0===i.height||0===t.particles.length)return;e.setBlendMode(t.blendMode);const r=this._drawCallCount++,s=this._drawCalls[r];s?(s.system=t,s.texture=i,s.blendMode=t.blendMode):this._drawCalls.push({system:t,texture:i,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,r=this._uniformBindGroup,s=this._staticVertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&r&&s&&this._instanceBuffer&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;const o=t.getScissorRect(),a=null!==o&&(o.width<=0||o.height<=0);if(0===this._drawCallCount||a){if(t.clearRequested){const i=e.createCommandEncoder(),r=i.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,r.end(),t.submit(i.finish())}this._drawCallCount=0}else{for(let a=0;a<this._drawCallCount;a++){const h=this._drawCalls[a],l=h.system,u=l.particles.length;if(0===u)continue;const c=this._getPipeline(h.blendMode,t.renderTargetFormat),d=t.getTextureBinding(h.texture),_=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:d.view},{binding:1,resource:d.sampler}]});this._ensureCapacity(u),this._writeInstanceData(l.vertices,l.texCoords,l.particles),this._writeUniformData(t,l,h.texture),e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,u*li),e.queue.writeBuffer(i,0,this._uniformData.buffer,this._uniformData.byteOffset,this._uniformData.byteLength);const p=e.createCommandEncoder(),f=p.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,null!==o&&f.setScissorRect(o.x,o.y,o.width,o.height),f.setBindGroup(0,r),f.setPipeline(c),f.setBindGroup(1,_),f.setVertexBuffer(0,s),f.setVertexBuffer(1,this._instanceBuffer),f.setIndexBuffer(n,"uint16"),f.drawIndexed(6,u,0,0,0),t.stats.batches++,t.stats.drawCalls++,f.end(),t.submit(p.finish())}this._drawCallCount=0}}destroy(){this.disconnect()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n projection: mat4x4<f32>,\n translation: mat4x4<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> uniforms: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar particleTexture: texture_2d<f32>;\n\n@group(1) @binding(1)\nvar particleSampler: sampler;\n\nstruct VertexInput {\n @location(0) unitPosition: vec2<f32>,\n @location(1) quadMin: vec2<f32>,\n @location(2) quadSize: vec2<f32>,\n @location(3) uvMin: vec2<f32>,\n @location(4) uvMax: vec2<f32>,\n @location(5) translation: vec2<f32>,\n @location(6) scale: vec2<f32>,\n @location(7) rotation: f32,\n @location(8) 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};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let localPosition = input.quadMin + (input.unitPosition * input.quadSize);\n let radians = radians(input.rotation);\n let sinValue = sin(radians);\n let cosValue = cos(radians);\n let rotated = vec2<f32>(\n (localPosition.x * (input.scale.x * cosValue)) + (localPosition.y * (input.scale.y * sinValue)) + input.translation.x,\n (localPosition.x * (input.scale.x * -sinValue)) + (localPosition.y * (input.scale.y * cosValue)) + input.translation.y\n );\n\n var output: VertexOutput;\n\n output.position = uniforms.projection * uniforms.translation * vec4<f32>(rotated, 0.0, 1.0);\n output.texcoord = input.uvMin + ((input.uvMax - input.uvMin) * input.unitPosition);\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(particleTexture, particleSampler, input.texcoord);\n let premultipliedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), uniforms.flags.x > 0.5);\n\n return premultipliedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),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:144,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._staticVertexBuffer=this._device.createBuffer({size:ui.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._staticVertexBuffer,0,ui.buffer,ui.byteOffset,ui.byteLength),this._indexBuffer=this._device.createBuffer({size:ci.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,ci.buffer,ci.byteOffset,ci.byteLength),this._ensureCapacity(1)}onDisconnect(){this.flush(),this._staticVertexBuffer?.destroy(),this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._indexBuffer=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._drawCallCount=0}_ensureCapacity(t){const e=t*li;if(e>this._instanceData.byteLength){let t=this._instanceData.byteLength;for(;t<e;)t*=2;this._instanceData=new ArrayBuffer(t),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData)}if(e>this._instanceBufferByteLength){let t=this._instanceBufferByteLength||li;for(;t<e;)t*=2;this._instanceBuffer?.destroy(),this._instanceBuffer=this._device.createBuffer({size:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._instanceBufferByteLength=t}}_writeUniformData(t,e,i){const r=t.view.getTransform().toArray(!1),s=e.getGlobalTransform().toArray(!1),n=t.shouldPremultiplyTextureSample(i);this._uniformData.set([r[0],r[1],0,0,r[3],r[4],0,0,0,0,1,0,r[6],r[7],0,r[8],s[0],s[1],0,0,s[3],s[4],0,0,0,0,1,0,s[6],s[7],0,s[8],n?1:0,0,0,0])}_writeInstanceData(t,e,i){const r=t[0],s=t[1],n=t[2]-t[0],o=t[3]-t[1],a=(65535&e[0])/65535,h=(e[0]>>>16&65535)/65535,l=(65535&e[2])/65535,u=(e[2]>>>16&65535)/65535;for(let t=0;t<i.length;t++){const e=i[t],c=14*t;this._float32View[c]=r,this._float32View[c+1]=s,this._float32View[c+2]=n,this._float32View[c+3]=o,this._float32View[c+4]=a,this._float32View[c+5]=h,this._float32View[c+6]=l,this._float32View[c+7]=u,this._float32View[c+8]=e.position.x,this._float32View[c+9]=e.position.y,this._float32View[c+10]=e.scale.x,this._float32View[c+11]=e.scale.y,this._float32View[c+12]=e.rotation,this._uint32View[c+13]=e.tint.toRgba()}}_getPipeline(t,e){const i=`${t}:${e}`,r=this._pipelines.get(i);if(r)return r;const s=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:li,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x2"},{shaderLocation:2,offset:8,format:"float32x2"},{shaderLocation:3,offset:16,format:"float32x2"},{shaderLocation:4,offset:24,format:"float32x2"},{shaderLocation:5,offset:32,format:"float32x2"},{shaderLocation:6,offset:40,format:"float32x2"},{shaderLocation:7,offset:48,format:"float32"},{shaderLocation:8,offset:52,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:ri(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,s),s}}const _i="rgba8unorm";class pi{backendType=Me.WebGpu;rendererRegistry=new Ke;_canvas;_rootRenderTarget;_clearColor=new Q;_textureStates=new Map;_textureDestroyHandlers=new Map;_renderTargetDestroyHandlers=new Map;_temporaryRenderTextures=[];_maskStack=[];_maskPixelStack=[];_maskPointA=new _e;_maskPointB=new _e;_mipmapShaderModule=null;_mipmapBindGroupLayout=null;_mipmapPipelineLayout=null;_mipmapPipeline=null;_mipmapSampler=null;_context=null;_device=null;_format=null;_initializePromise=null;_renderTarget;_renderer=null;_blendMode=null;_texture=null;_clearRequested=!1;_hasPresentedFrame=!1;_stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};constructor(t){const{width:e,height:i,clearColor:r}=t.options;this._canvas=t.canvas,this._rootRenderTarget=new pe(e,i,!0),this._renderTarget=this._rootRenderTarget,r&&this._clearColor.copy(r),this.rendererRegistry.registerRenderer(we,new oi),this.rendererRegistry.registerRenderer(Ye,new hi),this.rendererRegistry.registerRenderer(je,new di),this.resize(e,i)}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:_i}get clearRequested(){return this._clearRequested}get stats(){return this._stats}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(t=>{throw this._initializePromise=null,t})),this._initializePromise}resetStats(){return Ze(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setShader(t){if(null!==t)throw new Error("WebGPU shaders are not implemented yet.");return this}setTexture(t,e){if(null===t)return this._texture=null,this;if(t instanceof pe&&!(t instanceof fe))throw new Error("WebGPU render textures are not implemented yet.");return this._syncTexture(t),this._texture=t,this}setBlendMode(t){if(null===t)return this._blendMode=null,this;if(t!==Z.Normal&&t!==Z.Additive&&t!==Z.Subtract&&t!==Z.Multiply&&t!==Z.Screen)throw new Error(`WebGPU blend mode "${t}" is not implemented yet.`);return this._blendMode=t,this}setVao(t){if(null!==t)throw new Error("WebGPU vertex array objects are not implemented yet.");return this}setRenderTarget(t){const e=t??this._rootRenderTarget;if(!(e.root||e instanceof fe))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");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}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,r=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(r),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this}getScissorRect(){if(0===this._maskPixelStack.length)return null;const t=this._maskPixelStack[this._maskPixelStack.length-1];return{x:t.x,y:t.y,width:t.width,height:t.height}}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const r=this._temporaryRenderTextures[i];if(r.width===t&&r.height===e)return this._temporaryRenderTextures.splice(i,1),r}return new fe(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._clearColor.copy(t),this._clearRequested=!0,this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._hasPresentedFrame=!1,this}flush(){if(!this._device||!this._context)return this;if(this._renderer)this._flushActiveRenderer();else if(this._clearRequested){const t=this._device.createCommandEncoder();t.beginRenderPass({colorAttachments:[this.createColorAttachment()]}).end(),this._stats.renderPasses++,this.submit(t.finish())}return this}destroy(){this._setActiveRenderer(null),this.rendererRegistry.destroy(),this._destroyManagedTextures(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy();for(const t of Array.from(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._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=null;if(t===this._rootRenderTarget)e={view:this.context.getCurrentTexture().createView(),shouldClear:this._clearRequested||!this._hasPresentedFrame};else{if(!(t instanceof fe))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");{const i=this._syncTexture(t);e={view:i.view,shouldClear:this._clearRequested||!i.hasContent}}}return this._clearRequested=!1,{view:e.view,clearValue:{r:this._clearColor.r/255,g:this._clearColor.g/255,b:this._clearColor.b/255,a:this._clearColor.a},loadOp:e.shouldClear?"clear":"load",storeOp:"store"}}submit(t){if(this.device.queue.submit([t]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof fe){const t=this._syncTexture(this._renderTarget);t.hasContent=!0,t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}}getTextureBinding(t){const e=this._syncTexture(t);return{view:e.view,sampler:e.sampler}}shouldPremultiplyTextureSample(t){return!(t instanceof fe)&&t.premultiplyAlpha}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer?.flush()}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=null;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 r=null;try{r=await e.requestDevice()}catch(t){throw this._createInitializationError("Failed to request a WebGPU device.",t)}if(null===r)throw new Error("Could not acquire a WebGPU device.");const s=t.gpu.getPreferredCanvasFormat();try{i.configure({device:r,format:s,alphaMode:"opaque"})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}return this._context=i,this._device=r,this._format=s,this._blendMode=Z.Normal,this._hasPresentedFrame=!1,this.rendererRegistry.connect(this),this.resize(this._canvas.width,this._canvas.height),this}_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 Array.from(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:_i,mipLevelCount:this._getMipLevelCount(t),usage:this._getTextureUsage(t)});e={texture:i,view:i.createView(),sampler:this._createSampler(t),version:-1,width:t.width,height:t.height,mipLevelCount:this._getMipLevelCount(t),hasContent:!1};const r=()=>{this._evictTexture(t)};t.addDestroyListener(r),this._textureDestroyHandlers.set(t,r),this._textureStates.set(t,e)}return e}_syncTexture(t){if(!(t instanceof fe||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 fe?t.textureVersion:t.version,r=this._getMipLevelCount(t);if(e.version!==i){if(e.width!==t.width||e.height!==t.height||e.mipLevelCount!==r){e.texture.destroy();const i=this.device.createTexture({size:{width:t.width,height:t.height},format:_i,mipLevelCount:r,usage:this._getTextureUsage(t)});e.texture=i,e.view=i.createView(),e.width=t.width,e.height=t.height,e.mipLevelCount=r,e.hasContent=!1}if(e.sampler=this._createSampler(t),!(t instanceof fe)){const i=t.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:e.texture},{width:t.width,height:t.height}),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._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._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))}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),r=Math.min(e.x,i.x),s=Math.max(e.x,i.x),n=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(r))),u=Math.max(0,Math.min(a,Math.ceil(s))),c=Math.max(0,Math.min(h,Math.floor(n))),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)}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),r=Math.max(t.y,e.y),s=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:r,width:Math.max(0,s-i),height:Math.max(0,n-r)}}_createSampler(t){return this.device.createSampler({addressModeU:this._getAddressMode(t.wrapMode),addressModeV:this._getAddressMode(t.wrapMode),magFilter:this._getFilterMode(t.scaleMode),minFilter:this._getFilterMode(t.scaleMode),mipmapFilter:this._getMipmapFilterMode(t.scaleMode)})}_getTextureUsage(t){const e=this._getMipLevelCount(t)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return t instanceof fe?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|e:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|e}_getAddressMode(t){switch(t){case tt.Repeat:return"repeat";case tt.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case J.Nearest:case J.NearestMipmapNearest:case J.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case J.NearestMipmapLinear:case J.LinearMipmapLinear:return"linear";default:return"nearest"}}_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(),r=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}]}),n=r.beginRenderPass({colorAttachments:[{view:t.createView({baseMipLevel:s,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});n.setPipeline(i.pipeline),n.setBindGroup(0,e),n.draw(3),n.end()}this.device.queue.submit([r.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:_i,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}}}var fi,mi,gi,yi,xi,wi,vi;!function(t){t[t.Container=768]="Container",t[t.Category=256]="Category",t[t.Gamepad=64]="Gamepad"}(fi||(fi={})),function(t){t[t.Keyboard=0]="Keyboard",t[t.Pointers=256]="Pointers",t[t.Gamepads=512]="Gamepads"}(mi||(mi={})),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"}(gi||(gi={}));class bi{onConnect=new F;onDisconnect=new F;onUpdate=new F;indexValue;channelsValue;channelOffset;mappingValue;browserGamepad=null;info={name:"Generic Gamepad",label:"Generic Gamepad",vendorId:null,productId:null,productKey:null};constructor(t,e,i){const r="number"!=typeof t,s=r?t:null,n=r?t.index:t;if(this.indexValue=n,this.channelsValue=e,this.channelOffset=mi.Gamepads+n*fi.Gamepad,this.mappingValue=s?i.mapping:i,s){const t=i;this.setInfo({name:t.name,label:t.descriptor.label,vendorId:t.descriptor.vendorId,productId:t.descriptor.productId,productKey:t.descriptor.productKey}),this.connect(s)}}get mapping(){return this.mappingValue}set mapping(t){this.mappingValue=t}get mappingFamily(){return this.mappingValue.family}get channels(){return this.channelsValue}get gamepad(){return this.browserGamepad}get index(){return this.indexValue}get connected(){return null!==this.browserGamepad}get name(){return this.info.name}get label(){return this.info.label}get vendorId(){return this.info.vendorId}get productId(){return this.info.productId}get productKey(){return this.info.productKey}setInfo(t){return this.info=t,this}connect(t){const e=this.connected;return this.browserGamepad=t,e||this.onConnect.dispatch(this),this}disconnect(){return this.connected&&(this.browserGamepad=null,this.clearMappedChannels(),this.onDisconnect.dispatch(this)),this}update(){if(null===this.browserGamepad)return this;const t=this.channelsValue,{buttons:e,axes:i}=this.browserGamepad;for(const i of this.mappingValue.buttons){const r=this.resolveChannelOffset(i.channel);if(i.index<e.length){const s=i.transformValue(e[i.index].value)||0;t[r]!==s&&(t[r]=s,this.onUpdate.dispatch(i.channel,s,this))}}for(const e of this.mappingValue.axes){const r=this.resolveChannelOffset(e.channel);if(e.index<i.length){const s=e.transformValue(i[e.index])||0;t[r]!==s&&(t[r]=s,this.onUpdate.dispatch(e.channel,s,this))}}return this}clearChannels(){return this.clearMappedChannels(),this}destroy(){this.disconnect(),this.clearMappedChannels(),this.onConnect.destroy(),this.onDisconnect.destroy(),this.onUpdate.destroy()}resolveChannelOffset(t){return this.channelOffset+(t^mi.Gamepads)}static resolveChannelOffset(t,e){return mi.Gamepads+t*fi.Gamepad+(e^mi.Gamepads)}clearMappedChannels(){for(const t of this.mappingValue.buttons)this.channelsValue[this.resolveChannelOffset(t.channel)]=0;for(const t of this.mappingValue.axes)this.channelsValue[this.resolveChannelOffset(t.channel)]=0}}!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"}(yi||(yi={})),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"}(xi||(xi={}));class Ti{id;type;position;startPos=new _e(-1,-1);size;tilt;stateFlags=new lt;_canvas;_buttons;_pressure;_rotation;_currentState=xi.Unknown;constructor(t,i){const{pointerId:r,pointerType:s,clientX:n,clientY:o,width:a,height:h,tiltX:l,tiltY:u,buttons:c,pressure:d,twist:_}=t,{left:p,top:f}=i.getBoundingClientRect();this._canvas=i,this.id=r,this.type=s,this.position=new _e(n-p,o-f),this.size=new e(a,h),this.tilt=new _e(l,u),this._buttons=c,this._pressure=d,this._rotation=_,this.stateFlags.push(yi.Over)}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 currentState(){return this._currentState}handleEnter(t){this.handleEvent(t),this._currentState=xi.InsideCanvas}handleLeave(t){this.handleEvent(t),this.stateFlags.push(yi.Leave),this._currentState=xi.OutsideCanvas}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(yi.Down),this._currentState=xi.Pressed}handleMove(t){this.handleEvent(t),this.stateFlags.push(yi.Move),this._currentState=xi.Moving}handleRelease(t){this.handleEvent(t),this.stateFlags.push(yi.Up),this._currentState=xi.Released}handleCancel(t){this.handleEvent(t),this.stateFlags.push(yi.Cancel),this._currentState=xi.Cancelled}destroy(){this.position.destroy(),this.startPos.destroy(),this.size.destroy(),this.tilt.destroy(),this._canvas=null}handleEvent(t){const{clientX:e,clientY:i,width:r,height:s,tiltX:n,tiltY:o,buttons:a,pressure:h,twist:l}=t,{left:u,top:c}=this._canvas.getBoundingClientRect();return this.position.set(e-u,i-c),this.size.set(r,s),this.tilt.set(n,o),this._buttons=a,this._pressure=h,this._rotation=l,this}}!function(t){t[t.ButtonSouth=512]="ButtonSouth",t[t.ButtonWest=513]="ButtonWest",t[t.ButtonEast=514]="ButtonEast",t[t.ButtonNorth=515]="ButtonNorth",t[t.LeftShoulder=516]="LeftShoulder",t[t.RightShoulder=517]="RightShoulder",t[t.LeftTrigger=518]="LeftTrigger",t[t.RightTrigger=519]="RightTrigger",t[t.Select=520]="Select",t[t.Start=521]="Start",t[t.LeftStick=522]="LeftStick",t[t.RightStick=523]="RightStick",t[t.DPadUp=524]="DPadUp",t[t.DPadDown=525]="DPadDown",t[t.DPadLeft=526]="DPadLeft",t[t.DPadRight=527]="DPadRight",t[t.Guide=528]="Guide",t[t.Share=529]="Share",t[t.Capture=530]="Capture",t[t.Touchpad=531]="Touchpad",t[t.Paddle1=532]="Paddle1",t[t.LeftStickLeft=533]="LeftStickLeft",t[t.LeftStickRight=534]="LeftStickRight",t[t.LeftStickUp=535]="LeftStickUp",t[t.LeftStickDown=536]="LeftStickDown",t[t.RightStickLeft=537]="RightStickLeft",t[t.RightStickRight=538]="RightStickRight",t[t.RightStickUp=539]="RightStickUp",t[t.RightStickDown=540]="RightStickDown",t[t.AuxiliaryAxis0Negative=541]="AuxiliaryAxis0Negative",t[t.AuxiliaryAxis0Positive=542]="AuxiliaryAxis0Positive",t[t.AuxiliaryAxis1Negative=543]="AuxiliaryAxis1Negative",t[t.AuxiliaryAxis1Positive=544]="AuxiliaryAxis1Positive",t[t.AuxiliaryAxis2Negative=545]="AuxiliaryAxis2Negative",t[t.AuxiliaryAxis2Positive=546]="AuxiliaryAxis2Positive",t[t.AuxiliaryAxis3Negative=547]="AuxiliaryAxis3Negative",t[t.AuxiliaryAxis3Positive=548]="AuxiliaryAxis3Positive"}(wi||(wi={}));class Si{index;channel;invert;normalize;threshold;constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=z(i.threshold??.2,0,1)}transformValue(t){let e=z(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),e>this.threshold?e:0}}!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.ArcadeStick="arcadeStick"}(vi||(vi={}));class Ci{buttons;axes;constructor(t,e){this.buttons=t,this.axes=e}destroy(){this.buttons.length=0,this.axes.length=0}static createControls(t){return t.map(([t,e,i])=>new Si(t,e,i))}}const Mi=[[0,wi.ButtonSouth],[1,wi.ButtonEast],[2,wi.ButtonWest],[3,wi.ButtonNorth],[4,wi.LeftShoulder],[5,wi.RightShoulder],[6,wi.LeftTrigger],[7,wi.RightTrigger],[8,wi.Select],[9,wi.Start],[12,wi.DPadUp],[13,wi.DPadDown],[14,wi.DPadLeft],[15,wi.DPadRight],[16,wi.Guide]];class Pi extends Ci{family=vi.ArcadeStick;constructor(){super(Ci.createControls(Mi),[])}}const Bi=[[0,wi.ButtonSouth],[1,wi.ButtonEast],[2,wi.ButtonWest],[3,wi.ButtonNorth],[4,wi.LeftShoulder],[5,wi.RightShoulder],[6,wi.LeftTrigger],[7,wi.RightTrigger],[8,wi.Select],[9,wi.Start],[10,wi.LeftStick],[11,wi.RightStick],[12,wi.DPadUp],[13,wi.DPadDown],[14,wi.DPadLeft],[15,wi.DPadRight],[16,wi.Guide],[17,wi.Share],[18,wi.Capture],[19,wi.Touchpad],[20,wi.Paddle1]],Ei=[[0,wi.LeftStickLeft,{invert:!0}],[0,wi.LeftStickRight],[1,wi.LeftStickUp,{invert:!0}],[1,wi.LeftStickDown],[2,wi.RightStickLeft,{invert:!0}],[2,wi.RightStickRight],[3,wi.RightStickUp,{invert:!0}],[3,wi.RightStickDown],[4,wi.AuxiliaryAxis0Negative,{invert:!0}],[4,wi.AuxiliaryAxis0Positive],[5,wi.AuxiliaryAxis1Negative,{invert:!0}],[5,wi.AuxiliaryAxis1Positive],[6,wi.AuxiliaryAxis2Negative,{invert:!0}],[6,wi.AuxiliaryAxis2Positive],[7,wi.AuxiliaryAxis3Negative,{invert:!0}],[7,wi.AuxiliaryAxis3Positive]];class Ri extends Ci{family=vi.GenericDualAnalog;constructor(){super(Ci.createControls(Bi),Ci.createControls(Ei))}}class ki extends Ri{family=vi.GameCube}class Ai extends Ri{family=vi.JoyConLeft}class Li extends Ri{family=vi.JoyConRight}class Fi extends Ri{family=vi.PlayStation}class Di extends Ri{family=vi.SteamController}class Ni extends Ri{family=vi.SwitchPro}class Ii extends Ri{family=vi.Xbox}const Ui=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Vi=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,Oi=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,Gi=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,zi=(t,e,i)=>({ids:i,name:t,resolve:()=>({name:t,mapping:e()})}),Wi=t=>t.trim().toLowerCase(),qi=t=>{const e=t.replace(Vi,"").replace(Ui,"").replace(Gi,"").replace(Oi,"").replace(/\s+/g," ").trim();return e.length>0?e:null},Hi=t=>{if(!t)return[];return(Array.isArray(t)?t:[t]).map(Wi)},Yi=(t,e)=>{if(!e)return!0;for(const i of Hi(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},Xi=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=Vi.exec(t)||Ui.exec(t)||Gi.exec(t)||Oi.exec(t);return e?`${e[1].toLowerCase()}:${e[2].toLowerCase()}`:null})(e),r=i?.slice(0,4)??null,s=i?.slice(5)??null;return{id:t.id,index:t.index,label:e,vendorId:r,productId:s,productKey:i,name:qi(e)}},ji=(t,e)=>Yi(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,$i=(t,e=Ki)=>{const i="connected"in t?Xi(t):t;for(const t of e){const e=ji(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new Ri}},Ki=[...[zi("Xbox 360 Controller",()=>new Ii,"045e:028e"),zi("Xbox One Controller",()=>new Ii,["045e:02d1","045e:02dd"]),zi("Xbox Wireless Controller",()=>new Ii,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),zi("Xbox One Elite Controller",()=>new Ii,"045e:02e3"),zi("Xbox Elite Wireless Controller Series 2",()=>new Ii,["045e:0b00","045e:0b05","045e:0b22"]),zi("Xbox Series Controller",()=>new Ii,["045e:0b12","045e:0b13"]),zi("PlayStation 3 Controller",()=>new Fi,"054c:0268"),zi("DualShock 4 Controller",()=>new Fi,["054c:05c4","054c:09cc","054c:0ba0"]),zi("DualSense Controller",()=>new Fi,"054c:0ce6"),zi("DualSense Edge Controller",()=>new Fi,"054c:0df2"),zi("GameCube Controller Adapter",()=>new ki,"057e:0337"),zi("Joy-Con (L)",()=>new Ai,"057e:2006"),zi("Joy-Con (R)",()=>new Li,"057e:2007"),zi("Joy-Con Charging Grip",()=>new Ni,"057e:200e"),zi("Switch Pro Controller",()=>new Ni,"057e:2009"),zi("Joy-Con 2 (L)",()=>new Ai,"057e:2066"),zi("Joy-Con 2 (R)",()=>new Li,"057e:2067"),zi("Switch 2 Pro Controller",()=>new Ni,"057e:2069"),zi("Switch 2 GameCube Controller",()=>new ki,"057e:2073"),zi("Steam Controller",()=>new Di,["28de:1102","28de:1142"]),zi("F310 Gamepad",()=>new Ri,"046d:c216"),zi("F710 Gamepad",()=>new Ri,["046d:c219","046d:c21f"]),zi("8BitDo P30 Controller",()=>new Ri,["2dc8:5107","2dc8:5108"]),zi("8BitDo SF30 Pro Controller",()=>new Ni,["2dc8:3000","2dc8:6100","2dc8:6101"]),zi("8BitDo SN30 Controller",()=>new Ni,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),zi("8BitDo NES30 Controller",()=>new Ri,"2dc8:ab12"),zi("PowerA Switch Controller",()=>new Ni,"20d6:a713"),zi("PowerA OPS Pro Wireless Controller",()=>new Ri,"20d6:4033"),zi("PowerA OPS Wireless Controller",()=>new Ri,"20d6:4026"),zi("Nacon Revolution 3 Controller",()=>new Fi,"146b:0611"),zi("Nacon Revolution Unlimited Pro Controller",()=>new Fi,"146b:0d08"),zi("Nacon Revolution Infinity Controller",()=>new Fi,"146b:0d10"),zi("Nacon Revolution 5 Pro Controller",()=>new Fi,["3285:0d17","3285:0d19"]),zi("Razer Raiju Controller",()=>new Fi,"1532:1000"),zi("Razer Raiju Mobile Controller",()=>new Fi,["1532:0705","1532:0707"]),zi("Razer Raiju Tournament Edition Controller",()=>new Fi,["1532:1007","1532:100a"]),zi("Razer Raiju Ultimate Controller",()=>new Fi,["1532:1004","1532:1009"]),zi("Razer Raion Controller",()=>new Pi,"1532:1100")],...[zi("Microsoft Controller",()=>new Ii,"045e"),zi("Sony Controller",()=>new Fi,"054c")],zi("Generic Gamepad",()=>new Ri)];var Qi;!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"}(Qi||(Qi={}));class Zi{canvas;channels=new Float32Array(fi.Container);inputs=new Set;pointers={};gamepadsValue=[];gamepadsByIndex=new Map;gamepadSlotsActive=new Uint8Array(fi.Category/fi.Gamepad);wheelOffset=new _e;flags=new lt;channelsPressed=[];channelsReleased=[];gamepadDefinitions;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);onPointerEnter=new F;onPointerLeave=new F;onPointerDown=new F;onPointerMove=new F;onPointerUp=new F;onPointerTap=new F;onPointerSwipe=new F;onPointerCancel=new F;onMouseWheel=new F;onKeyDown=new F;onKeyUp=new F;onGamepadConnected=new F;onGamepadDisconnected=new F;onGamepadUpdated=new F;constructor(t){const{gamepadDefinitions:e=[],pointerDistanceThreshold:i}=t.options;this.canvas=t.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=i,this.gamepadDefinitions=[...e,...Ki],this.addEventListeners()}get pointersInCanvas(){return Object.values(this.pointers).some(t=>t.currentState!==xi.OutsideCanvas&&t.currentState!==xi.Cancelled)}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this.gamepadsValue}getGamepad(t){return this.gamepadsByIndex.get(t)??null}add(t){return Array.isArray(t)?(t.forEach(t=>this.add(t)),this):(this.inputs.add(t),this)}remove(t){return Array.isArray(t)?(t.forEach(t=>this.remove(t)),this):(this.inputs.delete(t),this)}clear(t=!1){if(t)for(const t of this.inputs)t.destroy();return this.inputs.clear(),this}update(){this.updateGamepads();for(const t of this.inputs)t.update(this.channels);return this.flags.value!==Qi.None&&this.updateEvents(),this}destroy(){this.removeEventListeners();for(const t of Object.values(this.pointers))t.destroy();for(const t of this.gamepadsValue)t.destroy();this.inputs.clear(),this.gamepadsByIndex.clear(),this.gamepadsValue.length=0,this.channelsPressed.length=0,this.channelsReleased.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.onGamepadUpdated.destroy()}handleKeyDown(t){const e=mi.Keyboard+t.keyCode;this.channels[e]=1,this.channelsPressed.push(e),this.flags.push(Qi.KeyDown)}handleKeyUp(t){const e=mi.Keyboard+t.keyCode;this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(Qi.KeyUp)}handlePointerOver(t){this.pointers[t.pointerId]=new Ti(t,this.canvas),this.flags.push(Qi.PointerUpdate)}handlePointerLeave(t){this.pointers[t.pointerId].handleLeave(t),this.flags.push(Qi.PointerUpdate)}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0,this.pointers[t.pointerId].handlePress(t),this.flags.push(Qi.PointerUpdate),t.preventDefault()}handlePointerMove(t){this.pointers[t.pointerId].handleMove(t),this.flags.push(Qi.PointerUpdate)}handlePointerUp(t){this.pointers[t.pointerId].handleRelease(t),this.flags.push(Qi.PointerUpdate),t.preventDefault()}handlePointerCancel(t){this.pointers[t.pointerId].handleCancel(t),this.flags.push(Qi.PointerUpdate)}handleMouseWheel(t){this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(Qi.MouseWheel),this.canvasFocusedValue&&t.preventDefault()}handleCanvasFocus(){this.canvasFocusedValue=!0}handleCanvasBlur(){this.canvasFocusedValue=!1}handleWindowBlur(){this.canvasFocusedValue=!1}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",m,e),this.canvas.addEventListener("selectstart",m,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",m,t),this.canvas.removeEventListener("selectstart",m,t)}updateGamepads(){const t=window.navigator.getGamepads();this.gamepadSlotsActive.fill(0);for(const e of t){if(!e)continue;const t=e.index;if(t<0||t>=this.gamepadSlotsActive.length)continue;this.gamepadSlotsActive[t]=1;let i=this.gamepadsByIndex.get(t);if(i)i.connect(e);else{const r=$i(e,this.gamepadDefinitions);i=new bi(e,this.channels,r),this.gamepadsByIndex.set(t,i),this.insertGamepadByIndex(i),this.onGamepadConnected.dispatch(i,this.gamepadsValue)}i.update(),this.onGamepadUpdated.dispatch(i,this.gamepadsValue)}for(let t=this.gamepadsValue.length-1;t>=0;t-=1){const e=this.gamepadsValue[t];0===this.gamepadSlotsActive[e.index]&&(e.disconnect(),this.gamepadsValue.splice(t,1),this.gamepadsByIndex.delete(e.index),this.onGamepadDisconnected.dispatch(e,this.gamepadsValue),e.destroy())}return this}insertGamepadByIndex(t){let e=0;for(;e<this.gamepadsValue.length&&this.gamepadsValue[e].index<t.index;)e+=1;this.gamepadsValue.splice(e,0,t)}updateEvents(){if(this.flags.pop(Qi.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(Qi.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(Qi.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(Qi.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of Object.values(this.pointers)){const{stateFlags:e}=t;if(e.value!==yi.None){if(e.pop(yi.Over)&&this.onPointerEnter.dispatch(t),e.pop(yi.Down)&&this.onPointerDown.dispatch(t),e.pop(yi.Move)&&this.onPointerMove.dispatch(t),e.pop(yi.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(yi.Cancel)&&this.onPointerCancel.dispatch(t),e.pop(yi.Leave)&&(this.onPointerLeave.dispatch(t),delete this.pointers[t.id])}}}}class Ji{onStart=new F;onStop=new F;_duration;_volume;_playbackRate;_loop;_muted;get duration(){return this._duration}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 progress(){const t=this.currentTime,e=this.duration;return t%e/e}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}constructor(t){const{duration:e,volume:i,playbackRate:r,loop:s,muted:n}=t;this._duration=e,this._volume=i,this._playbackRate=r,this._loop=s,this._muted=n}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:r,time:s,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==r&&(this.playbackRate=r),void 0!==s&&(this.currentTime=s),void 0!==n&&(this.muted=n),this}destroy(){this.stop(),this.onStart.destroy(),this.onStop.destroy()}}const tr=["mousedown","touchstart","touchend"];let er=null,ir=null,rr=!1,sr=!1,nr=!1;const or=()=>"undefined"!=typeof document,ar=()=>er,hr=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===er&&(er=new AudioContext),er},lr=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===ir){const t=hr();ir=new OfflineAudioContext(1,2,t.sampleRate)}return ir},ur=()=>{const t=ar();t&&"running"===t.state&&!nr&&(nr=!0,(()=>{if(rr&&or()){for(const t of tr)document.removeEventListener(t,_r,!1);rr=!1}})(),pr.dispatch(t))},cr=()=>{ur()},dr=()=>{const t=hr();sr||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",cr),sr=!0),ur(),nr||(()=>{if(!rr&&or()){for(const t of tr)document.addEventListener(t,_r,!1);rr=!0}})()},_r=()=>{const t=hr();"running"!==t.state?t.resume().then(()=>{ur()}):ur()};const pr=new class extends F{add(t,e){return super.add(t,e),dr(),this}once(t,e){return super.once(t,e),dr(),this}},fr=()=>{const t=hr();return dr(),t},mr=()=>{const t=ar();return null!==t&&"running"===t.state},gr=()=>lr(),yr=async t=>lr().decodeAudioData(t);class xr extends Ji{_audioElement;_audioSetup=null;constructor(t,e){super(t),this._audioElement=t,e&&this.applyOptions(e),mr()?this.setupWithAudioContext(fr()):pr.once(this.setupWithAudioContext,this)}setVolume(t){const e=z(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,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._audioElement.loop=t),this}setPlaybackRate(t){const e=z(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._audioElement.playbackRate=e),this}getTime(){return this._audioElement.currentTime}setTime(t){return this._audioElement.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,10)}return this}get paused(){return this._audioElement.paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._audioElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._audioElement.pause(),this.onStop.dispatch()),this}destroy(){super.destroy(),pr.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._audioElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class wr extends Ji{_audioBuffer;_pooledSources=[];_queuedPooledPlays=[];_sprites=new Map;_audioSetup=null;_paused=!0;_startTime=0;_currentTime=0;_sourceNode=null;_poolSize=1;get paused(){return this._paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}get poolSize(){return this._poolSize}set poolSize(t){this.setPoolSize(t)}constructor(t,e={}){super({duration:t.duration,volume:1,playbackRate:1,loop:!1,muted:!1}),this._audioBuffer=t;const{poolSize:i,sprites:r,...s}=e;this._poolSize=Math.max(1,Math.floor(i??1)),Object.keys(s).length>0&&this.applyOptions(s),r&&this.setSprites(r),mr()?this.setupWithAudioContext(fr()):pr.once(this.setupWithAudioContext,this)}setVolume(t){const e=z(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,10)}return this}setLoop(t){return this._loop=t,this._sourceNode&&(this._sourceNode.loop=t,t&&(this._sourceNode.loopStart=0,this._sourceNode.loopEnd=this.duration)),this}setPlaybackRate(t){return this._playbackRate=z(t,.1,20),this._sourceNode&&(this._sourceNode.playbackRate.value=this._playbackRate),this}getTime(){return this._audioSetup&&!this._paused&&this._sourceNode?this._currentTime+(this._audioSetup.audioContext.currentTime-this._startTime)*this._playbackRate:this._currentTime}setTime(t){const e=Math.max(0,t);return this.paused||!this._audioSetup?(this._currentTime=e,this):(this.pause(),this._currentTime=e,this.play(),this)}setMuted(t){if(this._muted=t,this._audioSetup){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}setPoolSize(t){const e=Math.max(1,Math.floor(t));return this._poolSize===e||(this._poolSize=e,this._trimPooledSources()),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,r=e.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${t}" has an invalid start time (${i}).`);if(!Number.isFinite(r)||r<=i)throw new Error(`Sound sprite "${t}" has an invalid end time (${r}).`);if(r>this.duration)throw new Error(`Sound sprite "${t}" ends at ${r}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(t,{start:i,end:r,loop:e.loop??!1}),this}hasSprite(t){return this._sprites.has(t)}removeSprite(t){return this._sprites.delete(t),this}play(t){return t&&this.applyOptions(t),this._paused?(this._audioSetup&&this.createSourceNode(this._audioSetup),this._paused=!1,this.onStart.dispatch(),this):this}playPooled(t={}){const e=z(t.playbackRate??this._playbackRate,.1,20),i=Math.max(0,t.time??0),r=t.loop??!1;if(void 0!==t.volume&&this.setVolume(t.volume),void 0!==t.muted&&this.setMuted(t.muted),i>=this.duration)return this;const s=r?void 0:this.duration-i;return this._enqueuePooledPlay({offset:i,duration:s,loop:r,loopStart:0,loopEnd:this.duration,playbackRate:e}),this.onStart.dispatch(),this}playSprite(t,e={}){const i=this._sprites.get(t);if(!i)throw new Error(`Sound sprite "${t}" is not defined.`);const r=Math.max(0,e.time??0),s=i.start+r;if(s>=i.end)throw new Error(`Sound sprite "${t}" offset (${r}s) exceeds clip duration (${i.end-i.start}s).`);const n=e.loop??i.loop,o=z(e.playbackRate??this._playbackRate,.1,20);return void 0!==e.volume&&this.setVolume(e.volume),void 0!==e.muted&&this.setMuted(e.muted),this._enqueuePooledPlay({offset:s,duration:n?void 0:i.end-s,loop:n,loopStart:i.start,loopEnd:i.end,playbackRate:o}),this.onStart.dispatch(),this}stopPooled(){return this._pooledSources.length>0&&(this._stopPooledSources(),this.onStop.dispatch()),this._queuedPooledPlays.length=0,this}pause(t){if(t&&this.applyOptions(t),this._paused&&0===this._pooledSources.length)return this;if(!this._paused&&this._audioSetup){const t=this.duration,e=this.currentTime;this._currentTime=t>0?e%t:0}const e=this._pooledSources.length>0;this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0;const i=!this._paused||e;return this._paused=!0,i&&this.onStop.dispatch(),this}destroy(){super.destroy(),pr.clearByContext(this),this._audioSetup?.gainNode.disconnect(),this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0,this._sprites.clear()}createSourceNode(t){const{audioContext:e}=t;this._stopPrimarySource();const i=this._createBufferSourceNode(t,{offset:Math.min(Math.max(0,this._currentTime),Math.max(0,this.duration)),duration:void 0,loop:this._loop,loopStart:0,loopEnd:this.duration,playbackRate:this._playbackRate});i.onended=()=>{this._sourceNode===i&&(this._sourceNode=null,this._startTime=0,this._currentTime=0,this._paused||(this._paused=!0,this.onStop.dispatch()))},this._sourceNode=i,this._startTime=e.currentTime}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination),this._audioSetup={audioContext:t,gainNode:e},this._paused||this.createSourceNode(this._audioSetup),this._flushQueuedPooledPlays()}_enqueuePooledPlay(t){this._audioSetup?this._playPooledNow(t):this._queuedPooledPlays.push(t)}_flushQueuedPooledPlays(){if(!this._audioSetup||0===this._queuedPooledPlays.length)return;const t=[...this._queuedPooledPlays];this._queuedPooledPlays.length=0;for(const e of t)this._playPooledNow(e)}_playPooledNow(t){if(!this._audioSetup)return;const e=this._createBufferSourceNode(this._audioSetup,t);e.onended=()=>{const t=this._pooledSources.indexOf(e);-1!==t&&this._pooledSources.splice(t,1),e.disconnect()},this._pooledSources.push(e),this._trimPooledSources()}_trimPooledSources(){for(;this._pooledSources.length>this._poolSize;){const t=this._pooledSources.shift();t&&(t.onended=null,this._stopSourceNode(t))}}_stopPrimarySource(){this._sourceNode&&(this._sourceNode.onended=null,this._stopSourceNode(this._sourceNode),this._sourceNode=null,this._startTime=0)}_stopPooledSources(){for(const t of this._pooledSources)t.onended=null,this._stopSourceNode(t);this._pooledSources.length=0}_stopSourceNode(t){try{t.stop(0)}catch{}t.disconnect()}_createBufferSourceNode(t,e){const{gainNode:i}=t,r=t.audioContext.createBufferSource();r.buffer=this._audioBuffer,r.loop=e.loop,r.playbackRate.value=e.playbackRate,e.loop&&(r.loopStart=e.loopStart??0,r.loopEnd=e.loopEnd??this.duration),r.connect(i);const s=e.duration;return!e.loop&&void 0!==s&&s>0?r.start(0,e.offset,s):r.start(0,e.offset),r}}class vr extends Ye{onStart=new F;onStop=new F;_videoElement;_duration;_volume=1;_playbackRate=1;_loop=!1;_muted=!1;_audioSetup=null;_textureDirty=!0;_lastVideoTime=Number.NaN;_videoFrameCallbackHandle=null;_onMetadataHandler;_onResizeHandler;_onVideoFrameHandler;constructor(t,e,i){super(new $e(t,i));const{duration:r,volume:s,playbackRate:n,loop:o,muted:a}=t;this._videoElement=t,this._duration=r,this._volume=s,this._playbackRate=n,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),mr()?this.setupWithAudioContext(fr()):pr.once(this.setupWithAudioContext,this),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}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:r,time:s,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==r&&(this.playbackRate=r),void 0!==s&&(this.currentTime=s),void 0!==n&&(this.muted=n),this}setVolume(t){const e=z(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,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._videoElement.loop=t),this}setPlaybackRate(t){const e=z(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,10)}return this}render(t){return this.visible&&(this._markTextureDirtyIfPlaybackAdvanced(),this.updateTexture(),super.render(t)),this}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(oe.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(),pr.clearByContext(this),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()}_markTextureDirtyIfPlaybackAdvanced(){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,10),e.connect(t.destination);const i=t.createMediaElementSource(this._videoElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class br{}class Tr{}class Sr{}class Cr{}class Mr{_factories=new Map;register(t,e){this._factories.set(t,e)}resolve(t){let e,i=t;for(;null!==i&&!e;)if(e=this._factories.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No factory registered for ${t.name}. Register one with loader.register() before loading.`);return e}has(t){let e=t;for(;null!==e;){if(this._factories.has(e))return!0;const t=Object.getPrototypeOf(e.prototype);e=t?.constructor??null}return!1}destroy(){for(const t of this._factories.values())t.destroy();this._factories.clear()}}class Pr{_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 Br extends Pr{storageName="font";_addedFontFaces=[];async process(t){return await t.arrayBuffer()}async create(t,e){if(!e?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:r,addToDocument:s}=e;if(t.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${t.byteLength}.`);const n=await new FontFace(i,t,r).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${t.byteLength} bytes).`)});return!1!==s&&(document.fonts.add(n),this._addedFontFaces.push(n)),n}destroy(){for(const t of this._addedFontFaces)document.fonts.delete(t);this._addedFontFaces.length=0,super.destroy()}}const Er=[{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]}],Rr=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of Er)if(!(e.length<t.pattern.length)&&t.pattern.every((i,r)=>(e[r]&t.mask[r])===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]),r=e.subarray(4,4100),s=r.findIndex((t,e,i)=>66===i[e]&&130===i[e+1]);return!(!i||-1===s)&&"webm"===String.fromCharCode(...r.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],e[5],e[6],e[7]))return!1;const i=String.fromCharCode(e[8],e[9],e[10],e[11]);return"avif"===i||"avis"===i})(t)?"image/avif":"text/plain"};class kr extends Pr{storageName="image";async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??Rr(t)}),r=this.createObjectUrl(i);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(r)};i.addEventListener("load",()=>{s(),t(i)},{once:!0}),i.addEventListener("error",()=>{s(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(Error("Image loading was canceled."))},{once:!0}),i.src=r})}}class Ar extends Pr{storageName="json";async process(t){return await t.json()}async create(t){return t}}const Lr={once:!0};class Fr extends Pr{storageName="music";_audioElements=[];async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:r,playbackOptions:s}=e,n=new Blob([t],{type:i??Rr(t)});return new Promise((t,e)=>{const i=document.createElement("audio");this._audioElements.push(i),i.addEventListener("error",()=>e(Error("Error loading audio source.")),Lr),i.addEventListener("abort",()=>e(Error("Audio loading was canceled.")),Lr),i.addEventListener(r??"canplaythrough",()=>t(new xr(i,s)),Lr),i.preload="auto",i.src=this.createObjectUrl(n)})}destroy(){for(const t of this._audioElements)t.pause(),t.src="",t.load();this._audioElements.length=0,super.destroy()}}class Dr extends Pr{storageName="sound";async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=await yr(t);return new wr(i,{...e.playbackOptions,poolSize:e.poolSize,sprites:e.sprites})}}class Nr extends Pr{storageName="text";async process(t){return await t.text()}async create(t){return t}}class Ir extends Pr{storageName="texture";async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,samplerOptions:r}=e,s=new Blob([t],{type:i??Rr(t)}),n=this.createObjectUrl(s);return new Promise((t,e)=>{const i=new Image,s=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{s(),t(new $e(i,r))},{once:!0}),i.addEventListener("error",()=>{s(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{s(),e(Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const Ur={once:!0};class Vr extends Pr{storageName="video";_videoElements=[];async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:r,playbackOptions:s,samplerOptions:n}=e,o=new Blob([t],{type:i??Rr(t)});return new Promise((t,e)=>{const i=document.createElement("video");this._videoElements.push(i),i.addEventListener("error",()=>e(Error("Video loading error.")),Ur),i.addEventListener("abort",()=>e(Error("Video loading error: cancelled.")),Ur),i.addEventListener("emptied",()=>e(Error("Video loading error: emptied.")),Ur),i.addEventListener(r??"canplaythrough",()=>t(new vr(i,s,n)),Ur),i.preload="auto",i.src=this.createObjectUrl(o)})}destroy(){for(const t of this._videoElements)t.pause(),t.src="",t.load();this._videoElements.length=0,super.destroy()}}class Or extends Pr{storageName="svg";async process(t){return await t.text()}async create(t){const e=new Blob([t],{type:"image/svg+xml"}),i=this.createObjectUrl(e);return new Promise((t,e)=>{const r=new Image,s=()=>{this.revokeObjectUrl(i)};r.addEventListener("load",()=>{s(),t(r)},{once:!0}),r.addEventListener("error",()=>{s(),e(Error("Error loading image source."))},{once:!0}),r.addEventListener("abort",()=>{s(),e(Error("Image loading was canceled."))},{once:!0}),r.src=i})}}class Gr extends Pr{storageName="binary";async process(t){return t.arrayBuffer()}async create(t){return t}}class zr extends Pr{storageName="wasm";async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}const Wr=t=>{const e=t.split(":");let i=0;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};class qr extends Pr{storageName="vtt";async process(t){return t.text()}async create(t){const e=[],i=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n");let r=0;for(;r<i.length&&!i[r].includes("--\x3e");)r++;for(;r<i.length;){const t=i[r].trim();if(t.includes("--\x3e")){const s=t.indexOf("--\x3e"),n=t.slice(0,s).trim(),o=t.slice(s+3).trim().split(/\s+/)[0],a=Wr(n),h=Wr(o);r++;const l=[];for(;r<i.length&&""!==i[r].trim();)l.push(i[r]),r++;e.push(new VTTCue(a,h,l.join("\n")))}else r++}return e}}class Hr 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 Yr(t){return function(t){if(!Xr(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!Xr(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;i.forEach((i,r)=>{const s=`bundle "${e}" entry[${r}]`;if(!Xr(i))throw new Error(`Invalid asset manifest: ${s} must be an object.`);if("function"!=typeof i.type)throw new Error(`Invalid asset manifest: ${s} has an invalid "type" token.`);jr(i.alias,`${s} has an invalid "alias".`),jr(i.path,`${s} has an invalid "path".`);const n=i.type,o=i.alias;t.has(n)||t.set(n,new Set);const a=t.get(n);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${$r(n)}, "${o}") in bundle "${e}".`);a.add(o)})}}(t),t}function Xr(t){return"object"==typeof t&&null!==t}function jr(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function $r(t){return t.name.length>0?t.name:"(anonymous type)"}class Kr{_registry=new Mr;_resources=new Map;_manifest=new Map;_bundles=new Map;_inFlight=new Map;_typeIds=new WeakMap;_preventStoreKeys=new Set;_stores;_resourcePath;_requestOptions;_concurrency;_nextTypeId=1;_backgroundQueue=[];_backgroundActive=0;_backgroundTotal=0;_backgroundLoaded=0;_backgroundResolve=null;onProgress=new F;onBundleProgress=new F;onLoaded=new F;onError=new F;constructor(t={}){this._resourcePath=t.resourcePath??"",this._requestOptions=t.requestOptions??{},this._concurrency=t.concurrency??6,this._stores=t.cache?Array.isArray(t.cache)?t.cache:[t.cache]:[],this._registerBuiltinFactories()}register(t,e){return this._registry.register(t,e),this}add(t,e){const i=t;if("string"==typeof e)this._addManifestEntry(i,e,e);else if(Array.isArray(e))for(const t of e)this._addManifestEntry(i,t,t);else for(const[t,r]of Object.entries(e))this._addManifestEntry(i,t,r);return this}registerManifest(t){const e=Yr(t),i=new Map,r=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 r of s){const s=r.type,n=this._key(s,r.alias),o=i.get(n)??this._getManifestEntry(s,r.alias);if(o&&!this._isManifestDefinitionEquivalent(o,r.path,r.options))throw new Error(`Conflicting asset definition for (${this._describeType(s)}, "${r.alias}") while registering bundle "${t}".`);i.set(n,{path:r.path,options:r.options}),e.push({type:s,alias:r.alias,path:r.path,options:r.options})}r.push([t,e])}for(const[t,e]of r){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 r=i.length;let s=0;const n=new Array;if(0!==r){if(await Promise.all(i.map(async i=>{try{e.background?await this._loadSingleBackground(i.type,i.alias,i.path,i.options):await this._loadSingle(i.type,i.alias,i.options,i.path)}catch(t){n.push({type:i.type,alias:i.alias,error:this._normalizeError(t)})}finally{s++,this._emitBundleProgress(t,s,r,e.onProgress)}})),n.length>0)throw new Hr(t,n)}else this._emitBundleProgress(t,0,0,e.onProgress)}hasBundle(t){const e=this._bundles.get(t);return!!e&&e.every(t=>this._hasResource(t.type,t.alias))}async load(t,e,i){const r=t;if("string"==typeof e)return this._loadSingle(r,e,i);if(Array.isArray(e))return Promise.all(e.map(t=>this._loadSingle(r,t,i)));const s=Object.entries(e),n={};return await Promise.all(s.map(async([t,e])=>{n[t]=await this._loadSingle(r,t,i,e)})),n}backgroundLoad(){for(const[t,e]of this._manifest)for(const[i,r]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:r.path,options:r.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,r=this._resources.get(i);if(!r?.has(e))throw new Error(`Missing resource "${e}" for type ${i.name}.`);return r.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}unload(t,e){const i=t,r=this._key(i,e);return this._resources.get(i)?.delete(e),this._inFlight.has(r)&&this._preventStoreKeys.add(r),this}unloadAll(t){if(t)this._resources.get(t)?.clear();else for(const t of this._resources.values())t.clear();return this}get resourcePath(){return this._resourcePath}set resourcePath(t){this._resourcePath=t}get requestOptions(){return this._requestOptions}set requestOptions(t){this._requestOptions=t}destroy(){this._registry.destroy();for(const t of this._stores)t.destroy();this._resources.clear(),this._manifest.clear(),this._bundles.clear(),this._inFlight.clear(),this._preventStoreKeys.clear(),this._backgroundQueue.length=0,this.onProgress.destroy(),this.onBundleProgress.destroy(),this.onLoaded.destroy(),this.onError.destroy()}async _loadSingle(t,e,i,r){if(this._hasResource(t,e))return this._resources.get(t).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 n=this._getManifestEntry(t,e),o=r??n?.path??e,a=i??n?.options;return this._trackInFlight(s,this._fetch(t,e,o,a))}_loadSingleBackground(t,e,i,r){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const s=this._key(t,e),n=this._inFlight.get(s);if(n)return n;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:r}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(s);return o||this._waitForBackgroundEntry(t,e)}async _fetch(t,e,i,r){const s=this._registry.resolve(t),n=this._resolveUrl(i);let o=null;for(const i of this._stores)if(o=await i.load(s.storageName,e),null!=o)try{const i=await s.create(o,r);return this._storeResource(t,e,i),i}catch{await i.delete(s.storageName,e),o=null}const a=await fetch(n,this._requestOptions);if(!a.ok)throw new Error(`Failed to fetch "${e}" from "${n}" (${a.status} ${a.statusText}).`);o=await s.process(a);const h=await s.create(o,r).catch(t=>{const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to create "${e}" from "${n}": ${i}`)});for(const t of this._stores)try{await t.save(s.storageName,e,o)}catch{}return this._storeResource(t,e,h),h}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const t=this._backgroundQueue.shift(),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[r]=this._backgroundQueue.splice(i,1);this._startBackgroundEntry(r)}_isQueuedInBackground(t,e){return this._backgroundQueue.some(i=>i.type===t&&i.alias===e)}_waitForBackgroundEntry(t,e){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const i=this._key(t,e),r=this._inFlight.get(i);return r||new Promise((r,s)=>{const n=(i,s,n)=>{i===t&&s===e&&(a(),r(n))},o=(i,r,n)=>{i===t&&r===e&&(a(),s(n))},a=()=>{this.onLoaded.remove(n),this.onError.remove(o)};this.onLoaded.add(n),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(r,s);this._hasResource(t,e)&&(a(),r(this._resources.get(t).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,r){this.onBundleProgress.dispatch(t,e,i),r&&r(e,i)}_addManifestEntry(t,e,i,r){this._manifest.has(t)||this._manifest.set(t,new Map),this._manifest.get(t).set(e,{path:i,options:r})}_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 r=t,s=e,n=Object.keys(r),o=Object.keys(s);if(n.length!==o.length)return!1;for(const t of n){if(!Object.prototype.hasOwnProperty.call(s,t))return!1;if(!this._areOptionsEquivalent(r[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 r=this._key(t,e);this._preventStoreKeys.delete(r)||(this._resources.has(t)||this._resources.set(t,new Map),this._resources.get(t).set(e,i),this.onLoaded.dispatch(t,e,i))}_key(t,e){let i=this._typeIds.get(t);return void 0===i&&(i=this._nextTypeId++,this._typeIds.set(t,i)),`${i}:${e}`}_resolveUrl(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?t:`${this._resourcePath}${t}`}_registerBuiltinFactories(){this._registry.register($e,new Ir),this._registry.register(wr,new Dr),this._registry.register(xr,new Fr),this._registry.register(vr,new Vr),this._registry.register(br,new Ar),this._registry.register(Tr,new Nr),this._registry.register(Sr,new Or),this._registry.register(Cr,new qr),this._registry.register(ArrayBuffer,new Gr),"undefined"!=typeof FontFace&&this._registry.register(FontFace,new Br),"undefined"!=typeof HTMLImageElement&&this._registry.register(HTMLImageElement,new kr),"undefined"!=typeof WebAssembly&&this._registry.register(WebAssembly.Module,new zr)}}var Qr;!function(t){t[t.Loading=1]="Loading",t[t.Running=2]="Running",t[t.Halting=3]="Halting",t[t.Stopped=4]="Stopped"}(Qr||(Qr={}));const Zr={type:"auto"},Jr={width:800,height:600,clearColor:Q.cornflowerBlue,debug:!1,spriteRendererBatchSize:4096,particleRendererBatchSize:8192,primitiveRendererBatchSize:65536,gamepadDefinitions:[],pointerDistanceThreshold:10,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1},resourcePath:"",requestOptions:{method:"GET",mode:"cors",cache:"default"},cache:void 0,backend:Zr};class ts{options;canvas;loader;inputManager;sceneManager;onResize=new F;_updateHandler;_startupClock=new L;_activeClock=new L;_frameClock=new L;_status=Qr.Stopped;_frameCount=0;_frameRequest=0;_backendType;_renderManager;constructor(t){this.options={canvas:t?.canvas??document.createElement("canvas"),...Jr,...t,backend:t?.backend??Zr},this.canvas=this.options.canvas,this.canvas.hasAttribute("tabindex")||this.canvas.setAttribute("tabindex","-1"),this.loader=new Kr({resourcePath:this.options.resourcePath,requestOptions:this.options.requestOptions,cache:this.options.cache}),this._backendType=this.resolveInitialBackendType(),this._renderManager=this.createRenderManager(this._backendType),this.inputManager=new Zi(this),this.sceneManager=new Te(this),this._updateHandler=this.update.bind(this),this._startupClock.start()}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 renderManager(){return this._renderManager}async start(t){if(this._status===Qr.Stopped){this._status=Qr.Loading;try{await this.initializeRenderManager(),await this.sceneManager.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._activeClock.start(),this._status=Qr.Running}catch(t){throw this._status=Qr.Stopped,t}}return this}update(){if(this._status===Qr.Running){const t=this._frameClock.elapsedTime,e=performance.now();this.renderManager.resetStats(),this.inputManager.update();const i=this.renderManager.view;i&&"function"==typeof i.update&&i.update(t.milliseconds),this.sceneManager.update(t),this.renderManager.flush(),this.renderManager.stats.frameTimeMs=performance.now()-e,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===Qr.Running&&(this._status=Qr.Halting,cancelAnimationFrame(this._frameRequest),this.sceneManager.setScene(null).catch(t=>{console.error("Application.stop() failed to unload the active scene.",t)}),this._activeClock.stop(),this._frameClock.stop(),this._status=Qr.Stopped),this}resize(t,e){return this.renderManager.resize(t,e),this.onResize.dispatch(t,e,this),this}destroy(){this.stop(),this.loader.destroy(),this.inputManager.destroy(),this._renderManager.destroy(),this.sceneManager.destroy(),this._startupClock.destroy(),this._activeClock.destroy(),this._frameClock.destroy(),this.onResize.destroy()}resolveInitialBackendType(){const t=this.options.backend?.type;return"webgl2"===t?"webgl2":"webgpu"===t||this.canUseWebGpu()?"webgpu":"webgl2"}createRenderManager(t){return"webgpu"===t?new pi(this):new ei(this)}async initializeRenderManager(){try{await this._renderManager.initialize()}catch(t){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw t;this._renderManager.destroy(),this._backendType="webgl2",this._renderManager=this.createRenderManager(this._backendType),await this._renderManager.initialize()}}canUseWebGpu(){return!!navigator.gpu}}class es{static maxSceneNodes=50;static maxLevel=5;level;_bounds;_quadTrees=new Map;_sceneNodes=new Set;constructor(t,e=0){this._bounds=t.clone(),this.level=e}addSceneNode(t){const e=this._getQuadTree(t);return e?(e.addSceneNode(t),this):(this._sceneNodes.add(t),this._sceneNodes.size>es.maxSceneNodes&&this.level<es.maxLevel&&this._split(),this)}getRelatedChildren(t){const e=this._getQuadTree(t);return null===e?[...this._sceneNodes]:[...e.getRelatedChildren(t),...this._sceneNodes]}getBounds(){return this._bounds}clear(){if(this._quadTrees.size>0){for(const t of this._quadTrees.values())t.destroy();this._quadTrees.clear()}return this._sceneNodes.clear(),this}destroy(){this.clear(),this._bounds.destroy()}_getQuadTree(t){if(this._quadTrees.size>0){const e=t.getBounds();for(const t of this._quadTrees.values())if(t.getBounds().containsRect(e))return t}return null}_split(){if(0===this._quadTrees.size){const{top:t,left:e,width:i,height:r}=this.getBounds(),s=i/2|0,n=r/2|0,o=this.level+1;this._quadTrees.set(0,new es(oe.temp.set(e,t,s,n),o)),this._quadTrees.set(1,new es(oe.temp.set(e+s,t,s,n),o)),this._quadTrees.set(2,new es(oe.temp.set(e,t+n,s,n),o)),this._quadTrees.set(3,new es(oe.temp.set(e+s,t+n,s,n),o))}this._passSceneNodesToQuadTrees()}_passSceneNodesToQuadTrees(){for(const t of this._sceneNodes){const e=this._getQuadTree(t);e&&(this._sceneNodes.delete(t),e.addSceneNode(t))}}}class is extends ye{_children=[];_sortableChildren=!1;_sortDirty=!1;_nextChildOrder=0;get children(){return this._children}get sortableChildren(){return this._sortableChildren}set sortableChildren(t){this._sortableChildren!==t&&(this._sortableChildren=t,this._sortDirty=t)}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this.scale.x=t/this.bounds.width}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this.scale.y=t/this.bounds.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.parentNode&&t.parentNode.removeChild(t),t.parentNode=this,t.setChildOrder(this._nextChildOrder++),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache()),this}swapChildren(t,e){if(t!==e){const i=this.getChildIndex(t),r=this.getChildIndex(e);this._children[i]=e,this._children[r]=t,this.markSortDirty(),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 B(this._children,this.getChildIndex(t),1),this._children.splice(e,0,t),this.markSortDirty(),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 B(this._children,t,1),e&&e.parentNode===this&&(e.parentNode=null),this.markSortDirty(),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.");for(let i=t;i<e;i++){const t=this._children[i];t&&t.parentNode===this&&(t.parentNode=null)}return B(this._children,t,i),this.markSortDirty(),this.invalidateCache(),this}render(t){return this.visible&&0!==this._children.length?this.inView(t.view)?(this.renderVisualContent(t,()=>{this._sortChildrenIfNeeded();for(const e of this._children)e.render(t)}),this):(t.stats.culledNodes++,this):this}contains(t,e){return this._children.some(i=>i.contains(t,e))}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()}markSortDirty(){return this._sortableChildren&&(this._sortDirty=!0),this}sortChildren(){return!this._sortableChildren||!this._sortDirty||this._children.length<=1?(this._sortDirty=!1,this):(this._children.sort((t,e)=>t.zIndex===e.zIndex?t.childOrder-e.childOrder:t.zIndex-e.zIndex),this._sortDirty=!1,this.invalidateCache(),this)}_sortChildrenIfNeeded(){this._sortableChildren&&this._sortDirty&&this.sortChildren()}}class rs{_app=null;_root=new is;_stackMode="overlay";_inputMode="capture";static create(t){return Object.assign(new rs,t)}constructor(){}get app(){return this._app}set app(t){this._app=t}get root(){return this._root}get stackMode(){return this._stackMode}set stackMode(t){this._stackMode=t}get inputMode(){return this._inputMode}set inputMode(t){this._inputMode=t}addChild(t){return this._root.addChild(t),this}removeChild(t){return this._root.removeChild(t),this}setParticipationPolicy(t){return t.mode&&(this._stackMode=t.mode),t.input&&(this._inputMode=t.input),this}getParticipationPolicy(){return{mode:this._stackMode,input:this._inputMode}}load(t){}init(t){}update(t){}draw(t){}handleInput(t){}unload(t){}destroy(){this._root.destroy(),this._app=null}}class ss extends L{_limit;constructor(t,e=!1){super(),this._limit=t.clone(),e&&this.restart()}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/s.seconds}get remainingMinutes(){return this.remainingMilliseconds/s.minutes}get remainingHours(){return this.remainingMilliseconds/s.hours}}class ns{_media;_fftSize;_minDecibels;_maxDecibels;_smoothingTimeConstant;_frequencyBinCount;_timeDomainData;_frequencyData;_preciseTimeDomainData;_preciseFrequencyData;_analyser=null;_audioContext=null;_analyserTarget=null;constructor(t,e={}){const{fftSize:i,minDecibels:r,maxDecibels:s,smoothingTimeConstant:n}=e;this._media=t,this._fftSize=i??2048,this._minDecibels=r??-100,this._maxDecibels=s??-30,this._smoothingTimeConstant=n??.8,this._frequencyBinCount=this._fftSize/2,this._timeDomainData=new Uint8Array(this._frequencyBinCount),this._frequencyData=new Uint8Array(this._frequencyBinCount),this._preciseTimeDomainData=new Float32Array(this._frequencyBinCount),this._preciseFrequencyData=new Float32Array(this._frequencyBinCount),mr()?this.setupWithAudioContext(fr()):pr.once(this.setupWithAudioContext,this)}connect(){if(!this._analyser||null!==this._analyserTarget)return this;const t=this._media.analyserTarget;if(!t)throw new Error("No AudioNode on property analyserTarget.");return this._analyserTarget=t,t.connect(this._analyser),this}get timeDomainData(){return this._analyser&&(this.connect(),this._analyser.getByteTimeDomainData(this._timeDomainData)),this._timeDomainData}get frequencyData(){return this._analyser&&(this.connect(),this._analyser.getByteFrequencyData(this._frequencyData)),this._frequencyData}get preciseTimeDomainData(){return this._analyser&&(this.connect(),this._analyser.getFloatTimeDomainData(this._preciseTimeDomainData)),this._preciseTimeDomainData}get preciseFrequencyData(){return this._analyser&&(this.connect(),this._analyser.getFloatFrequencyData(this._preciseFrequencyData)),this._preciseFrequencyData}destroy(){pr.clearByContext(this),this._analyserTarget?.disconnect(),this._analyser?.disconnect()}setupWithAudioContext(t){this._audioContext=t,this._analyser=t.createAnalyser(),this._analyser.fftSize=this._fftSize,this._analyser.minDecibels=this._minDecibels,this._analyser.maxDecibels=this._maxDecibels,this._analyser.smoothingTimeConstant=this._smoothingTimeConstant}}const os=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]]]),as=new Map([["ButtonNorth",wi.ButtonNorth],["ButtonWest",wi.ButtonWest],["ButtonEast",wi.ButtonEast],["ButtonSouth",wi.ButtonSouth],["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]]),hs=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"]]),ls=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"]]),us=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"]]),cs=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"]]),ds=new Map([[vi.GenericDualAnalog,hs],[vi.Xbox,ls],[vi.PlayStation,us],[vi.SwitchPro,cs],[vi.JoyConLeft,cs],[vi.JoyConRight,cs],[vi.GameCube,hs],[vi.SteamController,hs],[vi.ArcadeStick,hs]]);class _s{static controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];static getControlPosition(t){return os.get(t)??[.5,.5]}static getControlLabels(t){return ds.get(t)??hs}static buildControlChannelMap(){return as}}class ps{static triggerThreshold=300;channels=new Set;triggerTimer;valueState=0;onStart=new F;onStop=new F;onActive=new F;onTrigger=new F;constructor(t,{onStart:e,onStop:i,onActive:r,onTrigger:s,context:n,threshold:o}={}){this.channels=new Set(Array.isArray(t)?t:[t]),this.triggerTimer=new ss(T(o??ps.triggerThreshold)),e&&this.onStart.add(e,n),i&&this.onStop.add(i,n),r&&this.onActive.add(r,n),s&&this.onTrigger.add(s,n)}get activeChannels(){return this.channels}get value(){return this.valueState}update(t){this.valueState=0;for(const e of this.channels)this.valueState=Math.max(t[e],this.valueState);return this.valueState?(this.triggerTimer.running||(this.triggerTimer.restart(),this.onStart.dispatch(this.valueState)),this.onActive.dispatch(this.valueState)):this.triggerTimer.running&&(this.onStop.dispatch(this.valueState),this.triggerTimer.expired||this.onTrigger.dispatch(this.valueState),this.triggerTimer.stop()),this}destroy(){this.channels.clear(),this.triggerTimer.destroy(),this.onStart.destroy(),this.onStop.destroy(),this.onActive.destroy(),this.onTrigger.destroy()}}function fs(t,e,i=2){const r=e&&e.length,s=r?e[0]*i:t.length;let n=ms(t,0,s,i,!0);const o=[];if(!n||n.next===n.prev)return o;let a,h,l;if(r&&(n=function(t,e,i,r){const s=[];for(let i=0,n=e.length;i<n;i++){const o=ms(t,e[i]*r,i<n-1?e[i+1]*r:t.length,r,!1);o===o.next&&(o.steiner=!0),s.push(Ps(o))}s.sort(Ts);for(let t=0;t<s.length;t++)i=Ss(s[t],i);return i}(t,e,n,i)),t.length>80*i){a=t[0],h=t[1];let e=a,r=h;for(let n=i;n<s;n+=i){const i=t[n],s=t[n+1];i<a&&(a=i),s<h&&(h=s),i>e&&(e=i),s>r&&(r=s)}l=Math.max(e-a,r-h),l=0!==l?32767/l:0}return ys(n,o,i,a,h,l,0),o}function ms(t,e,i,r,s){let n;if(s===function(t,e,i,r){let s=0;for(let n=e,o=i-r;n<i;n+=r)s+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return s}(t,e,i,r)>0)for(let s=e;s<i;s+=r)n=Us(s/r|0,t[s],t[s+1],n);else for(let s=i-r;s>=e;s-=r)n=Us(s/r|0,t[s],t[s+1],n);return n&&As(n,n.next)&&(Vs(n),n=n.next),n}function gs(t,e){if(!t)return t;e||(e=t);let i,r=t;do{if(i=!1,r.steiner||!As(r,r.next)&&0!==ks(r.prev,r,r.next))r=r.next;else{if(Vs(r),r=e=r.prev,r===r.next)break;i=!0}}while(i||r!==e);return e}function ys(t,e,i,r,s,n,o){if(!t)return;!o&&n&&function(t,e,i,r){let s=t;do{0===s.z&&(s.z=Ms(s.x,s.y,e,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){let e,i=1;do{let r,s=t;t=null;let n=null;for(e=0;s;){e++;let o=s,a=0;for(let t=0;t<i&&(a++,o=o.nextZ,o);t++);let h=i;for(;a>0||h>0&&o;)0!==a&&(0===h||!o||s.z<=o.z)?(r=s,s=s.nextZ,a--):(r=o,o=o.nextZ,h--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;s=o}n.nextZ=null,i*=2}while(e>1)}(s)}(t,r,s,n);let a=t;for(;t.prev!==t.next;){const h=t.prev,l=t.next;if(n?ws(t,r,s,n):xs(t))e.push(h.i,t.i,l.i),Vs(t),t=l.next,a=l.next;else if((t=l)===a){o?1===o?ys(t=vs(gs(t),e),e,i,r,s,n,2):2===o&&bs(t,e,i,r,s,n):ys(gs(t),e,i,r,s,n,1);break}}}function xs(t){const e=t.prev,i=t,r=t.next;if(ks(e,i,r)>=0)return!1;const s=e.x,n=i.x,o=r.x,a=e.y,h=i.y,l=r.y,u=Math.min(s,n,o),c=Math.min(a,h,l),d=Math.max(s,n,o),_=Math.max(a,h,l);let p=r.next;for(;p!==e;){if(p.x>=u&&p.x<=d&&p.y>=c&&p.y<=_&&Es(s,a,n,h,o,l,p.x,p.y)&&ks(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function ws(t,e,i,r){const s=t.prev,n=t,o=t.next;if(ks(s,n,o)>=0)return!1;const a=s.x,h=n.x,l=o.x,u=s.y,c=n.y,d=o.y,_=Math.min(a,h,l),p=Math.min(u,c,d),f=Math.max(a,h,l),m=Math.max(u,c,d),g=Ms(_,p,e,i,r),y=Ms(f,m,e,i,r);let x=t.prevZ,w=t.nextZ;for(;x&&x.z>=g&&w&&w.z<=y;){if(x.x>=_&&x.x<=f&&x.y>=p&&x.y<=m&&x!==s&&x!==o&&Es(a,u,h,c,l,d,x.x,x.y)&&ks(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,w.x>=_&&w.x<=f&&w.y>=p&&w.y<=m&&w!==s&&w!==o&&Es(a,u,h,c,l,d,w.x,w.y)&&ks(w.prev,w,w.next)>=0)return!1;w=w.nextZ}for(;x&&x.z>=g;){if(x.x>=_&&x.x<=f&&x.y>=p&&x.y<=m&&x!==s&&x!==o&&Es(a,u,h,c,l,d,x.x,x.y)&&ks(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;w&&w.z<=y;){if(w.x>=_&&w.x<=f&&w.y>=p&&w.y<=m&&w!==s&&w!==o&&Es(a,u,h,c,l,d,w.x,w.y)&&ks(w.prev,w,w.next)>=0)return!1;w=w.nextZ}return!0}function vs(t,e){let i=t;do{const r=i.prev,s=i.next.next;!As(r,s)&&Ls(r,i,i.next,s)&&Ns(r,s)&&Ns(s,r)&&(e.push(r.i,i.i,s.i),Vs(i),Vs(i.next),i=t=s),i=i.next}while(i!==t);return gs(i)}function bs(t,e,i,r,s,n){let o=t;do{let t=o.next.next;for(;t!==o.prev;){if(o.i!==t.i&&Rs(o,t)){let a=Is(o,t);return o=gs(o,o.next),a=gs(a,a.next),ys(o,e,i,r,s,n,0),void ys(a,e,i,r,s,n,0)}t=t.next}o=o.next}while(o!==t)}function Ts(t,e){let i=t.x-e.x;if(0===i&&(i=t.y-e.y,0===i)){i=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)}return i}function Ss(t,e){const i=function(t,e){let i=e;const r=t.x,s=t.y;let n,o=-1/0;if(As(t,i))return i;do{if(As(t,i.next))return i.next;if(s<=i.y&&s>=i.next.y&&i.next.y!==i.y){const t=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=r&&t>o&&(o=t,n=i.x<i.next.x?i:i.next,t===r))return n}i=i.next}while(i!==e);if(!n)return null;const a=n,h=n.x,l=n.y;let u=1/0;i=n;do{if(r>=i.x&&i.x>=h&&r!==i.x&&Bs(s<l?r:o,s,h,l,s<l?o:r,s,i.x,i.y)){const e=Math.abs(s-i.y)/(r-i.x);Ns(i,t)&&(e<u||e===u&&(i.x>n.x||i.x===n.x&&Cs(n,i)))&&(n=i,u=e)}i=i.next}while(i!==a);return n}(t,e);if(!i)return e;const r=Is(i,t);return gs(r,r.next),gs(i,i.next)}function Cs(t,e){return ks(t.prev,t,e.prev)<0&&ks(e.next,t,t.next)<0}function Ms(t,e,i,r,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*s|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Ps(t){let e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function Bs(t,e,i,r,s,n,o,a){return(s-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(r-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(s-o)*(r-a)}function Es(t,e,i,r,s,n,o,a){return!(t===o&&e===a)&&Bs(t,e,i,r,s,n,o,a)}function Rs(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&Ls(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(Ns(t,e)&&Ns(e,t)&&function(t,e){let i=t,r=!1;const s=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==t);return r}(t,e)&&(ks(t.prev,t,e.prev)||ks(t,e.prev,e))||As(t,e)&&ks(t.prev,t,t.next)>0&&ks(e.prev,e,e.next)>0)}function ks(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function As(t,e){return t.x===e.x&&t.y===e.y}function Ls(t,e,i,r){const s=Ds(ks(t,e,i)),n=Ds(ks(t,e,r)),o=Ds(ks(i,r,t)),a=Ds(ks(i,r,e));return s!==n&&o!==a||(!(0!==s||!Fs(t,i,e))||(!(0!==n||!Fs(t,r,e))||(!(0!==o||!Fs(i,t,r))||!(0!==a||!Fs(i,e,r)))))}function Fs(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function Ds(t){return t>0?1:t<0?-1:0}function Ns(t,e){return ks(t.prev,t,t.next)<0?ks(t,e,t.next)>=0&&ks(t,t.prev,e)>=0:ks(t,e,t.prev)<0||ks(t,t.next,e)<0}function Is(t,e){const i=Os(t.i,t.x,t.y),r=Os(e.i,e.x,e.y),s=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function Us(t,e,i,r){const s=Os(t,e,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function Vs(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Os(t,e,i){return{i:t,x:e,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const Gs=(t,e,i,r,s,n=[],o=[])=>{const a=[t,e,i,r],h=s/2,l=n.length/6,u=new _e(t-i,e-r).perp().normalize().multiply(h),c=new _e(i-t,r-e).perp().normalize().multiply(h);return n.push(t-u.x,e-u.y),n.push(t+u.x,e+u.y),n.push(i-c.x,r-c.y),n.push(i+c.x,r+c.y),o.push(l,l,l+1,l+2,l+3,l+3),new ve({vertices:n,indices:o,points:a})},zs=(t,e,i=[],r=[])=>{if(t.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const s=e/2,n=new _e(t[0],t[1]),o=new _e(t[t.length-2],t[t.length-1]);if(n.x===o.x&&n.y===o.y){(t=t.slice()).pop(),t.pop(),o.set(t[t.length-2],t[t.length-1]);const e=o.x+.5*(n.x-o.x),i=o.y+.5*(n.y-o.y);t.unshift(e,i),t.push(e,i)}const a=t.length/2;let h=t.length,l=i.length/6,u=t[0],c=t[1],d=t[2],_=t[3],p=0,f=0,m=-(c-_),g=u-d,y=0,x=0,w=0,v=0,b=Math.sqrt(m*m+g*g);m/=b,g/=b,m*=s,g*=s,i.push(u-m,c-g),i.push(u+m,c+g);for(let e=1;e<a-1;e++){u=t[2*(e-1)],c=t[2*(e-1)+1],d=t[2*e],_=t[2*e+1],p=t[2*(e+1)],f=t[2*(e+1)+1],m=-(c-_),g=u-d,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=s,g*=s,y=-(_-f),x=d-p,b=Math.sqrt(y*y+x*x),y/=b,x/=b,y*=s,x*=s;const r=-g+c-(-g+_),n=-m+d-(-m+u),o=(-m+u)*(-g+_)-(-m+d)*(-g+c),a=-x+f-(-x+_),l=-y+d-(-y+p),T=(-y+p)*(-x+_)-(-y+d)*(-x+f);let S=r*l-a*n;if(Math.abs(S)<.1){S+=10.1,i.push(d-m,_-g),i.push(d+m,_+g);continue}const C=(n*T-l*o)/S,M=(a*o-r*T)/S;(C-d)*(C-d)+(M-_)*(M-_)>196*s*s?(w=m-y,v=g-x,b=Math.sqrt(w*w+v*v),w/=b,v/=b,w*=s,v*=s,i.push(d-w,_-v),i.push(d+w,_+v),i.push(d-w,_-v),h++):(i.push(C,M),i.push(d-(C-d),_-(M-_)))}u=t[2*(a-2)],c=t[2*(a-2)+1],d=t[2*(a-1)],_=t[2*(a-1)+1],m=-(c-_),g=u-d,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=s,g*=s,i.push(d-m,_-g),i.push(d+m,_+g),r.push(l);for(let t=0;t<h;t++)r.push(l++);return r.push(l-1),new ve({vertices:i,indices:r,points:t})},Ws=(t,e,i,r=[],s=[])=>{const n=Math.floor(15*Math.sqrt(i+i)),o=2*Math.PI/n,a=[];let h=r.length/6;s.push(h);for(let l=0;l<n+1;l++){const n=t+Math.sin(o*l)*i,u=e+Math.cos(o*l)*i;a.push(n,u),r.push(t,e),r.push(n,u),s.push(h++,h++)}return s.push(h-1),new ve({vertices:r,indices:s,points:a})},qs=(t,e,i,r,s=[],n=[])=>{const o=Math.floor(15*Math.sqrt(i+r)),a=2*Math.PI/o,h=[];let l=s.length/6;n.push(l);for(let u=0;u<o+1;u++){const o=t+Math.sin(a*u)*i,c=e+Math.cos(a*u)*r;h.push(o,c),s.push(t,e),s.push(o,c),n.push(l++,l++)}return n.push(l-1),new ve({vertices:s,indices:n,points:h})},Hs=(t,e=[],i=[])=>{if(t.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const r=e.length/6,s=t.length/2,n=fs(t,[],2);if(n){for(let t=0;t<n.length;t+=3)i.push(n[t]+r),i.push(n[t]+r),i.push(n[t+1]+r),i.push(n[t+2]+r),i.push(n[t+2]+r);for(let i=0;i<s;i++)e.push(t[2*i],t[2*i+1])}return new ve({vertices:e,indices:i,points:t})},Ys=(t,e,i,r,s=[],n=[])=>{const o=[t,e,t+i,e,t,e+r,t+i,e+r],a=s.length/6;return s.push(...o),n.push(a,a,a+1,a+2,a+3,a+3),new ve({vertices:s,indices:n,points:o})},Xs=(t,e,i,r,s=r/2,n=0)=>{const o=Math.PI/-2+n,a=2*i,h=D/a,l=[];for(let i=0;i<a;i++){const n=o+i*h,a=i%2?s:r;l.push(t+a*Math.cos(n),e+a*Math.sin(n))}return Hs(l)};let js=null;class $s{collisionType=pt.Line;_fromPosition;_toPosition;constructor(t=0,e=0,i=0,r=0){this._fromPosition=new _e(t,e),this._toPosition=new _e(i,r)}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,r){return this._fromPosition.set(t,e),this._toPosition.set(i,r),this}copy(t){return this._fromPosition.copy(t.fromPosition),this.toPosition.copy(t.toPosition),this}clone(){return new $s(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:t,fromY:e,toX:i,toY:r}=this,s=Math.min(t,i),n=Math.min(e,r);return new oe(s,n,Math.max(t,i)-s,Math.max(e,r)-n)}getNormals(){return[]}project(t,e=new _t){return e}intersectsWith(t){switch(t.collisionType){case pt.SceneNode:return Dt(this,t.getBounds());case pt.Rectangle:return Dt(this,t);case pt.Polygon:return Ut(this,t);case pt.Circle:return Nt(this,t);case pt.Ellipse:return It(this,t);case pt.Line:return Ft(this,t);case pt.Point:return Et(t,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return Et(_e.temp.set(t,e),this,i)}equals({fromX:t,fromY:e,toX:i,toY:r}={}){return!(void 0!==t&&this.fromX!==t||void 0!==e&&this.fromY!==e||void 0!==i&&this.toX!==i||void 0!==r&&this.toY!==r)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===js&&(js=new $s),js}}let Ks=null;class Qs{static collisionSegments=32;collisionType=pt.Circle;_position;_collisionVertices=null;_radius;constructor(t=0,e=0,i=0){this._position=new _e(t,e),this._radius=i}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=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t){return this._radius=t,this}set(t,e,i){return this._position.set(t,e),this._radius=i,this}copy(t){return this._position.copy(t.position),this._radius=t.radius,this}clone(){return new Qs(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 oe(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){return this.getCollisionVertices().map((t,e,i)=>i[(e+1)%i.length].clone().subtract(t.x,t.y).rperp().normalize())}project(t,e=new _t){const i=t.dot(this.x,this.y),r=this.radius*t.length;return e.set(i-r,i+r)}contains(t,e){return kt(_e.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case pt.SceneNode:return Ot(t.getBounds(),this);case pt.Rectangle:return Ot(t,this);case pt.Polygon:return jt(this,t);case pt.Circle:return Wt(this,t);case pt.Ellipse:return qt(this,t);case pt.Line:return Nt(t,this);case pt.Point:return kt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case pt.SceneNode:return te(this,t.getBounds());case pt.Rectangle:return te(this,t);case pt.Polygon:return ee(t,this,!0);case pt.Circle:return Jt(this,t);default:return null}}destroy(){this._position.destroy()}getCollisionVertices(){if(null===this._collisionVertices){this._collisionVertices=[];for(let t=0;t<Qs.collisionSegments;t++)this._collisionVertices.push(this.getCollisionVertex(t))}return this._collisionVertices}getCollisionVertex(t){const e=2*t*Math.PI/Qs.collisionSegments-Math.PI/2,i=Math.cos(e)*this._radius,r=Math.sin(e)*this._radius;return new _e(this._radius+i,this._radius+r)}static get temp(){return null===Ks&&(Ks=new Qs),Ks}}class Zs{collisionType=pt.Ellipse;_position;_radius;constructor(t=0,e=0,i=0,r=i){this._position=new _e(t,e),this._radius=new _e(i,r)}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,r){return this._position.set(t,e),this._radius.set(i,r),this}copy(t){return this._position.copy(t.position),this._radius.copy(t.radius),this}clone(){return new Zs(this.x,this.y,this.rx,this.ry)}getBounds(){return new oe(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new _t){return e}intersectsWith(t){switch(t.collisionType){case pt.SceneNode:return Gt(t.getBounds(),this);case pt.Rectangle:return Gt(t,this);case pt.Polygon:return Kt(this,t);case pt.Circle:return qt(t,this);case pt.Ellipse:return $t(this,t);case pt.Line:return It(t,this);case pt.Point:return At(t,this);default:return!1}}collidesWith(t){return null}contains(t,e){return At(_e.temp.set(t,e),this)}equals({x:t,y:e,rx:i,ry:r}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.rx!==i||void 0!==r&&this.ry!==r)}destroy(){this._position.destroy(),this._radius.destroy()}}let Js=null;class tn{collisionType=pt.Polygon;_position;_points=[];_edges=[];_normals=[];constructor(t=[],e=0,i=0){this._position=new _e(e,i),this.setPoints(t)}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 points(){return this._points}set points(t){this.setPoints(t)}get edges(){return this._edges}get normals(){return this._normals}setPosition(t,e){return this._position.set(t,e),this}setPoints(t){const e=this._points.length,i=t.length,r=e-i,s=Math.min(e,i);for(let e=0;e<s;e++)this._points[e].copy(t[e]);if(r>0)this._points.splice(i).forEach(t=>t.destroy()),this._edges.splice(i).forEach(t=>t.destroy()),this._normals.splice(i).forEach(t=>t.destroy());else if(r<0)for(let r=e;r<i;r++)this._points.push(t[r].clone()),this._edges.push(t[r].clone()),this._normals.push(t[r].clone());for(let t=0;t<i;t++){const e=this._points[t],r=this._points[(t+1)%i];this._edges[t].set(r.x-e.x,r.y-e.y),this._normals[t].copy(this._edges[t]).rperp().normalize()}return this}set(t,e,i){return this._position.set(t,e),this.setPoints(i),this}copy(t){return this._position.copy(t.position),this.setPoints(t.points),this}clone(){return new tn(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,r=-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),r=Math.max(s.y,r);return new oe(this.x+t,this.y+e,i-t,r-e)}getNormals(){return this._normals}project(t,e=new _t){const i=t.clone().normalize(),r=this._points.map(t=>i.dot(t.x,t.y));return e.set(Math.min(...r),Math.max(...r))}contains(t,e){return Lt(_e.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case pt.SceneNode:return zt(t.getBounds(),this);case pt.Rectangle:return zt(t,this);case pt.Polygon:return Qt(this,t);case pt.Circle:return jt(t,this);case pt.Ellipse:return Kt(t,this);case pt.Line:return Ut(t,this);case pt.Point:return Lt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case pt.SceneNode:case pt.Rectangle:case pt.Polygon:return ie(this,t);case pt.Circle:return ee(this,t);default:return null}}destroy(){for(const t of this._points)t.destroy();this._position.destroy(),this._points.length=0}static get temp(){return null===Js&&(Js=new tn),Js}}let en=null;class rn{_startPoint;_endPoint;constructor(t=0,e=0,i=0,r=0){this._startPoint=new _e(t,e),this._endPoint=new _e(i,r)}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,r){return this._startPoint.set(t,e),this._endPoint.set(i,r),this}copy(t){return this._startPoint.copy(t.startPoint),this._endPoint.copy(t.endPoint),this}clone(){return new rn(this.startX,this.startY,this.endX,this.endY)}equals({startX:t,startY:e,endX:i,endY:r}={}){return!(void 0!==t&&this.startX!==t||void 0!==e&&this.startY!==e||void 0!==i&&this.endX!==i||void 0!==r&&this.endY!==r)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===en&&(en=new rn),en}}class sn{radius;phi;constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new sn(t.length,0)}toVector(){return _e.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}class nn{_fromColor;_toColor;constructor(t,e){this._fromColor=t.clone(),this._toColor=e.clone()}get fromColor(){return this._fromColor}set fromColor(t){this.setFromColor(t)}get toColor(){return this._toColor}set toColor(t){this.setToColor(t)}setFromColor(t){return this._fromColor.copy(t),this}setToColor(t){return this._toColor.copy(t),this}apply(t,e){const i=t.elapsedRatio,{r:r,g:s,b:n,a:o}=this._fromColor,{r:a,g:h,b:l,a:u}=this._toColor;return t.tint.set((a-r)*i+r,(h-s)*i+s,(l-n)*i+n,(u-o)*i+o),this}destroy(){this._fromColor.destroy(),this._toColor.destroy()}}class on{_acceleration;constructor(t,e){this._acceleration=new _e(t,e)}get acceleration(){return this._acceleration}set acceleration(t){this.setAcceleration(t)}setAcceleration(t){return this._acceleration.copy(t),this}apply(t,e){return t.velocity.add(e.seconds*this._acceleration.x,e.seconds*this._acceleration.y),this}destroy(){this._acceleration.destroy()}}class an{_scaleFactor;constructor(t,e){this._scaleFactor=new _e(t,e)}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this.setScaleFactor(t)}setScaleFactor(t){return this._scaleFactor.copy(t),this}apply(t,e){return t.scale.add(e.seconds*this._scaleFactor.x,e.seconds*this._scaleFactor.y),this}destroy(){this._scaleFactor.destroy()}}class hn{_angularAcceleration;constructor(t){this._angularAcceleration=t}get angularAcceleration(){return this._angularAcceleration}set angularAcceleration(t){this.setAngularAcceleration(t)}setAngularAcceleration(t){return this._angularAcceleration=t,this}apply(t,e){return t.rotationSpeed+=e.seconds*this._angularAcceleration,this}destroy(){}}class ln{_totalLifetime;_elapsedLifetime;_position;_velocity;_scale;_tint;_rotation;_rotationSpeed;_textureIndex;constructor(t={}){const{totalLifetime:e,elapsedLifetime:i,position:r,velocity:n,scale:o,rotation:a,rotationSpeed:h,textureIndex:l,tint:u}=t;this._totalLifetime=(e??s.oneSecond).clone(),this._elapsedLifetime=(i??s.zero).clone(),this._position=(r??_e.zero).clone(),this._velocity=(n??_e.zero).clone(),this._scale=(o??_e.one).clone(),this._tint=(u??Q.white).clone(),this._rotation=a??0,this._rotationSpeed=h??0,this._textureIndex=l??0}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=V(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get tint(){return this._tint}set tint(t){this._tint.copy(t)}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class un{_emissionRate;_particleOptions;_emissionDelta=0;constructor(t,e){this._emissionRate=t,this._particleOptions=e??new ln}get emissionRate(){return this._emissionRate}set emissionRate(t){this._emissionRate=t}get particleOptions(){return this._particleOptions}set particleOptions(t){this._particleOptions=t}computeParticleCount(t){const e=this._emissionRate*t.seconds+this._emissionDelta,i=0|e;return this._emissionDelta=e-i,i}apply(t,e){const i=this.computeParticleCount(e),r=this._particleOptions;for(let e=0;e<i;e++){const e=t.requestParticle();e.applyOptions(r),t.emitParticle(e)}return this}destroy(){this._particleOptions.destroy()}}class cn extends ve{constructor(t,e,i){const r=Math.floor(15*Math.sqrt(i+i)),s=2*Math.PI/r,n=[],o=[],a=[];let h=n.length/6;o.push(h);for(let l=0;l<r+1;l++){const r=t+Math.sin(s*l)*i,u=e+Math.cos(s*l)*i;a.push(r,u),n.push(t,e),n.push(r,u),o.push(h++,h++)}o.push(h-1),super({vertices:n,indices:o,points:a})}}class dn extends is{_lineWidth=0;_lineColor=new Q;_fillColor=new Q;_currentPoint=new _e(0,0);get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t}get lineColor(){return this._lineColor}set lineColor(t){this._lineColor.copy(t)}get fillColor(){return this._fillColor}set fillColor(t){this._fillColor.copy(t)}get currentPoint(){return this._currentPoint}getChildAt(t){return super.getChildAt(t)}addChild(t){if(!(t instanceof we))throw new Error("Graphics can only contain DrawableShape children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof we))throw new Error("Graphics can only contain DrawableShape children.");return super.addChildAt(t,e)}moveTo(t,e){return this._currentPoint.set(t,e),this}lineTo(t,e){const{x:i,y:r}=this._currentPoint;return this.drawPath([i,r,t,e]),this.moveTo(t,e),this}quadraticCurveTo(t,e,i,r){const{x:s,y:n}=this._currentPoint;return this.drawPath($(s,n,t,e,i,r)),this.moveTo(i,r),this}bezierCurveTo(t,e,i,r,s,n){const{x:o,y:a}=this._currentPoint;return this.drawPath(j(o,a,t,e,i,r,s,n)),this.moveTo(s,n),this}arcTo(t,e,i,r,s){const{x:n,y:o}=this._currentPoint,a=Math.abs(s);if(0===a||n===t&&o===e||t===i&&e===r)return this.lineTo(t,e);const h=t-n,l=e-o,u=i-t,c=r-e,d=Math.hypot(h,l),_=Math.hypot(u,c);if(0===d||0===_)return this.lineTo(t,e);const p=h/d,f=l/d,m=u/_,g=c/_,y=z(p*m+f*g,-1,1),x=Math.acos(y);if(0===x||x===Math.PI)return this.lineTo(t,e);const w=a/Math.tan(x/2);if(!Number.isFinite(w)||w>d||w>_)return this.lineTo(t,e);const v=t-p*w,b=e-f*w,T=t+m*w,S=e+g*w,C=p*g-f*m>0,M=v+(C?-f:f)*a,P=b+(C?p:-p)*a,B=Math.atan2(b-P,v-M),E=Math.atan2(S-P,T-M);return this.lineTo(v,b),this.drawArc(M,P,a,B,E,C)}drawArc(t,e,i,r,s,n=!1){const o=Math.abs(i);if(0===o)return this;let a=s-r;if(!n&&a<0?a+=D:n&&a>0&&(a-=D),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=r+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,r){return this.addChild(new we(Gs(t,e,i,r,this._lineWidth),this._lineColor,et.TriangleStrip)),this}drawPath(t){return this.addChild(new we(zs(t,this._lineWidth),this._lineColor,et.TriangleStrip)),this}drawPolygon(t){const e=Hs(t);return this.addChild(new we(e,this._fillColor,et.TriangleStrip)),this._lineWidth>0&&this.drawPath(e.points),this}drawCircle(t,e,i){const r=new cn(t,e,i);return this.addChild(new we(r,this._fillColor,et.TriangleStrip)),this._lineWidth>0&&this.drawPath(r.points),this}drawEllipse(t,e,i,r){const s=qs(t,e,i,r);return this.addChild(new we(s,this._fillColor,et.TriangleStrip)),this._lineWidth>0&&this.drawPath(s.points),this}drawRectangle(t,e,i,r){const s=Ys(t,e,i,r);return this.addChild(new we(s,this._fillColor,et.TriangleStrip)),this._lineWidth>0&&this.drawPath(s.points),this}drawStar(t,e,i,r,s=r/2,n=0){const o=Xs(t,e,i,r,s,n);return this.addChild(new we(o,this._fillColor,et.TriangleStrip)),this._lineWidth>0&&this.drawPath(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._lineColor.copy(Q.black),this._fillColor.copy(Q.black),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}}class _n{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:r,w:s,h:n}=e.frame,o=new oe(i,r,s,n),a=new Ye(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(!Array.isArray(e)||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()}}class pn extends Ye{_clips=new Map;_currentClipName=null;_currentFrameIndex=0;_playing=!1;_loopOverride=null;_elapsedFrameTimeMs=0;onComplete=new F;onFrame=new F;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.");if(!Array.isArray(e.frames)||0===e.frames.length)throw new Error(`AnimatedSprite clip "${t}" must define at least one frame.`);const i=e.fps??12;if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid fps value (${i}).`);return this._clips.set(t,{frames:e.frames.map(t=>t.clone()),frameDurationMs:1e3/i,loop:e.loop??!0}),this}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 r=this._currentClipName===t,s=e.restart??!0;return r&&!s||(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,r]of t.animations)e[i]={frames:r.map(e=>t.getFrame(e)),loop:!0};return new pn(t.texture,e)}_applyFrame(t){this.setTextureFrame(t,!1)}}class fn{_align;_fill;_stroke;_strokeThickness;_fontSize;_fontWeight;_fontFamily;_wordWrap;_wordWrapWidth;_baseline;_lineJoin;_miterLimit;_padding;_dirty=!0;constructor(t={}){this._align=t.align??"left",this._fill=t.fill??"black",this._stroke=t.stroke??"black",this._strokeThickness=t.strokeThickness??1,this._fontSize=t.fontSize??20,this._fontWeight=t.fontWeight??"bold",this._fontFamily=t.fontFamily??"Arial",this._wordWrap=t.wordWrap??!1,this._wordWrapWidth=t.wordWrapWidth??100,this._baseline=t.baseline??"alphabetic",this._lineJoin=t.lineJoin??"miter",this._miterLimit=t.miterLimit??10,this._padding=t.padding??0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this._dirty=!0)}get fill(){return this._fill}set fill(t){this._fill!==t&&(this._fill=t,this._dirty=!0)}get stroke(){return this._stroke}set stroke(t){this._stroke!==t&&(this._stroke=t,this._dirty=!0)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this._dirty=!0)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this._dirty=!0)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this._dirty=!0)}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this._dirty=!0)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this._dirty=!0)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this._dirty=!0)}get baseline(){return this._baseline}set baseline(t){this._baseline!==t&&(this._baseline=t,this._dirty=!0)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this._dirty=!0)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this._dirty=!0)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this._dirty=!0)}get dirty(){return this._dirty}set dirty(t){this._dirty=t}get font(){return`${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}apply(t){return t.font=this.font,t.fillStyle=this.fill,t.strokeStyle=this.stroke,t.lineWidth=this.strokeThickness,t.textBaseline=this.baseline,t.lineJoin=this.lineJoin,t.miterLimit=this.miterLimit,this}copy(t){return t!==this&&(this.align=t.align,this.fill=t.fill,this.stroke=t.stroke,this.strokeThickness=t.strokeThickness,this.fontSize=t.fontSize,this.fontWeight=t.fontWeight,this.fontFamily=t.fontFamily,this.wordWrap=t.wordWrap,this.wordWrapWidth=t.wordWrapWidth,this.baseline=t.baseline,this.lineJoin=t.lineJoin,this.miterLimit=t.miterLimit,this.padding=t.padding,this.dirty=t.dirty),this}clone(){return(new fn).copy(this)}}const mn=/(?:\r\n|\r|\n)/;class gn extends Ye{_text;_style;_canvas;_context;_dirty=!0;constructor(t,e,i,r=document.createElement("canvas")){super(new $e(r,i)),this._text=t,this._style=e&&e instanceof fn?e:new fn(e),this._canvas=r,this._context=r.getContext("2d"),this.updateTexture()}get text(){return this._text}set text(t){this.setText(t)}get style(){return this._style}set style(t){this.setStyle(t)}get canvas(){return this._canvas}set canvas(t){this.setCanvas(t)}setText(t){return this._text!==t&&(this._text=t,this._dirty=!0),this}setStyle(t){return this._style=t instanceof fn?t:new fn(t),this._dirty=!0,this}setCanvas(t){return this._canvas!==t&&(this._canvas=t,this._context=this._getContext(t),this._dirty=!0,this.texture.setSource.call(this.texture,t),this.setTextureFrame(oe.temp.set(0,0,t.width,t.height))),this}updateTexture(){if(this._style&&(this._dirty||this._style.dirty)){const t=this._canvas,e=this._context,i=this._style.apply(e),r=i.wordWrap?this.getWordWrappedText():this._text,s=(t=>{if(!Oe.has(t)){const e=document.body,i=document.createElement("div");i.appendChild(document.createTextNode("M")),i.setAttribute("style",`font: ${t};position:absolute;top:0;left:0`),e.appendChild(i),Oe.set(t,i.offsetHeight),e.removeChild(i)}return Oe.get(t)})(e.font)+i.strokeThickness,n=r.split(mn),o=n.map(t=>e.measureText(t)),a=o.reduce((t,e)=>Math.max(t,e.width),0),h=Math.ceil(a+i.strokeThickness+2*i.padding),l=Math.ceil(s*n.length+2*i.padding);h!==t.width||l!==t.height?(t.width=h,t.height=l,this.setTextureFrame(oe.temp.set(0,0,h,l))):e.clearRect(0,0,h,l),i.apply(e);for(let t=0;t<n.length;t++){const r=o[t],h=a-r.width,l="right"===i.align?h:h/2,u=i.padding+i.strokeThickness/2,c=r.actualBoundingBoxLeft+("left"===i.align?0:l)+u,d=r.actualBoundingBoxAscent+s*t+u;i.stroke&&i.strokeThickness&&e.strokeText(n[t],c,d),i.fill&&e.fillText(n[t],c,d)}this.texture.updateSource(),this._dirty=!1,this._style.dirty=!1}return this}getWordWrappedText(){const t=this._context,e=this._style.wordWrapWidth,i=this._text.split("\n"),r=t.measureText(" ").width;let s=e,n="";for(let o=0;o<i.length;o++){const a=i[o].split(" ");o>0&&(n+="\n");for(let i=0;i<a.length;i++){const o=a[i],h=t.measureText(o).width+r;h>s?(i>0&&(n+="\n"),s=e):s-=h,n+=`${o} `}}return n}render(t){return this.visible&&(this.updateTexture(),super.render(t)),this}_getContext(t){const e=t.getContext("2d");if(null===e)throw new Error("Could not create a 2D canvas context.");return e}}class yn{_context;_sampler;_scaleMode;_wrapMode;_premultiplyAlpha;_generateMipMap;_flipY;constructor(t,e){const{scaleMode:i,wrapMode:r,premultiplyAlpha:s,generateMipMap:n,flipY:o}=e;this._context=t,this._sampler=t.createSampler(),this._scaleMode=i,this._wrapMode=r,this._premultiplyAlpha=s,this._generateMipMap=n,this._flipY=o,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)}}class xn{_callback;constructor(t){this._callback=t}execute(t){this._callback(t)}}class wn{}class vn extends wn{_sprite=new Ye(null);_sampleTint=Q.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 r=this._radius,s=this._quality,n=Math.max(1,2*s+1),o=1/(r<=0?1:2*n);this._sampleTint.set(255,255,255,o),this._sprite.setTexture(e).setBlendMode(Z.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new me(()=>{if(r<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<n;e++){const i=(2*(1===n?0:e/(n-1))-1)*r;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:i,view:i.view,clearColor:Q.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}}class bn extends wn{_color;_sprite=new Ye(null);constructor(t=Q.white){super(),this._color=t.clone()}get color(){return this._color}apply(t,e,i){this._sprite.setTexture(e).setBlendMode(Z.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 me(()=>{this._sprite.render(t)},{target:i,view:i.view,clearColor:Q.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}}class Tn{async resolve(t,e){const{storageName:i,key:r,url:s,requestOptions:n,factory:o}=t;for(const t of e){const e=await t.load(i,r);if(null!=e)try{return await o.create(e),e}catch{await t.delete(i,r)}}const a=await fetch(s,n);if(!a.ok)throw new Error(`Failed to fetch "${s}" (${a.status} ${a.statusText}).`);const h=await o.process(a);for(const t of e)try{await t.save(i,r,h)}catch{}return h}}class Sn{async resolve(t,e){const i=await fetch(t.url,t.requestOptions);if(!i.ok)throw new Error(`Failed to fetch "${t.url}" (${i.status} ${i.statusText}).`);return t.factory.process(i)}}const Cn=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"];class Mn{name;version;_storeNames;_migrations;_onCloseHandler=this.disconnect.bind(this);_connected=!1;_database=null;get connected(){return this._connected}constructor(t,e=1,i=Cn,r){if(!y)throw new Error("This browser does not support indexedDB!");this.name=t,this.version=e,this._storeNames=i,this._migrations=r}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 r=i.result,s=i.transaction,n=[...s.objectStoreNames],{oldVersion:o,newVersion:a}=t;if(r.addEventListener("error",()=>e(Error("An error occurred while opening the database."))),r.addEventListener("abort",()=>e(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){if(!this._migrations[e](r,s))return void s.abort()}}else{for(const t of n)this._storeNames.includes(t)||r.deleteObjectStore(t);for(const t of this._storeNames)n.includes(t)||r.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(Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>e(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,r)=>{const s=i.get(e);s.addEventListener("success",()=>t(s.result?.data??null)),s.addEventListener("error",()=>r(Error("An error occurred while loading an item.")))})}async save(t,e,i){const r=await this.getObjectStore(t,"readwrite");return new Promise((t,s)=>{const n=r.put({name:e,data:i});n.addEventListener("success",()=>t()),n.addEventListener("error",()=>s(Error("An error occurred while saving an item.")))})}async delete(t,e){const i=await this.getObjectStore(t,"readwrite");return new Promise((t,r)=>{const s=i.delete(e);s.addEventListener("success",()=>t(!0)),s.addEventListener("error",()=>r(Error("An error occurred while deleting an item.")))})}async clearStorage(t){const e=await this.getObjectStore(t,"readwrite");return new Promise((t,i)=>{const r=e.clear();r.addEventListener("success",()=>t(!0)),r.addEventListener("error",()=>i(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(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 Pn{_db;constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new Mn(e.name,e.version??1,e.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"],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()}}const Bn="@dimforge/rapier2d-compat",En=65535,Rn=1/60,kn={lineWidth:1,solidLineColor:new Q(64,196,255,1),solidFillColor:new Q(64,196,255,.12),triggerLineColor:new Q(255,180,48,1),triggerFillColor:new Q(255,180,48,.08)},An=async()=>await import(Bn),Ln=(t,e)=>{if(!Number.isFinite(t))throw new Error(`${e} must be a finite number.`)},Fn=(t,e)=>{if(Ln(t,e),t<=0)throw new Error(`${e} must be greater than zero.`)},Dn=(t,e)=>{if(!Number.isInteger(t)||t<0||t>15)throw new Error(`${e} must be an integer between 0 and 15.`)},Nn=(t,e)=>void 0===t?e:"number"==typeof t?(Dn(t,"collision group"),1<<t):0===t.length?0:t.reduce((t,e,i)=>(Dn(e,`collision groups[${i}]`),t|1<<e),0),In=t=>{const e=Nn(t?.membership,1),i=Nn(t?.collidesWith,En);return(e&En)<<16|i&En},Un=t=>({x:t.offsetX??0,y:t.offsetY??0}),Vn=(t,e,i)=>{const r=Math.cos(i),s=Math.sin(i);return{x:t*r-e*s,y:t*s+e*r}},On=t=>{(t=>{if("box"===t.type)return Fn(t.width,"Box width"),Fn(t.height,"Box height"),Ln(t.offsetX??0,"Box offsetX"),Ln(t.offsetY??0,"Box offsetY"),void Ln(t.offsetRotation??0,"Box offsetRotation");Fn(t.radius,"Circle radius"),Ln(t.offsetX??0,"Circle offsetX"),Ln(t.offsetY??0,"Circle offsetY")})(t.shape),Ln(t.friction??0,"friction"),Ln(t.restitution??0,"restitution"),Ln(t.density??0,"density"),Ln(t.gravityScale??1,"gravityScale"),Ln(t.linearDamping??0,"linearDamping"),Ln(t.angularDamping??0,"angularDamping"),In(t.collisionFilter)};class Gn{_world;_body;_collider;_syncMode;node;bodyType;shape;trigger;constructor(t,e,i,r,s){this._world=t,this.node=e,this._body=i,this._collider=r,this.bodyType=s.type??"dynamic",this.shape=s.shape,this.trigger=s.trigger??!1,this._syncMode=s.syncMode??"physicsToNode"}get bodyHandle(){return this._body.handle}get colliderHandle(){return this._collider.handle}getBody(){return this._body}get syncMode(){return this._syncMode}set syncMode(t){this._syncMode=t}get x(){return this._body.translation().x}get y(){return this._body.translation().y}get rotation(){return this._body.rotation()}setSyncMode(t){return this._syncMode=t,this}teleport(t,e,i=this.node.rotation){return this._world.writeBodyTransform(this._body,t,e,i,!0),this.node.setPosition(t,e),this.node.setRotation(i),this}syncBodyFromNode(t=!0){return this._world.writeBodyTransform(this._body,this.node.x,this.node.y,this.node.rotation,t),this}syncNodeFromBody(){const t=this._body.translation();return this.node.setPosition(t.x,t.y),this.node.setRotation(this._body.rotation()),this}setCollisionFilter(t){const e=In(t);return this._collider.setCollisionGroups(e),this._collider.setSolverGroups(e),this}destroy(){this._world.removeBinding(this)}}class zn{onCollisionEnter=new F;onCollisionExit=new F;onTriggerEnter=new F;onTriggerExit=new F;_rapier;_world;_eventQueue;_bindings=new Set;_nodeBindings=new Map;_colliderBindings=new Map;constructor(t,e,i){this._rapier=t,this._world=e,this._eventQueue=i}static async create(t={}){const e=t.moduleLoader??An;let i=null;try{i=await e()}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Rapier physics module is unavailable. Install "${Bn}" or provide a custom module loader. Original error: ${e}`,{cause:t})}const r=(t=>{const e=t,i=e.Vector2,r=e.World,s=e.EventQueue,n=e.RigidBodyDesc,o=e.ColliderDesc;if("function"!=typeof i||"function"!=typeof r||"function"!=typeof s)throw new Error("Invalid Rapier module loader result. Expected Vector2, World, and EventQueue exports.");if("object"!=typeof n||null===n||"object"!=typeof o||null===o)throw new Error("Invalid Rapier module loader result. Expected RigidBodyDesc and ColliderDesc exports.");const a=e.ActiveEvents,h="number"==typeof a?.COLLISION_EVENTS?a.COLLISION_EVENTS:void 0;return{init:"function"==typeof e.init?e.init:void 0,vector2:i,worldConstructor:r,eventQueueConstructor:s,rigidBodyDescFactory:n,colliderDescFactory:o,activeCollisionEvents:h}})(i);"function"==typeof r.init&&await r.init();const s=t.gravityX??0,n=t.gravityY??9.81;Ln(s,"gravityX"),Ln(n,"gravityY");const o=new r.worldConstructor(new r.vector2(s,n)),a=new r.eventQueueConstructor(!0);return new zn(r,o,a)}get gravity(){return{x:this._world.gravity.x,y:this._world.gravity.y}}setGravity(t,e){return Ln(t,"gravityX"),Ln(e,"gravityY"),this._world.gravity.x=t,this._world.gravity.y=e,this}hasNode(t){return this._nodeBindings.has(t)}getBinding(t){return this._nodeBindings.get(t)??null}attachNode(t,e){if(this._nodeBindings.has(t))throw new Error("This SceneNode is already attached to a physics body.");On(e);const i=this.createBodyDescriptor(t,e),r=this._world.createRigidBody(i),s=this.createColliderDescriptor(e),n=this._world.createCollider(s,r),o=new Gn(this,t,r,n,e);return this._bindings.add(o),this._nodeBindings.set(t,o),this._colliderBindings.set(n.handle,o),o}detachNode(t){const e=this._nodeBindings.get(t);return e&&this.removeBinding(e),this}step(t=Rn){if(Ln(t,"deltaSeconds"),t<0)throw new Error("deltaSeconds must be zero or greater.");return this.applyStepDelta(t),this._world.step(this._eventQueue),this.drainCollisionEvents(),this.syncNodeTransforms(),this}syncNodeTransforms(){for(const t of this._bindings)"physicsToNode"===t.syncMode&&t.syncNodeFromBody();return this}createDebugGraphics(t={}){const e=new dn;return e.setCullable(!1),this.updateDebugGraphics(e,t),e}updateDebugGraphics(t,e={}){const i=e.lineWidth??kn.lineWidth,r=e.solidLineColor??kn.solidLineColor,s=e.solidFillColor??kn.solidFillColor,n=e.triggerLineColor??kn.triggerLineColor,o=e.triggerFillColor??kn.triggerFillColor;t.clear(),t.lineWidth=i;for(const e of this._bindings){const i={x:e.x,y:e.y},a=e.rotation,h=e.trigger?n:r,l=e.trigger?o:s;if(t.lineColor=h,t.fillColor=l,"box"===e.shape.type){const r=this.buildBoxPath(e.shape,i.x,i.y,a);t.drawPolygon(r)}else{const r=Un(e.shape),s=Vn(r.x,r.y,a);t.drawCircle(i.x+s.x,i.y+s.y,e.shape.radius)}}return t}destroy(){for(const t of Array.from(this._bindings))this.removeBinding(t);this.onCollisionEnter.destroy(),this.onCollisionExit.destroy(),this.onTriggerEnter.destroy(),this.onTriggerExit.destroy()}writeBodyTransform(t,e,i,r,s){t.setTranslation(new this._rapier.vector2(e,i),s),t.setRotation(r,s)}removeBinding(t){this._bindings.has(t)&&(this._bindings.delete(t),this._nodeBindings.delete(t.node),this._colliderBindings.delete(t.colliderHandle),this._world.removeRigidBody(t.getBody()))}createBodyDescriptor(t,e){const i=e.type??"dynamic";let r=this._rapier.rigidBodyDescFactory.dynamic();switch(i){case"static":r=this._rapier.rigidBodyDescFactory.fixed();break;case"kinematic":if("function"==typeof this._rapier.rigidBodyDescFactory.kinematicPositionBased)r=this._rapier.rigidBodyDescFactory.kinematicPositionBased();else{if("function"!=typeof this._rapier.rigidBodyDescFactory.kinematicVelocityBased)throw new Error("Rapier module does not expose a kinematic rigid-body descriptor.");r=this._rapier.rigidBodyDescFactory.kinematicVelocityBased()}break;default:r=this._rapier.rigidBodyDescFactory.dynamic()}return r.setTranslation(t.x,t.y).setRotation(t.rotation).setLinearDamping(e.linearDamping??0).setAngularDamping(e.angularDamping??0).setGravityScale(e.gravityScale??1).lockRotations(e.lockRotation??!1),r}createColliderDescriptor(t){const e=t.shape,i="box"===e.type?this._rapier.colliderDescFactory.cuboid(e.width/2,e.height/2):this._rapier.colliderDescFactory.ball(e.radius),r=Un(e),s=In(t.collisionFilter);i.setTranslation(r.x,r.y).setRotation("box"===e.type?e.offsetRotation??0:0).setSensor(t.trigger??!1).setFriction(t.friction??.5).setRestitution(t.restitution??0).setDensity(t.density??1).setCollisionGroups(s).setSolverGroups(s);const n=this._rapier.activeCollisionEvents;return"number"==typeof n&&i.setActiveEvents(n),i}applyStepDelta(t){const e=this._world;"number"==typeof e.timestep&&(e.timestep=t),e.integrationParameters&&"number"==typeof e.integrationParameters.dt&&(e.integrationParameters.dt=t)}drainCollisionEvents(){this._eventQueue.drainCollisionEvents((t,e,i)=>{const r=this._colliderBindings.get(t),s=this._colliderBindings.get(e);if(!r||!s)return;const n=r.trigger||s.trigger,o={started:i,trigger:n,first:r,second:s};n?i?this.onTriggerEnter.dispatch(o):this.onTriggerExit.dispatch(o):i?this.onCollisionEnter.dispatch(o):this.onCollisionExit.dispatch(o)})}buildBoxPath(t,e,i,r){const s=t.width/2,n=t.height/2,o=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}],a=Un(t),h=t.offsetRotation??0,l=[];for(const t of o){const s=Vn(t.x,t.y,h),n={x:s.x+a.x,y:s.y+a.y},o=Vn(n.x,n.y,r);l.push(e+o.x,i+o.y)}return l}}const Wn=async(t={})=>await zn.create(t);export{Pr as AbstractAssetFactory,Ji as AbstractMedia,Ge as AbstractWebGl2BatchedRenderer,Pe as AbstractWebGl2Renderer,ii as AbstractWebGpuRenderer,pn as AnimatedSprite,ts as Application,Qr as ApplicationStatus,Pi as ArcadeStickGamepadMapping,ns as AudioAnalyser,Gr as BinaryFactory,Z as BlendModes,vn as BlurFilter,ae as Bounds,it as BufferTypes,rt as BufferUsage,Hr as BundleLoadError,Tn as CacheFirstStrategy,xn as CallbackRenderPass,mi as ChannelOffset,fi as ChannelSize,Qs as Circle,cn as CircleGeometry,L as Clock,pt as CollisionType,Q as Color,nn as ColorAffector,bn as ColorFilter,is as Container,xe as Drawable,we as DrawableShape,Zs as Ellipse,Mr as FactoryRegistry,wn as Filter,lt as Flags,Br as FontFactory,on as ForceAffector,ki as GameCubeGamepadMapping,bi as Gamepad,wi as GamepadChannel,Si as GamepadControl,Ci as GamepadMapping,vi as GamepadMappingFamily,_s as GamepadPromptLayouts,Ri as GenericDualAnalogGamepadMapping,ve as Geometry,dn as Graphics,kr as ImageFactory,Mn as IndexedDbDatabase,Pn as IndexedDbStore,ps as Input,Zi as InputManager,_t as Interval,Ai as JoyConLeftGamepadMapping,Li as JoyConRightGamepadMapping,br as Json,Ar as JsonFactory,gi as Keyboard,$s as Line,Kr as Loader,ht as Matrix,xr as Music,Fr as MusicFactory,Sn as NetworkOnlyStrategy,le as ObservableSize,ot as ObservableVector,Xe as Particle,ln as ParticleOptions,je as ParticleSystem,Fi as PlayStationGamepadMapping,Ti as Pointer,xi as PointerState,yi as PointerStateFlag,sn as PolarVector,tn as Polygon,es as Quadtree,i as Random,Gn as RapierPhysicsBinding,zn as RapierPhysicsWorld,oe as Rectangle,Me as RenderBackendType,ye as RenderNode,pe as RenderTarget,me as RenderTargetPass,fe as RenderTexture,Ke as RendererRegistry,et as RenderingPrimitives,yn as Sampler,an as ScaleAffector,J as ScaleModes,rs as Scene,Te as SceneManager,he as SceneNode,rn as Segment,Be as Shader,Ae as ShaderAttribute,st as ShaderPrimitives,Le as ShaderUniform,F as Signal,e as Size,wr as Sound,Dr as SoundFactory,Ye as Sprite,He as SpriteFlags,_n as Spritesheet,Di as SteamControllerGamepadMapping,Sr as SvgAsset,Or as SvgFactory,Ni as SwitchProGamepadMapping,gn as Text,Tr as TextAsset,Nr as TextFactory,fn as TextStyle,$e as Texture,Ir as TextureFactory,s as Time,ss as Timer,hn as TorqueAffector,ct as Transformable,ut as TransformableFlags,un as UniversalEmitter,_e as Vector,vr as Video,Vr as VideoFactory,ce as View,ue as ViewFlags,U as VoronoiRegion,Cr as VttAsset,qr as VttFactory,zr as WasmFactory,We as WebGl2ParticleRenderer,qe as WebGl2PrimitiveRenderer,Ue as WebGl2RenderBuffer,ei as WebGl2RenderManager,Fe as WebGl2ShaderBlock,ze as WebGl2SpriteRenderer,Ce as WebGl2VertexArrayObject,di as WebGpuParticleRenderer,oi as WebGpuPrimitiveRenderer,pi as WebGpuRenderManager,hi as WebGpuSpriteRenderer,tt as WrapModes,Ii as XboxGamepadMapping,j as bezierCurveTo,Ws as buildCircle,qs as buildEllipse,Gs as buildLine,zs as buildPath,Hs as buildPolygon,Ys as buildRectangle,Xs as buildStar,Ki as builtInGamepadDefinitions,A as canvasSourceToDataUrl,z as clamp,Wn as createRapierPhysicsWorld,Qe as createRenderStats,Ne as createWebGl2ShaderRuntime,yr as decodeAudioData,Yr as defineAssetManifest,I as degreesPerRadian,O as degreesToRadians,Rr as determineMimeType,P as emptyArrayBuffer,fr as getAudioContext,R as getCanvasSourceSize,Jt as getCollisionCircleCircle,te as getCollisionCircleRectangle,ee as getCollisionPolygonCircle,Zt as getCollisionRectangleRectangle,ie as getCollisionSat,X as getDistance,gr as getOfflineAudioContext,b as getPreciseTime,k as getTextureSourceSize,K as getVoronoiRegion,ri as getWebGpuBlendState,M as hours,Y as inRange,Wt as intersectionCircleCircle,qt as intersectionCircleEllipse,jt as intersectionCirclePoly,$t as intersectionEllipseEllipse,Kt as intersectionEllipsePoly,Nt as intersectionLineCircle,It as intersectionLineEllipse,Ft as intersectionLineLine,Ut as intersectionLinePoly,Dt as intersectionLineRect,kt as intersectionPointCircle,At as intersectionPointEllipse,Et as intersectionPointLine,Bt as intersectionPointPoint,Lt as intersectionPointPoly,Rt as intersectionPointRect,Qt as intersectionPolyPoly,Ot as intersectionRectCircle,Gt as intersectionRectEllipse,zt as intersectionRectPoly,Vt as intersectionRectRect,Pt as intersectionSat,mr as isAudioContextReady,H as isPowerOfTwo,q as lerp,Yi as matchesIds,T as milliseconds,C as minutes,f as noop,Hi as normalizeIds,pr as onAudioContextReady,Xi as parseGamepadDescriptor,$ as quadraticCurveTo,N as radiansPerDegree,G as radiansToDegrees,p as rand,B as removeArrayItems,Ze as resetRenderStats,ji as resolveDefinition,$i as resolveGamepadDefinition,S as seconds,W as sign,m as stopEvent,E as supportsCodec,v as supportsEventOptions,y as supportsIndexedDb,w as supportsPointerEvents,x as supportsTouchEvents,g as supportsWebAudio,D as tau,V as trimRotation,Re as webGl2PrimitiveArrayConstructors,Ee as webGl2PrimitiveByteSizeMapping,ke as webGl2PrimitiveTypeNames};
|
|
2
|
+
//# sourceMappingURL=exo.esm.min.js.map
|