@datamoc/mw_games 0.43.0 → 0.45.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/3d/models.d.ts +1 -0
- package/3d/models.js +1 -0
- package/3d.d.ts +1 -0
- package/3d.js +1 -0
- package/README.md +5 -710
- package/actors.d.ts +1 -0
- package/actors.js +1 -0
- package/ai/lua.d.ts +1 -0
- package/ai/lua.js +1 -0
- package/ai.d.ts +1 -0
- package/ai.js +1 -0
- package/assets/binary.d.ts +1 -0
- package/assets/binary.js +1 -0
- package/assets/paths.d.ts +1 -0
- package/assets/paths.js +1 -0
- package/assets.d.ts +1 -0
- package/assets.js +1 -0
- package/audio.d.ts +1 -0
- package/audio.js +1 -0
- package/battle.d.ts +1 -0
- package/battle.js +1 -0
- package/board.d.ts +1 -0
- package/board.js +1 -0
- package/core.d.ts +1 -0
- package/core.js +1 -0
- package/headless.d.ts +1 -0
- package/headless.js +1 -0
- package/i18n.d.ts +1 -0
- package/i18n.js +1 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/mwl/presentation.d.ts +1 -0
- package/mwl/presentation.js +1 -0
- package/mwl/pyroeis.d.ts +1 -0
- package/mwl/pyroeis.js +1 -0
- package/mwl.d.ts +1 -0
- package/mwl.js +1 -0
- package/package.json +212 -387
- package/physics/xpbd.d.ts +1 -0
- package/physics/xpbd.js +1 -0
- package/physics.d.ts +1 -0
- package/physics.js +1 -0
- package/roguelike.d.ts +1 -0
- package/roguelike.js +1 -0
- package/rpg.d.ts +1 -0
- package/rpg.js +1 -0
- package/simulation.d.ts +1 -0
- package/simulation.js +1 -0
- package/skeleton.d.ts +1 -0
- package/skeleton.js +1 -0
- package/testing.d.ts +1 -0
- package/testing.js +1 -0
- package/threads.d.ts +1 -0
- package/threads.js +1 -0
- package/tools/asset-report.d.mts +1 -37
- package/tools/asset-report.mjs +1 -157
- package/tools/audio.d.mts +1 -0
- package/tools/audio.mjs +1 -0
- package/tools/audit-adoptions.d.mts +1 -65
- package/tools/audit-adoptions.mjs +1 -252
- package/tools/benchmark-browser.d.mts +1 -33
- package/tools/benchmark-browser.mjs +1 -169
- package/tools/benchmark-history.d.mts +1 -8
- package/tools/benchmark-history.mjs +1 -31
- package/tools/browser-driver.d.mts +1 -122
- package/tools/browser-driver.mjs +1 -861
- package/tools/browser-smoke.d.mts +1 -30
- package/tools/browser-smoke.mjs +1 -184
- package/tools/build-tablebases.d.mts +1 -22
- package/tools/build-tablebases.mjs +1 -557
- package/tools/bundle-size.d.mts +1 -11
- package/tools/bundle-size.mjs +1 -142
- package/tools/classic-html.d.mts +1 -6
- package/tools/classic-html.mjs +1 -69
- package/tools/compile-openings.d.mts +1 -20
- package/tools/compile-openings.mjs +1 -138
- package/tools/compile-resources.d.mts +1 -66
- package/tools/compile-resources.mjs +1 -406
- package/tools/compress-dist.d.mts +1 -42
- package/tools/compress-dist.mjs +1 -193
- package/tools/csp.d.mts +1 -7
- package/tools/csp.mjs +1 -65
- package/tools/emit-page.d.mts +1 -61
- package/tools/emit-page.mjs +1 -273
- package/tools/extract-html.d.mts +1 -18
- package/tools/extract-html.mjs +1 -235
- package/tools/extract-rgssad.d.mts +1 -5
- package/tools/extract-rgssad.mjs +1 -64
- package/tools/find-chrome.d.mts +1 -7
- package/tools/find-chrome.mjs +1 -106
- package/tools/i18n-edit.d.mts +1 -29
- package/tools/i18n-edit.mjs +1 -748
- package/tools/init.d.mts +1 -5
- package/tools/init.mjs +1 -155
- package/tools/make-example-assets.d.mts +1 -2
- package/tools/make-example-assets.mjs +1 -731
- package/tools/multiplayer-server.d.mts +1 -27
- package/tools/multiplayer-server.mjs +1 -199
- package/tools/play-uci.d.mts +1 -26
- package/tools/play-uci.mjs +1 -205
- package/tools/sbom.d.mts +1 -83
- package/tools/sbom.mjs +1 -340
- package/tools/single-file.d.mts +1 -33
- package/tools/single-file.mjs +1 -239
- package/tools/soundfonts.d.mts +1 -79
- package/tools/soundfonts.mjs +1 -301
- package/tools/svg-optimise.d.mts +1 -8
- package/tools/svg-optimise.mjs +1 -45
- package/tools/verify-scenarios.d.mts +1 -15
- package/tools/verify-scenarios.mjs +1 -133
- package/tools/vite.d.mts +1 -17
- package/tools/vite.mjs +1 -102
- package/tools/webp-convert.d.mts +1 -8
- package/tools/webp-convert.mjs +1 -98
- package/two-d/pixi-interop.d.ts +1 -0
- package/two-d/pixi-interop.js +1 -0
- package/two-d/presentation.d.ts +1 -0
- package/two-d/presentation.js +1 -0
- package/two-d/render.d.ts +1 -0
- package/two-d/render.js +1 -0
- package/two-d/stage.d.ts +1 -0
- package/two-d/stage.js +1 -0
- package/two-d/ui.d.ts +1 -0
- package/two-d/ui.js +1 -0
- package/two-d.d.ts +1 -0
- package/two-d.js +1 -0
- package/world.d.ts +1 -0
- package/world.js +1 -0
- package/CHANGELOG.md +0 -3129
- package/LICENSE +0 -373
- package/MWG - Best Practices.md +0 -97
- package/MWG - Deep Code and Architecture Review.md +0 -238
- package/REFERENCE.md +0 -2180
- package/api-surface.json +0 -17102
- package/data/microgm-essential.PROVENANCE.md +0 -13
- package/data/microgm-essential.sf2 +0 -0
- package/data/microgm-opt.PROVENANCE.md +0 -23
- package/data/microgm-opt.sf2 +0 -0
- package/data/soundfont-catalog.json +0 -191
- package/dist/actors/Advancement.d.ts +0 -90
- package/dist/actors/Advancement.d.ts.map +0 -1
- package/dist/actors/Advancement.js +0 -115
- package/dist/actors/Advancement.js.map +0 -1
- package/dist/actors/Affix.d.ts +0 -96
- package/dist/actors/Affix.d.ts.map +0 -1
- package/dist/actors/Affix.js +0 -68
- package/dist/actors/Affix.js.map +0 -1
- package/dist/actors/Appearances.d.ts +0 -48
- package/dist/actors/Appearances.d.ts.map +0 -1
- package/dist/actors/Appearances.js +0 -62
- package/dist/actors/Appearances.js.map +0 -1
- package/dist/actors/Aura.d.ts +0 -45
- package/dist/actors/Aura.d.ts.map +0 -1
- package/dist/actors/Aura.js +0 -85
- package/dist/actors/Aura.js.map +0 -1
- package/dist/actors/Barrier.d.ts +0 -60
- package/dist/actors/Barrier.d.ts.map +0 -1
- package/dist/actors/Barrier.js +0 -70
- package/dist/actors/Barrier.js.map +0 -1
- package/dist/actors/Charges.d.ts +0 -66
- package/dist/actors/Charges.d.ts.map +0 -1
- package/dist/actors/Charges.js +0 -61
- package/dist/actors/Charges.js.map +0 -1
- package/dist/actors/EntityTemplate.d.ts +0 -127
- package/dist/actors/EntityTemplate.d.ts.map +0 -1
- package/dist/actors/EntityTemplate.js +0 -117
- package/dist/actors/EntityTemplate.js.map +0 -1
- package/dist/actors/Equipment.d.ts +0 -88
- package/dist/actors/Equipment.d.ts.map +0 -1
- package/dist/actors/Equipment.js +0 -107
- package/dist/actors/Equipment.js.map +0 -1
- package/dist/actors/Inventory.d.ts +0 -123
- package/dist/actors/Inventory.d.ts.map +0 -1
- package/dist/actors/Inventory.js +0 -165
- package/dist/actors/Inventory.js.map +0 -1
- package/dist/actors/ItemState.d.ts +0 -43
- package/dist/actors/ItemState.d.ts.map +0 -1
- package/dist/actors/ItemState.js +0 -63
- package/dist/actors/ItemState.js.map +0 -1
- package/dist/actors/ItemStatusEffect.d.ts +0 -40
- package/dist/actors/ItemStatusEffect.d.ts.map +0 -1
- package/dist/actors/ItemStatusEffect.js +0 -39
- package/dist/actors/ItemStatusEffect.js.map +0 -1
- package/dist/actors/Loot.d.ts +0 -38
- package/dist/actors/Loot.d.ts.map +0 -1
- package/dist/actors/Loot.js +0 -28
- package/dist/actors/Loot.js.map +0 -1
- package/dist/actors/Progression.d.ts +0 -52
- package/dist/actors/Progression.d.ts.map +0 -1
- package/dist/actors/Progression.js +0 -59
- package/dist/actors/Progression.js.map +0 -1
- package/dist/actors/Resource.d.ts +0 -53
- package/dist/actors/Resource.d.ts.map +0 -1
- package/dist/actors/Resource.js +0 -58
- package/dist/actors/Resource.js.map +0 -1
- package/dist/actors/Scaling.d.ts +0 -30
- package/dist/actors/Scaling.d.ts.map +0 -1
- package/dist/actors/Scaling.js +0 -9
- package/dist/actors/Scaling.js.map +0 -1
- package/dist/actors/Shop.d.ts +0 -40
- package/dist/actors/Shop.d.ts.map +0 -1
- package/dist/actors/Shop.js +0 -36
- package/dist/actors/Shop.js.map +0 -1
- package/dist/actors/SkillPoints.d.ts +0 -72
- package/dist/actors/SkillPoints.d.ts.map +0 -1
- package/dist/actors/SkillPoints.js +0 -87
- package/dist/actors/SkillPoints.js.map +0 -1
- package/dist/actors/StatBlock.d.ts +0 -86
- package/dist/actors/StatBlock.d.ts.map +0 -1
- package/dist/actors/StatBlock.js +0 -110
- package/dist/actors/StatBlock.js.map +0 -1
- package/dist/actors/StatusEffect.d.ts +0 -67
- package/dist/actors/StatusEffect.d.ts.map +0 -1
- package/dist/actors/StatusEffect.js +0 -59
- package/dist/actors/StatusEffect.js.map +0 -1
- package/dist/actors/Support.d.ts +0 -43
- package/dist/actors/Support.d.ts.map +0 -1
- package/dist/actors/Support.js +0 -71
- package/dist/actors/Support.js.map +0 -1
- package/dist/actors/Traits.d.ts +0 -43
- package/dist/actors/Traits.d.ts.map +0 -1
- package/dist/actors/Traits.js +0 -35
- package/dist/actors/Traits.js.map +0 -1
- package/dist/actors/craft.d.ts +0 -63
- package/dist/actors/craft.d.ts.map +0 -1
- package/dist/actors/craft.js +0 -86
- package/dist/actors/craft.js.map +0 -1
- package/dist/actors/index.d.ts +0 -46
- package/dist/actors/index.d.ts.map +0 -1
- package/dist/actors/index.js +0 -24
- package/dist/actors/index.js.map +0 -1
- package/dist/actors/skillCheck.d.ts +0 -21
- package/dist/actors/skillCheck.d.ts.map +0 -1
- package/dist/actors/skillCheck.js +0 -24
- package/dist/actors/skillCheck.js.map +0 -1
- package/dist/ai/Heuristics.d.ts +0 -240
- package/dist/ai/Heuristics.d.ts.map +0 -1
- package/dist/ai/Heuristics.js +0 -298
- package/dist/ai/Heuristics.js.map +0 -1
- package/dist/ai/Neural.d.ts +0 -65
- package/dist/ai/Neural.d.ts.map +0 -1
- package/dist/ai/Neural.js +0 -169
- package/dist/ai/Neural.js.map +0 -1
- package/dist/ai/Suggest.d.ts +0 -54
- package/dist/ai/Suggest.d.ts.map +0 -1
- package/dist/ai/Suggest.js +0 -48
- package/dist/ai/Suggest.js.map +0 -1
- package/dist/ai/index.d.ts +0 -136
- package/dist/ai/index.d.ts.map +0 -1
- package/dist/ai/index.js +0 -207
- package/dist/ai/index.js.map +0 -1
- package/dist/ai/lua.d.ts +0 -74
- package/dist/ai/lua.d.ts.map +0 -1
- package/dist/ai/lua.js +0 -217
- package/dist/ai/lua.js.map +0 -1
- package/dist/ai/score.d.ts +0 -162
- package/dist/ai/score.d.ts.map +0 -1
- package/dist/ai/score.js +0 -147
- package/dist/ai/score.js.map +0 -1
- package/dist/ai/search.d.ts +0 -108
- package/dist/ai/search.d.ts.map +0 -1
- package/dist/ai/search.js +0 -148
- package/dist/ai/search.js.map +0 -1
- package/dist/assets/ByteProgress.d.ts +0 -37
- package/dist/assets/ByteProgress.d.ts.map +0 -1
- package/dist/assets/ByteProgress.js +0 -54
- package/dist/assets/ByteProgress.js.map +0 -1
- package/dist/assets/Streaming.d.ts +0 -56
- package/dist/assets/Streaming.d.ts.map +0 -1
- package/dist/assets/Streaming.js +0 -100
- package/dist/assets/Streaming.js.map +0 -1
- package/dist/assets/SvgParts.d.ts +0 -31
- package/dist/assets/SvgParts.d.ts.map +0 -1
- package/dist/assets/SvgParts.js +0 -54
- package/dist/assets/SvgParts.js.map +0 -1
- package/dist/assets/SvgSource.d.ts +0 -3
- package/dist/assets/SvgSource.d.ts.map +0 -1
- package/dist/assets/SvgSource.js +0 -22
- package/dist/assets/SvgSource.js.map +0 -1
- package/dist/assets/binary.d.ts +0 -52
- package/dist/assets/binary.d.ts.map +0 -1
- package/dist/assets/binary.js +0 -57
- package/dist/assets/binary.js.map +0 -1
- package/dist/assets/index.d.ts +0 -27
- package/dist/assets/index.d.ts.map +0 -1
- package/dist/assets/index.js +0 -20
- package/dist/assets/index.js.map +0 -1
- package/dist/assets/loader.d.ts +0 -70
- package/dist/assets/loader.d.ts.map +0 -1
- package/dist/assets/loader.js +0 -115
- package/dist/assets/loader.js.map +0 -1
- package/dist/assets/paths.d.ts +0 -73
- package/dist/assets/paths.d.ts.map +0 -1
- package/dist/assets/paths.js +0 -91
- package/dist/assets/paths.js.map +0 -1
- package/dist/assets/svg.d.ts +0 -87
- package/dist/assets/svg.d.ts.map +0 -1
- package/dist/assets/svg.js +0 -166
- package/dist/assets/svg.js.map +0 -1
- package/dist/audio/AudioLoader.d.ts +0 -28
- package/dist/audio/AudioLoader.d.ts.map +0 -1
- package/dist/audio/AudioLoader.js +0 -53
- package/dist/audio/AudioLoader.js.map +0 -1
- package/dist/audio/Captions.d.ts +0 -27
- package/dist/audio/Captions.d.ts.map +0 -1
- package/dist/audio/Captions.js +0 -16
- package/dist/audio/Captions.js.map +0 -1
- package/dist/audio/Channels.d.ts +0 -218
- package/dist/audio/Channels.d.ts.map +0 -1
- package/dist/audio/Channels.js +0 -486
- package/dist/audio/Channels.js.map +0 -1
- package/dist/audio/LoopTags.d.ts +0 -37
- package/dist/audio/LoopTags.d.ts.map +0 -1
- package/dist/audio/LoopTags.js +0 -116
- package/dist/audio/LoopTags.js.map +0 -1
- package/dist/audio/Midi.d.ts +0 -184
- package/dist/audio/Midi.d.ts.map +0 -1
- package/dist/audio/Midi.js +0 -339
- package/dist/audio/Midi.js.map +0 -1
- package/dist/audio/MidiRender.d.ts +0 -113
- package/dist/audio/MidiRender.d.ts.map +0 -1
- package/dist/audio/MidiRender.js +0 -371
- package/dist/audio/MidiRender.js.map +0 -1
- package/dist/audio/Music.d.ts +0 -70
- package/dist/audio/Music.d.ts.map +0 -1
- package/dist/audio/Music.js +0 -191
- package/dist/audio/Music.js.map +0 -1
- package/dist/audio/MusicPlayer.d.ts +0 -80
- package/dist/audio/MusicPlayer.d.ts.map +0 -1
- package/dist/audio/MusicPlayer.js +0 -147
- package/dist/audio/MusicPlayer.js.map +0 -1
- package/dist/audio/Orchestrator.d.ts +0 -58
- package/dist/audio/Orchestrator.d.ts.map +0 -1
- package/dist/audio/Orchestrator.js +0 -74
- package/dist/audio/Orchestrator.js.map +0 -1
- package/dist/audio/Playable.d.ts +0 -31
- package/dist/audio/Playable.d.ts.map +0 -1
- package/dist/audio/Playable.js +0 -29
- package/dist/audio/Playable.js.map +0 -1
- package/dist/audio/Positional.d.ts +0 -125
- package/dist/audio/Positional.d.ts.map +0 -1
- package/dist/audio/Positional.js +0 -135
- package/dist/audio/Positional.js.map +0 -1
- package/dist/audio/SampleDecoder.d.ts +0 -55
- package/dist/audio/SampleDecoder.d.ts.map +0 -1
- package/dist/audio/SampleDecoder.js +0 -74
- package/dist/audio/SampleDecoder.js.map +0 -1
- package/dist/audio/Sound.d.ts +0 -57
- package/dist/audio/Sound.d.ts.map +0 -1
- package/dist/audio/Sound.js +0 -79
- package/dist/audio/Sound.js.map +0 -1
- package/dist/audio/SoundFont.d.ts +0 -192
- package/dist/audio/SoundFont.d.ts.map +0 -1
- package/dist/audio/SoundFont.js +0 -862
- package/dist/audio/SoundFont.js.map +0 -1
- package/dist/audio/Synth.d.ts +0 -64
- package/dist/audio/Synth.d.ts.map +0 -1
- package/dist/audio/Synth.js +0 -133
- package/dist/audio/Synth.js.map +0 -1
- package/dist/audio/humanize/Groove.d.ts +0 -80
- package/dist/audio/humanize/Groove.d.ts.map +0 -1
- package/dist/audio/humanize/Groove.js +0 -102
- package/dist/audio/humanize/Groove.js.map +0 -1
- package/dist/audio/humanize/GrooveConverter.d.ts +0 -49
- package/dist/audio/humanize/GrooveConverter.d.ts.map +0 -1
- package/dist/audio/humanize/GrooveConverter.js +0 -344
- package/dist/audio/humanize/GrooveConverter.js.map +0 -1
- package/dist/audio/humanize/GrooveExtractor.d.ts +0 -49
- package/dist/audio/humanize/GrooveExtractor.d.ts.map +0 -1
- package/dist/audio/humanize/GrooveExtractor.js +0 -179
- package/dist/audio/humanize/GrooveExtractor.js.map +0 -1
- package/dist/audio/humanize/GrooveHumanizer.d.ts +0 -34
- package/dist/audio/humanize/GrooveHumanizer.d.ts.map +0 -1
- package/dist/audio/humanize/GrooveHumanizer.js +0 -37
- package/dist/audio/humanize/GrooveHumanizer.js.map +0 -1
- package/dist/audio/humanize/Humanize.d.ts +0 -54
- package/dist/audio/humanize/Humanize.d.ts.map +0 -1
- package/dist/audio/humanize/Humanize.js +0 -239
- package/dist/audio/humanize/Humanize.js.map +0 -1
- package/dist/audio/humanize/HumanizerFactory.d.ts +0 -68
- package/dist/audio/humanize/HumanizerFactory.d.ts.map +0 -1
- package/dist/audio/humanize/HumanizerFactory.js +0 -84
- package/dist/audio/humanize/HumanizerFactory.js.map +0 -1
- package/dist/audio/humanize/LiteHumanizer.d.ts +0 -30
- package/dist/audio/humanize/LiteHumanizer.d.ts.map +0 -1
- package/dist/audio/humanize/LiteHumanizer.js +0 -35
- package/dist/audio/humanize/LiteHumanizer.js.map +0 -1
- package/dist/audio/humanize/Onsets.d.ts +0 -26
- package/dist/audio/humanize/Onsets.d.ts.map +0 -1
- package/dist/audio/humanize/Onsets.js +0 -164
- package/dist/audio/humanize/Onsets.js.map +0 -1
- package/dist/audio/index.d.ts +0 -43
- package/dist/audio/index.d.ts.map +0 -1
- package/dist/audio/index.js +0 -22
- package/dist/audio/index.js.map +0 -1
- package/dist/battle/AttackDialog.d.ts +0 -75
- package/dist/battle/AttackDialog.d.ts.map +0 -1
- package/dist/battle/AttackDialog.js +0 -115
- package/dist/battle/AttackDialog.js.map +0 -1
- package/dist/battle/AttackPreview.d.ts +0 -70
- package/dist/battle/AttackPreview.d.ts.map +0 -1
- package/dist/battle/AttackPreview.js +0 -78
- package/dist/battle/AttackPreview.js.map +0 -1
- package/dist/battle/BattleAI.d.ts +0 -40
- package/dist/battle/BattleAI.d.ts.map +0 -1
- package/dist/battle/BattleAI.js +0 -63
- package/dist/battle/BattleAI.js.map +0 -1
- package/dist/battle/BattleStats.d.ts +0 -45
- package/dist/battle/BattleStats.d.ts.map +0 -1
- package/dist/battle/BattleStats.js +0 -63
- package/dist/battle/BattleStats.js.map +0 -1
- package/dist/battle/Evolution.d.ts +0 -34
- package/dist/battle/Evolution.d.ts.map +0 -1
- package/dist/battle/Evolution.js +0 -37
- package/dist/battle/Evolution.js.map +0 -1
- package/dist/battle/Field.d.ts +0 -36
- package/dist/battle/Field.d.ts.map +0 -1
- package/dist/battle/Field.js +0 -31
- package/dist/battle/Field.js.map +0 -1
- package/dist/battle/Hooks.d.ts +0 -39
- package/dist/battle/Hooks.d.ts.map +0 -1
- package/dist/battle/Hooks.js +0 -38
- package/dist/battle/Hooks.js.map +0 -1
- package/dist/battle/Move.d.ts +0 -45
- package/dist/battle/Move.d.ts.map +0 -1
- package/dist/battle/Move.js +0 -23
- package/dist/battle/Move.js.map +0 -1
- package/dist/battle/Party.d.ts +0 -32
- package/dist/battle/Party.d.ts.map +0 -1
- package/dist/battle/Party.js +0 -62
- package/dist/battle/Party.js.map +0 -1
- package/dist/battle/Species.d.ts +0 -50
- package/dist/battle/Species.d.ts.map +0 -1
- package/dist/battle/Species.js +0 -41
- package/dist/battle/Species.js.map +0 -1
- package/dist/battle/StatStages.d.ts +0 -52
- package/dist/battle/StatStages.d.ts.map +0 -1
- package/dist/battle/StatStages.js +0 -50
- package/dist/battle/StatStages.js.map +0 -1
- package/dist/battle/TypeMatrix.d.ts +0 -25
- package/dist/battle/TypeMatrix.d.ts.map +0 -1
- package/dist/battle/TypeMatrix.js +0 -35
- package/dist/battle/TypeMatrix.js.map +0 -1
- package/dist/battle/UnitSelector.d.ts +0 -72
- package/dist/battle/UnitSelector.d.ts.map +0 -1
- package/dist/battle/UnitSelector.js +0 -117
- package/dist/battle/UnitSelector.js.map +0 -1
- package/dist/battle/Whiteboard.d.ts +0 -50
- package/dist/battle/Whiteboard.d.ts.map +0 -1
- package/dist/battle/Whiteboard.js +0 -94
- package/dist/battle/Whiteboard.js.map +0 -1
- package/dist/battle/index.d.ts +0 -26
- package/dist/battle/index.d.ts.map +0 -1
- package/dist/battle/index.js +0 -15
- package/dist/battle/index.js.map +0 -1
- package/dist/board/Army.d.ts +0 -92
- package/dist/board/Army.d.ts.map +0 -1
- package/dist/board/Army.js +0 -123
- package/dist/board/Army.js.map +0 -1
- package/dist/board/Classics.d.ts +0 -419
- package/dist/board/Classics.d.ts.map +0 -1
- package/dist/board/Classics.js +0 -754
- package/dist/board/Classics.js.map +0 -1
- package/dist/board/Engine.d.ts +0 -93
- package/dist/board/Engine.d.ts.map +0 -1
- package/dist/board/Engine.js +0 -545
- package/dist/board/Engine.js.map +0 -1
- package/dist/board/FogOfWar.d.ts +0 -79
- package/dist/board/FogOfWar.d.ts.map +0 -1
- package/dist/board/FogOfWar.js +0 -150
- package/dist/board/FogOfWar.js.map +0 -1
- package/dist/board/HexSkirmish.d.ts +0 -213
- package/dist/board/HexSkirmish.d.ts.map +0 -1
- package/dist/board/HexSkirmish.js +0 -329
- package/dist/board/HexSkirmish.js.map +0 -1
- package/dist/board/Tactics.d.ts +0 -212
- package/dist/board/Tactics.d.ts.map +0 -1
- package/dist/board/Tactics.js +0 -305
- package/dist/board/Tactics.js.map +0 -1
- package/dist/board/bitboard.d.ts +0 -132
- package/dist/board/bitboard.d.ts.map +0 -1
- package/dist/board/bitboard.js +0 -495
- package/dist/board/bitboard.js.map +0 -1
- package/dist/board/chess.d.ts +0 -167
- package/dist/board/chess.d.ts.map +0 -1
- package/dist/board/chess.js +0 -578
- package/dist/board/chess.js.map +0 -1
- package/dist/board/index.d.ts +0 -23
- package/dist/board/index.d.ts.map +0 -1
- package/dist/board/index.js +0 -12
- package/dist/board/index.js.map +0 -1
- package/dist/board/openings.d.ts +0 -58
- package/dist/board/openings.d.ts.map +0 -1
- package/dist/board/openings.js +0 -45
- package/dist/board/openings.js.map +0 -1
- package/dist/board/tablebase.d.ts +0 -118
- package/dist/board/tablebase.d.ts.map +0 -1
- package/dist/board/tablebase.js +0 -414
- package/dist/board/tablebase.js.map +0 -1
- package/dist/board/tourney.d.ts +0 -97
- package/dist/board/tourney.d.ts.map +0 -1
- package/dist/board/tourney.js +0 -1019
- package/dist/board/tourney.js.map +0 -1
- package/dist/core/Achievements.d.ts +0 -101
- package/dist/core/Achievements.d.ts.map +0 -1
- package/dist/core/Achievements.js +0 -141
- package/dist/core/Achievements.js.map +0 -1
- package/dist/core/ActionJournal.d.ts +0 -43
- package/dist/core/ActionJournal.d.ts.map +0 -1
- package/dist/core/ActionJournal.js +0 -77
- package/dist/core/ActionJournal.js.map +0 -1
- package/dist/core/Blob.d.ts +0 -79
- package/dist/core/Blob.d.ts.map +0 -1
- package/dist/core/Blob.js +0 -140
- package/dist/core/Blob.js.map +0 -1
- package/dist/core/Clone.d.ts +0 -31
- package/dist/core/Clone.d.ts.map +0 -1
- package/dist/core/Clone.js +0 -84
- package/dist/core/Clone.js.map +0 -1
- package/dist/core/Collection.d.ts +0 -59
- package/dist/core/Collection.d.ts.map +0 -1
- package/dist/core/Collection.js +0 -77
- package/dist/core/Collection.js.map +0 -1
- package/dist/core/Csv.d.ts +0 -74
- package/dist/core/Csv.d.ts.map +0 -1
- package/dist/core/Csv.js +0 -201
- package/dist/core/Csv.js.map +0 -1
- package/dist/core/DialogueText.d.ts +0 -72
- package/dist/core/DialogueText.d.ts.map +0 -1
- package/dist/core/DialogueText.js +0 -68
- package/dist/core/DialogueText.js.map +0 -1
- package/dist/core/Entity.d.ts +0 -42
- package/dist/core/Entity.d.ts.map +0 -1
- package/dist/core/Entity.js +0 -61
- package/dist/core/Entity.js.map +0 -1
- package/dist/core/Feedback.d.ts +0 -27
- package/dist/core/Feedback.d.ts.map +0 -1
- package/dist/core/Feedback.js +0 -33
- package/dist/core/Feedback.js.map +0 -1
- package/dist/core/FixedStepper.d.ts +0 -38
- package/dist/core/FixedStepper.d.ts.map +0 -1
- package/dist/core/FixedStepper.js +0 -56
- package/dist/core/FixedStepper.js.map +0 -1
- package/dist/core/Grid.d.ts +0 -179
- package/dist/core/Grid.d.ts.map +0 -1
- package/dist/core/Grid.js +0 -201
- package/dist/core/Grid.js.map +0 -1
- package/dist/core/Handles.d.ts +0 -42
- package/dist/core/Handles.d.ts.map +0 -1
- package/dist/core/Handles.js +0 -38
- package/dist/core/Handles.js.map +0 -1
- package/dist/core/Hex.d.ts +0 -79
- package/dist/core/Hex.d.ts.map +0 -1
- package/dist/core/Hex.js +0 -161
- package/dist/core/Hex.js.map +0 -1
- package/dist/core/Hooks.d.ts +0 -48
- package/dist/core/Hooks.d.ts.map +0 -1
- package/dist/core/Hooks.js +0 -33
- package/dist/core/Hooks.js.map +0 -1
- package/dist/core/HttpTransport.d.ts +0 -53
- package/dist/core/HttpTransport.d.ts.map +0 -1
- package/dist/core/HttpTransport.js +0 -108
- package/dist/core/HttpTransport.js.map +0 -1
- package/dist/core/Input.d.ts +0 -256
- package/dist/core/Input.d.ts.map +0 -1
- package/dist/core/Input.js +0 -557
- package/dist/core/Input.js.map +0 -1
- package/dist/core/JavaRandom.d.ts +0 -55
- package/dist/core/JavaRandom.d.ts.map +0 -1
- package/dist/core/JavaRandom.js +0 -81
- package/dist/core/JavaRandom.js.map +0 -1
- package/dist/core/Loading.d.ts +0 -65
- package/dist/core/Loading.d.ts.map +0 -1
- package/dist/core/Loading.js +0 -119
- package/dist/core/Loading.js.map +0 -1
- package/dist/core/Log.d.ts +0 -48
- package/dist/core/Log.d.ts.map +0 -1
- package/dist/core/Log.js +0 -59
- package/dist/core/Log.js.map +0 -1
- package/dist/core/Math.d.ts +0 -14
- package/dist/core/Math.d.ts.map +0 -1
- package/dist/core/Math.js +0 -16
- package/dist/core/Math.js.map +0 -1
- package/dist/core/Motion.d.ts +0 -47
- package/dist/core/Motion.d.ts.map +0 -1
- package/dist/core/Motion.js +0 -122
- package/dist/core/Motion.js.map +0 -1
- package/dist/core/Multiplayer.d.ts +0 -101
- package/dist/core/Multiplayer.d.ts.map +0 -1
- package/dist/core/Multiplayer.js +0 -156
- package/dist/core/Multiplayer.js.map +0 -1
- package/dist/core/News.d.ts +0 -51
- package/dist/core/News.d.ts.map +0 -1
- package/dist/core/News.js +0 -65
- package/dist/core/News.js.map +0 -1
- package/dist/core/Pathfinding.d.ts +0 -41
- package/dist/core/Pathfinding.d.ts.map +0 -1
- package/dist/core/Pathfinding.js +0 -86
- package/dist/core/Pathfinding.js.map +0 -1
- package/dist/core/PlayerInput.d.ts +0 -57
- package/dist/core/PlayerInput.d.ts.map +0 -1
- package/dist/core/PlayerInput.js +0 -82
- package/dist/core/PlayerInput.js.map +0 -1
- package/dist/core/Presentation.d.ts +0 -56
- package/dist/core/Presentation.d.ts.map +0 -1
- package/dist/core/Presentation.js +0 -78
- package/dist/core/Presentation.js.map +0 -1
- package/dist/core/Random.d.ts +0 -259
- package/dist/core/Random.d.ts.map +0 -1
- package/dist/core/Random.js +0 -408
- package/dist/core/Random.js.map +0 -1
- package/dist/core/Reactions.d.ts +0 -67
- package/dist/core/Reactions.d.ts.map +0 -1
- package/dist/core/Reactions.js +0 -92
- package/dist/core/Reactions.js.map +0 -1
- package/dist/core/Registry.d.ts +0 -31
- package/dist/core/Registry.d.ts.map +0 -1
- package/dist/core/Registry.js +0 -46
- package/dist/core/Registry.js.map +0 -1
- package/dist/core/Replay.d.ts +0 -126
- package/dist/core/Replay.d.ts.map +0 -1
- package/dist/core/Replay.js +0 -162
- package/dist/core/Replay.js.map +0 -1
- package/dist/core/ReplayFile.d.ts +0 -197
- package/dist/core/ReplayFile.d.ts.map +0 -1
- package/dist/core/ReplayFile.js +0 -257
- package/dist/core/ReplayFile.js.map +0 -1
- package/dist/core/RunHistory.d.ts +0 -54
- package/dist/core/RunHistory.d.ts.map +0 -1
- package/dist/core/RunHistory.js +0 -40
- package/dist/core/RunHistory.js.map +0 -1
- package/dist/core/Sanitize.d.ts +0 -101
- package/dist/core/Sanitize.d.ts.map +0 -1
- package/dist/core/Sanitize.js +0 -162
- package/dist/core/Sanitize.js.map +0 -1
- package/dist/core/Save.d.ts +0 -123
- package/dist/core/Save.d.ts.map +0 -1
- package/dist/core/Save.js +0 -216
- package/dist/core/Save.js.map +0 -1
- package/dist/core/SaveSync.d.ts +0 -43
- package/dist/core/SaveSync.d.ts.map +0 -1
- package/dist/core/SaveSync.js +0 -56
- package/dist/core/SaveSync.js.map +0 -1
- package/dist/core/Scene.d.ts +0 -63
- package/dist/core/Scene.d.ts.map +0 -1
- package/dist/core/Scene.js +0 -81
- package/dist/core/Scene.js.map +0 -1
- package/dist/core/SceneComponents.d.ts +0 -67
- package/dist/core/SceneComponents.d.ts.map +0 -1
- package/dist/core/SceneComponents.js +0 -76
- package/dist/core/SceneComponents.js.map +0 -1
- package/dist/core/SceneStack.d.ts +0 -61
- package/dist/core/SceneStack.d.ts.map +0 -1
- package/dist/core/SceneStack.js +0 -91
- package/dist/core/SceneStack.js.map +0 -1
- package/dist/core/Scramble.d.ts +0 -21
- package/dist/core/Scramble.d.ts.map +0 -1
- package/dist/core/Scramble.js +0 -52
- package/dist/core/Scramble.js.map +0 -1
- package/dist/core/Session.d.ts +0 -31
- package/dist/core/Session.d.ts.map +0 -1
- package/dist/core/Session.js +0 -11
- package/dist/core/Session.js.map +0 -1
- package/dist/core/Settings.d.ts +0 -96
- package/dist/core/Settings.d.ts.map +0 -1
- package/dist/core/Settings.js +0 -190
- package/dist/core/Settings.js.map +0 -1
- package/dist/core/Signal.d.ts +0 -35
- package/dist/core/Signal.d.ts.map +0 -1
- package/dist/core/Signal.js +0 -41
- package/dist/core/Signal.js.map +0 -1
- package/dist/core/Spawner.d.ts +0 -65
- package/dist/core/Spawner.d.ts.map +0 -1
- package/dist/core/Spawner.js +0 -82
- package/dist/core/Spawner.js.map +0 -1
- package/dist/core/State.d.ts +0 -97
- package/dist/core/State.d.ts.map +0 -1
- package/dist/core/State.js +0 -177
- package/dist/core/State.js.map +0 -1
- package/dist/core/Stats.d.ts +0 -46
- package/dist/core/Stats.d.ts.map +0 -1
- package/dist/core/Stats.js +0 -47
- package/dist/core/Stats.js.map +0 -1
- package/dist/core/StoredValue.d.ts +0 -30
- package/dist/core/StoredValue.d.ts.map +0 -1
- package/dist/core/StoredValue.js +0 -38
- package/dist/core/StoredValue.js.map +0 -1
- package/dist/core/SyncGuard.d.ts +0 -57
- package/dist/core/SyncGuard.d.ts.map +0 -1
- package/dist/core/SyncGuard.js +0 -116
- package/dist/core/SyncGuard.js.map +0 -1
- package/dist/core/Telemetry.d.ts +0 -63
- package/dist/core/Telemetry.d.ts.map +0 -1
- package/dist/core/Telemetry.js +0 -83
- package/dist/core/Telemetry.js.map +0 -1
- package/dist/core/Twee.d.ts +0 -101
- package/dist/core/Twee.d.ts.map +0 -1
- package/dist/core/Twee.js +0 -174
- package/dist/core/Twee.js.map +0 -1
- package/dist/core/Tween.d.ts +0 -60
- package/dist/core/Tween.d.ts.map +0 -1
- package/dist/core/Tween.js +0 -98
- package/dist/core/Tween.js.map +0 -1
- package/dist/core/UndoHistory.d.ts +0 -52
- package/dist/core/UndoHistory.d.ts.map +0 -1
- package/dist/core/UndoHistory.js +0 -49
- package/dist/core/UndoHistory.js.map +0 -1
- package/dist/core/index.d.ts +0 -94
- package/dist/core/index.d.ts.map +0 -1
- package/dist/core/index.js +0 -53
- package/dist/core/index.js.map +0 -1
- package/dist/headless/index.d.ts +0 -87
- package/dist/headless/index.d.ts.map +0 -1
- package/dist/headless/index.js +0 -87
- package/dist/headless/index.js.map +0 -1
- package/dist/i18n/Content.d.ts +0 -151
- package/dist/i18n/Content.d.ts.map +0 -1
- package/dist/i18n/Content.js +0 -218
- package/dist/i18n/Content.js.map +0 -1
- package/dist/i18n/EditSession.d.ts +0 -101
- package/dist/i18n/EditSession.d.ts.map +0 -1
- package/dist/i18n/EditSession.js +0 -150
- package/dist/i18n/EditSession.js.map +0 -1
- package/dist/i18n/Fluent.d.ts +0 -7
- package/dist/i18n/Fluent.d.ts.map +0 -1
- package/dist/i18n/Fluent.js +0 -98
- package/dist/i18n/Fluent.js.map +0 -1
- package/dist/i18n/Format.d.ts +0 -25
- package/dist/i18n/Format.d.ts.map +0 -1
- package/dist/i18n/Format.js +0 -32
- package/dist/i18n/Format.js.map +0 -1
- package/dist/i18n/FormatSpec.d.ts +0 -76
- package/dist/i18n/FormatSpec.d.ts.map +0 -1
- package/dist/i18n/FormatSpec.js +0 -306
- package/dist/i18n/FormatSpec.js.map +0 -1
- package/dist/i18n/Po.d.ts +0 -54
- package/dist/i18n/Po.d.ts.map +0 -1
- package/dist/i18n/Po.js +0 -192
- package/dist/i18n/Po.js.map +0 -1
- package/dist/i18n/SemanticMessage.d.ts +0 -84
- package/dist/i18n/SemanticMessage.d.ts.map +0 -1
- package/dist/i18n/SemanticMessage.js +0 -54
- package/dist/i18n/SemanticMessage.js.map +0 -1
- package/dist/i18n/SoundMarkers.d.ts +0 -38
- package/dist/i18n/SoundMarkers.d.ts.map +0 -1
- package/dist/i18n/SoundMarkers.js +0 -48
- package/dist/i18n/SoundMarkers.js.map +0 -1
- package/dist/i18n/Validate.d.ts +0 -82
- package/dist/i18n/Validate.d.ts.map +0 -1
- package/dist/i18n/Validate.js +0 -106
- package/dist/i18n/Validate.js.map +0 -1
- package/dist/i18n/index.d.ts +0 -177
- package/dist/i18n/index.d.ts.map +0 -1
- package/dist/i18n/index.js +0 -331
- package/dist/i18n/index.js.map +0 -1
- package/dist/index.d.ts +0 -26
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -26
- package/dist/index.js.map +0 -1
- package/dist/mw_games.global.js +0 -1407
- package/dist/mwl/MapFile.d.ts +0 -41
- package/dist/mwl/MapFile.d.ts.map +0 -1
- package/dist/mwl/MapFile.js +0 -53
- package/dist/mwl/MapFile.js.map +0 -1
- package/dist/mwl/actors.d.ts +0 -62
- package/dist/mwl/actors.d.ts.map +0 -1
- package/dist/mwl/actors.js +0 -82
- package/dist/mwl/actors.js.map +0 -1
- package/dist/mwl/campaign.d.ts +0 -51
- package/dist/mwl/campaign.d.ts.map +0 -1
- package/dist/mwl/campaign.js +0 -58
- package/dist/mwl/campaign.js.map +0 -1
- package/dist/mwl/carryover.d.ts +0 -86
- package/dist/mwl/carryover.d.ts.map +0 -1
- package/dist/mwl/carryover.js +0 -70
- package/dist/mwl/carryover.js.map +0 -1
- package/dist/mwl/catalog.d.ts +0 -98
- package/dist/mwl/catalog.d.ts.map +0 -1
- package/dist/mwl/catalog.js +0 -259
- package/dist/mwl/catalog.js.map +0 -1
- package/dist/mwl/compiler.d.ts +0 -135
- package/dist/mwl/compiler.d.ts.map +0 -1
- package/dist/mwl/compiler.js +0 -216
- package/dist/mwl/compiler.js.map +0 -1
- package/dist/mwl/conditions.d.ts +0 -18
- package/dist/mwl/conditions.d.ts.map +0 -1
- package/dist/mwl/conditions.js +0 -171
- package/dist/mwl/conditions.js.map +0 -1
- package/dist/mwl/content.d.ts +0 -140
- package/dist/mwl/content.d.ts.map +0 -1
- package/dist/mwl/content.js +0 -179
- package/dist/mwl/content.js.map +0 -1
- package/dist/mwl/expression.d.ts +0 -42
- package/dist/mwl/expression.d.ts.map +0 -1
- package/dist/mwl/expression.js +0 -164
- package/dist/mwl/expression.js.map +0 -1
- package/dist/mwl/grammar.d.ts +0 -100
- package/dist/mwl/grammar.d.ts.map +0 -1
- package/dist/mwl/grammar.js +0 -588
- package/dist/mwl/grammar.js.map +0 -1
- package/dist/mwl/hooks.d.ts +0 -201
- package/dist/mwl/hooks.d.ts.map +0 -1
- package/dist/mwl/hooks.js +0 -165
- package/dist/mwl/hooks.js.map +0 -1
- package/dist/mwl/index.d.ts +0 -40
- package/dist/mwl/index.d.ts.map +0 -1
- package/dist/mwl/index.js +0 -20
- package/dist/mwl/index.js.map +0 -1
- package/dist/mwl/objects.d.ts +0 -31
- package/dist/mwl/objects.d.ts.map +0 -1
- package/dist/mwl/objects.js +0 -83
- package/dist/mwl/objects.js.map +0 -1
- package/dist/mwl/persistence.d.ts +0 -67
- package/dist/mwl/persistence.d.ts.map +0 -1
- package/dist/mwl/persistence.js +0 -135
- package/dist/mwl/persistence.js.map +0 -1
- package/dist/mwl/presentation.d.ts +0 -86
- package/dist/mwl/presentation.d.ts.map +0 -1
- package/dist/mwl/presentation.js +0 -419
- package/dist/mwl/presentation.js.map +0 -1
- package/dist/mwl/pyroeis-runtime.d.ts +0 -82
- package/dist/mwl/pyroeis-runtime.d.ts.map +0 -1
- package/dist/mwl/pyroeis-runtime.js +0 -535
- package/dist/mwl/pyroeis-runtime.js.map +0 -1
- package/dist/mwl/pyroeis.d.ts +0 -54
- package/dist/mwl/pyroeis.d.ts.map +0 -1
- package/dist/mwl/pyroeis.js +0 -189
- package/dist/mwl/pyroeis.js.map +0 -1
- package/dist/mwl/readers.d.ts +0 -77
- package/dist/mwl/readers.d.ts.map +0 -1
- package/dist/mwl/readers.js +0 -150
- package/dist/mwl/readers.js.map +0 -1
- package/dist/mwl/report.d.ts +0 -44
- package/dist/mwl/report.d.ts.map +0 -1
- package/dist/mwl/report.js +0 -88
- package/dist/mwl/report.js.map +0 -1
- package/dist/mwl/runtime.d.ts +0 -577
- package/dist/mwl/runtime.d.ts.map +0 -1
- package/dist/mwl/runtime.js +0 -1741
- package/dist/mwl/runtime.js.map +0 -1
- package/dist/mwl/schema.d.ts +0 -151
- package/dist/mwl/schema.d.ts.map +0 -1
- package/dist/mwl/schema.js +0 -979
- package/dist/mwl/schema.js.map +0 -1
- package/dist/mwl/scripts.d.ts +0 -26
- package/dist/mwl/scripts.d.ts.map +0 -1
- package/dist/mwl/scripts.js +0 -34
- package/dist/mwl/scripts.js.map +0 -1
- package/dist/mwl/tables.d.ts +0 -95
- package/dist/mwl/tables.d.ts.map +0 -1
- package/dist/mwl/tables.js +0 -100
- package/dist/mwl/tables.js.map +0 -1
- package/dist/mwl/utils.d.ts +0 -10
- package/dist/mwl/utils.d.ts.map +0 -1
- package/dist/mwl/utils.js +0 -40
- package/dist/mwl/utils.js.map +0 -1
- package/dist/physics/PhysicsWorld.d.ts +0 -158
- package/dist/physics/PhysicsWorld.d.ts.map +0 -1
- package/dist/physics/PhysicsWorld.js +0 -375
- package/dist/physics/PhysicsWorld.js.map +0 -1
- package/dist/physics/XpbdWorld.d.ts +0 -213
- package/dist/physics/XpbdWorld.d.ts.map +0 -1
- package/dist/physics/XpbdWorld.js +0 -336
- package/dist/physics/XpbdWorld.js.map +0 -1
- package/dist/physics/cloth/index.d.ts +0 -99
- package/dist/physics/cloth/index.d.ts.map +0 -1
- package/dist/physics/cloth/index.js +0 -226
- package/dist/physics/cloth/index.js.map +0 -1
- package/dist/physics/index.d.ts +0 -7
- package/dist/physics/index.d.ts.map +0 -1
- package/dist/physics/index.js +0 -4
- package/dist/physics/index.js.map +0 -1
- package/dist/physics/spring/index.d.ts +0 -91
- package/dist/physics/spring/index.d.ts.map +0 -1
- package/dist/physics/spring/index.js +0 -120
- package/dist/physics/spring/index.js.map +0 -1
- package/dist/physics/xpbd.d.ts +0 -3
- package/dist/physics/xpbd.d.ts.map +0 -1
- package/dist/physics/xpbd.js +0 -2
- package/dist/physics/xpbd.js.map +0 -1
- package/dist/roguelike/Boss.d.ts +0 -79
- package/dist/roguelike/Boss.d.ts.map +0 -1
- package/dist/roguelike/Boss.js +0 -126
- package/dist/roguelike/Boss.js.map +0 -1
- package/dist/roguelike/Cave.d.ts +0 -124
- package/dist/roguelike/Cave.d.ts.map +0 -1
- package/dist/roguelike/Cave.js +0 -216
- package/dist/roguelike/Cave.js.map +0 -1
- package/dist/roguelike/Combat.d.ts +0 -35
- package/dist/roguelike/Combat.d.ts.map +0 -1
- package/dist/roguelike/Combat.js +0 -33
- package/dist/roguelike/Combat.js.map +0 -1
- package/dist/roguelike/ContentRoll.d.ts +0 -53
- package/dist/roguelike/ContentRoll.d.ts.map +0 -1
- package/dist/roguelike/ContentRoll.js +0 -48
- package/dist/roguelike/ContentRoll.js.map +0 -1
- package/dist/roguelike/Doors.d.ts +0 -73
- package/dist/roguelike/Doors.d.ts.map +0 -1
- package/dist/roguelike/Doors.js +0 -115
- package/dist/roguelike/Doors.js.map +0 -1
- package/dist/roguelike/DungeonParity.d.ts +0 -57
- package/dist/roguelike/DungeonParity.d.ts.map +0 -1
- package/dist/roguelike/DungeonParity.js +0 -87
- package/dist/roguelike/DungeonParity.js.map +0 -1
- package/dist/roguelike/Elevation.d.ts +0 -41
- package/dist/roguelike/Elevation.d.ts.map +0 -1
- package/dist/roguelike/Elevation.js +0 -52
- package/dist/roguelike/Elevation.js.map +0 -1
- package/dist/roguelike/Features.d.ts +0 -59
- package/dist/roguelike/Features.d.ts.map +0 -1
- package/dist/roguelike/Features.js +0 -76
- package/dist/roguelike/Features.js.map +0 -1
- package/dist/roguelike/FieldOfView.d.ts +0 -86
- package/dist/roguelike/FieldOfView.d.ts.map +0 -1
- package/dist/roguelike/FieldOfView.js +0 -148
- package/dist/roguelike/FieldOfView.js.map +0 -1
- package/dist/roguelike/Level.d.ts +0 -139
- package/dist/roguelike/Level.d.ts.map +0 -1
- package/dist/roguelike/Level.js +0 -189
- package/dist/roguelike/Level.js.map +0 -1
- package/dist/roguelike/MonsterAI.d.ts +0 -54
- package/dist/roguelike/MonsterAI.d.ts.map +0 -1
- package/dist/roguelike/MonsterAI.js +0 -83
- package/dist/roguelike/MonsterAI.js.map +0 -1
- package/dist/roguelike/MultiStageAbility.d.ts +0 -59
- package/dist/roguelike/MultiStageAbility.d.ts.map +0 -1
- package/dist/roguelike/MultiStageAbility.js +0 -76
- package/dist/roguelike/MultiStageAbility.js.map +0 -1
- package/dist/roguelike/MultiTurnBeam.d.ts +0 -108
- package/dist/roguelike/MultiTurnBeam.d.ts.map +0 -1
- package/dist/roguelike/MultiTurnBeam.js +0 -164
- package/dist/roguelike/MultiTurnBeam.js.map +0 -1
- package/dist/roguelike/Overworld.d.ts +0 -89
- package/dist/roguelike/Overworld.d.ts.map +0 -1
- package/dist/roguelike/Overworld.js +0 -325
- package/dist/roguelike/Overworld.js.map +0 -1
- package/dist/roguelike/Pathfinder.d.ts +0 -103
- package/dist/roguelike/Pathfinder.d.ts.map +0 -1
- package/dist/roguelike/Pathfinder.js +0 -213
- package/dist/roguelike/Pathfinder.js.map +0 -1
- package/dist/roguelike/Placement.d.ts +0 -62
- package/dist/roguelike/Placement.d.ts.map +0 -1
- package/dist/roguelike/Placement.js +0 -79
- package/dist/roguelike/Placement.js.map +0 -1
- package/dist/roguelike/RoomBuilders.d.ts +0 -60
- package/dist/roguelike/RoomBuilders.d.ts.map +0 -1
- package/dist/roguelike/RoomBuilders.js +0 -57
- package/dist/roguelike/RoomBuilders.js.map +0 -1
- package/dist/roguelike/Scheduler.d.ts +0 -96
- package/dist/roguelike/Scheduler.d.ts.map +0 -1
- package/dist/roguelike/Scheduler.js +0 -154
- package/dist/roguelike/Scheduler.js.map +0 -1
- package/dist/roguelike/Secrets.d.ts +0 -57
- package/dist/roguelike/Secrets.d.ts.map +0 -1
- package/dist/roguelike/Secrets.js +0 -77
- package/dist/roguelike/Secrets.js.map +0 -1
- package/dist/roguelike/Stealth.d.ts +0 -47
- package/dist/roguelike/Stealth.d.ts.map +0 -1
- package/dist/roguelike/Stealth.js +0 -48
- package/dist/roguelike/Stealth.js.map +0 -1
- package/dist/roguelike/Targeting.d.ts +0 -312
- package/dist/roguelike/Targeting.d.ts.map +0 -1
- package/dist/roguelike/Targeting.js +0 -483
- package/dist/roguelike/Targeting.js.map +0 -1
- package/dist/roguelike/TriggerTracker.d.ts +0 -46
- package/dist/roguelike/TriggerTracker.d.ts.map +0 -1
- package/dist/roguelike/TriggerTracker.js +0 -59
- package/dist/roguelike/TriggerTracker.js.map +0 -1
- package/dist/roguelike/generate.d.ts +0 -139
- package/dist/roguelike/generate.d.ts.map +0 -1
- package/dist/roguelike/generate.js +0 -166
- package/dist/roguelike/generate.js.map +0 -1
- package/dist/roguelike/index.d.ts +0 -48
- package/dist/roguelike/index.d.ts.map +0 -1
- package/dist/roguelike/index.js +0 -27
- package/dist/roguelike/index.js.map +0 -1
- package/dist/rpg/Collision.d.ts +0 -61
- package/dist/rpg/Collision.d.ts.map +0 -1
- package/dist/rpg/Collision.js +0 -94
- package/dist/rpg/Collision.js.map +0 -1
- package/dist/rpg/Event.d.ts +0 -50
- package/dist/rpg/Event.d.ts.map +0 -1
- package/dist/rpg/Event.js +0 -36
- package/dist/rpg/Event.js.map +0 -1
- package/dist/rpg/EventRunner.d.ts +0 -139
- package/dist/rpg/EventRunner.d.ts.map +0 -1
- package/dist/rpg/EventRunner.js +0 -125
- package/dist/rpg/EventRunner.js.map +0 -1
- package/dist/rpg/FreeMover.d.ts +0 -59
- package/dist/rpg/FreeMover.d.ts.map +0 -1
- package/dist/rpg/FreeMover.js +0 -79
- package/dist/rpg/FreeMover.js.map +0 -1
- package/dist/rpg/GameState.d.ts +0 -36
- package/dist/rpg/GameState.d.ts.map +0 -1
- package/dist/rpg/GameState.js +0 -49
- package/dist/rpg/GameState.js.map +0 -1
- package/dist/rpg/GridMover.d.ts +0 -71
- package/dist/rpg/GridMover.d.ts.map +0 -1
- package/dist/rpg/GridMover.js +0 -119
- package/dist/rpg/GridMover.js.map +0 -1
- package/dist/rpg/Marshal.d.ts +0 -81
- package/dist/rpg/Marshal.d.ts.map +0 -1
- package/dist/rpg/Marshal.js +0 -422
- package/dist/rpg/Marshal.js.map +0 -1
- package/dist/rpg/MovableSprite.d.ts +0 -31
- package/dist/rpg/MovableSprite.d.ts.map +0 -1
- package/dist/rpg/MovableSprite.js +0 -10
- package/dist/rpg/MovableSprite.js.map +0 -1
- package/dist/rpg/MoveRoute.d.ts +0 -118
- package/dist/rpg/MoveRoute.d.ts.map +0 -1
- package/dist/rpg/MoveRoute.js +0 -139
- package/dist/rpg/MoveRoute.js.map +0 -1
- package/dist/rpg/Quest.d.ts +0 -173
- package/dist/rpg/Quest.d.ts.map +0 -1
- package/dist/rpg/Quest.js +0 -221
- package/dist/rpg/Quest.js.map +0 -1
- package/dist/rpg/automap.d.ts +0 -81
- package/dist/rpg/automap.d.ts.map +0 -1
- package/dist/rpg/automap.js +0 -107
- package/dist/rpg/automap.js.map +0 -1
- package/dist/rpg/dialogue-text.d.ts +0 -81
- package/dist/rpg/dialogue-text.d.ts.map +0 -1
- package/dist/rpg/dialogue-text.js +0 -88
- package/dist/rpg/dialogue-text.js.map +0 -1
- package/dist/rpg/index.d.ts +0 -25
- package/dist/rpg/index.d.ts.map +0 -1
- package/dist/rpg/index.js +0 -14
- package/dist/rpg/index.js.map +0 -1
- package/dist/rpg/twee-events.d.ts +0 -48
- package/dist/rpg/twee-events.d.ts.map +0 -1
- package/dist/rpg/twee-events.js +0 -35
- package/dist/rpg/twee-events.js.map +0 -1
- package/dist/simulation/Campaign.d.ts +0 -60
- package/dist/simulation/Campaign.d.ts.map +0 -1
- package/dist/simulation/Campaign.js +0 -89
- package/dist/simulation/Campaign.js.map +0 -1
- package/dist/simulation/CampaignSave.d.ts +0 -68
- package/dist/simulation/CampaignSave.d.ts.map +0 -1
- package/dist/simulation/CampaignSave.js +0 -54
- package/dist/simulation/CampaignSave.js.map +0 -1
- package/dist/simulation/EventPresentation.d.ts +0 -111
- package/dist/simulation/EventPresentation.d.ts.map +0 -1
- package/dist/simulation/EventPresentation.js +0 -120
- package/dist/simulation/EventPresentation.js.map +0 -1
- package/dist/simulation/Harness.d.ts +0 -26
- package/dist/simulation/Harness.d.ts.map +0 -1
- package/dist/simulation/Harness.js +0 -26
- package/dist/simulation/Harness.js.map +0 -1
- package/dist/simulation/Runtime.d.ts +0 -189
- package/dist/simulation/Runtime.d.ts.map +0 -1
- package/dist/simulation/Runtime.js +0 -244
- package/dist/simulation/Runtime.js.map +0 -1
- package/dist/simulation/Scenario.d.ts +0 -44
- package/dist/simulation/Scenario.d.ts.map +0 -1
- package/dist/simulation/Scenario.js +0 -40
- package/dist/simulation/Scenario.js.map +0 -1
- package/dist/simulation/Training.d.ts +0 -220
- package/dist/simulation/Training.d.ts.map +0 -1
- package/dist/simulation/Training.js +0 -366
- package/dist/simulation/Training.js.map +0 -1
- package/dist/simulation/Turns.d.ts +0 -40
- package/dist/simulation/Turns.d.ts.map +0 -1
- package/dist/simulation/Turns.js +0 -41
- package/dist/simulation/Turns.js.map +0 -1
- package/dist/simulation/index.d.ts +0 -25
- package/dist/simulation/index.d.ts.map +0 -1
- package/dist/simulation/index.js +0 -16
- package/dist/simulation/index.js.map +0 -1
- package/dist/skeleton/index.d.ts +0 -212
- package/dist/skeleton/index.d.ts.map +0 -1
- package/dist/skeleton/index.js +0 -325
- package/dist/skeleton/index.js.map +0 -1
- package/dist/testing/SceneControls.d.ts +0 -35
- package/dist/testing/SceneControls.d.ts.map +0 -1
- package/dist/testing/SceneControls.js +0 -49
- package/dist/testing/SceneControls.js.map +0 -1
- package/dist/testing/index.d.ts +0 -123
- package/dist/testing/index.d.ts.map +0 -1
- package/dist/testing/index.js +0 -156
- package/dist/testing/index.js.map +0 -1
- package/dist/threads/index.d.ts +0 -3
- package/dist/threads/index.d.ts.map +0 -1
- package/dist/threads/index.js +0 -2
- package/dist/threads/index.js.map +0 -1
- package/dist/threads/spawn.d.ts +0 -41
- package/dist/threads/spawn.d.ts.map +0 -1
- package/dist/threads/spawn.js +0 -143
- package/dist/threads/spawn.js.map +0 -1
- package/dist/threads/worker.d.ts +0 -51
- package/dist/threads/worker.d.ts.map +0 -1
- package/dist/threads/worker.js +0 -84
- package/dist/threads/worker.js.map +0 -1
- package/dist/three-d/Character3D.d.ts +0 -74
- package/dist/three-d/Character3D.d.ts.map +0 -1
- package/dist/three-d/Character3D.js +0 -122
- package/dist/three-d/Character3D.js.map +0 -1
- package/dist/three-d/Collision3D.d.ts +0 -111
- package/dist/three-d/Collision3D.d.ts.map +0 -1
- package/dist/three-d/Collision3D.js +0 -119
- package/dist/three-d/Collision3D.js.map +0 -1
- package/dist/three-d/Engine3D.d.ts +0 -25
- package/dist/three-d/Engine3D.d.ts.map +0 -1
- package/dist/three-d/Engine3D.js +0 -45
- package/dist/three-d/Engine3D.js.map +0 -1
- package/dist/three-d/Grid.d.ts +0 -30
- package/dist/three-d/Grid.d.ts.map +0 -1
- package/dist/three-d/Grid.js +0 -24
- package/dist/three-d/Grid.js.map +0 -1
- package/dist/three-d/Heightmap.d.ts +0 -38
- package/dist/three-d/Heightmap.d.ts.map +0 -1
- package/dist/three-d/Heightmap.js +0 -29
- package/dist/three-d/Heightmap.js.map +0 -1
- package/dist/three-d/Models.d.ts +0 -49
- package/dist/three-d/Models.d.ts.map +0 -1
- package/dist/three-d/Models.js +0 -77
- package/dist/three-d/Models.js.map +0 -1
- package/dist/three-d/TileGrid3D.d.ts +0 -27
- package/dist/three-d/TileGrid3D.d.ts.map +0 -1
- package/dist/three-d/TileGrid3D.js +0 -66
- package/dist/three-d/TileGrid3D.js.map +0 -1
- package/dist/three-d/Vox.d.ts +0 -43
- package/dist/three-d/Vox.d.ts.map +0 -1
- package/dist/three-d/Vox.js +0 -108
- package/dist/three-d/Vox.js.map +0 -1
- package/dist/three-d/index.d.ts +0 -15
- package/dist/three-d/index.d.ts.map +0 -1
- package/dist/three-d/index.js +0 -8
- package/dist/three-d/index.js.map +0 -1
- package/dist/two-d/Game.d.ts +0 -229
- package/dist/two-d/Game.d.ts.map +0 -1
- package/dist/two-d/Game.js +0 -463
- package/dist/two-d/Game.js.map +0 -1
- package/dist/two-d/QualityScaler.d.ts +0 -63
- package/dist/two-d/QualityScaler.d.ts.map +0 -1
- package/dist/two-d/QualityScaler.js +0 -92
- package/dist/two-d/QualityScaler.js.map +0 -1
- package/dist/two-d/ResolutionFit.d.ts +0 -28
- package/dist/two-d/ResolutionFit.d.ts.map +0 -1
- package/dist/two-d/ResolutionFit.js +0 -39
- package/dist/two-d/ResolutionFit.js.map +0 -1
- package/dist/two-d/Scene2D.d.ts +0 -43
- package/dist/two-d/Scene2D.d.ts.map +0 -1
- package/dist/two-d/Scene2D.js +0 -53
- package/dist/two-d/Scene2D.js.map +0 -1
- package/dist/two-d/index.d.ts +0 -22
- package/dist/two-d/index.d.ts.map +0 -1
- package/dist/two-d/index.js +0 -19
- package/dist/two-d/index.js.map +0 -1
- package/dist/two-d/pixi-interop.d.ts +0 -66
- package/dist/two-d/pixi-interop.d.ts.map +0 -1
- package/dist/two-d/pixi-interop.js +0 -72
- package/dist/two-d/pixi-interop.js.map +0 -1
- package/dist/two-d/presentation/MwlPresentation.d.ts +0 -117
- package/dist/two-d/presentation/MwlPresentation.d.ts.map +0 -1
- package/dist/two-d/presentation/MwlPresentation.js +0 -755
- package/dist/two-d/presentation/MwlPresentation.js.map +0 -1
- package/dist/two-d/presentation/index.d.ts +0 -3
- package/dist/two-d/presentation/index.d.ts.map +0 -1
- package/dist/two-d/presentation/index.js +0 -2
- package/dist/two-d/presentation/index.js.map +0 -1
- package/dist/two-d/render/ActorAnimator.d.ts +0 -92
- package/dist/two-d/render/ActorAnimator.d.ts.map +0 -1
- package/dist/two-d/render/ActorAnimator.js +0 -97
- package/dist/two-d/render/ActorAnimator.js.map +0 -1
- package/dist/two-d/render/AnimatedSprite.d.ts +0 -154
- package/dist/two-d/render/AnimatedSprite.d.ts.map +0 -1
- package/dist/two-d/render/AnimatedSprite.js +0 -197
- package/dist/two-d/render/AnimatedSprite.js.map +0 -1
- package/dist/two-d/render/Autotile.d.ts +0 -74
- package/dist/two-d/render/Autotile.d.ts.map +0 -1
- package/dist/two-d/render/Autotile.js +0 -149
- package/dist/two-d/render/Autotile.js.map +0 -1
- package/dist/two-d/render/Beam.d.ts +0 -136
- package/dist/two-d/render/Beam.d.ts.map +0 -1
- package/dist/two-d/render/Beam.js +0 -203
- package/dist/two-d/render/Beam.js.map +0 -1
- package/dist/two-d/render/Camera.d.ts +0 -255
- package/dist/two-d/render/Camera.d.ts.map +0 -1
- package/dist/two-d/render/Camera.js +0 -376
- package/dist/two-d/render/Camera.js.map +0 -1
- package/dist/two-d/render/Capabilities.d.ts +0 -84
- package/dist/two-d/render/Capabilities.d.ts.map +0 -1
- package/dist/two-d/render/Capabilities.js +0 -129
- package/dist/two-d/render/Capabilities.js.map +0 -1
- package/dist/two-d/render/ClothSprite.d.ts +0 -83
- package/dist/two-d/render/ClothSprite.d.ts.map +0 -1
- package/dist/two-d/render/ClothSprite.js +0 -105
- package/dist/two-d/render/ClothSprite.js.map +0 -1
- package/dist/two-d/render/ColorBlindness.d.ts +0 -39
- package/dist/two-d/render/ColorBlindness.d.ts.map +0 -1
- package/dist/two-d/render/ColorBlindness.js +0 -45
- package/dist/two-d/render/ColorBlindness.js.map +0 -1
- package/dist/two-d/render/ColorTransformBatcher.d.ts +0 -143
- package/dist/two-d/render/ColorTransformBatcher.d.ts.map +0 -1
- package/dist/two-d/render/ColorTransformBatcher.js +0 -395
- package/dist/two-d/render/ColorTransformBatcher.js.map +0 -1
- package/dist/two-d/render/Flights.d.ts +0 -90
- package/dist/two-d/render/Flights.d.ts.map +0 -1
- package/dist/two-d/render/Flights.js +0 -135
- package/dist/two-d/render/Flights.js.map +0 -1
- package/dist/two-d/render/FogLayer.d.ts +0 -68
- package/dist/two-d/render/FogLayer.d.ts.map +0 -1
- package/dist/two-d/render/FogLayer.js +0 -83
- package/dist/two-d/render/FogLayer.js.map +0 -1
- package/dist/two-d/render/Halo.d.ts +0 -58
- package/dist/two-d/render/Halo.d.ts.map +0 -1
- package/dist/two-d/render/Halo.js +0 -48
- package/dist/two-d/render/Halo.js.map +0 -1
- package/dist/two-d/render/HazeLayer.d.ts +0 -112
- package/dist/two-d/render/HazeLayer.d.ts.map +0 -1
- package/dist/two-d/render/HazeLayer.js +0 -185
- package/dist/two-d/render/HazeLayer.js.map +0 -1
- package/dist/two-d/render/ImageModifiers.d.ts +0 -310
- package/dist/two-d/render/ImageModifiers.d.ts.map +0 -1
- package/dist/two-d/render/ImageModifiers.js +0 -723
- package/dist/two-d/render/ImageModifiers.js.map +0 -1
- package/dist/two-d/render/LayeredSprite.d.ts +0 -54
- package/dist/two-d/render/LayeredSprite.d.ts.map +0 -1
- package/dist/two-d/render/LayeredSprite.js +0 -80
- package/dist/two-d/render/LayeredSprite.js.map +0 -1
- package/dist/two-d/render/LightningArc.d.ts +0 -57
- package/dist/two-d/render/LightningArc.d.ts.map +0 -1
- package/dist/two-d/render/LightningArc.js +0 -91
- package/dist/two-d/render/LightningArc.js.map +0 -1
- package/dist/two-d/render/LiquidLayer.d.ts +0 -62
- package/dist/two-d/render/LiquidLayer.d.ts.map +0 -1
- package/dist/two-d/render/LiquidLayer.js +0 -102
- package/dist/two-d/render/LiquidLayer.js.map +0 -1
- package/dist/two-d/render/Minimap.d.ts +0 -100
- package/dist/two-d/render/Minimap.d.ts.map +0 -1
- package/dist/two-d/render/Minimap.js +0 -157
- package/dist/two-d/render/Minimap.js.map +0 -1
- package/dist/two-d/render/NeonGlow.d.ts +0 -100
- package/dist/two-d/render/NeonGlow.d.ts.map +0 -1
- package/dist/two-d/render/NeonGlow.js +0 -183
- package/dist/two-d/render/NeonGlow.js.map +0 -1
- package/dist/two-d/render/PaletteRemap.d.ts +0 -154
- package/dist/two-d/render/PaletteRemap.d.ts.map +0 -1
- package/dist/two-d/render/PaletteRemap.js +0 -217
- package/dist/two-d/render/PaletteRemap.js.map +0 -1
- package/dist/two-d/render/Particles.d.ts +0 -262
- package/dist/two-d/render/Particles.d.ts.map +0 -1
- package/dist/two-d/render/Particles.js +0 -370
- package/dist/two-d/render/Particles.js.map +0 -1
- package/dist/two-d/render/Projectile.d.ts +0 -67
- package/dist/two-d/render/Projectile.d.ts.map +0 -1
- package/dist/two-d/render/Projectile.js +0 -78
- package/dist/two-d/render/Projectile.js.map +0 -1
- package/dist/two-d/render/RpgmAutotile.d.ts +0 -324
- package/dist/two-d/render/RpgmAutotile.d.ts.map +0 -1
- package/dist/two-d/render/RpgmAutotile.js +0 -933
- package/dist/two-d/render/RpgmAutotile.js.map +0 -1
- package/dist/two-d/render/SceneTransition.d.ts +0 -272
- package/dist/two-d/render/SceneTransition.d.ts.map +0 -1
- package/dist/two-d/render/SceneTransition.js +0 -431
- package/dist/two-d/render/SceneTransition.js.map +0 -1
- package/dist/two-d/render/ScreenEffects.d.ts +0 -124
- package/dist/two-d/render/ScreenEffects.d.ts.map +0 -1
- package/dist/two-d/render/ScreenEffects.js +0 -214
- package/dist/two-d/render/ScreenEffects.js.map +0 -1
- package/dist/two-d/render/Shape2D.d.ts +0 -146
- package/dist/two-d/render/Shape2D.d.ts.map +0 -1
- package/dist/two-d/render/Shape2D.js +0 -166
- package/dist/two-d/render/Shape2D.js.map +0 -1
- package/dist/two-d/render/SkeletalSprite.d.ts +0 -121
- package/dist/two-d/render/SkeletalSprite.d.ts.map +0 -1
- package/dist/two-d/render/SkeletalSprite.js +0 -213
- package/dist/two-d/render/SkeletalSprite.js.map +0 -1
- package/dist/two-d/render/SpringSprite.d.ts +0 -40
- package/dist/two-d/render/SpringSprite.d.ts.map +0 -1
- package/dist/two-d/render/SpringSprite.js +0 -39
- package/dist/two-d/render/SpringSprite.js.map +0 -1
- package/dist/two-d/render/SpriteAttachment.d.ts +0 -55
- package/dist/two-d/render/SpriteAttachment.d.ts.map +0 -1
- package/dist/two-d/render/SpriteAttachment.js +0 -60
- package/dist/two-d/render/SpriteAttachment.js.map +0 -1
- package/dist/two-d/render/SpriteDeform.d.ts +0 -156
- package/dist/two-d/render/SpriteDeform.d.ts.map +0 -1
- package/dist/two-d/render/SpriteDeform.js +0 -278
- package/dist/two-d/render/SpriteDeform.js.map +0 -1
- package/dist/two-d/render/SpriteGroup.d.ts +0 -83
- package/dist/two-d/render/SpriteGroup.d.ts.map +0 -1
- package/dist/two-d/render/SpriteGroup.js +0 -107
- package/dist/two-d/render/SpriteGroup.js.map +0 -1
- package/dist/two-d/render/SpriteMotion.d.ts +0 -121
- package/dist/two-d/render/SpriteMotion.d.ts.map +0 -1
- package/dist/two-d/render/SpriteMotion.js +0 -193
- package/dist/two-d/render/SpriteMotion.js.map +0 -1
- package/dist/two-d/render/SpriteSheet.d.ts +0 -62
- package/dist/two-d/render/SpriteSheet.d.ts.map +0 -1
- package/dist/two-d/render/SpriteSheet.js +0 -122
- package/dist/two-d/render/SpriteSheet.js.map +0 -1
- package/dist/two-d/render/StatusVisuals.d.ts +0 -86
- package/dist/two-d/render/StatusVisuals.d.ts.map +0 -1
- package/dist/two-d/render/StatusVisuals.js +0 -111
- package/dist/two-d/render/StatusVisuals.js.map +0 -1
- package/dist/two-d/render/SvgSkeleton.d.ts +0 -54
- package/dist/two-d/render/SvgSkeleton.d.ts.map +0 -1
- package/dist/two-d/render/SvgSkeleton.js +0 -112
- package/dist/two-d/render/SvgSkeleton.js.map +0 -1
- package/dist/two-d/render/TerrainGraphics.d.ts +0 -142
- package/dist/two-d/render/TerrainGraphics.d.ts.map +0 -1
- package/dist/two-d/render/TerrainGraphics.js +0 -161
- package/dist/two-d/render/TerrainGraphics.js.map +0 -1
- package/dist/two-d/render/TerrainGraphicsLayer.d.ts +0 -55
- package/dist/two-d/render/TerrainGraphicsLayer.d.ts.map +0 -1
- package/dist/two-d/render/TerrainGraphicsLayer.js +0 -54
- package/dist/two-d/render/TerrainGraphicsLayer.js.map +0 -1
- package/dist/two-d/render/TileMap.d.ts +0 -395
- package/dist/two-d/render/TileMap.d.ts.map +0 -1
- package/dist/two-d/render/TileMap.js +0 -967
- package/dist/two-d/render/TileMap.js.map +0 -1
- package/dist/two-d/render/TiledMap.d.ts +0 -113
- package/dist/two-d/render/TiledMap.d.ts.map +0 -1
- package/dist/two-d/render/TiledMap.js +0 -129
- package/dist/two-d/render/TiledMap.js.map +0 -1
- package/dist/two-d/render/TintedSprite.d.ts +0 -60
- package/dist/two-d/render/TintedSprite.d.ts.map +0 -1
- package/dist/two-d/render/TintedSprite.js +0 -88
- package/dist/two-d/render/TintedSprite.js.map +0 -1
- package/dist/two-d/render/Types2D.d.ts +0 -56
- package/dist/two-d/render/Types2D.d.ts.map +0 -1
- package/dist/two-d/render/Types2D.js +0 -45
- package/dist/two-d/render/Types2D.js.map +0 -1
- package/dist/two-d/render/Viewport.d.ts +0 -68
- package/dist/two-d/render/Viewport.d.ts.map +0 -1
- package/dist/two-d/render/Viewport.js +0 -74
- package/dist/two-d/render/Viewport.js.map +0 -1
- package/dist/two-d/render/index.d.ts +0 -81
- package/dist/two-d/render/index.d.ts.map +0 -1
- package/dist/two-d/render/index.js +0 -43
- package/dist/two-d/render/index.js.map +0 -1
- package/dist/two-d/stage/DialogueStage.d.ts +0 -90
- package/dist/two-d/stage/DialogueStage.d.ts.map +0 -1
- package/dist/two-d/stage/DialogueStage.js +0 -218
- package/dist/two-d/stage/DialogueStage.js.map +0 -1
- package/dist/two-d/stage/StoryScreen.d.ts +0 -110
- package/dist/two-d/stage/StoryScreen.d.ts.map +0 -1
- package/dist/two-d/stage/StoryScreen.js +0 -178
- package/dist/two-d/stage/StoryScreen.js.map +0 -1
- package/dist/two-d/stage/dialogue-text.d.ts +0 -81
- package/dist/two-d/stage/dialogue-text.d.ts.map +0 -1
- package/dist/two-d/stage/dialogue-text.js +0 -95
- package/dist/two-d/stage/dialogue-text.js.map +0 -1
- package/dist/two-d/stage/index.d.ts +0 -10
- package/dist/two-d/stage/index.d.ts.map +0 -1
- package/dist/two-d/stage/index.js +0 -6
- package/dist/two-d/stage/index.js.map +0 -1
- package/dist/two-d/stage/script.d.ts +0 -160
- package/dist/two-d/stage/script.d.ts.map +0 -1
- package/dist/two-d/stage/script.js +0 -207
- package/dist/two-d/stage/script.js.map +0 -1
- package/dist/two-d/stage/twee.d.ts +0 -35
- package/dist/two-d/stage/twee.d.ts.map +0 -1
- package/dist/two-d/stage/twee.js +0 -28
- package/dist/two-d/stage/twee.js.map +0 -1
- package/dist/two-d/ui/Bar.d.ts +0 -83
- package/dist/two-d/ui/Bar.d.ts.map +0 -1
- package/dist/two-d/ui/Bar.js +0 -112
- package/dist/two-d/ui/Bar.js.map +0 -1
- package/dist/two-d/ui/BitmapLabel.d.ts +0 -58
- package/dist/two-d/ui/BitmapLabel.d.ts.map +0 -1
- package/dist/two-d/ui/BitmapLabel.js +0 -82
- package/dist/two-d/ui/BitmapLabel.js.map +0 -1
- package/dist/two-d/ui/Button.d.ts +0 -133
- package/dist/two-d/ui/Button.d.ts.map +0 -1
- package/dist/two-d/ui/Button.js +0 -254
- package/dist/two-d/ui/Button.js.map +0 -1
- package/dist/two-d/ui/Checkbox.d.ts +0 -44
- package/dist/two-d/ui/Checkbox.d.ts.map +0 -1
- package/dist/two-d/ui/Checkbox.js +0 -89
- package/dist/two-d/ui/Checkbox.js.map +0 -1
- package/dist/two-d/ui/DataTable.d.ts +0 -79
- package/dist/two-d/ui/DataTable.d.ts.map +0 -1
- package/dist/two-d/ui/DataTable.js +0 -164
- package/dist/two-d/ui/DataTable.js.map +0 -1
- package/dist/two-d/ui/Dropdown.d.ts +0 -75
- package/dist/two-d/ui/Dropdown.d.ts.map +0 -1
- package/dist/two-d/ui/Dropdown.js +0 -129
- package/dist/two-d/ui/Dropdown.js.map +0 -1
- package/dist/two-d/ui/DropdownView.d.ts +0 -86
- package/dist/two-d/ui/DropdownView.d.ts.map +0 -1
- package/dist/two-d/ui/DropdownView.js +0 -216
- package/dist/two-d/ui/DropdownView.js.map +0 -1
- package/dist/two-d/ui/EventDialogue.d.ts +0 -23
- package/dist/two-d/ui/EventDialogue.d.ts.map +0 -1
- package/dist/two-d/ui/EventDialogue.js +0 -33
- package/dist/two-d/ui/EventDialogue.js.map +0 -1
- package/dist/two-d/ui/FloatingText.d.ts +0 -123
- package/dist/two-d/ui/FloatingText.d.ts.map +0 -1
- package/dist/two-d/ui/FloatingText.js +0 -152
- package/dist/two-d/ui/FloatingText.js.map +0 -1
- package/dist/two-d/ui/FloatingTextStack.d.ts +0 -150
- package/dist/two-d/ui/FloatingTextStack.d.ts.map +0 -1
- package/dist/two-d/ui/FloatingTextStack.js +0 -170
- package/dist/two-d/ui/FloatingTextStack.js.map +0 -1
- package/dist/two-d/ui/HelpScreen.d.ts +0 -45
- package/dist/two-d/ui/HelpScreen.d.ts.map +0 -1
- package/dist/two-d/ui/HelpScreen.js +0 -59
- package/dist/two-d/ui/HelpScreen.js.map +0 -1
- package/dist/two-d/ui/IconGrid.d.ts +0 -143
- package/dist/two-d/ui/IconGrid.d.ts.map +0 -1
- package/dist/two-d/ui/IconGrid.js +0 -326
- package/dist/two-d/ui/IconGrid.js.map +0 -1
- package/dist/two-d/ui/Label.d.ts +0 -63
- package/dist/two-d/ui/Label.d.ts.map +0 -1
- package/dist/two-d/ui/Label.js +0 -134
- package/dist/two-d/ui/Label.js.map +0 -1
- package/dist/two-d/ui/Layout.d.ts +0 -139
- package/dist/two-d/ui/Layout.d.ts.map +0 -1
- package/dist/two-d/ui/Layout.js +0 -221
- package/dist/two-d/ui/Layout.js.map +0 -1
- package/dist/two-d/ui/ListView.d.ts +0 -130
- package/dist/two-d/ui/ListView.d.ts.map +0 -1
- package/dist/two-d/ui/ListView.js +0 -325
- package/dist/two-d/ui/ListView.js.map +0 -1
- package/dist/two-d/ui/LoadingScreen.d.ts +0 -54
- package/dist/two-d/ui/LoadingScreen.d.ts.map +0 -1
- package/dist/two-d/ui/LoadingScreen.js +0 -87
- package/dist/two-d/ui/LoadingScreen.js.map +0 -1
- package/dist/two-d/ui/MarkupText.d.ts +0 -66
- package/dist/two-d/ui/MarkupText.d.ts.map +0 -1
- package/dist/two-d/ui/MarkupText.js +0 -156
- package/dist/two-d/ui/MarkupText.js.map +0 -1
- package/dist/two-d/ui/MessageBox.d.ts +0 -134
- package/dist/two-d/ui/MessageBox.d.ts.map +0 -1
- package/dist/two-d/ui/MessageBox.js +0 -263
- package/dist/two-d/ui/MessageBox.js.map +0 -1
- package/dist/two-d/ui/MessageLog.d.ts +0 -90
- package/dist/two-d/ui/MessageLog.d.ts.map +0 -1
- package/dist/two-d/ui/MessageLog.js +0 -131
- package/dist/two-d/ui/MessageLog.js.map +0 -1
- package/dist/two-d/ui/Meter.d.ts +0 -76
- package/dist/two-d/ui/Meter.d.ts.map +0 -1
- package/dist/two-d/ui/Meter.js +0 -134
- package/dist/two-d/ui/Meter.js.map +0 -1
- package/dist/two-d/ui/NinePatch.d.ts +0 -49
- package/dist/two-d/ui/NinePatch.d.ts.map +0 -1
- package/dist/two-d/ui/NinePatch.js +0 -59
- package/dist/two-d/ui/NinePatch.js.map +0 -1
- package/dist/two-d/ui/OnScreenKeyboard.d.ts +0 -91
- package/dist/two-d/ui/OnScreenKeyboard.d.ts.map +0 -1
- package/dist/two-d/ui/OnScreenKeyboard.js +0 -109
- package/dist/two-d/ui/OnScreenKeyboard.js.map +0 -1
- package/dist/two-d/ui/RadioGroup.d.ts +0 -68
- package/dist/two-d/ui/RadioGroup.d.ts.map +0 -1
- package/dist/two-d/ui/RadioGroup.js +0 -177
- package/dist/two-d/ui/RadioGroup.js.map +0 -1
- package/dist/two-d/ui/RebindScreen.d.ts +0 -70
- package/dist/two-d/ui/RebindScreen.d.ts.map +0 -1
- package/dist/two-d/ui/RebindScreen.js +0 -129
- package/dist/two-d/ui/RebindScreen.js.map +0 -1
- package/dist/two-d/ui/RichLabel.d.ts +0 -62
- package/dist/two-d/ui/RichLabel.d.ts.map +0 -1
- package/dist/two-d/ui/RichLabel.js +0 -146
- package/dist/two-d/ui/RichLabel.js.map +0 -1
- package/dist/two-d/ui/ScrollBox.d.ts +0 -157
- package/dist/two-d/ui/ScrollBox.d.ts.map +0 -1
- package/dist/two-d/ui/ScrollBox.js +0 -329
- package/dist/two-d/ui/ScrollBox.js.map +0 -1
- package/dist/two-d/ui/ScrollText.d.ts +0 -122
- package/dist/two-d/ui/ScrollText.d.ts.map +0 -1
- package/dist/two-d/ui/ScrollText.js +0 -202
- package/dist/two-d/ui/ScrollText.js.map +0 -1
- package/dist/two-d/ui/SelectionModel.d.ts +0 -50
- package/dist/two-d/ui/SelectionModel.d.ts.map +0 -1
- package/dist/two-d/ui/SelectionModel.js +0 -73
- package/dist/two-d/ui/SelectionModel.js.map +0 -1
- package/dist/two-d/ui/SettingsScreen.d.ts +0 -112
- package/dist/two-d/ui/SettingsScreen.d.ts.map +0 -1
- package/dist/two-d/ui/SettingsScreen.js +0 -338
- package/dist/two-d/ui/SettingsScreen.js.map +0 -1
- package/dist/two-d/ui/Skins.d.ts +0 -59
- package/dist/two-d/ui/Skins.d.ts.map +0 -1
- package/dist/two-d/ui/Skins.js +0 -77
- package/dist/two-d/ui/Skins.js.map +0 -1
- package/dist/two-d/ui/Slider.d.ts +0 -91
- package/dist/two-d/ui/Slider.d.ts.map +0 -1
- package/dist/two-d/ui/Slider.js +0 -170
- package/dist/two-d/ui/Slider.js.map +0 -1
- package/dist/two-d/ui/Spinner.d.ts +0 -67
- package/dist/two-d/ui/Spinner.d.ts.map +0 -1
- package/dist/two-d/ui/Spinner.js +0 -137
- package/dist/two-d/ui/Spinner.js.map +0 -1
- package/dist/two-d/ui/StatsScreen.d.ts +0 -40
- package/dist/two-d/ui/StatsScreen.d.ts.map +0 -1
- package/dist/two-d/ui/StatsScreen.js +0 -42
- package/dist/two-d/ui/StatsScreen.js.map +0 -1
- package/dist/two-d/ui/TabbedList.d.ts +0 -118
- package/dist/two-d/ui/TabbedList.d.ts.map +0 -1
- package/dist/two-d/ui/TabbedList.js +0 -221
- package/dist/two-d/ui/TabbedList.js.map +0 -1
- package/dist/two-d/ui/TextModel.d.ts +0 -90
- package/dist/two-d/ui/TextModel.d.ts.map +0 -1
- package/dist/two-d/ui/TextModel.js +0 -175
- package/dist/two-d/ui/TextModel.js.map +0 -1
- package/dist/two-d/ui/TextPrompt.d.ts +0 -122
- package/dist/two-d/ui/TextPrompt.d.ts.map +0 -1
- package/dist/two-d/ui/TextPrompt.js +0 -236
- package/dist/two-d/ui/TextPrompt.js.map +0 -1
- package/dist/two-d/ui/TextSharpness.d.ts +0 -33
- package/dist/two-d/ui/TextSharpness.d.ts.map +0 -1
- package/dist/two-d/ui/TextSharpness.js +0 -56
- package/dist/two-d/ui/TextSharpness.js.map +0 -1
- package/dist/two-d/ui/Toast.d.ts +0 -57
- package/dist/two-d/ui/Toast.d.ts.map +0 -1
- package/dist/two-d/ui/Toast.js +0 -101
- package/dist/two-d/ui/Toast.js.map +0 -1
- package/dist/two-d/ui/Tooltip.d.ts +0 -177
- package/dist/two-d/ui/Tooltip.d.ts.map +0 -1
- package/dist/two-d/ui/Tooltip.js +0 -275
- package/dist/two-d/ui/Tooltip.js.map +0 -1
- package/dist/two-d/ui/TreeView.d.ts +0 -68
- package/dist/two-d/ui/TreeView.d.ts.map +0 -1
- package/dist/two-d/ui/TreeView.js +0 -133
- package/dist/two-d/ui/TreeView.js.map +0 -1
- package/dist/two-d/ui/VerticalLabel.d.ts +0 -69
- package/dist/two-d/ui/VerticalLabel.d.ts.map +0 -1
- package/dist/two-d/ui/VerticalLabel.js +0 -110
- package/dist/two-d/ui/VerticalLabel.js.map +0 -1
- package/dist/two-d/ui/Window.d.ts +0 -188
- package/dist/two-d/ui/Window.d.ts.map +0 -1
- package/dist/two-d/ui/Window.js +0 -311
- package/dist/two-d/ui/Window.js.map +0 -1
- package/dist/two-d/ui/WindowStack.d.ts +0 -63
- package/dist/two-d/ui/WindowStack.d.ts.map +0 -1
- package/dist/two-d/ui/WindowStack.js +0 -132
- package/dist/two-d/ui/WindowStack.js.map +0 -1
- package/dist/two-d/ui/a11y.d.ts +0 -43
- package/dist/two-d/ui/a11y.d.ts.map +0 -1
- package/dist/two-d/ui/a11y.js +0 -79
- package/dist/two-d/ui/a11y.js.map +0 -1
- package/dist/two-d/ui/contrast.d.ts +0 -30
- package/dist/two-d/ui/contrast.d.ts.map +0 -1
- package/dist/two-d/ui/contrast.js +0 -42
- package/dist/two-d/ui/contrast.js.map +0 -1
- package/dist/two-d/ui/index.d.ts +0 -96
- package/dist/two-d/ui/index.d.ts.map +0 -1
- package/dist/two-d/ui/index.js +0 -49
- package/dist/two-d/ui/index.js.map +0 -1
- package/dist/two-d/ui/markdown.d.ts +0 -55
- package/dist/two-d/ui/markdown.d.ts.map +0 -1
- package/dist/two-d/ui/markdown.js +0 -147
- package/dist/two-d/ui/markdown.js.map +0 -1
- package/dist/two-d/ui/markup.d.ts +0 -189
- package/dist/two-d/ui/markup.d.ts.map +0 -1
- package/dist/two-d/ui/markup.js +0 -387
- package/dist/two-d/ui/markup.js.map +0 -1
- package/dist/two-d/ui/reveal.d.ts +0 -41
- package/dist/two-d/ui/reveal.d.ts.map +0 -1
- package/dist/two-d/ui/reveal.js +0 -22
- package/dist/two-d/ui/reveal.js.map +0 -1
- package/dist/two-d/ui/theme.d.ts +0 -133
- package/dist/two-d/ui/theme.d.ts.map +0 -1
- package/dist/two-d/ui/theme.js +0 -122
- package/dist/two-d/ui/theme.js.map +0 -1
- package/dist/two-d/ui/themedText.d.ts +0 -20
- package/dist/two-d/ui/themedText.d.ts.map +0 -1
- package/dist/two-d/ui/themedText.js +0 -9
- package/dist/two-d/ui/themedText.js.map +0 -1
- package/dist/version.d.ts +0 -13
- package/dist/version.d.ts.map +0 -1
- package/dist/version.js +0 -13
- package/dist/version.js.map +0 -1
- package/dist/world/Encounters.d.ts +0 -32
- package/dist/world/Encounters.d.ts.map +0 -1
- package/dist/world/Encounters.js +0 -9
- package/dist/world/Encounters.js.map +0 -1
- package/dist/world/Environment.d.ts +0 -58
- package/dist/world/Environment.d.ts.map +0 -1
- package/dist/world/Environment.js +0 -89
- package/dist/world/Environment.js.map +0 -1
- package/dist/world/Overworld.d.ts +0 -39
- package/dist/world/Overworld.d.ts.map +0 -1
- package/dist/world/Overworld.js +0 -40
- package/dist/world/Overworld.js.map +0 -1
- package/dist/world/SideTurns.d.ts +0 -115
- package/dist/world/SideTurns.d.ts.map +0 -1
- package/dist/world/SideTurns.js +0 -138
- package/dist/world/SideTurns.js.map +0 -1
- package/dist/world/TurnClock.d.ts +0 -41
- package/dist/world/TurnClock.d.ts.map +0 -1
- package/dist/world/TurnClock.js +0 -49
- package/dist/world/TurnClock.js.map +0 -1
- package/dist/world/World.d.ts +0 -64
- package/dist/world/World.d.ts.map +0 -1
- package/dist/world/World.js +0 -91
- package/dist/world/World.js.map +0 -1
- package/dist/world/index.d.ts +0 -12
- package/dist/world/index.d.ts.map +0 -1
- package/dist/world/index.js +0 -7
- package/dist/world/index.js.map +0 -1
- package/sbom.cdx.json +0 -5996
- package/tools/mwl.mjs +0 -324
- package/tools/vendored/rgssad-wasm/LICENSE-MIT +0 -21
- package/tools/vendored/rgssad-wasm/README.md +0 -15
- package/tools/vendored/rgssad-wasm/package.json +0 -17
- package/tools/vendored/rgssad-wasm/rgssad_wasm.d.ts +0 -41
- package/tools/vendored/rgssad-wasm/rgssad_wasm.js +0 -6
- package/tools/vendored/rgssad-wasm/rgssad_wasm_bg.js +0 -399
- package/tools/vendored/rgssad-wasm/rgssad_wasm_bg.wasm +0 -0
- package/tools/vendored/rgssad-wasm/rgssad_wasm_bg.wasm.d.ts +0 -17
- package/tools.md +0 -219
package/dist/mw_games.global.js
DELETED
|
@@ -1,1407 +0,0 @@
|
|
|
1
|
-
var mw_games=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},c=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),l=(e,t)=>{let r={};for(var i in e)n(r,i,{get:e[i],enumerable:!0});return t||n(r,Symbol.toStringTag,{value:`Module`}),r},u=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},d=(e,r,i)=>(i=e==null?{}:t(a(e)),u(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),f=`0.43.0`,p=class{constructor(e=!1){this.listeners=[],this.stackMode=e}add(e){this.listeners.includes(e)||(this.stackMode?this.listeners.unshift(e):this.listeners.push(e))}remove(e){let t=this.listeners.indexOf(e);t!==-1&&this.listeners.splice(t,1)}removeAll(){this.listeners.length=0}get size(){return this.listeners.length}dispatch(e){let t=this.listeners.slice();for(let n of t)if(this.listeners.includes(n)&&n(e)===!0)return!0;return!1}},m=class{constructor(){this.onDestroy=new p,this.destroyed=!1}update(e){}resize(e,t){}onSuspend(){}onResume(e){}destroy(){this.destroyed||(this.destroyed=!0,this.onDestroy.dispatch(),this.onDestroy.removeAll(),this.teardown())}teardown(){}get isDestroyed(){return this.destroyed}},h=class{constructor(){this.scenes=[]}get current(){return this.scenes.length===0?null:this.scenes[this.scenes.length-1]}get depth(){return this.scenes.length}replace(e){for(let e of this.scenes)e.destroy();this.scenes=[e],e.create()}push(e){this.current?.onSuspend(),this.scenes.push(e),e.create()}pop(e){if(this.scenes.length<=1)throw Error(`cannot pop the last scene off the stack - switchScene somewhere instead`);this.scenes.pop()?.destroy(),this.current?.onResume(e)}update(e){this.current?.update(e)}resize(e,t){for(let n of this.scenes)n.resize(e,t)}destroy(){for(let e of this.scenes)e.destroy();this.scenes=[]}},g=class{constructor(){this.items=new Map}register(e,t){if(this.items.has(e))throw Error(`"${e}" is already registered`);this.items.set(e,t)}get(e){let t=this.items.get(e);if(t===void 0)throw Error(`no registration named "${e}"`);return t}has(e){return this.items.has(e)}list(){return[...this.items.keys()]}};function _(){let e=1,t=new Map;return{get size(){return t.size},put(n){let r=e++;return t.set(r,n),r},get(e){let n=t.get(e);if(n===void 0)throw Error(`unknown handle ${e}`);return n},drop(e){t.delete(e)},clear(){t.clear()},with(n,r){let i=e++;t.set(i,n);try{return r(i)}finally{t.delete(i)}}}}var v=class{constructor(){this.order=[],this.registry=new g}add(e,t){this.registry.register(e.name,e),this.order.push(e),e.create?.(t)}has(e){return this.registry.has(e)}get(e){return this.registry.get(e)}update(e,t){for(let n of this.order)n.update?.(e,t)}resize(e,t,n){for(let r of this.order)r.resize?.(e,t,n)}onSuspend(e){for(let t of this.order)t.onSuspend?.(e)}onResume(e,t){for(let n of this.order)n.onResume?.(e,t)}destroy(e){for(let t=this.order.length-1;t>=0;t--)this.order[t].destroy?.(e);this.order=[],this.registry=new g}},y={debug:0,info:1,warn:2,error:3},b=class{constructor(e,t={}){if(!e)throw Error(`a logger needs a category`);this.category=e,this.level=t.level??`debug`,this.sink=t.sink??x}setLevel(e){this.level=e}debug(e,t){this.write(`debug`,e,t)}info(e,t){this.write(`info`,e,t)}warn(e,t){this.write(`warn`,e,t)}error(e,t){this.write(`error`,e,t)}write(e,t,n){y[e]<y[this.level]||this.sink({level:e,category:this.category,message:t,data:n,time:Date.now()})}};function x(e){let t=`[${e.category}] ${e.message}`;e.level===`debug`?console.debug(t,e.data??``):e.level===`info`?console.info(t,e.data??``):e.level===`warn`?console.warn(t,e.data??``):console.error(t,e.data??``)}var S=class{constructor(){this.hooks=[]}on(e,t,n){this.hooks.push({event:e,handler:t,source:n})}off(e){this.hooks=this.hooks.filter(t=>t.handler!==e)}offSource(e){this.hooks=this.hooks.filter(t=>t.source!==e)}emit(e,...t){for(let n of[...this.hooks])n.event===e&&n.handler(...t)}get size(){return this.hooks.length}clear(){this.hooks=[]}},C=l({Generator:()=>j,MersenneTwister:()=>he,RandomStreams:()=>ge,active:()=>ee,chance:()=>A,element:()=>re,float:()=>D,int:()=>O,normalRange:()=>k,pop:()=>T,push:()=>w,range:()=>ne,reset:()=>te,shuffle:()=>oe,weighted:()=>ie,weightedKey:()=>ae,withSeed:()=>E});function ee(){return le()}function w(e){let t=new j(e);return ce.push(t),t}function T(){if(ce.length===1)throw Error(`the base random generator cannot be popped`);ce.pop()}function E(e,t){w(e);try{return t()}finally{T()}}function te(){ce.length=0,ce.push(new j)}function D(e,t,n){let r=n??le();return e===void 0?r.float():t===void 0?r.float()*e:e+r.float()*(t-e)}function O(e,t,n){let r=n??le();return t===void 0?r.int(e):e+r.int(t-e)}function ne(e,t,n){return e+(n??le()).int(t-e+1)}function k(e,t,n){let r=n??le();return e+Math.floor((r.float()+r.float())*(t-e+1)/2)}function A(e,t){return(t??le()).float()<e}function re(e,t){return e.length>0?e[(t??le()).int(e.length)]:null}function ie(e,t){let n=0;for(let t of e)n+=t;if(n<=0)return null;let r=(t??le()).float()*n;for(let t=0;t<e.length;t++)if(r-=e[t],r<0)return t;return e.length-1}function ae(e,t){let n=[...e.keys()],r=ie(n.map(t=>e.get(t)??0),t);return r===null?null:n[r]}function oe(e,t){for(let n=e.length-1;n>0;n--){let r=(t??le()).int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}function se(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t>>>0}var j,ce,le,ue,de,fe,pe,me,he,ge,_e=s((()=>{j=class{constructor(e){this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.seed=e===void 0?Math.random()*4294967296>>>0:e>>>0;let t=this.seed,n=()=>{t=t+2654435769>>>0;let e=t;return e=Math.imul(e^e>>>16,569420461),e=Math.imul(e^e>>>15,1935289751),(e^e>>>15)>>>0};this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n(),(this.s0|this.s1|this.s2|this.s3)===0&&(this.s0=1)}nextUint32(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0>>>0,t=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2^=t,this.s3=this.rotl(this.s3,11),e}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}getState(){return[this.s0,this.s1,this.s2,this.s3]}setState(e){[this.s0,this.s1,this.s2,this.s3]=e}rotl(e,t){return(e<<t|e>>>32-t)>>>0}},ce=[new j],le=()=>ce[ce.length-1],ue=624,de=397,fe=2567483615,pe=2147483648,me=2147483647,he=class{constructor(e=5489){this.state=new Uint32Array(ue),this.index=ue,this.seedValue=5489,this.produced=0,this.seed(e)}seed(e){this.seedValue=e>>>0,this.state[0]=this.seedValue;for(let e=1;e<ue;e++){let t=this.state[e-1]^this.state[e-1]>>>30;this.state[e]=Math.imul(1812433253,t)+e>>>0}this.index=ue,this.produced=0}generate(){for(let e=0;e<ue;e++){let t=this.state[e]&pe|this.state[(e+1)%ue]&me,n=this.state[(e+de)%ue]^t>>>1;t&1&&(n^=fe),this.state[e]=n>>>0}this.index=0}nextUint32(){this.index>=ue&&this.generate();let e=this.state[this.index++];return e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,this.produced++,e>>>0}float(){return this.nextUint32()/4294967296}int(e){if(e<=0)return 0;let t=4294967296-4294967296%e,n=this.nextUint32();for(;n>=t;)n=this.nextUint32();return n%e}discard(e){for(let t=0;t<e;t++)this.nextUint32()}get discardCount(){return this.produced}getState(){return{seed:this.seedValue,state:[...this.state],index:this.index,discard:this.produced}}setState(e){this.seedValue=e.seed>>>0;for(let t=0;t<ue;t++)this.state[t]=(e.state[t]??0)>>>0;this.index=e.index,this.produced=e.discard}},ge=class{constructor(e=0){this.streams=new Map,this.baseSeed=e>>>0}stream(e){let t=this.streams.get(e);if(!t){let n=(this.baseSeed^se(e))>>>0;t={seed:n,engine:new he(n)},this.streams.set(e,t)}return t.engine}seedOf(e){return this.streams.get(e)?.seed}reseed(e){this.baseSeed=e>>>0,this.streams.clear()}names(){return[...this.streams.keys()]}getState(){let e={};for(let[t,n]of this.streams)e[t]=n.engine.getState();return e}setState(e){for(let[t,n]of Object.entries(e)){let e=new he(n.seed);e.setState(n),this.streams.set(t,{seed:n.seed,engine:e})}}}})),ve=l({DEFAULT_BINDINGS:()=>je,actionsForKey:()=>Pe,attach:()=>gt,attachPointer:()=>ht,attachSwipe:()=>mt,bind:()=>Me,bindAxis:()=>at,bindButton:()=>it,bindTouch:()=>lt,detach:()=>_t,dispatchAction:()=>Te,dispatchComposition:()=>Ee,dispatchText:()=>we,endFrame:()=>Ke,exportBindings:()=>Le,gamepadAxisCode:()=>rt,gamepadButtonCode:()=>nt,importBindings:()=>Re,isDown:()=>Ue,justPressed:()=>We,justReleased:()=>Ge,keysFor:()=>Ie,onAction:()=>P,onComposition:()=>F,onKey:()=>xe,onText:()=>Se,onWheel:()=>De,pollGamepads:()=>ot,pressTouch:()=>ut,releaseTouch:()=>dt,resetBindings:()=>ze,rumble:()=>st,textFromKey:()=>Ce,touchCode:()=>ct,unbind:()=>Fe,wheelActionFor:()=>Oe}),M=new Map,N=new Set,ye=new Set,be=new Set,P=new p(!0),xe=new p(!0),Se=new p(!0),F=new p(!0);function Ce(e){return e.isComposing||e.ctrlKey||e.metaKey||e.altKey?null:e.key.length===1?e.key:null}function we(e){e.length>0&&Se.dispatch(e)}function Te(e){P.dispatch(e)}function Ee(e){F.dispatch({phase:e.phase,text:e.text})}var De=new p(!0);function Oe(e){return e.ctrlKey||e.metaKey?`zoom`:e.shiftKey?`scrollHorizontal`:`scroll`}function ke(e){let t=Oe(e);t===`zoom`&&e.preventDefault();let n=t===`scrollHorizontal`&&e.deltaX!==0?e.deltaX:e.deltaY;De.dispatch({action:t,delta:n})}var Ae=!1,je={up:[`ArrowUp`,`KeyW`,`Numpad8`],down:[`ArrowDown`,`KeyS`,`Numpad2`],left:[`ArrowLeft`,`KeyA`,`Numpad4`],right:[`ArrowRight`,`KeyD`,`Numpad6`],upLeft:[`Numpad7`],upRight:[`Numpad9`],downLeft:[`Numpad1`],downRight:[`Numpad3`],wait:[`Numpad5`,`Period`],confirm:[`Enter`,`Space`,`NumpadEnter`],cancel:[`Escape`,`Backspace`],menu:[`KeyI`,`Tab`]};function Me(e,t){M.set(e,new Set(t))}function Ne(e,t){let n=M.get(e)??new Set;for(let e of t)n.add(e);M.set(e,n)}function Pe(e){return Be(e)}function Fe(e){M.delete(e)}function Ie(e){return[...M.get(e)??[]]}function Le(){let e={};for(let[t,n]of M)e[t]=[...n];return e}function Re(e){M.clear();for(let[t,n]of Object.entries(e))Me(t,n)}function ze(){Re(je)}ze();function Be(e){let t=[];for(let[n,r]of M)r.has(e)&&t.push(n);return t}function Ve(e){if(!N.has(e)){N.add(e);for(let t of Be(e))ye.add(t),P.dispatch(t)}}function He(e){if(N.has(e)){N.delete(e);for(let t of Be(e))be.add(t)}}function Ue(e){let t=M.get(e);if(!t)return!1;for(let e of t)if(N.has(e))return!0;return!1}function We(e){return ye.has(e)}function Ge(e){return be.has(e)}function Ke(){ye.clear(),be.clear()}function qe(e){let t=Ce(e);t!==null&&we(t)}function Je(e){e.repeat?(xe.dispatch(e),qe(e)):(Ve(e.code),xe.dispatch(e),qe(e))}function Ye(e){He(e.code)}function Xe(e){Ee({phase:`start`,text:e.data??``})}function Ze(e){Ee({phase:`update`,text:e.data??``})}function Qe(e){Ee({phase:`end`,text:e.data??``})}function $e(){N.clear(),ye.clear(),be.clear()}var et=.5,tt=new Set;function nt(e,t){return`Gamepad${e}Button${t}`}function rt(e,t,n){return`Gamepad${e}Axis${t}${n>0?`+`:`-`}`}function it(e,t,n){Ne(e,n.map(e=>nt(t,e)))}function at(e,t,n,r){Ne(e,[rt(t,n,r)])}function ot(e=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){tt.clear();for(let t of e)if(t){for(let e=0;e<t.buttons.length;e++)t.buttons[e].pressed&&tt.add(nt(t.index,e));for(let e=0;e<t.axes.length;e++){let n=t.axes[e];n>=et?tt.add(rt(t.index,e,1)):n<=-.5&&tt.add(rt(t.index,e,-1))}}for(let e of tt)Ve(e);for(let e of N)!tt.has(e)&&e.startsWith(`Gamepad`)&&He(e)}function st(e,t,n=typeof navigator?.getGamepads==`function`?navigator.getGamepads():[]){(n[e]?.vibrationActuator)?.playEffect(`dual-rumble`,{duration:t.duration,weakMagnitude:t.weakMagnitude??1,strongMagnitude:t.strongMagnitude??1})}function ct(e){return`Touch:${e}`}function lt(e,t=e){Ne(e,[ct(t)])}function ut(e){Ve(ct(e))}function dt(e){He(ct(e))}var ft={up:`up`,down:`down`,left:`left`,right:`right`,upLeft:`upLeft`,upRight:`upRight`,downLeft:`downLeft`,downRight:`downRight`},pt=[`right`,`downRight`,`down`,`downLeft`,`left`,`upLeft`,`up`,`upRight`];function mt(e,t={}){let n={...ft,...t.actions},r=t.minDistance??24;for(let e of[...pt,`tap`]){let t=n[e];t&<(t,`swipe:${e}`)}let i=!1,a=-1,o=0,s=0;function c(e){ut(`swipe:${e}`),dt(`swipe:${e}`)}function l(e){i=!0,a=e.pointerId,o=e.clientX,s=e.clientY}function u(e){if(!i||e.pointerId!==a)return;i=!1;let t=e.clientX-o,l=e.clientY-s;if(Math.hypot(t,l)<r){n.tap&&c(`tap`);return}let u=pt[(Math.round(Math.atan2(l,t)/(Math.PI/4))%8+8)%8];n[u]&&c(u)}return e.addEventListener(`pointerdown`,l),e.addEventListener(`pointerup`,u),e.addEventListener(`pointercancel`,u),()=>{e.removeEventListener(`pointerdown`,l),e.removeEventListener(`pointerup`,u),e.removeEventListener(`pointercancel`,u)}}function ht(e,t={}){let n=t.dragThreshold??4,r=t.toWorld??((e,t)=>({x:e,y:t})),i=new p,a=new p,o=new p,s=new p,c=-1,l=!1,u=!1,d=0,f=0,m=null;function h(t){let n=e.getBoundingClientRect?.()??{left:0,top:0},i=t.clientX-n.left,a=t.clientY-n.top,o=r(i,a);return{x:i,y:a,worldX:o.x,worldY:o.y,dx:l?i-d:0,dy:l?a-f:0,pointerId:t.pointerId,pressed:l}}function g(t){if(l)return;l=!0,u=!1,c=t.pointerId;let n=e.getBoundingClientRect?.()??{left:0,top:0};d=t.clientX-n.left,f=t.clientY-n.top,m=h(t),i.dispatch(m)}function _(e){l&&e.pointerId!==c||(m=h(e),a.dispatch(m),l&&(!u&&Math.hypot(m.dx,m.dy)>=n&&(u=!0),u&&o.dispatch(m)))}function v(e){if(!l||e.pointerId!==c)return;let t=u,n=h(e);l=!1,u=!1,m={...n,pressed:!1,dx:0,dy:0},s.dispatch({...n,pressed:!1,dragged:t})}return e.addEventListener(`pointerdown`,g),e.addEventListener(`pointermove`,_),e.addEventListener(`pointerup`,v),e.addEventListener(`pointercancel`,v),{down:i,move:a,drag:o,up:s,get current(){return m},detach(){e.removeEventListener(`pointerdown`,g),e.removeEventListener(`pointermove`,_),e.removeEventListener(`pointerup`,v),e.removeEventListener(`pointercancel`,v)}}}function gt(e=window){Ae||(Ae=!0,e.addEventListener(`keydown`,Je),e.addEventListener(`keyup`,Ye),e.addEventListener(`compositionstart`,Xe),e.addEventListener(`compositionupdate`,Ze),e.addEventListener(`compositionend`,Qe),window.addEventListener(`blur`,$e),e.addEventListener(`wheel`,ke,{passive:!1}))}function _t(e=window){Ae&&(Ae=!1,e.removeEventListener(`keydown`,Je),e.removeEventListener(`keyup`,Ye),e.removeEventListener(`compositionstart`,Xe),e.removeEventListener(`compositionupdate`,Ze),e.removeEventListener(`compositionend`,Qe),e.removeEventListener(`wheel`,ke),window.removeEventListener(`blur`,$e),$e())}var vt=class{constructor(e,t={}){if(!e)throw Error(`a player needs a non-empty id`);this.id=e,this.padIndex=t.padIndex}scoped(e){return`${this.id}:${e}`}bind(e,t){Me(this.scoped(e),t)}bindButton(e,t){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad button to`);it(this.scoped(e),this.padIndex,t)}bindAxis(e,t,n){if(this.padIndex===void 0)throw Error(`player "${this.id}" has no padIndex to bind a gamepad axis to`);at(this.scoped(e),this.padIndex,t,n)}bindTouch(e,t=e){lt(this.scoped(e),`${this.id}:${t}`)}pressTouch(e){ut(`${this.id}:${e}`)}releaseTouch(e){dt(`${this.id}:${e}`)}isDown(e){return Ue(this.scoped(e))}justPressed(e){return We(this.scoped(e))}justReleased(e){return Ge(this.scoped(e))}keysFor(e){return Ie(this.scoped(e))}},yt=25214903917n,bt=11n,xt=(1n<<48n)-1n,St=class{constructor(e=0,t={}){this.state=0n,this.onDraw=t.onDraw,this.setSeed(e)}setSeed(e){this.state=(BigInt.asIntN(64,BigInt(e))^yt)&xt}next(e){if(!Number.isInteger(e)||e<1||e>32)throw Error(`next needs 1 to 32 bits, got ${e}`);this.state=this.state*yt+bt&xt;let t=Number(this.state>>BigInt(48-e)),n=e===32?t|0:t;return this.onDraw?.({bits:e,value:n}),n}nextInt(e){if(e===void 0)return this.next(32);if(!Number.isInteger(e)||e<=0||e>2147483647)throw Error(`nextInt needs a bound from 1 to 2147483647, got ${e}`);if((e&-e)===e)return Math.floor(e*this.next(31)/2147483648);let t,n;do t=this.next(31),n=t%e;while(t-n+(e-1)>2147483647);return n}nextLong(){let e=BigInt(this.next(32)),t=BigInt(this.next(32));return BigInt.asIntN(64,(e<<32n)+t)}nextDouble(){return(this.next(26)*134217728+this.next(27))/2**53}nextFloat(){return this.next(24)/16777216}nextBoolean(){return this.next(1)!==0}};_e();function Ct(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=new TextEncoder().encode(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return Tt(i)}function wt(e,t){if(!t)throw Error(`scramble needs a non-empty key`);let n=Et(e),r=new TextEncoder().encode(t),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n[e]^r[e%r.length];return new TextDecoder(`utf-8`,{fatal:!0}).decode(i)}function Tt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function Et(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Dt=10485760;function Ot(e,t={}){let n=t.maxBytes??Dt,r=typeof e==`string`?new TextEncoder().encode(e).length:e.length;if(r>n)throw Error(`inbound data exceeds the ${n}-byte limit (${r} bytes)`)}function kt(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n!==9&&n!==10&&n!==13&&(n<=31||n===127))throw Error(`inbound data contains a control character (0x${n.toString(16).padStart(2,`0`)}) at index ${t}`)}}function At(e,t={}){return Ot(e,t),kt(e),e}var jt=new Set([`__proto__`,`constructor`,`prototype`]);function Mt(e,t=`$`){if(Array.isArray(e))e.forEach((e,n)=>Mt(e,`${t}[${n}]`));else if(typeof e==`object`&&e)for(let n of Object.keys(e)){if(jt.has(n))throw Error(`${t} contains a forbidden key "${n}"`);Mt(e[n],`${t}.${n}`)}}function Nt(e,t,n=`$`){if(e===void 0){if(t.optional)return;throw Error(`${n} is required`)}switch(t.type){case`string`:if(typeof e!=`string`)throw Error(`${n} must be a string`);return;case`number`:if(typeof e!=`number`||!Number.isFinite(e))throw Error(`${n} must be a finite number`);if(t.min!==void 0&&e<t.min)throw Error(`${n} must be >= ${t.min}`);if(t.max!==void 0&&e>t.max)throw Error(`${n} must be <= ${t.max}`);return;case`boolean`:if(typeof e!=`boolean`)throw Error(`${n} must be a boolean`);return;case`array`:if(!Array.isArray(e))throw Error(`${n} must be an array`);if(t.maxLength!==void 0&&e.length>t.maxLength)throw Error(`${n} exceeds its maximum length of ${t.maxLength}`);e.forEach((e,r)=>Nt(e,t.items,`${n}[${r}]`));return;case`object`:if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${n} must be an object`);for(let t of Object.keys(e))if(jt.has(t))throw Error(`${n} contains a forbidden key "${t}"`);for(let[r,i]of Object.entries(t.fields))Nt(e[r],i,`${n}.${r}`);return}}function Pt(e,t={}){let n=t.label??`inbound data`;At(e,t);try{return JSON.parse(e,(e,t)=>{if(jt.has(e))throw new Ft(e);return t})}catch(e){throw e instanceof Ft?Error(`${n} contains a forbidden key "${e.key}"`):Error(`${n} is not valid JSON (${e instanceof Error?e.message:String(e)})`)}}var Ft=class{constructor(e){this.key=e}};function It(e,t){let n=Pt(e,{label:t}),r=n?.meta;if(typeof n!=`object`||!n||Array.isArray(n)||!(`state`in n))throw Error(`${t} is not save data (expected { meta, state })`);if(typeof r!=`object`||!r||!Number.isSafeInteger(r.version)||r.version<0)throw Error(`${t} has no valid meta.version`);if(typeof r.savedAt!=`number`||!Number.isFinite(r.savedAt))throw Error(`${t} has no valid meta.savedAt`);return n}var Lt=class{constructor(){this.data=new Map}read(e){return this.data.get(e)??null}write(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}keys(){return[...this.data.keys()]}};function Rt(){return typeof localStorage>`u`?new Lt:{read:e=>localStorage.getItem(e),write:(e,t)=>localStorage.setItem(e,t),remove:e=>localStorage.removeItem(e),keys:()=>Object.keys(localStorage)}}var zt=class{constructor(e){this.namespace=e.namespace,this.version=e.version,this.migrations=e.migrations??{},this.storage=e.storage??Rt()}key(e){return`mwg-save:${this.namespace}:${e}`}save(e,t,n){let r={meta:{version:this.version,savedAt:Date.now(),preview:n},state:t};this.storage.write(this.key(e),JSON.stringify(r))}load(e){let t=this.storage.read(this.key(e));if(!t)return null;try{let n=It(t,`save slot "${e}"`),r=n.state;for(let e=n.meta.version;e<this.version;e++)r=(this.migrations[e]??(e=>e))(r);return{meta:{...n.meta,version:this.version},state:r}}catch{return null}}importExternal(e,t,n,r){Ot(t);let i=n(t);for(let e=0;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{version:this.version,savedAt:Date.now(),preview:r},state:i};this.storage.write(this.key(e),JSON.stringify(a))}delete(e){this.storage.remove(this.key(e))}exportSlot(e,t){let n=this.storage.read(this.key(e));return n===null?null:t?Ct(n,t):n}importSlot(e,t,n){Ot(t);let r=It(n?wt(t,n):t,`SaveSystem.importSlot: payload`),i=r.state;for(let e=r.meta.version;e<this.version;e++)i=(this.migrations[e]??(e=>e))(i);let a={meta:{...r.meta,version:this.version},state:i};this.storage.write(this.key(e),JSON.stringify(a))}list(){let e=`mwg-save:${this.namespace}:`,t=[];for(let n of this.storage.keys()){if(!n.startsWith(e))continue;let r=this.storage.read(n);if(r)try{t.push({slot:n.slice(e.length),meta:It(r,n).meta})}catch{}}return t}},Bt=class{constructor(e,t){this.storage=e,this.key=t}read(e){let t=this.storage.read(this.key);return t?Pt(t,{label:`stored value "${this.key}"`}):e}write(e){this.storage.write(this.key,JSON.stringify(e))}remove(){this.storage.remove(this.key)}};function Vt(e,t=`value`){return Ht(e,t,new Set)}function Ht(e,t,n){if(typeof e==`function`||typeof e==`symbol`)return t;if(typeof e!=`object`||!e||n.has(e)||(n.add(e),Ut(e)))return null;let r=[];if(e instanceof Map)for(let[n,i]of e)r.push([`${t}.get(${JSON.stringify(n)??String(n)})`,i]);else if(e instanceof Set)for(let n of e)r.push([`${t}.item`,n]);else if(Array.isArray(e))e.forEach((e,n)=>r.push([`${t}[${n}]`,e]));else for(let[n,i]of Object.entries(e))r.push([`${t}.${n}`,i]);for(let[e,t]of r){let r=Ht(t,e,n);if(r)return r}return t}function Ut(e){try{return structuredClone(e),!0}catch{return!1}}function Wt(e,t){try{return structuredClone(e)}catch(n){let r=Vt(e,t)??t;throw TypeError(`${r} cannot be structured-cloned (${n instanceof Error?n.message:String(n)}). Journals, snapshots and undo checkpoints copy their contents with structuredClone, so they must hold plain data: refer to a live object (an actor, anything carrying callbacks such as a ReactionTable) by its id and resolve it inside the rule.`,{cause:n})}}var Gt=class{constructor(e,t={}){this._state=Wt(e,`initial state`),this.version=t.version??1,this.migrations=t.migrations??{},this.extensions=t.extensions??new Kt}get state(){return structuredClone(this._state)}set(e){this._state=Wt(e,`state`)}update(e){let t=e(this.state);return this.set(t),this.state}snapshot(){let e=this.extensions.snapshot();return{version:this.version,state:this.state,extensions:e.extensions,extensionVersions:e.versions}}restore(e,t={}){if(!Number.isSafeInteger(e.version)||e.version<1)throw Error(`canonical state snapshot version must be a positive integer`);if(e.version>this.version)throw Error(`canonical state snapshot version ${e.version} is newer than ${this.version}`);let n=this.snapshot();try{let n=Wt(e.state,`snapshot.state`);for(let t=e.version;t<this.version;t++){let e=this.migrations[t+1];if(!e)throw Error(`missing canonical state migration to version ${t+1}`);n=e(n)}return this._state=Wt(n,`migrated state`),this.extensions.restore({extensions:e.extensions,versions:e.extensionVersions},t)}catch(e){throw this._state=structuredClone(n.state),this.extensions.restore({extensions:n.extensions,versions:n.extensionVersions},{missing:`keep`}),e}}transaction(e){let t=this.snapshot();try{return e(this)}catch(e){throw this.restore(t),e}}},Kt=class{constructor(){this.extensions=new Map}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid state extension id: ${e.id}`);if(this.extensions.has(e.id))throw Error(`state extension already registered: ${e.id}`);return this.extensions.set(e.id,{id:e.id,capture:()=>e.capture(),restore:t=>e.restore(t),version:e.version??1,migrations:e.migrations,reset:e.reset,remove:e.remove}),()=>this.extensions.delete(e.id)}snapshot(){let e={};for(let[t,n]of this.extensions)e[t]=Wt(n.capture(),`extension ${t}`);let t={};for(let[e,n]of this.extensions)t[e]=n.version??1;return{extensions:e,versions:t}}restore(e,t={}){let n=this.snapshot(),r=[];try{for(let[n,i]of this.extensions){if(!(n in e.extensions)){t.missing===`reset`?(i.reset&&i.reset(),r.push({extension:n,from:0,to:i.version??1,status:`reset`})):t.missing===`remove`&&(i.remove&&i.remove(),r.push({extension:n,from:0,to:i.version??1,status:`removed`}));continue}let a=e.versions?.[n]??1,o=i.version??1,s=Wt(e.extensions[n],`snapshot.extensions.${n}`);for(let e=a;e<o;e++){let t=i.migrations?.[e+1];if(!t)throw Error(`missing state migration for ${n} to version ${e+1}`);s=t(s)}i.restore(Wt(s,`migrated extension ${n}`)),r.push({extension:n,from:a,to:o,status:a===o?`unchanged`:`migrated`})}}catch(e){for(let[e,t]of this.extensions)e in n.extensions&&t.restore(structuredClone(n.extensions[e]));throw e}for(let e of r)t.onDiagnostic?.(e);return r}transaction(e){let t=this.snapshot();try{return e()}catch(e){throw this.restore(t),e}}},qt=new Set([`localhost`,`127.0.0.1`,`[::1]`]);function Jt(e,t,n=!1){if(n||!/^[a-z][a-z0-9+.-]*:/i.test(e))return;let r=new URL(e);if(r.protocol!==`https:`&&r.protocol!==`wss:`&&(r.protocol!==`http:`&&r.protocol!==`ws:`||!qt.has(r.hostname)))throw Error(`${t} url must use https: or wss: (got ${r.protocol}//${r.host}); pass allowInsecure: true to accept it`)}var Yt=class{constructor(e,t){if(!e.endpoint)throw Error(`${t} endpoint is required`);if(Jt(e.endpoint,`${t} endpoint`,e.allowInsecure),this.endpoint=e.endpoint,this.label=t,this.maxResponseBytes=e.maxResponseBytes??10485760,this.timeoutMs=e.timeoutMs??1e4,!(this.timeoutMs>0))throw Error(`${t} timeout must be positive`);if(this.fetchFn=e.fetch??globalThis.fetch,!this.fetchFn)throw Error(`fetch is unavailable; provide ${t}Options.fetch`)}async withTimeout(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{return await e(t.signal)}finally{clearTimeout(n)}}async readText(e){let t=this.maxResponseBytes,n=Number(e.headers?.get?.(`content-length`));if(n>t)throw Error(`${this.label} response exceeds the ${t}-byte limit (${n} bytes)`);if(!e.body){let n=await e.text();return Ot(n,{maxBytes:t}),n}let r=e.body.getReader(),i=[],a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel(),Error(`${this.label} response exceeds the ${t}-byte limit`);i.push(n)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return new TextDecoder().decode(o)}async readJson(e,t){return Pt(await this.readText(e),{maxBytes:this.maxResponseBytes,label:`${this.label} ${t}`})}},Xt=class extends Yt{constructor(e){super(e,`save sync`)}async upload(e,t){if(!e)throw Error(`save sync slot name is required`);if(!t)throw Error(`save sync payload cannot be empty`);return this.withTimeout(async n=>{let r=await this.fetchFn(this.slotUrl(e),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({payload:t}),signal:n});if(!r.ok)throw Error(`save upload failed with HTTP ${r.status}`);return{ok:!0,status:r.status}})}async download(e){if(!e)throw Error(`save sync slot name is required`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.slotUrl(e),{signal:t});if(!n.ok)throw Error(`save download failed with HTTP ${n.status}`);let r=await this.readJson(n,`download`);if(typeof r?.payload!=`string`)throw Error(`save download response missing a string payload`);return r.payload})}async list(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`save slot list failed with HTTP ${t.status}`);let n=await this.readJson(t,`slot list`);if(!Array.isArray(n?.slots)||!n.slots.every(e=>typeof e==`string`))throw Error(`save slot list response missing a string array of slots`);return n.slots})}slotUrl(e){let t=this.endpoint.includes(`?`)?`&`:`?`;return`${this.endpoint}${t}slot=${encodeURIComponent(e)}`}},Zt=1,Qt=class{constructor(e){if(this.onWelcome=new p,this.onTick=new p,this.onReject=new p,this.onDesync=new p,this.onClose=new p,this.onProtocolError=new p,this.socket=null,this._id=null,!e.url)throw Error(`lockstep client url is required`);Jt(e.url,`lockstep client`,e.allowInsecure),this.url=e.url,this.createSocket=e.create??(e=>new WebSocket(e)),this.validateInput=e.validateInput,this.maxMessageBytes=e.maxMessageBytes??1048576}get id(){return this._id}get connected(){return this.socket!==null&&this.socket.readyState===Zt}connect(){if(this.socket)throw Error(`lockstep client is already connected`);let e=this.createSocket(this.url);e.onmessage=e=>this.handleMessage(e.data),e.onclose=()=>{this.socket=null,this._id=null,this.onClose.dispatch()},this.socket=e}submitInput(e,t){if(!this.connected)return;let n=this.validateInput?.(e);n===!1||typeof n==`string`?this.onReject.dispatch({reason:n===!1?`input rejected by client validation`:n}):this.socket?.send(JSON.stringify({type:`input`,payload:e,...t===void 0?{}:{checksum:t}}))}close(){this.socket?.close()}handleMessage(e){let t;try{if(typeof e!=`string`)throw Error(`lockstep message is not text`);t=en(Pt(e,{maxBytes:this.maxMessageBytes,label:`lockstep message`}))}catch(e){this.onProtocolError.dispatch({reason:e instanceof Error?e.message:String(e)});return}if(t.type===`welcome`)this._id=t.id,this.onWelcome.dispatch({id:t.id,...t.seed===void 0?{}:{seed:t.seed},...t.initialState===void 0?{}:{initialState:t.initialState}});else if(t.type===`tick`){let e={tick:t.tick,inputs:t.inputs,...t.checksums===void 0?{}:{checksums:t.checksums}};if(this.onTick.dispatch(e),t.checksums){let e=Object.values(t.checksums);e.some(t=>t!==e[0])&&this.onDesync.dispatch({tick:t.tick,checksums:t.checksums})}}else this.onReject.dispatch({reason:t.reason??`input rejected by server`})}},$t=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function en(e){if(!$t(e)||typeof e.type!=`string`)throw Error(`lockstep message has no type`);switch(e.type){case`welcome`:if(typeof e.id!=`string`||e.id===``)throw Error(`welcome needs a string id`);if(e.seed!==void 0&&!Number.isSafeInteger(e.seed))throw Error(`welcome seed must be an integer`);return e;case`tick`:if(!Number.isSafeInteger(e.tick)||e.tick<0)throw Error(`tick needs a non-negative integer tick`);if(!$t(e.inputs))throw Error(`tick needs an inputs object`);if(e.checksums!==void 0&&(!$t(e.checksums)||Object.values(e.checksums).some(e=>typeof e!=`number`)))throw Error(`tick checksums must map ids to numbers`);return e;case`rejected`:if(e.reason!==void 0&&typeof e.reason!=`string`)throw Error(`rejected reason must be a string`);return e;default:throw Error(`unknown lockstep message type "${e.type}"`)}}var tn=class{constructor(e){this.store=new Bt(e.storage??Rt(),`mwg-runs:${e.namespace}`),this.limit=e.limit}readAll(){return this.store.read([])}record(e){let t=this.readAll(),n={id:`${Date.now()}-${t.length}`,endedAt:Date.now(),summary:e};return t.push(n),this.limit!==void 0&&t.length>this.limit&&t.splice(0,t.length-this.limit),this.store.write(t),n}all(){return this.readAll()}ranked(e,t=`desc`){let n=this.readAll(),r=t===`desc`?-1:1;return n.sort((t,n)=>r*(e(t.summary)-e(n.summary)))}clear(){this.store.remove()}},nn=class{constructor(e){this.store=new Bt(e.storage??Rt(),`mwg-stats:${e.namespace}`),this.initial=e.initial,this.combine=e.combine}get(){return this.store.read(this.initial)}record(e){let t=this.combine(this.get(),e);return this.store.write(t),t}reset(){this.store.remove()}},rn=class extends Yt{constructor(e){super(e,`telemetry`),this.consented=!1,this.maxStringLength=e.maxStringLength??256,this.maxProperties=e.maxProperties??32,this.allowed=e.allowedProperties?new Set(e.allowedProperties):null}get hasConsent(){return this.consented}setConsent(e){this.consented=e}async send(e){if(!e.name)throw Error(`telemetry event needs a name`);return this.consented?this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(this.bounded(e)),signal:t});if(!n.ok)throw Error(`telemetry request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}}):null}bounded(e){let t=e=>e.length>this.maxStringLength?e.slice(0,this.maxStringLength):e;if(!e.properties)return{name:t(e.name)};let n={},r=0;for(let[i,a]of Object.entries(e.properties))if(!this.allowed||this.allowed.has(i)){if(r++>=this.maxProperties)break;n[t(i)]=typeof a==`string`?t(a):a}return{name:t(e.name),properties:n}}},an=class extends Yt{constructor(e){super(e,`news`)}async fetchItems(){return this.withTimeout(async e=>{let t=await this.fetchFn(this.endpoint,{signal:e});if(!t.ok)throw Error(`news request failed with HTTP ${t.status}`);let n=await this.readJson(t,`response`);if(!Array.isArray(n))throw Error(`news response was not an array`);return n.map((e,t)=>on(e,t))})}};function on(e,t){if(typeof e!=`object`||!e)throw Error(`news item ${t} was not an object`);let n=e;if(typeof n.id!=`string`||!n.id)throw Error(`news item ${t} is missing a string id`);if(typeof n.title!=`string`)throw Error(`news item ${t} is missing a string title`);if(typeof n.body!=`string`)throw Error(`news item ${t} is missing a string body`);return{id:n.id,title:n.title,body:n.body,publishedAt:typeof n.publishedAt==`number`?n.publishedAt:void 0}}var sn=class{constructor(e){this.store=new Bt(e.storage??Rt(),`mwg-news-seen:${e.namespace}`)}readSeen(){return new Set(this.store.read([]))}isSeen(e){return this.readSeen().has(e)}markSeen(e){let t=this.readSeen();t.add(e),this.store.write([...t])}unseen(e){let t=this.readSeen();return e.filter(e=>!t.has(e.id))}},cn=class{constructor(e,t={}){if(!e)throw Error(`a collection needs a name`);this.prefix=`mwg-db:${t.namespace??`default`}:${e}:`,this.storage=t.storage??Rt()}get size(){return this.keys().length}all(){return this.keys().map(e=>this.read(e))}get(e){let t=this.storage.read(this.prefix+e);return t===null?void 0:this.parse(t,this.prefix+e)}put(e){if(typeof e!=`object`||!e||Array.isArray(e)||typeof e.id!=`string`||e.id===``)throw Error(`a record must be an object with a string id`);this.storage.write(this.prefix+e.id,JSON.stringify(e))}remove(e){this.storage.remove(this.prefix+e)}where(e){return this.all().filter(e)}clear(){for(let e of this.keys())this.storage.remove(e)}keys(){return this.storage.keys().filter(e=>e.startsWith(this.prefix))}read(e){return this.parse(this.storage.read(e),e)}parse(e,t){return Pt(e,{label:`record "${t}"`})}},ln=class{constructor(e,t,n){if(this.recorded=[],this.fromFrame=n?.fromFrame??0,!Number.isInteger(this.fromFrame)||this.fromFrame<0)throw RangeError(`a resumed recorder needs a non-negative fromFrame`);this.frameStamp=this.fromFrame,this.actions=e,this.frames=t,this.onAction=e=>{this.recorded.push({frame:this.frameStamp,action:e})},this.onFrame=()=>{this.frameStamp++},e.add(this.onAction),t.add(this.onFrame)}get events(){return this.recorded}get frame(){return this.frameStamp}toJSON(){return this.recorded.map(e=>({frame:e.frame,action:e.action}))}stop(){this.actions.remove(this.onAction),this.frames.remove(this.onFrame)}},un=class{constructor(e,t,n,r){if(this.events=e,this.dispatch=t,this.frames=n,this.fromFrame=r?.fromFrame??0,!Number.isInteger(this.fromFrame)||this.fromFrame<0)throw RangeError(`a resumed player needs a non-negative fromFrame`);this.index=this.events.findIndex(e=>e.frame>=this.fromFrame),this.index<0&&(this.index=this.events.length),this.frame=this.fromFrame,this.onFrame=()=>this.pump(),n.add(this.onFrame)}get done(){return this.index>=this.events.length}stop(){this.frames.remove(this.onFrame)}pump(){for(;this.index<this.events.length&&this.events[this.index].frame<=this.frame;)this.dispatch(this.events[this.index].action),this.index++;this.frame++}};function dn(e){return JSON.stringify(e)}function fn(e){return pn(JSON.parse(e))}function pn(e){if(!Array.isArray(e))throw Error(`a replay must be an array of {frame, action}`);return e.map(e=>{if(typeof e!=`object`||!e||!Number.isInteger(e.frame)||e.frame<0||typeof e.action!=`string`)throw Error(`a replay entry must be {frame: a non-negative integer, action: a string}`);return{frame:e.frame,action:e.action}})}function mn(e,t){if(typeof t!=`string`||!t.length)throw TypeError(`a replay file needs a non-empty ${e}`);return t}function hn(e){let t=e;if(!Number.isInteger(t)||t<0||t>4294967295)throw RangeError(`a replay seed must be uint32`);return t}function gn(e,t){let n={format:`mwg-replay`,version:1,framework:mn(`framework`,t.framework),game:mn(`game`,t.game),events:pn(e)};if(t.seed!==void 0&&(n.seed=hn(t.seed)),t.recordedAt!==void 0){if(typeof t.recordedAt!=`number`||!Number.isFinite(t.recordedAt))throw TypeError(`recordedAt must be a finite number`);n.recordedAt=t.recordedAt}return JSON.stringify(n)}function _n(e,t){let n=Pt(e,{label:`replay file`});if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`a replay file must be a JSON object`);if(n.format!==`mwg-replay`)throw Error(`not a replay file: expected format "mwg-replay", found ${JSON.stringify(n.format)}`);if(n.version!==1)throw Error(`replay file version ${JSON.stringify(n.version)} is not supported (this build reads 1)`);if(n.game!==t.game)throw Error(`a replay of ${JSON.stringify(n.game)} cannot be imported into ${JSON.stringify(t.game)}`);if(n.framework!==t.framework)throw Error(`a replay recorded against mwg ${JSON.stringify(n.framework)} cannot be imported into ${JSON.stringify(t.framework)}`);let r=pn(n.events);return{format:`mwg-replay`,version:1,framework:n.framework,game:n.game,...n.seed===void 0?{}:{seed:hn(n.seed)},...n.recordedAt===void 0?{}:{recordedAt:n.recordedAt},events:r}}var vn=class{constructor(e){if(typeof e.namespace!=`string`||!e.namespace.length)throw TypeError(`a last-run store needs a non-empty namespace`);let t=e.maxEvents??1e4;if(!Number.isInteger(t)||t<1||t>1e6)throw RangeError(`last-run maxEvents must be in 1..1000000`);this.maxEvents=t,this.store=new Bt(e.storage??Rt(),`mwg-last-run:${e.namespace}`)}keep(e,t){let n=pn(e);n.length>this.maxEvents&&(n=n.slice(n.length-this.maxEvents));let r=t===void 0?{version:1,events:n}:{version:1,seed:hn(t),events:n};Ot(JSON.stringify(r)),this.store.write(r)}load(){let e=this.store.read(null);if(e===null)return null;if(e?.version!==1)throw Error(`the kept last-run recording is not version 1; clear() it and record again`);return{version:1,...e.seed===void 0?{}:{seed:hn(e.seed)},events:pn(e.events)}}clear(){this.store.remove()}};function yn(e,t){return{version:1,frame:e.frame,events:e.toJSON(),state:t}}function bn(e,t,n){if(typeof e!=`object`||!e||e.version!==1)throw Error(`a run checkpoint must be { version: 1, frame, events, state }`);return new un(pn(e.events),t,n,{fromFrame:e.frame})}function xn(e,t){if(typeof document>`u`)throw Error(`downloadReplayFile needs a browser document`);let n=document.createElement(`a`);n.href=URL.createObjectURL(new Blob([e],{type:`application/json`})),n.download=t,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(n.href),0)}async function Sn(e){return await e.text()}async function Cn(e=`.json`){if(typeof document>`u`)throw Error(`pickReplayFile needs a browser document`);return await new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.style.display=`none`;let r=!1,i=e=>{r||(r=!0,n.remove(),t(e))};n.addEventListener(`change`,()=>i(n.files?.[0]??null)),n.addEventListener(`cancel`,()=>i(null)),document.body.appendChild(n),n.click()})}var wn=class e{constructor(){this.entries=[],this.nextSequence=0}append(e,t=[]){let n={sequence:this.nextSequence,action:Wt(e,`action`),events:Wt([...t],`events`)};return this.nextSequence++,this.entries.push(n),structuredClone(n)}get size(){return this.entries.length}get all(){return structuredClone(this.entries)}mark(){return this.nextSequence}since(e){return structuredClone(this.entries.filter(t=>t.sequence>=e))}truncate(e){this.entries=this.entries.filter(t=>t.sequence<e),this.nextSequence=e}toJSON(){return this.all}replace(t){let n=e.fromJSON(t);this.entries=n.entries,this.nextSequence=n.nextSequence}static fromJSON(t){let n=new e,r=0;for(let e of t){if(!Number.isSafeInteger(e.sequence)||e.sequence!==r)throw Error(`action journal sequences must be contiguous from zero`);n.entries.push(structuredClone({sequence:e.sequence,action:e.action,events:[...e.events]})),r++}return n.nextSequence=r,n}};function Tn(e){if(e.criteria)return e.criteria;if(e.counter===void 0||e.target===void 0)throw Error(`achievement "${e.id}" needs either counter/target or criteria`);return[{counter:e.counter,target:e.target}]}var En=class e{constructor(){this.definitions=new Map,this.counts=new Map,this.fresh=[]}define(e){this.definitions.set(e.id,e)}count(e){return this.counts.get(e)??0}increment(e,t=1){let n=this.count(e);this.counts.set(e,n+t);let r=[];for(let t of this.definitions.values()){let i=Tn(t);i.some(t=>t.counter===e)&&(i.every(t=>t.counter===e?n>=t.target:this.count(t.counter)>=t.target)||i.every(e=>this.count(e.counter)>=e.target)&&(r.push(t.id),this.fresh.push(t.id)))}return r}unlocked(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return Tn(t).every(e=>this.count(e.counter)>=e.target)}progress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);let n=Tn(t);if(n.length!==1)throw Error(`achievement "${e}" has several criteria - use subProgress`);return{count:this.count(n[0].counter),target:n[0].target}}subProgress(e){let t=this.definitions.get(e);if(!t)throw Error(`no such achievement: "${e}"`);return Tn(t).map(e=>{let t=this.count(e.counter);return{counter:e.counter,count:t,target:e.target,met:t>=e.target}})}drainNew(){let e=this.fresh;return this.fresh=[],e}toJSON(){return{counts:[...this.counts]}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.counts)r.counts.set(e,t);return r}},Dn=class e{constructor(e=[]){this.active=new Set,this.spent=new Set,this.rules=[...e]}add(e){this.rules.push(e)}remove(e){this.rules=this.rules.filter(t=>t.id!==e),this.active.delete(e)}check(e){let t=[];for(let n of this.rules){if(n.once&&this.spent.has(n.id))continue;let r=n.when(e);r&&!this.active.has(n.id)&&(n.action(e),t.push(n.id),n.once&&this.spent.add(n.id)),r?this.active.add(n.id):this.active.delete(n.id)}return t}isActive(e){return this.active.has(e)}reset(){this.active.clear(),this.spent.clear()}toJSON(){return{active:[...this.active],spent:[...this.spent]}}static fromJSON(t,n){let r=new e(t);for(let e of n.active)r.active.add(e);for(let e of n.spent)r.spent.add(e);return r}},On=class{constructor(e={}){let t=e.storage??Rt(),n=`mwg-session:${e.namespace??`default`}`,r=Number(t.read(n)??`0`);this.launches=(Number.isFinite(r)?r:0)+1,t.write(n,String(this.launches))}};function kn(e,t,n){return e<t?t:e>n?n:e}function An(){return{musicVolume:1,sfxVolume:1,muted:!1,zoom:1,bindings:In(je),custom:{}}}function jn(e){return e.muted?0:e.musicVolume}function Mn(e){return e.muted?0:e.sfxVolume}var Nn=class{constructor(e={}){this.storage=e.storage??Rt(),this.key=`mwg-settings:${e.namespace??`default`}`,this.value=Vn(this.storage,this.key),Re(this.value.bindings)}get current(){return{...this.value,bindings:In(this.value.bindings),custom:{...this.value.custom}}}getCustom(e,t){return this.value.custom[e]??t}setCustom(e,t){this.value.custom[e]=t,Hn(this.storage,this.key,this.value)}setMusicVolume(e){this.update({musicVolume:e})}setSfxVolume(e){this.update({sfxVolume:e})}setMuted(e){this.update({muted:e})}setZoom(e){this.update({zoom:e})}setBindings(e){this.update({bindings:e})}update(e){e.musicVolume!==void 0&&(this.value.musicVolume=Pn(e.musicVolume)),e.sfxVolume!==void 0&&(this.value.sfxVolume=Pn(e.sfxVolume)),e.muted!==void 0&&(this.value.muted=e.muted),e.zoom!==void 0&&(this.value.zoom=Fn(e.zoom)),e.bindings!==void 0&&(this.value.bindings=Ln(e.bindings),Re(this.value.bindings)),e.custom!==void 0&&(this.value.custom=zn(e.custom)),Hn(this.storage,this.key,this.value)}applyBindings(){Re(this.value.bindings)}reset(){this.value=An(),Re(this.value.bindings),Hn(this.storage,this.key,this.value)}};function Pn(e){return Number.isFinite(e)?kn(e,0,1):1}function Fn(e){return Number.isFinite(e)?Math.max(.01,e):1}function In(e){let t={};for(let[n,r]of Object.entries(e))t[n]=[...r];return t}function Ln(e){if(typeof e!=`object`||!e||Array.isArray(e))return In(je);let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let e=r.filter(e=>typeof e==`string`);e.length>0&&(t[n]=e)}return Object.keys(t).length>0?t:In(je)}function Rn(e){let t=typeof e;return t===`string`||t===`number`||t===`boolean`}function zn(e){if(typeof e!=`object`||!e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))Rn(r)&&(t[n]=r);return t}function Bn(e){let t=An();if(typeof e!=`object`||!e||Array.isArray(e))return t;let n=e;return{musicVolume:typeof n.musicVolume==`number`?Pn(n.musicVolume):t.musicVolume,sfxVolume:typeof n.sfxVolume==`number`?Pn(n.sfxVolume):t.sfxVolume,muted:typeof n.muted==`boolean`?n.muted:t.muted,zoom:typeof n.zoom==`number`?Fn(n.zoom):t.zoom,bindings:Ln(n.bindings),custom:zn(n.custom)}}function Vn(e,t){let n=e.read(t);if(!n)return An();try{return Bn(Pt(n,{label:`settings`}))}catch{return An()}}function Hn(e,t,n){e.write(t,JSON.stringify(n))}var Un=class extends Yt{constructor(e){super(e,`feedback`)}async submit(e){if(!e.message?.trim())throw Error(`feedback message cannot be empty`);return this.withTimeout(async t=>{let n=await this.fetchFn(this.endpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:t});if(!n.ok)throw Error(`feedback request failed with HTTP ${n.status}`);return{ok:!0,status:n.status}})}},Wn=class{constructor(e){this.schedule=[],this.cursor=0,this.elapsed=0,this.startedWaves=new Set,this.completed=!1,this.onSpawn=e.onSpawn,this.onWaveStart=e.onWaveStart,this.onComplete=e.onComplete,e.waves.forEach((e,t)=>{let n=e.entries.reduce((e,t)=>e+t.count,0),r=e.duration??0,i=0;for(let a of e.entries)for(let o=0;o<a.count;o++,i++){let o=n>1&&r>0?i/(n-1)*r:0;this.schedule.push({time:e.delay+o,kind:a.kind,waveIndex:t})}}),this.schedule.sort((e,t)=>e.time-t.time),this.schedule.length===0&&(this.completed=!0,this.onComplete?.())}update(e){if(!this.completed){for(this.elapsed+=e;this.cursor<this.schedule.length&&this.schedule[this.cursor].time<=this.elapsed;){let e=this.schedule[this.cursor];this.startedWaves.has(e.waveIndex)||(this.startedWaves.add(e.waveIndex),this.onWaveStart?.(e.waveIndex)),this.onSpawn(e.kind),this.cursor++}this.cursor>=this.schedule.length&&(this.completed=!0,this.onComplete?.())}}get isComplete(){return this.completed}};function Gn(e,t){let n=e,r=t-(e-(e&1))/2;return{x:n,y:-n-r,z:r}}function Kn(e){return{x:e.x,y:e.z+(e.x-(e.x&1))/2}}var qn=[{x:1,y:-1,z:0},{x:1,y:0,z:-1},{x:0,y:1,z:-1},{x:-1,y:1,z:0},{x:-1,y:0,z:1},{x:0,y:-1,z:1}];function Jn(e,t){let n=Gn(e,t);return qn.map(e=>Kn({x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}))}function Yn(e,t){let n=Gn(e.x,e.y),r=Gn(t.x,t.y);return Math.max(Math.abs(n.x-r.x),Math.abs(n.y-r.y),Math.abs(n.z-r.z))}function Xn(e){let t=Math.round(e.x),n=Math.round(e.y),r=Math.round(e.z),i=Math.abs(t-e.x),a=Math.abs(n-e.y),o=Math.abs(r-e.z);return i>a&&i>o?t=-n-r:a>o?n=-t-r:r=-t-n,{x:t,y:n,z:r}}function Zn(e,t){let n=Yn(e,t);if(n===0)return[{x:e.x,y:e.y}];let r=Gn(e.x,e.y),i=Gn(t.x,t.y),a=[];for(let e=0;e<=n;e++){let t=e/n;a.push(Kn(Xn({x:r.x+(i.x-r.x)*t,y:r.y+(i.y-r.y)*t,z:r.z+(i.z-r.z)*t})))}return a}function Qn(e,t){let n=Gn(e.x,e.y),r=[];for(let e=-t;e<=t;e++)for(let i=Math.max(-t,-e-t);i<=Math.min(t,-e+t);i++){let t=-e-i;r.push(Kn({x:n.x+e,y:n.y+i,z:n.z+t}))}return r}function $n(e,t,n,r,i={}){let a=+((i.offset??`odd`)===`odd`);return(i.orientation??`flat-top`)===`pointy-top`?{x:e*n+((t&1)===a?n/2:0)+n/2,y:t*r*.75+r/2}:{x:e*n*.75+n/2,y:t*r+((e&1)===a?r/2:0)+r/2}}function er(e,t,n,r,i={}){let a=(i.orientation??`flat-top`)===`pointy-top`,o=a?n:n*.75,s=a?r*.75:r,c=Math.round((e-n/2)/o),l=Math.round((t-r/2)/s),u={x:c,y:l},d=1/0;for(let a=-2;a<=2;a++)for(let o=-2;o<=2;o++){let s={x:c+a,y:l+o},f=$n(s.x,s.y,n,r,i),p=(f.x-e)**2+(f.y-t)**2;p<d&&(d=p,u=s)}return u}function tr(e,t,n,r){return n>=0&&r>=0&&n<e&&r<t}function nr(e,t,n){return n*e+t}function rr(e,t){return t%e}function ir(e,t){return Math.floor(t/e)}function ar(e,t){return`${e},${t}`}function or(e){let t=/^(-?\d+),(-?\d+)$/.exec(e);return t?{x:Number(t[1]),y:Number(t[2])}:null}var sr=[[0,-1],[1,0],[0,1],[-1,0]],cr=[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]],lr=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];function ur(e,t){return Math.hypot(e.x-t.x,e.y-t.y)}function dr(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function fr(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function pr(e,t,n){switch(e){case`euclidean`:return ur(t,n);case`manhattan`:return fr(t,n);case`chebyshev`:return dr(t,n);default:throw RangeError(`unknown distance metric: ${e}`)}}var mr=.12,hr=null,gr,_r=new p;function vr(){if(gr===void 0&&(gr=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):null,gr)){let e=()=>{_r.dispatch(br())};typeof gr.addEventListener==`function`?gr.addEventListener(`change`,e):typeof gr.addListener==`function`&&gr.addListener(e)}return gr}function yr(){return vr()?.matches??!1}function br(){return hr??yr()}function xr(e){hr=e,_r.dispatch(br())}function Sr(e){return vr(),_r.add(e),()=>_r.remove(e)}function Cr(e,t=`decorative`){return br()?t===`meaningful`?Math.min(e,mr):0:e}var wr=class e{constructor(e,t){this.width=e,this.height=t,this.volume=new Float32Array(e*t)}index(e,t){return e<0||t<0||e>=this.width||t>=this.height?-1:t*this.width+e}volumeAt(e,t){let n=this.index(e,t);return n<0?0:this.volume[n]}total(){let e=0;for(let t=0;t<this.volume.length;t++)e+=this.volume[t];return e}seed(e,t,n){let r=this.index(e,t);r>=0&&(this.volume[r]+=n)}clear(e,t){let n=this.index(e,t);n>=0&&(this.volume[n]=0)}spread(e,t=.25,n=.9){let r=new Float32Array(this.volume.length);for(let n=0;n<this.height;n++)for(let i=0;i<this.width;i++){let a=n*this.width+i,o=this.volume[a];if(o<=0)continue;let s=[];for(let[t,r]of sr){let a=i+t,o=n+r,c=this.index(a,o);c>=0&&e(a,o)&&s.push(c)}if(s.length===0)r[a]+=o;else{let e=o*t/s.length;r[a]+=o-e*s.length;for(let t of s)r[t]+=e}}let i=[];for(let e=0;e<r.length;e++){let t=r[e]*n,a=t<.001?0:t;a===0&&this.volume[e]>0&&i.push({x:e%this.width,y:Math.floor(e/this.width)}),this.volume[e]=a}return i}cellsAbove(e){let t=[];for(let n=0;n<this.height;n++)for(let r=0;r<this.width;r++){let i=this.volume[n*this.width+r];i>=e&&t.push({x:r,y:n,volume:i})}return t}toJSON(){return{width:this.width,height:this.height,volume:[...this.volume]}}static fromJSON(t){let n=new e(t.width,t.height);return n.volume.set(t.volume.slice(0,n.volume.length)),n}},Tr=class{constructor(e=1/60,t=5){if(this.accumulator=0,!(e>0))throw Error(`a fixed step must be positive`);this.step=e,this.maxSubsteps=Math.max(1,Math.floor(t))}advance(e,t){this.accumulator+=Math.max(0,e);let n=0;for(;this.accumulator>=this.step&&n<this.maxSubsteps;)t(this.step),this.accumulator-=this.step,n++;return this.accumulator>=this.step&&(this.accumulator=0),n}get alpha(){return this.accumulator/this.step}reset(){this.accumulator=0}},Er={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:1-(-2*e+2)**2/2,easeInCubic:e=>e*e*e,easeOutCubic:e=>1-(1-e)**3,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2},Dr=class{constructor(){this.tweens=[]}tween(e,t,n=Er.linear){let{ease:r=Er.linear,intent:i=`decorative`,alternate:a}=typeof n==`function`?{ease:n}:n,o=br()&&a!==void 0,s=o?a:t,c=Cr(e,o?`meaningful`:i);return c>0?new Promise(e=>{this.tweens.push({elapsed:0,duration:c,ease:r,apply:s,resolve:e,finishOnReduced:!o&&i===`decorative`})}):(s(1),Promise.resolve())}update(e){if(this.tweens.length!==0)for(let t of[...this.tweens]){if(t.finishOnReduced&&br()){this.tweens.splice(this.tweens.indexOf(t),1),t.apply(1),t.resolve();continue}t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.apply(t.ease(n)),n>=1&&(this.tweens.splice(this.tweens.indexOf(t),1),t.resolve())}}get isBusy(){return this.tweens.length>0}clear(){this.tweens=[]}},Or=class{constructor(e={}){this.history=[],this.cursor=-1,this.limit=Math.max(1,e.limit??50)}push(e){this.history.length=this.cursor+1,this.history.push(e),this.history.length>this.limit&&this.history.shift(),this.cursor=this.history.length-1}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}undo(){return this.canUndo?(this.cursor--,this.history[this.cursor]):null}redo(){return this.canRedo?(this.cursor++,this.history[this.cursor]):null}get current(){return this.cursor>=0?this.history[this.cursor]:null}clear(){this.history=[],this.cursor=-1}};function kr(e,t){if(!Number.isFinite(t.maxCost)||t.maxCost<0)return new Map;let n=t.key(e),r=new Map([[n,{cell:e,cost:0}]]),i=[{cell:e,key:n,cost:0}];for(;i.length>0;){let e=jr(i),n=r.get(e.key);if(n&&e.cost===n.cost&&!t.stop?.(e.cell,e.cost))for(let n of t.neighbors(e.cell)){let a=t.cost(e.cell,n);if(!Number.isFinite(a)||a<0)continue;let o=e.cost+a;if(o>t.maxCost||t.canEnter&&!t.canEnter(n,e.cell,o))continue;let s=t.key(n);if(o>=(r.get(s)?.cost??1/0))continue;let c={cell:n,key:s,cost:o};r.set(s,c),Ar(i,c)}}return r}function Ar(e,t){e.push(t);let n=e.length-1;for(;n>0;){let t=Math.floor((n-1)/2);if(e[t].cost<=e[n].cost)break;[e[t],e[n]]=[e[n],e[t]],n=t}}function jr(e){let t=e[0],n=e.pop();if(!t||!n||e.length===0)return t;e[0]=n;let r=0;for(;;){let t=r*2+1,n=t+1,i=r;if(t<e.length&&e[t].cost<e[i].cost&&(i=t),n<e.length&&e[n].cost<e[i].cost&&(i=n),i===r)break;[e[r],e[i]]=[e[i],e[r]],r=i}return t}var Mr=class{constructor(){this.changed=new p,this.tasks=[],this.progress=new Map,this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1}add(e){if(!e.id)throw Error(`load task needs an id`);if(this.tasks.some(t=>t.id===e.id))throw Error(`duplicate load task "${e.id}"`);if(e.weight!==void 0&&!(e.weight>0))throw Error(`load task weight must be positive`);if(this.status_===`loading`)throw Error(`cannot add a task while loading`);return this.tasks.push(e),this.progress.set(e.id,0),this.emit(),this}get snapshot(){let e=this.tasks.reduce((e,t)=>e+(t.weight??1),0),t=this.tasks.reduce((e,t)=>e+(t.weight??1)*(this.progress.get(t.id)??0),0);return{status:this.status_,completed:t,total:e,current:this.current_,error:this.error_}}async start(){if(this.status_===`loading`)throw Error(`load queue is already running`);this.status_=`loading`,this.cancelled=!1,this.error_=null,this.emit();try{for(let e of this.tasks){if(this.cancelled)break;this.current_=e.id,this.emit();let t=this;await e.run({get cancelled(){return t.cancelled},report:t=>this.report(e.id,t)}),this.cancelled||this.report(e.id,1)}this.current_=null,this.status_=this.cancelled?`cancelled`:`ready`,this.emit()}catch(e){throw this.current_=null,this.error_=e,this.status_=`failed`,this.emit(),e}}cancel(){this.status_===`loading`&&(this.cancelled=!0)}retry(){if(this.status_===`loading`)throw Error(`cannot retry while loading`);this.status_=`idle`,this.current_=null,this.error_=null,this.cancelled=!1;for(let e of this.tasks)this.progress.set(e.id,0);this.emit()}report(e,t){if(!Number.isFinite(t))throw Error(`load progress must be finite`);this.progress.set(e,Math.max(0,Math.min(1,t))),this.emit()}emit(){this.changed.dispatch(this.snapshot)}},Nr=class{constructor(){this.entities=new Map,this.ids=new Map,this.sequence=0}add(e,t){let n=this.ids.get(e);if(n!==void 0){if(t!==void 0&&t!==n)throw Error(`entity already has id ${n}`);return n}let r=t;if(r!==void 0){if(r.length===0)throw Error(`entity id must not be empty`);if(this.entities.has(r))throw Error(`entity id already exists: ${r}`)}else do r=`e${this.sequence++}`;while(this.entities.has(r));return this.entities.set(r,e),this.ids.set(e,r),r}get(e){return this.entities.get(e)}idOf(e){return this.ids.get(e)}has(e){return this.entities.has(e)}remove(e){let t=this.entities.get(e);return t!==void 0&&(this.entities.delete(e),this.ids.delete(t),!0)}get size(){return this.entities.size}},Pr=class{constructor(e){this.queue=[],this.busy=!1,this.remaining=0,this.play=e.play}enqueue(e){this.queue.push(...e),this.busy||this.advance()}update(e){this.busy&&(this.remaining-=e,this.remaining<=0&&this.advance())}get isBusy(){return this.busy}clear(){this.queue=[],this.busy=!1,this.remaining=0}advance(){let e=this.queue.shift();if(e===void 0){this.busy=!1,this.remaining=0;return}this.busy=!0;let t=this.play(e)||0;t>0?this.remaining=t:this.advance()}},Fr=2166136261,Ir=16777619;function Lr(e,t=!1){if(e==null)return`null`;switch(typeof e){case`boolean`:return e?`true`:`false`;case`number`:return Number.isFinite(e)?String(e):`null`;case`string`:return JSON.stringify(e);case`bigint`:return JSON.stringify(e.toString());case`function`:case`symbol`:return t?`null`:`undefined`}return Array.isArray(e)?`[${e.map(e=>Lr(e,!0)).join(`,`)}]`:`{${Object.entries(e).filter(([,e])=>e!==void 0&&typeof e!=`function`&&typeof e!=`symbol`).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${JSON.stringify(e)}:${Lr(t)}`).join(`,`)}}`}function Rr(e){let t=Lr(e),n=Fr;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,Ir)>>>0;return n>>>0}var zr=class{constructor(){this.reference=new Map,this.desyncTick=null}observe(e,t){let n=this.reference.get(e);return n===void 0?(this.reference.set(e,t),!0):n===t||(this.desyncTick===null&&(this.desyncTick=e),!1)}get divergent(){return this.desyncTick!==null}get atTick(){return this.desyncTick}reset(){this.reference.clear(),this.desyncTick=null}};function Br(e,t={}){let n=Ur(e);if(n.length===0)return[];let[r,...i]=n,a=t.listDelimiter??`;`,o=t.mapDelimiter??`=`;return i.map((e,n)=>{let i={};return r.forEach((r,s)=>{let c=e[s]??``;c!==``&&(i[r]=Vr(c,t.columns?.[r]??`string`,r,n,a,o))}),i})}function Vr(e,t,n,r,i,a){return Hr(e,t,{column:n,rowIndex:r,listDelimiter:i,mapDelimiter:a,error:()=>t===`number`?`CSV row ${r+1}, column "${n}": "${e}" is not a number`:t===`boolean`?`CSV row ${r+1}, column "${n}": "${e}" is not "true" or "false"`:t===`map`?`CSV row ${r+1}, column "${n}": "${e.split(i).map(e=>e.trim()).find(e=>e&&!e.includes(a))??e}" has no "${a}" to split a key from its value`:`CSV row ${r+1}, column "${n}": "${e}" is invalid`})}function Hr(e,t,n={}){let r=n.column??`value`,i=n.listDelimiter??`;`,a=n.mapDelimiter??`=`,o=e=>{throw Error(n.error?.(e)??e)};switch(t){case`string`:return e;case`number`:{let t=Number(e);return Number.isFinite(t)||o(`${r} must be a number`),t}case`boolean`:{let t=e.toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1;if(n.acceptYesNo&&t===`yes`)return!0;if(n.acceptYesNo&&t===`no`)return!1;o(`${r} must be true, false${n.acceptYesNo?`, yes, or no`:``}`)}case`list`:return e.split(i).map(e=>e.trim()).filter(e=>e.length>0);case`map`:{let t={};for(let n of e.split(i).map(e=>e.trim()).filter(e=>e.length>0)){let e=n.indexOf(a);e===-1&&o(`${r} map entry must contain ${a}`),t[n.slice(0,e).trim()]=n.slice(e+a.length).trim()}return t}}}function Ur(e){let t=[],n=[],r=``,i=!1,a=0;for(;a<e.length;){let o=e[a];if(i){if(o===`"`){if(e[a+1]===`"`){r+=`"`,a+=2;continue}i=!1,a++;continue}r+=o,a++}else o===`"`?(i=!0,a++):o===`,`?(n.push(r),r=``,a++):o===`\r`?a++:o===`
|
|
2
|
-
`?(n.push(r),t.push(n),n=[],r=``,a++):(r+=o,a++)}return(r.length>0||n.length>0)&&(n.push(r),t.push(n)),t.filter(e=>e.length!==1||e[0]!==``)}function Wr(e){let t=[],n=[],r,i=e=>{if(!n.includes(e)){if(n.length>=2)throw Error(`dialogue text supports at most two speakers for the "-" shorthand; found a third speaker "${e}" after "${n[0]}" and "${n[1]}" were already established`);n.push(e)}};for(let a of e.split(`
|
|
3
|
-
`)){let e=a.trim();if(e===``)continue;let o=/^@(\S+)(?:\s+(.*))?$/.exec(e);if(o){let[,e,n]=o;i(e),n&&(t.push({text:n.trim(),speaker:e}),r=e)}else if(e.startsWith(`-`)){if(n.length<2)throw Error(`a "-" line needs two established speakers first (write two "@id text" lines before it)`);let i=e.slice(1).trim(),a=n.find(e=>e!==r)??n[0];t.push({text:i,speaker:a}),r=a}else t.push({text:e}),r=void 0}return t}function Gr(e){let t=Kr(e);if(t.length===0)throw Error(`this twee source has no passages - passages start with ":: Name"`);let n={},r,i;for(let e of t)if(e.name===`StoryTitle`)r=e.body.trim()||void 0;else if(e.name===`StoryData`)i=Jr(e.body);else{if(Object.prototype.hasOwnProperty.call(n,e.name))throw Error(`this twee source defines "${e.name}" twice`);n[e.name]=Yr(e.name,e.body)}let a=Object.keys(n);if(a.length===0)throw Error(`this twee source has no story passages, only StoryTitle/StoryData`);if(i!==void 0&&!Object.prototype.hasOwnProperty.call(n,i))throw Error(`StoryData starts at "${i}", which is not a passage in this file`);for(let[e,t]of Object.entries(n))for(let r of t)if(`ask`in r){for(let t of r.choices)if(t.goto!==void 0&&!Object.prototype.hasOwnProperty.call(n,t.goto))throw Error(`passage "${e}" links to "${t.goto}", which is not a passage in this file`)}return{story:n,start:i??a[0],title:r}}function Kr(e){let t=[],n=null,r=[],i=()=>{n!==null&&t.push({name:n,body:r.join(`
|
|
4
|
-
`)})};for(let t of e.split(`
|
|
5
|
-
`))t.startsWith(`::`)?(i(),n=qr(t),r=[]):n!==null&&r.push(t);return i(),t}function qr(e){let t=e.slice(2).trim(),n=t.search(/[[{]/),r=(n===-1?t:t.slice(0,n)).trim();if(!r)throw Error(`a twee passage header needs a name, got "${e}"`);return r}function Jr(e){let t;try{t=JSON.parse(e.trim())}catch{throw Error(`StoryData must be JSON - check the braces`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`StoryData must be a JSON object`);let n=t.start;if(n!==void 0&&typeof n!=`string`)throw Error(`StoryData "start" must be a passage name`);return n}function Yr(e,t){let n=[],r=[];for(let i of t.split(`
|
|
6
|
-
`)){let t=Xr(i,r,e).replace(/\s+/g,` `).trim();t!==``&&n.push(t)}if(r.length===0)return n.map(e=>({say:e}));let i=n.pop()??``;return[...n.map(e=>({say:e})),{ask:i,choices:r}]}function Xr(e,t,n){let r=``,i=e;for(;;){let a=i.indexOf(`[[`);if(a===-1)return r+i;let o=i.indexOf(`]]`,a);if(o===-1)throw Error(`passage "${n}" has a "[[" with no closing "]]" in "${e.trim()}"`);r+=i.slice(0,a),t.push(Zr(i.slice(a+2,o),n)),i=i.slice(o+2)}}function Zr(e,t){if(e.includes(`[`)||e.includes(`]`))throw Error(`passage "${t}" links with a setter ("${e.trim()}") - story-format macros are not imported, so the link is refused rather than half-read`);let n=e.indexOf(`->`);if(n!==-1)return{text:e.slice(0,n).trim(),goto:e.slice(n+2).trim()};let r=e.indexOf(`<-`);if(r!==-1)return{text:e.slice(r+2).trim(),goto:e.slice(0,r).trim()};let i=e.trim();return{text:i,goto:i}}var I,Qr,$r,L,R=s((()=>{I=(e=>(e.Application=`application`,e.WebGLPipes=`webgl-pipes`,e.WebGLPipesAdaptor=`webgl-pipes-adaptor`,e.WebGLSystem=`webgl-system`,e.WebGLLoader=`webgl-loader`,e.WebGPUPipes=`webgpu-pipes`,e.WebGPUPipesAdaptor=`webgpu-pipes-adaptor`,e.WebGPUSystem=`webgpu-system`,e.WebGPULoader=`webgpu-loader`,e.CanvasSystem=`canvas-system`,e.CanvasPipesAdaptor=`canvas-pipes-adaptor`,e.CanvasPipes=`canvas-pipes`,e.CanvasLoader=`canvas-loader`,e.Asset=`asset`,e.LoadParser=`load-parser`,e.ResolveParser=`resolve-parser`,e.CacheParser=`cache-parser`,e.DetectionParser=`detection-parser`,e.MaskEffect=`mask-effect`,e.BlendMode=`blend-mode`,e.TextureSource=`texture-source`,e.TextureUploaderWebGL=`texture-uploader-webgl`,e.TextureUploaderWebGPU=`texture-uploader-webgpu`,e.Environment=`environment`,e.ShapeBuilder=`shape-builder`,e.Batcher=`batcher`,e))(I||{}),Qr=e=>{if(typeof e==`function`||typeof e==`object`&&e.extension){if(!e.extension)throw Error(`Extension class must have an extension object`);e={...typeof e.extension==`object`?e.extension:{type:e.extension},ref:e}}if(typeof e==`object`)e={...e};else throw Error(`Invalid extension type`);return typeof e.type==`string`&&(e.type=[e.type]),e},$r=(e,t)=>Qr(e).priority??t,L={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...e){return e.map(Qr).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...e){return e.map(Qr).forEach(e=>{e.type.forEach(t=>{let n=this._addHandlers,r=this._queue;n[t]?n[t]?.(e):(r[t]=r[t]||[],r[t]?.push(e))})}),this},handle(e,t,n){let r=this._addHandlers,i=this._removeHandlers;if(r[e]||i[e])throw Error(`Extension type ${e} already has a handler`);r[e]=t,i[e]=n;let a=this._queue;return a[e]&&(a[e]?.forEach(e=>t(e)),delete a[e]),this},handleByMap(e,t){return this.handle(e,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(e,t,n=-1){return this.handle(e,e=>{t.findIndex(t=>t.name===e.name)>=0||(t.push({name:e.name,value:e.ref}),t.sort((e,t)=>$r(t.value,n)-$r(e.value,n)))},e=>{let n=t.findIndex(t=>t.name===e.name);n!==-1&&t.splice(n,1)})},handleByList(e,t,n=-1){return this.handle(e,e=>{t.includes(e.ref)||(t.push(e.ref),t.sort((e,t)=>$r(t,n)-$r(e,n)))},e=>{let n=t.indexOf(e.ref);n!==-1&&t.splice(n,1)})},mixin(e,...t){for(let n of t)Object.defineProperties(e.prototype,Object.getOwnPropertyDescriptors(n))}}})),ei=c(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)})),ti,ni,ri=s((()=>{ti=d(ei(),1),ni=ti.default})),ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni=s((()=>{ii={grad:.9,turn:360,rad:360/(2*Math.PI)},ai=function(e){return typeof e==`string`?e.length>0:typeof e==`number`},oi=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=10**t),Math.round(n*e)/n+0},si=function(e,t,n){return t===void 0&&(t=0),n===void 0&&(n=1),e>n?n:e>t?e:t},ci=function(e){return(e=isFinite(e)?e%360:0)>0?e:e+360},li=function(e){return{r:si(e.r,0,255),g:si(e.g,0,255),b:si(e.b,0,255),a:si(e.a)}},ui=function(e){return{r:oi(e.r),g:oi(e.g),b:oi(e.b),a:oi(e.a,3)}},di=/^#([0-9a-f]{3,8})$/i,fi=function(e){var t=e.toString(16);return t.length<2?`0`+t:t},pi=function(e){var t=e.r,n=e.g,r=e.b,i=e.a,a=Math.max(t,n,r),o=a-Math.min(t,n,r),s=o?a===t?(n-r)/o:a===n?2+(r-t)/o:4+(t-n)/o:0;return{h:60*(s<0?s+6:s),s:a?o/a*100:0,v:a/255*100,a:i}},mi=function(e){var t=e.h,n=e.s,r=e.v,i=e.a;t=t/360*6,n/=100,r/=100;var a=Math.floor(t),o=r*(1-n),s=r*(1-(t-a)*n),c=r*(1-(1-t+a)*n),l=a%6;return{r:255*[r,s,o,o,c,r][l],g:255*[c,r,r,s,o,o][l],b:255*[o,o,c,r,r,s][l],a:i}},hi=function(e){return{h:ci(e.h),s:si(e.s,0,100),l:si(e.l,0,100),a:si(e.a)}},gi=function(e){return{h:oi(e.h),s:oi(e.s),l:oi(e.l),a:oi(e.a,3)}},_i=function(e){return mi((n=(t=e).s,{h:t.h,s:(n*=((r=t.l)<50?r:100-r)/100)>0?2*n/(r+n)*100:0,v:r+n,a:t.a}));var t,n,r},vi=function(e){return{h:(t=pi(e)).h,s:(i=(200-(n=t.s))*(r=t.v)/100)>0&&i<200?n*r/100/(i<=100?i:200-i)*100:0,l:i/2,a:t.a};var t,n,r,i},yi=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,bi=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,xi=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Si=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Ci={string:[[function(e){var t=di.exec(e);return t?(e=t[1]).length<=4?{r:parseInt(e[0]+e[0],16),g:parseInt(e[1]+e[1],16),b:parseInt(e[2]+e[2],16),a:e.length===4?oi(parseInt(e[3]+e[3],16)/255,2):1}:e.length===6||e.length===8?{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16),a:e.length===8?oi(parseInt(e.substr(6,2),16)/255,2):1}:null:null},`hex`],[function(e){var t=xi.exec(e)||Si.exec(e);return t?t[2]!==t[4]||t[4]!==t[6]?null:li({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},`rgb`],[function(e){var t=yi.exec(e)||bi.exec(e);if(!t)return null;var n,r;return _i(hi({h:(n=t[1],r=t[2],r===void 0&&(r=`deg`),Number(n)*(ii[r]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)}))},`hsl`]],object:[[function(e){var t=e.r,n=e.g,r=e.b,i=e.a,a=i===void 0?1:i;return ai(t)&&ai(n)&&ai(r)?li({r:Number(t),g:Number(n),b:Number(r),a:Number(a)}):null},`rgb`],[function(e){var t=e.h,n=e.s,r=e.l,i=e.a,a=i===void 0?1:i;return!ai(t)||!ai(n)||!ai(r)?null:_i(hi({h:Number(t),s:Number(n),l:Number(r),a:Number(a)}))},`hsl`],[function(e){var t=e.h,n=e.s,r=e.v,i=e.a,a=i===void 0?1:i;return!ai(t)||!ai(n)||!ai(r)?null:mi(function(e){return{h:ci(e.h),s:si(e.s,0,100),v:si(e.v,0,100),a:si(e.a)}}({h:Number(t),s:Number(n),v:Number(r),a:Number(a)}))},`hsv`]]},wi=function(e,t){for(var n=0;n<t.length;n++){var r=t[n][0](e);if(r)return[r,t[n][1]]}return[null,void 0]},Ti=function(e){return typeof e==`string`?wi(e.trim(),Ci.string):typeof e==`object`&&e?wi(e,Ci.object):[null,void 0]},Ei=function(e,t){var n=vi(e);return{h:n.h,s:si(n.s+100*t,0,100),l:n.l,a:n.a}},Di=function(e){return(299*e.r+587*e.g+114*e.b)/1e3/255},Oi=function(e,t){var n=vi(e);return{h:n.h,s:n.s,l:si(n.l+100*t,0,100),a:n.a}},ki=function(){function e(e){this.parsed=Ti(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return e.prototype.isValid=function(){return this.parsed!==null},e.prototype.brightness=function(){return oi(Di(this.rgba),2)},e.prototype.isDark=function(){return Di(this.rgba)<.5},e.prototype.isLight=function(){return Di(this.rgba)>=.5},e.prototype.toHex=function(){return e=ui(this.rgba),t=e.r,n=e.g,r=e.b,a=(i=e.a)<1?fi(oi(255*i)):``,`#`+fi(t)+fi(n)+fi(r)+a;var e,t,n,r,i,a},e.prototype.toRgb=function(){return ui(this.rgba)},e.prototype.toRgbString=function(){return e=ui(this.rgba),t=e.r,n=e.g,r=e.b,(i=e.a)<1?`rgba(`+t+`, `+n+`, `+r+`, `+i+`)`:`rgb(`+t+`, `+n+`, `+r+`)`;var e,t,n,r,i},e.prototype.toHsl=function(){return gi(vi(this.rgba))},e.prototype.toHslString=function(){return e=gi(vi(this.rgba)),t=e.h,n=e.s,r=e.l,(i=e.a)<1?`hsla(`+t+`, `+n+`%, `+r+`%, `+i+`)`:`hsl(`+t+`, `+n+`%, `+r+`%)`;var e,t,n,r,i},e.prototype.toHsv=function(){return e=pi(this.rgba),{h:oi(e.h),s:oi(e.s),v:oi(e.v),a:oi(e.a,3)};var e},e.prototype.invert=function(){return Ai({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},e.prototype.saturate=function(e){return e===void 0&&(e=.1),Ai(Ei(this.rgba,e))},e.prototype.desaturate=function(e){return e===void 0&&(e=.1),Ai(Ei(this.rgba,-e))},e.prototype.grayscale=function(){return Ai(Ei(this.rgba,-1))},e.prototype.lighten=function(e){return e===void 0&&(e=.1),Ai(Oi(this.rgba,e))},e.prototype.darken=function(e){return e===void 0&&(e=.1),Ai(Oi(this.rgba,-e))},e.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},e.prototype.alpha=function(e){return typeof e==`number`?Ai({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):oi(this.rgba.a,3);var t},e.prototype.hue=function(e){var t=vi(this.rgba);return typeof e==`number`?Ai({h:e,s:t.s,l:t.l,a:t.a}):oi(t.h)},e.prototype.isEqual=function(e){return this.toHex()===Ai(e).toHex()},e}(),Ai=function(e){return e instanceof ki?e:new ki(e)},ji=[],Mi=function(e){e.forEach(function(e){ji.indexOf(e)<0&&(e(ki,Ci),ji.push(e))})}}));function Pi(e,t){var n={white:`#ffffff`,bisque:`#ffe4c4`,blue:`#0000ff`,cadetblue:`#5f9ea0`,chartreuse:`#7fff00`,chocolate:`#d2691e`,coral:`#ff7f50`,antiquewhite:`#faebd7`,aqua:`#00ffff`,azure:`#f0ffff`,whitesmoke:`#f5f5f5`,papayawhip:`#ffefd5`,plum:`#dda0dd`,blanchedalmond:`#ffebcd`,black:`#000000`,gold:`#ffd700`,goldenrod:`#daa520`,gainsboro:`#dcdcdc`,cornsilk:`#fff8dc`,cornflowerblue:`#6495ed`,burlywood:`#deb887`,aquamarine:`#7fffd4`,beige:`#f5f5dc`,crimson:`#dc143c`,cyan:`#00ffff`,darkblue:`#00008b`,darkcyan:`#008b8b`,darkgoldenrod:`#b8860b`,darkkhaki:`#bdb76b`,darkgray:`#a9a9a9`,darkgreen:`#006400`,darkgrey:`#a9a9a9`,peachpuff:`#ffdab9`,darkmagenta:`#8b008b`,darkred:`#8b0000`,darkorchid:`#9932cc`,darkorange:`#ff8c00`,darkslateblue:`#483d8b`,gray:`#808080`,darkslategray:`#2f4f4f`,darkslategrey:`#2f4f4f`,deeppink:`#ff1493`,deepskyblue:`#00bfff`,wheat:`#f5deb3`,firebrick:`#b22222`,floralwhite:`#fffaf0`,ghostwhite:`#f8f8ff`,darkviolet:`#9400d3`,magenta:`#ff00ff`,green:`#008000`,dodgerblue:`#1e90ff`,grey:`#808080`,honeydew:`#f0fff0`,hotpink:`#ff69b4`,blueviolet:`#8a2be2`,forestgreen:`#228b22`,lawngreen:`#7cfc00`,indianred:`#cd5c5c`,indigo:`#4b0082`,fuchsia:`#ff00ff`,brown:`#a52a2a`,maroon:`#800000`,mediumblue:`#0000cd`,lightcoral:`#f08080`,darkturquoise:`#00ced1`,lightcyan:`#e0ffff`,ivory:`#fffff0`,lightyellow:`#ffffe0`,lightsalmon:`#ffa07a`,lightseagreen:`#20b2aa`,linen:`#faf0e6`,mediumaquamarine:`#66cdaa`,lemonchiffon:`#fffacd`,lime:`#00ff00`,khaki:`#f0e68c`,mediumseagreen:`#3cb371`,limegreen:`#32cd32`,mediumspringgreen:`#00fa9a`,lightskyblue:`#87cefa`,lightblue:`#add8e6`,midnightblue:`#191970`,lightpink:`#ffb6c1`,mistyrose:`#ffe4e1`,moccasin:`#ffe4b5`,mintcream:`#f5fffa`,lightslategray:`#778899`,lightslategrey:`#778899`,navajowhite:`#ffdead`,navy:`#000080`,mediumvioletred:`#c71585`,powderblue:`#b0e0e6`,palegoldenrod:`#eee8aa`,oldlace:`#fdf5e6`,paleturquoise:`#afeeee`,mediumturquoise:`#48d1cc`,mediumorchid:`#ba55d3`,rebeccapurple:`#663399`,lightsteelblue:`#b0c4de`,mediumslateblue:`#7b68ee`,thistle:`#d8bfd8`,tan:`#d2b48c`,orchid:`#da70d6`,mediumpurple:`#9370db`,purple:`#800080`,pink:`#ffc0cb`,skyblue:`#87ceeb`,springgreen:`#00ff7f`,palegreen:`#98fb98`,red:`#ff0000`,yellow:`#ffff00`,slateblue:`#6a5acd`,lavenderblush:`#fff0f5`,peru:`#cd853f`,palevioletred:`#db7093`,violet:`#ee82ee`,teal:`#008080`,slategray:`#708090`,slategrey:`#708090`,aliceblue:`#f0f8ff`,darkseagreen:`#8fbc8f`,darkolivegreen:`#556b2f`,greenyellow:`#adff2f`,seagreen:`#2e8b57`,seashell:`#fff5ee`,tomato:`#ff6347`,silver:`#c0c0c0`,sienna:`#a0522d`,lavender:`#e6e6fa`,lightgreen:`#90ee90`,orange:`#ffa500`,orangered:`#ff4500`,steelblue:`#4682b4`,royalblue:`#4169e1`,turquoise:`#40e0d0`,yellowgreen:`#9acd32`,salmon:`#fa8072`,saddlebrown:`#8b4513`,sandybrown:`#f4a460`,rosybrown:`#bc8f8f`,darksalmon:`#e9967a`,lightgoldenrodyellow:`#fafad2`,snow:`#fffafa`,lightgrey:`#d3d3d3`,lightgray:`#d3d3d3`,dimgray:`#696969`,dimgrey:`#696969`,olivedrab:`#6b8e23`,olive:`#808000`},r={};for(var i in n)r[n[i]]=i;var a={};e.prototype.toName=function(t){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return`transparent`;var i,o,s=r[this.toHex()];if(s)return s;if(t?.closest){var c=this.toRgb(),l=1/0,u=`black`;if(!a.length)for(var d in n)a[d]=new e(n[d]).toRgb();for(var f in n){var p=(i=c,o=a[f],(i.r-o.r)**2+(i.g-o.g)**2+(i.b-o.b)**2);p<l&&(l=p,u=f)}return u}},t.string.push([function(t){var r=t.toLowerCase(),i=r===`transparent`?`#0000`:n[r];return i?new e(i).toRgb():null},`name`])}var Fi=s((()=>{})),Ii,Li,Ri=s((()=>{Ni(),Fi(),Mi([Pi]),Ii=class e{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(t){if(t instanceof e)this._value=this._cloneSource(t._value),this._int=t._int,this._components.set(t._components);else if(t===null)throw Error(`Cannot set Color#value to null`);else(this._value===null||!this._isSourceEqual(this._value,t))&&(this._value=this._cloneSource(t),this._normalize(this._value))}get value(){return this._value}_cloneSource(e){return typeof e==`string`||typeof e==`number`||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e==`object`&&e?{...e}:e}_isSourceEqual(e,t){let n=typeof e;if(n!==typeof t)return!1;if(n===`number`||n===`string`||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length===t.length&&e.every((e,n)=>e===t[n]);if(e!==null&&t!==null){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>e[n]===t[n])}return e===t}toRgba(){let[e,t,n,r]=this._components;return{r:e,g:t,b:n,a:r}}toRgb(){let[e,t,n]=this._components;return{r:e,g:t,b:n}}toRgbaString(){let[e,t,n]=this.toUint8RgbArray();return`rgba(${e},${t},${n},${this.alpha})`}toUint8RgbArray(e){let[t,n,r]=this._components;return this._arrayRgb||=[],e||=this._arrayRgb,e[0]=Math.round(t*255),e[1]=Math.round(n*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||=[],e||=this._arrayRgba;let[t,n,r,i]=this._components;return e[0]=t,e[1]=n,e[2]=r,e[3]=i,e}toRgbArray(e){this._arrayRgb||=[],e||=this._arrayRgb;let[t,n,r]=this._components;return e[0]=t,e[1]=n,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){let[e,t,n]=this.toUint8RgbArray();return(n<<16)+(t<<8)+e}toLittleEndianNumber(){let e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(t){let[n,r,i,a]=e._temp.setValue(t)._components;return this._components[0]*=n,this._components[1]*=r,this._components[2]*=i,this._components[3]*=a,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let n=this._int>>16&255,r=this._int>>8&255,i=this._int&255;return t&&(n=n*e+.5|0,r=r*e+.5|0,i=i*e+.5|0),(e*255<<24)+(n<<16)+(r<<8)+i}toHex(){let e=this._int.toString(16);return`#${`000000`.substring(0,6-e.length)+e}`}toHexa(){let e=Math.round(this._components[3]*255).toString(16);return this.toHex()+`00`.substring(0,2-e.length)+e}setAlpha(e){return this._components[3]=this._clamp(e),this._value=null,this}_normalize(t){let n,r,i,a;if((typeof t==`number`||t instanceof Number)&&t>=0&&t<=16777215){let e=t;n=(e>>16&255)/255,r=(e>>8&255)/255,i=(e&255)/255,a=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[n,r,i,a=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[n,r,i,a=255]=t,n/=255,r/=255,i/=255,a/=255;else if(typeof t==`string`||typeof t==`object`){if(typeof t==`string`){let n=e.HEX_PATTERN.exec(t);n&&(t=`#${n[2]}`)}let o=Ai(t);o.isValid()&&({r:n,g:r,b:i,a}=o.rgba,n/=255,r/=255,i/=255)}if(n!==void 0)this._components[0]=n,this._components[1]=r,this._components[2]=i,this._components[3]=a,this._refreshInt();else throw Error(`Unable to convert color ${t}`)}_refreshInt(){this._clamp(this._components);let[e,t,n]=this._components;this._int=(e*255<<16)+(t*255<<8)+(n*255|0)}_clamp(e,t=0,n=1){return typeof e==`number`?Math.min(Math.max(e,t),n):(e.forEach((r,i)=>{e[i]=Math.min(Math.max(r,t),n)}),e)}static isColorLike(t){return typeof t==`number`||typeof t==`string`||t instanceof Number||t instanceof e||Array.isArray(t)||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t.r!==void 0&&t.g!==void 0&&t.b!==void 0||t.r!==void 0&&t.g!==void 0&&t.b!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0&&t.a!==void 0}},Ii.shared=new Ii,Ii._temp=new Ii,Ii.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i,Li=Ii})),zi,Bi=s((()=>{zi={cullArea:null,cullable:!1,cullableChildren:!0}})),Vi,Hi,Ui,Wi=s((()=>{Vi=Math.PI*2,Hi=180/Math.PI,Ui=Math.PI/180})),Gi,Ki,qi=s((()=>{Gi=class e{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new e(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Ki.x=0,Ki.y=0,Ki}},Ki=new Gi})),z,Ji,Yi,B=s((()=>{Wi(),qi(),z=class e{constructor(e=1,t=0,n=0,r=1,i=0,a=0){this.array=null,this.a=e,this.b=t,this.c=n,this.d=r,this.tx=i,this.ty=a}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,n,r,i,a){return this.a=e,this.b=t,this.c=n,this.d=r,this.tx=i,this.ty=a,this}toArray(e,t){this.array||=new Float32Array(9);let n=t||this.array;return e?(n[0]=this.a,n[1]=this.b,n[2]=0,n[3]=this.c,n[4]=this.d,n[5]=0,n[6]=this.tx,n[7]=this.ty,n[8]=1):(n[0]=this.a,n[1]=this.c,n[2]=this.tx,n[3]=this.b,n[4]=this.d,n[5]=this.ty,n[6]=0,n[7]=0,n[8]=1),n}apply(e,t){t||=new Gi;let n=e.x,r=e.y;return t.x=this.a*n+this.c*r+this.tx,t.y=this.b*n+this.d*r+this.ty,t}applyInverse(e,t){t||=new Gi;let n=this.a,r=this.b,i=this.c,a=this.d,o=this.tx,s=this.ty,c=1/(n*a+i*-r),l=e.x,u=e.y;return t.x=a*c*l+-i*c*u+(s*i-o*a)*c,t.y=n*c*u+-r*c*l+(-s*n+o*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){let t=Math.cos(e),n=Math.sin(e),r=this.a,i=this.c,a=this.tx;return this.a=r*t-this.b*n,this.b=r*n+this.b*t,this.c=i*t-this.d*n,this.d=i*n+this.d*t,this.tx=a*t-this.ty*n,this.ty=a*n+this.ty*t,this}append(e){let t=this.a,n=this.b,r=this.c,i=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*n+e.b*i,this.c=e.c*t+e.d*r,this.d=e.c*n+e.d*i,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*n+e.ty*i+this.ty,this}appendFrom(e,t){let n=e.a,r=e.b,i=e.c,a=e.d,o=e.tx,s=e.ty,c=t.a,l=t.b,u=t.c,d=t.d;return this.a=n*c+r*u,this.b=n*l+r*d,this.c=i*c+a*u,this.d=i*l+a*d,this.tx=o*c+s*u+t.tx,this.ty=o*l+s*d+t.ty,this}setTransform(e,t,n,r,i,a,o,s,c){return this.a=Math.cos(o+c)*i,this.b=Math.sin(o+c)*i,this.c=-Math.sin(o-s)*a,this.d=Math.cos(o-s)*a,this.tx=e-(n*this.a+r*this.c),this.ty=t-(n*this.b+r*this.d),this}prepend(e){let t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){let t=this.a,n=this.c;this.a=t*e.a+this.b*e.c,this.b=t*e.b+this.b*e.d,this.c=n*e.a+this.d*e.c,this.d=n*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){let t=this.a,n=this.b,r=this.c,i=this.d,a=e.pivot,o=-Math.atan2(-r,i),s=Math.atan2(n,t),c=Math.abs(o+s),l=Math.sqrt(t*t+n*n);return c<1e-5||Math.abs(Vi-c)<1e-5?(e.rotation=s,e.skew.x=e.skew.y=0):Math.abs(Math.PI-c)<1e-5?(e.rotation=s-Math.PI,e.skew.x=e.skew.y=0,l=-l):(e.rotation=0,e.skew.x=o,e.skew.y=s),e.scale.x=l,e.scale.y=Math.sqrt(r*r+i*i),e.position.x=this.tx+(a.x*t+a.y*r),e.position.y=this.ty+(a.x*n+a.y*i),e}invert(){let e=this.a,t=this.b,n=this.c,r=this.d,i=this.tx,a=e*r-t*n;return this.a=r/a,this.b=-t/a,this.c=-n/a,this.d=e/a,this.tx=(n*this.ty-r*i)/a,this.ty=-(e*this.ty-t*i)/a,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){let t=new e;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Yi.identity()}static get shared(){return Ji.identity()}},Ji=new z,Yi=new z})),Xi,Zi=s((()=>{Xi=class e{constructor(e,t,n){this._x=t||0,this._y=n||0,this._observer=e}clone(t){return new e(t??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}}));function Qi(e=`default`){return $i[e]===void 0&&($i[e]=-1),++$i[e]}var $i,ea=s((()=>{$i={default:-1}})),ta,V,na,ra,ia,aa,H,oa=s((()=>{ta=new Set,V=`8.0.0`,na=`8.3.4`,ra=`8.21.0`,ia=`8.22.0`,aa={quiet:!1,noColor:!1},H=((e,t,n=3)=>{if(aa.quiet||ta.has(t))return;let r=Error().stack,i=`${t}
|
|
7
|
-
Deprecated since v${e}`,a=typeof console.groupCollapsed==`function`&&!aa.noColor;r===void 0?console.warn(`PixiJS Deprecation Warning: `,i):(r=r.split(`
|
|
8
|
-
`).splice(n).join(`
|
|
9
|
-
`),a?(console.groupCollapsed(`%cPixiJS Deprecation Warning: %c%s`,`color:#614108;background:#fffbe6`,`font-weight:normal;color:#614108;background:#fffbe6`,i),console.warn(r),console.groupEnd()):(console.warn(`PixiJS Deprecation Warning: `,i),console.warn(r))),ta.add(t)}),Object.defineProperties(H,{quiet:{get:()=>aa.quiet,set:e=>{aa.quiet=e},enumerable:!0,configurable:!1},noColor:{get:()=>aa.noColor,set:e=>{aa.noColor=e},enumerable:!0,configurable:!1}})}));function U(...e){sa!==ca&&(sa++,sa===ca?console.warn(`PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS.`):console.warn(`PixiJS Warning: `,...e))}var sa,ca,W=s((()=>{sa=0,ca=500})),la,ua=s((()=>{la={_registeredResources:new Set,register(e){this._registeredResources.add(e)},unregister(e){this._registeredResources.delete(e)},release(){this._registeredResources.forEach(e=>e.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(e){return this._registeredResources.has(e)},reset(){this._registeredResources.clear()}}})),da,fa=s((()=>{da=class{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),t.init?.(e),t}return(e){e.reset?.(),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}})),pa,ma,ha=s((()=>{ua(),fa(),pa=class{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new da(e)),this._poolsByClass.get(e)}stats(){let e={};return this._poolsByClass.forEach(t=>{let n=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[n]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}},ma=new pa,la.register(ma)})),ga,_a=s((()=>{oa(),ga={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(e){typeof e==`boolean`&&e===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(e===!0?{}:e))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(e){H(`v8.6.0`,`cacheAsBitmap is deprecated, use cacheAsTexture instead.`),this.cacheAsTexture(e)}}}));function va(e,t,n){let r=e.length,i;if(t>=r||n===0)return;n=t+n>r?r-t:n;let a=r-n;for(i=t;i<a;++i)e[i]=e[i+n];e.length=a}var ya=s((()=>{})),ba,xa=s((()=>{ya(),oa(),ba={allowChildren:!0,removeChildren(e=0,t){let n=t??this.children.length,r=n-e,i=[];if(r>0&&r<=n){for(let t=n-1;t>=e;t--){let e=this.children[t];e&&(i.push(e),e.parent=null)}va(this.children,e,n);let t=this.renderGroup||this.parentRenderGroup;t&&t.removeChildren(i);for(let e=0;e<i.length;++e){let t=i[e];t.parentRenderLayer?.detach(t),this.emit(`childRemoved`,t,this,e),i[e].emit(`removed`,this)}return i.length>0&&this._didViewChangeTick++,i}if(r===0&&this.children.length===0)return i;throw RangeError(`removeChildren: numeric values are outside the acceptable range.`)},removeChildAt(e){let t=this.getChildAt(e);return this.removeChild(t)},getChildAt(e){if(e<0||e>=this.children.length)throw Error(`getChildAt: Index (${e}) does not exist.`);return this.children[e]},setChildIndex(e,t){if(t<0||t>=this.children.length)throw Error(`The index ${t} supplied is out of bounds ${this.children.length}`);this.getChildIndex(e),this.addChildAt(e,t)},getChildIndex(e){let t=this.children.indexOf(e);if(t===-1)throw Error(`The supplied Container must be a child of the caller`);return t},addChildAt(e,t){this.allowChildren||H(V,`addChildAt: Only Containers will be allowed to add children in v8.0.0`);let{children:n}=this;if(t<0||t>n.length)throw Error(`${e}addChildAt: The index ${t} supplied is out of bounds ${n.length}`);let r=e.parent===this;if(e.parent){let n=e.parent.children.indexOf(e);if(r){if(n===t)return e;e.parent.children.splice(n,1)}else e.removeFromParent()}t===n.length?n.push(e):n.splice(t,0,e);let i=this.renderGroup||this.parentRenderGroup;return this.sortableChildren&&(this.sortDirty=!0),r?(i&&(i.structureDidChange=!0),e):(e.parent=this,e.didChange=!0,e._updateFlags=15,i&&i.addChild(e),this.emit(`childAdded`,e,this,t),e.emit(`added`,this),e)},swapChildren(e,t){if(e===t)return;let n=this.getChildIndex(e),r=this.getChildIndex(t);this.children[n]=t,this.children[r]=e;let i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...e){return e.length===1?this.reparentChildAt(e[0],this.children.length):(e.forEach(e=>this.reparentChildAt(e,this.children.length)),e[0])},reparentChildAt(e,t){if(e.parent===this)return this.setChildIndex(e,t),e;let n=e.worldTransform.clone();e.removeFromParent(),this.addChildAt(e,t);let r=this.worldTransform.clone();return r.invert(),n.prepend(r),e.setFromMatrix(n),e},replaceChild(e,t){e.updateLocalTransform(),this.addChildAt(t,this.getChildIndex(e)),t.setFromMatrix(e.localTransform),t.updateLocalTransform(),this.removeChild(e)}}})),Sa,Ca=s((()=>{Sa={collectRenderables(e,t,n){this.parentRenderLayer&&this.parentRenderLayer!==n||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(e,t,n):this.renderGroup?t.renderPipes.renderGroup.addRenderGroup(this.renderGroup,e):this.collectRenderablesWithEffects(e,t,n))},collectRenderablesSimple(e,t,n){let r=this.children,i=r.length;for(let a=0;a<i;a++)r[a].collectRenderables(e,t,n)},collectRenderablesWithEffects(e,t,n){let{renderPipes:r}=t;for(let t=0;t<this.effects.length;t++){let n=this.effects[t];r[n.pipe].push(n,this,e)}this.collectRenderablesSimple(e,t,n);for(let t=this.effects.length-1;t>=0;t--){let n=this.effects[t];r[n.pipe].pop(n,this,e)}}}})),wa,Ta=s((()=>{wa=class{constructor(){this.pipe=`filter`,this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}})),Ea,Da,Oa=s((()=>{R(),ha(),Ea=class{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){let n=this._tests[t];if(n.test(e))return ma.get(n.maskClass,e)}return e}returnMaskEffect(e){ma.return(e)}},Da=new Ea,L.handleByList(I.MaskEffect,Da._effectClasses)})),ka,Aa=s((()=>{Ta(),Oa(),ka={_maskEffect:null,_maskOptions:{inverse:!1,channel:`red`},_filterEffect:null,effects:[],_markStructureAsChanged(){let e=this.renderGroup||this.parentRenderGroup;e&&(e.structureDidChange=!0)},addEffect(e){this.effects.indexOf(e)===-1&&(this.effects.push(e),this.effects.sort((e,t)=>e.priority-t.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(e){let t=this.effects.indexOf(e);t!==-1&&(this.effects.splice(t,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(e){let t=this._maskEffect;t?.mask!==e&&(t&&(this.removeEffect(t),Da.returnMaskEffect(t),this._maskEffect=null),e!=null&&(this._maskEffect=Da.getMaskEffect(e),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(e){this._maskOptions={...this._maskOptions,...e},e.mask&&(this.mask=e.mask),this._markStructureAsChanged()},set filters(e){!Array.isArray(e)&&e&&(e=[e]);let t=this._filterEffect||=new wa;e=e;let n=e?.length>0,r=n!==t.filters?.length>0;e=Array.isArray(e)?e.slice(0):e,t.filters=Object.freeze(e),r&&(n?this.addEffect(t):(this.removeEffect(t),t.filters=e??null))},get filters(){return this._filterEffect?.filters},set filterArea(e){this._filterEffect||=new wa,this._filterEffect.filterArea=e},get filterArea(){return this._filterEffect?.filterArea}}})),ja,Ma=s((()=>{oa(),ja={label:null,get name(){return H(V,`Container.name property has been removed, use Container.label instead`),this.label},set name(e){H(V,`Container.name property has been removed, use Container.label instead`),this.label=e},getChildByName(e,t=!1){return this.getChildByLabel(e,t)},getChildByLabel(e,t=!1){let n=this.children;for(let t=0;t<n.length;t++){let r=n[t];if(r.label===e||e instanceof RegExp&&e.test(r.label))return r}if(t)for(let t=0;t<n.length;t++){let r=n[t].getChildByLabel(e,!0);if(r)return r}return null},getChildrenByLabel(e,t=!1,n=[]){let r=this.children;for(let t=0;t<r.length;t++){let i=r[t];(i.label===e||e instanceof RegExp&&e.test(i.label))&&n.push(i)}if(t)for(let t=0;t<r.length;t++)r[t].getChildrenByLabel(e,!0,n);return n}}})),Na,G,Pa=s((()=>{qi(),Na=[new Gi,new Gi,new Gi,new Gi],G=class e{constructor(e=0,t=0,n=0,r=0){this.type=`rectangle`,this.x=Number(e),this.y=Number(t),this.width=Number(n),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new e(0,0,0,0)}clone(){return new e(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,n,r=.5){let{width:i,height:a}=this;if(i<=0||a<=0)return!1;let o=this.x,s=this.y,c=n*(1-r),l=n-c,u=o-c,d=o+i+c,f=s-c,p=s+a+c,m=o+l,h=o+i-l,g=s+l,_=s+a-l;return e>=u&&e<=d&&t>=f&&t<=p&&!(e>m&&e<h&&t>g&&t<_)}intersects(e,t){if(!t){let t=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=t)return!1;let n=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>n}let n=this.left,r=this.right,i=this.top,a=this.bottom;if(r<=n||a<=i)return!1;let o=Na[0].set(e.left,e.top),s=Na[1].set(e.left,e.bottom),c=Na[2].set(e.right,e.top),l=Na[3].set(e.right,e.bottom);if(c.x<=o.x||s.y<=o.y)return!1;let u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(o,o),t.apply(s,s),t.apply(c,c),t.apply(l,l),Math.max(o.x,s.x,c.x,l.x)<=n||Math.min(o.x,s.x,c.x,l.x)>=r||Math.max(o.y,s.y,c.y,l.y)<=i||Math.min(o.y,s.y,c.y,l.y)>=a))return!1;let d=u*(s.y-o.y),f=u*(o.x-s.x),p=d*n+f*i,m=d*r+f*i,h=d*n+f*a,g=d*r+f*a;if(Math.max(p,m,h,g)<=d*o.x+f*o.y||Math.min(p,m,h,g)>=d*l.x+f*l.y)return!1;let _=u*(o.y-c.y),v=u*(c.x-o.x),y=_*n+v*i,b=_*r+v*i,x=_*n+v*a,S=_*r+v*a;return!(Math.max(y,b,x,S)<=_*o.x+v*o.y||Math.min(y,b,x,S)>=_*l.x+v*l.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){let t=Math.max(this.x,e.x),n=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),i=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(n-t,0),this.y=r,this.height=Math.max(i-r,0),this}ceil(e=1,t=.001){let n=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=n-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){let t=Math.min(this.x,e.x),n=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),i=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=n-t,this.y=r,this.height=i-r,this}getBounds(t){return t||=new e,t.copyFrom(this),t}containsRect(e){if(this.width<=0||this.height<=0)return!1;let t=e.x,n=e.y,r=e.x+e.width,i=e.y+e.height;return t>=this.x&&t<this.x+this.width&&n>=this.y&&n<this.y+this.height&&r>=this.x&&r<=this.x+this.width&&i>=this.y&&i<=this.y+this.height}set(e,t,n,r){return this.x=e,this.y=t,this.width=n,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}})),Fa,Ia,La=s((()=>{B(),Pa(),Fa=new z,Ia=class e{constructor(e=1/0,t=1/0,n=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=Fa,this.minX=e,this.minY=t,this.maxX=n,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||=new G;let e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=Fa,this}set(e,t,n,r){this.minX=e,this.minY=t,this.maxX=n,this.maxY=r}addFrame(e,t,n,r,i){i||=this.matrix;let a=i.a,o=i.b,s=i.c,c=i.d,l=i.tx,u=i.ty,d=this.minX,f=this.minY,p=this.maxX,m=this.maxY,h=a*e+s*t+l,g=o*e+c*t+u;h<d&&(d=h),g<f&&(f=g),h>p&&(p=h),g>m&&(m=g),h=a*n+s*t+l,g=o*n+c*t+u,h<d&&(d=h),g<f&&(f=g),h>p&&(p=h),g>m&&(m=g),h=a*e+s*r+l,g=o*e+c*r+u,h<d&&(d=h),g<f&&(f=g),h>p&&(p=h),g>m&&(m=g),h=a*n+s*r+l,g=o*n+c*r+u,h<d&&(d=h),g<f&&(f=g),h>p&&(p=h),g>m&&(m=g),this.minX=d,this.minY=f,this.maxX=p,this.maxY=m}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){let t=this.minX,n=this.minY,r=this.maxX,i=this.maxY,{a,b:o,c:s,d:c,tx:l,ty:u}=e,d=a*t+s*n+l,f=o*t+c*n+u;this.minX=d,this.minY=f,this.maxX=d,this.maxY=f,d=a*r+s*n+l,f=o*r+c*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=a*t+s*i+l,f=o*t+c*i+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=a*r+s*i+l,f=o*r+c*i+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,n,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<n&&(this.minY=n),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new e(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){let t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){let t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,n,r){let i=this.minX,a=this.minY,o=this.maxX,s=this.maxY;r||=this.matrix;let c=r.a,l=r.b,u=r.c,d=r.d,f=r.tx,p=r.ty;for(let r=t;r<n;r+=2){let t=e[r],n=e[r+1],m=c*t+u*n+f,h=l*t+d*n+p;i=m<i?m:i,a=h<a?h:a,o=m>o?m:o,s=h>s?h:s}this.minX=i,this.minY=a,this.maxX=o,this.maxY=s}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}})),Ra,za,Ba=s((()=>{B(),ha(),La(),Ra=ma.getPool(z),za=ma.getPool(Ia)})),Va,Ha,Ua=s((()=>{B(),La(),Ba(),Va=new z,Ha={getFastGlobalBounds(e,t){t||=new Ia,t.clear(),this._getGlobalBoundsRecursive(!!e,t,this.parentRenderLayer),t.isValid||t.set(0,0,0,0);let n=this.renderGroup||this.parentRenderGroup;return t.applyMatrix(n.worldTransform),t},_getGlobalBoundsRecursive(e,t,n){let r=t;if(e&&this.parentRenderLayer&&this.parentRenderLayer!==n||this.localDisplayStatus!==7||!this.measurable)return;let i=!!this.effects.length;if((this.renderGroup||i)&&(r=za.get().clear()),this.boundsArea)t.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){let e=this.bounds;r.addFrame(e.minX,e.minY,e.maxX,e.maxY,this.groupTransform)}let t=this.children;for(let i=0;i<t.length;i++)t[i]._getGlobalBoundsRecursive(e,r,n)}if(i){let e=!1,n=this.renderGroup||this.parentRenderGroup;for(let t=0;t<this.effects.length;t++)this.effects[t].addBounds&&(e||(e=!0,r.applyMatrix(n.worldTransform)),this.effects[t].addBounds(r,!0));e&&r.applyMatrix(n.worldTransform.copyTo(Va).invert()),t.addBounds(r),za.return(r)}else this.renderGroup&&(t.addBounds(r,this.relativeGroupTransform),za.return(r))}}}));function Wa(e,t,n){n.clear();let r,i;return e.parent?t?r=e.parent.worldTransform:(i=Ra.get().identity(),r=Ka(e,i)):r=z.IDENTITY,Ga(e,n,r,t),i&&Ra.return(i),n.isValid||n.set(0,0,0,0),n}function Ga(e,t,n,r){if(!e.visible||!e.measurable)return;let i;r?i=e.worldTransform:(e.updateLocalTransform(),i=Ra.get(),i.appendFrom(e.localTransform,n));let a=t,o=!!e.effects.length;if(o&&(t=za.get().clear()),e.boundsArea)t.addRect(e.boundsArea,i);else{let n=e.bounds;n&&!n.isEmpty()&&(t.matrix=i,t.addBounds(n));for(let n=0;n<e.children.length;n++)Ga(e.children[n],t,i,r)}if(o){for(let n=0;n<e.effects.length;n++)e.effects[n].addBounds?.(t);a.addBounds(t,z.IDENTITY),za.return(t)}r||Ra.return(i)}function Ka(e,t){let n=e.parent;return n&&(Ka(n,t),n.updateLocalTransform(),t.append(n.localTransform)),t}var qa=s((()=>{B(),Ba()}));function Ja(e,t){if(e===16777215||!t)return t;if(t===16777215||!e)return e;let n=e>>16&255,r=e>>8&255,i=e&255,a=t>>16&255,o=t>>8&255,s=t&255,c=n*a/255|0,l=r*o/255|0,u=i*s/255|0;return(c<<16)+(l<<8)+u}var Ya=s((()=>{}));function Xa(e,t){return e===Za?t:t===Za?e:Ja(e,t)}var Za,Qa=s((()=>{Ya(),Za=16777215}));function $a(e){return((e&255)<<16)+(e&65280)+(e>>16&255)}var eo,to=s((()=>{B(),qa(),Ba(),Qa(),eo={getGlobalAlpha(e){if(e)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let t=this.alpha,n=this.parent;for(;n;)t*=n.alpha,n=n.parent;return t},getGlobalTransform(e=new z,t){if(t)return e.copyFrom(this.worldTransform);this.updateLocalTransform();let n=Ka(this,Ra.get().identity());return e.appendFrom(this.localTransform,n),Ra.return(n),e},getGlobalTint(e){if(e)return this.renderGroup?$a(this.renderGroup.worldColor):this.parentRenderGroup?$a(Xa(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let t=this.localColor,n=this.parent;for(;n;)t=Xa(t,n.localColor),n=n.parent;return $a(t)}}}));function no(e,t,n){return t.clear(),n||=z.IDENTITY,ro(e,t,n,e,!0),t.isValid||t.set(0,0,0,0),t}function ro(e,t,n,r,i){let a;if(i)a=Ra.get(),a=n.copyTo(a);else{if(!e.visible||!e.measurable)return;e.updateLocalTransform();let t=e.localTransform;a=Ra.get(),a.appendFrom(t,n)}let o=t,s=!!e.effects.length;if(s&&(t=za.get().clear()),e.boundsArea)t.addRect(e.boundsArea,a);else{e.renderPipeId&&(t.matrix=a,t.addBounds(e.bounds));let n=e.children;for(let e=0;e<n.length;e++)ro(n[e],t,a,r,!1)}if(s){for(let n=0;n<e.effects.length;n++)e.effects[n].addLocalBounds?.(t,r);o.addBounds(t,z.IDENTITY),za.return(t)}Ra.return(a)}var io=s((()=>{B(),Ba()}));function ao(e,t){let n=e.children;for(let e=0;e<n.length;e++){let r=n[e],i=r.uid,a=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,o=t.index;(t.data[o]!==i||t.data[o+1]!==a)&&(t.data[t.index]=i,t.data[t.index+1]=a,t.didChange=!0),t.index=o+2,r.children.length&&ao(r,t)}return t.didChange}var oo=s((()=>{})),so,co,lo=s((()=>{B(),La(),qa(),io(),oo(),so=new z,co={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(e,t){let n=Math.sign(this.scale.x)||1;t===0?this.scale.x=n:this.scale.x=e/t*n},_setHeight(e,t){let n=Math.sign(this.scale.y)||1;t===0?this.scale.y=n:this.scale.y=e/t*n},getLocalBounds(){this._localBoundsCacheData||={data:[],index:1,didChange:!1,localBounds:new Ia};let e=this._localBoundsCacheData;return e.index=1,e.didChange=!1,e.data[0]!==this._didViewChangeTick&&(e.didChange=!0,e.data[0]=this._didViewChangeTick),ao(this,e),e.didChange&&no(this,e.localBounds,so),e.localBounds},getBounds(e,t){return Wa(this,e,t||new Ia)}}})),uo,fo=s((()=>{uo={_onRender:null,set onRender(e){let t=this.renderGroup||this.parentRenderGroup;e?(this._onRender||t?.addOnRender(this),this._onRender=e):(this._onRender&&t?.removeOnRender(this),this._onRender=null)},get onRender(){return this._onRender}}}));function po(e,t){return e._zIndex-t._zIndex}var mo,ho=s((()=>{mo={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(e){this._zIndex!==e&&(this._zIndex=e,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(po))}}})),go,_o=s((()=>{qi(),Ba(),go={getGlobalPosition(e=new Gi,t=!1){return this.parent?this.parent.toGlobal(this._position,e,t):(e.x=this._position.x,e.y=this._position.y),e},toGlobal(e,t,n=!1){let r=this.getGlobalTransform(Ra.get(),n);return t=r.apply(e,t),Ra.return(r),t},toLocal(e,t,n,r){t&&(e=t.toGlobal(e,n,r));let i=this.getGlobalTransform(Ra.get(),r);return n=i.applyInverse(e,n),Ra.return(i),n}}})),vo,yo=s((()=>{ea(),vo=class{constructor(){this.uid=Qi(`instructionSet`),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){if(this.renderPipes)for(let e in this.renderPipes)this.renderPipes[e].destroyInstructionSet?.(this);this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,[`type`,`action`])}}}));function bo(e){return e+=+(e===0),--e,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+1}function xo(e){return!(e&e-1)&&!!e}var So=s((()=>{}));function Co(e){let t={};for(let n in e)e[n]!==void 0&&(t[n]=e[n]);return t}var wo=s((()=>{}));function To(e){let t=Eo[e];return t===void 0&&(Eo[e]=Qi(`resource`)),t}var Eo,Do,Oo,ko=s((()=>{ri(),ea(),oa(),Eo=Object.create(null),Do=class e extends ni{constructor(t={}){super(),this._resourceType=`textureSampler`,this._maxAnisotropy=1,this.destroyed=!1,t={...e.defaultOptions,...t},this.addressMode=t.addressMode,this.addressModeU=t.addressModeU??this.addressModeU,this.addressModeV=t.addressModeV??this.addressModeV,this.addressModeW=t.addressModeW??this.addressModeW,this.scaleMode=t.scaleMode,this.magFilter=t.magFilter??this.magFilter,this.minFilter=t.minFilter??this.minFilter,this.mipmapFilter=t.mipmapFilter??this.mipmapFilter,this.lodMinClamp=t.lodMinClamp,this.lodMaxClamp=t.lodMaxClamp,this.compare=t.compare,this.maxAnisotropy=t.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){H(V,`TextureStyle.wrapMode is now TextureStyle.addressMode`),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode=`linear`)}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit(`change`,this)}_generateResourceId(){let e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=To(e),this._resourceId}destroy(){this.destroyed=!0,this.emit(`destroy`,this),this.emit(`change`,this),this.removeAllListeners()}},Do.defaultOptions={addressMode:`clamp-to-edge`,scaleMode:`linear`},Oo=Do}));function Ao(e){return e.viewDimension?e.viewDimension:e.depth?`3d`:e.arrayLayerCount>1?`2d-array`:`2d`}function jo(e,t,n){if(e.depth!==void 0&&typeof e.depth!=`number`)throw Error(`[TextureSource] depth is a 3D texture's depth in texels, but got ${e.depth}. For a depth buffer, use the depth option of a RenderTarget or the renderer.`);if(e.depth&&e.arrayLayerCount>1)throw Error(`[TextureSource] depth and arrayLayerCount can't be combined: use depth for a 3D texture or arrayLayerCount for a 2D array.`);if(e.depth&&t!==`3d`)throw Error(`[TextureSource] depth makes a 3D texture, but viewDimension is '${t}'. Use arrayLayerCount for layered textures.`);if(t===`3d`&&e.arrayLayerCount>1)throw Error(`[TextureSource] a 3D texture takes depth, not arrayLayerCount.`);if(e.dimensions&&e.dimensions!==n)throw Error(`[TextureSource] dimensions '${e.dimensions}' doesn't match viewDimension '${t}'. Leave dimensions out; it is derived from the view.`);if(e.dimensions&&H(ia,`TextureSource dimensions is derived from viewDimension and depth; leave it out.`),n===`3d`&&e.antialias)throw Error(`[TextureSource] a 3D texture can't be antialiased: WebGPU has no multisampled 3D textures.`)}var Mo,No,Po=s((()=>{ri(),So(),wo(),ea(),oa(),ko(),Mo=class e extends ni{constructor(t={}){super(),this.options=t,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=Qi(`textureSource`),this._resourceType=`textureSource`,this._resourceId=Qi(`resource`),this.uploadMethodId=`unknown`,this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format=`rgba8unorm`,this.dimension=`2d`,this.viewDimension=`2d`,this.arrayLayerCount=1,this.depth=1,this._ownsStyle=!1,this.antialias=!1,this.transient=!1,this.storage=!1,this._batchTick=-1,this._textureBindLocation=-1;let n=t;t={...e.defaultOptions,...t};let r=Ao(t),i=r===`3d`||r===`1d`?r:`2d`;jo(n,r,i),this.label=t.label??``,this.resource=t.resource,this.autoGarbageCollect=t.autoGarbageCollect,this._resolution=t.resolution,this.pixelWidth=t.width?t.width*this._resolution:this.resource?this.resourceWidth??1:1,this.pixelHeight=t.height?t.height*this._resolution:this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=t.format,this.dimension=i,this.viewDimension=r,this.arrayLayerCount=t.arrayLayerCount,this.depth=i===`3d`?t.depth??1:1,this.mipLevelCount=t.mipLevelCount,this.autoGenerateMipmaps=t.autoGenerateMipmaps,this.sampleCount=t.sampleCount,this.antialias=i!==`3d`&&t.antialias,this.transient=t.transient??!1,this.storage=t.storage??!1,this.alphaMode=t.alphaMode,this.style=new Oo(Co(t)),this._ownsStyle=!0,this.destroyed=!1,this._refreshPOT()}get depthOrArrayLayers(){return this.dimension===`3d`?this.depth:this.arrayLayerCount||1}get source(){return this}get style(){return this._style}set style(e){this.style!==e&&(this._ownsStyle=!1,this._style?.off(`change`,this._onStyleChange,this),this._style=e,this._style?.on(`change`,this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit(`styleChange`,this)}update(){if(this.resource){let e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit(`update`,this)}destroy(){this.destroyed=!0,this.unload(),this.emit(`destroy`,this),this._style&&=(this._ownsStyle&&this._style.destroy(),null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=Qi(`resource`),this.emit(`change`,this),this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy?.();this._gpuData=Object.create(null)}get resourceWidth(){let{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){let{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,n){n||=this._resolution,e||=this.width,t||=this.height;let r=Math.round(e*n),i=Math.round(t*n);return this.width=r/n,this.height=i/n,this._resolution=n,this.pixelWidth===r&&this.pixelHeight===i?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=i,this.emit(`resize`,this),this._resourceId=Qi(`resource`),this.emit(`change`,this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit(`updateMipmaps`,this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=xo(this.pixelWidth)&&xo(this.pixelHeight)}static test(e){throw Error(`Unimplemented`)}},Mo.defaultOptions={resolution:1,format:`bgra8unorm`,alphaMode:`premultiply-alpha-on-upload`,arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1},No=Mo}));function Fo(){for(let e=0;e<16;e++){let t=[];Bo.push(t);for(let n=0;n<16;n++){let r=Ho(Io[e]*Io[n]+Ro[e]*Lo[n]),i=Ho(Lo[e]*Io[n]+zo[e]*Lo[n]),a=Ho(Io[e]*Ro[n]+Ro[e]*zo[n]),o=Ho(Lo[e]*Ro[n]+zo[e]*zo[n]);for(let e=0;e<16;e++)if(Io[e]===r&&Lo[e]===i&&Ro[e]===a&&zo[e]===o){t.push(e);break}}}for(let e=0;e<16;e++){let t=new z;t.set(Io[e],Lo[e],Ro[e],zo[e],0,0),Vo.push(t)}}var Io,Lo,Ro,zo,Bo,Vo,Ho,K,Uo=s((()=>{B(),Io=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Lo=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Ro=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],zo=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Bo=[],Vo=[],Ho=Math.sign,Fo(),K={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:e=>Io[e],uY:e=>Lo[e],vX:e=>Ro[e],vY:e=>zo[e],inv:e=>e&8?e&15:-e&7,add:(e,t)=>Bo[e][t],sub:(e,t)=>Bo[e][K.inv(t)],rotate180:e=>e^4,isVertical:e=>(e&3)==2,byDirection:(e,t)=>Math.abs(e)*2<=Math.abs(t)?t>=0?K.S:K.N:Math.abs(t)*2<=Math.abs(e)?e>0?K.E:K.W:t>0?e>0?K.SE:K.SW:e>0?K.NE:K.NW,matrixAppendRotationInv:(e,t,n=0,r=0,i=0,a=0)=>{let o=Vo[K.inv(t)],s=o.a,c=o.b,l=o.c,u=o.d,d=n-Math.min(0,s*i,l*a,s*i+l*a),f=r-Math.min(0,c*i,u*a,c*i+u*a),p=e.a,m=e.b,h=e.c,g=e.d;e.a=s*p+c*h,e.b=s*m+c*g,e.c=l*p+u*h,e.d=l*m+u*g,e.tx=d*p+f*h+e.tx,e.ty=d*m+f*g+e.ty},transformRectCoords:(e,t,n,r)=>{let{x:i,y:a,width:o,height:s}=e,{x:c,y:l,width:u,height:d}=t;return n===K.E?(r.set(i+c,a+l,o,s),r):n===K.S?r.set(u-a-s+c,i+l,s,o):n===K.W?r.set(u-i-o+c,d-a-s+l,o,s):n===K.N?r.set(a+c,d-i-o+l,s,o):r.set(i+c,a+l,o,s)}}})),Wo,Go=s((()=>{Wo=()=>{}}));function Ko(e){return e.endsWith(`int`)}var qo=s((()=>{})),Jo,Yo=s((()=>{R(),qo(),Po(),Jo=class extends No{constructor(e){let t=e.depth??e.arrayLayerCount??1,n=e.resource||new Float32Array(e.width*e.height*t*4),r=e.format;r||=n instanceof Float32Array?`rgba32float`:n instanceof Int32Array||n instanceof Uint32Array?`rgba32uint`:n instanceof Int16Array||n instanceof Uint16Array?`rgba16uint`:(n instanceof Int8Array,`bgra8unorm`);let i=Ko(r)||t>1;super({...i&&{alphaMode:`no-premultiply-alpha`},...e,resource:n,format:r}),this.uploadMethodId=`buffer`,this._updateStart=0,this._updateEnd=1/0}update(e=0,t=1/0){if((e>0||t<1/0)&&this.depthOrArrayLayers>1)throw Error(`[BufferImageSource] a 3D texture or 2D array uploads whole: call update() with no range.`);this._updateStart=e,this._updateEnd=t,super.update(),this._updateStart=0,this._updateEnd=1/0}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}},Jo.extension=I.TextureSource})),Xo,Zo,Qo=s((()=>{B(),Xo=new z,Zo=class{constructor(e,t){this.mapCoord=new z,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._updateID=0,this.clampOffset=0,this.clampMargin=t===void 0?e.width<10?0:.5:t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture?.removeListener(`update`,this.update,this),this._texture=e,this._texture.addListener(`update`,this.update,this)),this.update()}destroy(){this._texture?.removeListener(`update`,this.update,this),this._texture=null}multiplyUvs(e,t){t===void 0&&(t=e);let n=this.mapCoord;for(let r=0;r<e.length;r+=2){let i=e[r],a=e[r+1];t[r]=i*n.a+a*n.c+n.tx,t[r+1]=i*n.b+a*n.d+n.ty}return t}update(){let e=this._texture;this._updateID++;let t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);let n=e.orig,r=e.trim;r&&(Xo.set(n.width/r.width,0,0,n.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Xo));let i=e.source,a=this.uClampFrame,o=this.clampMargin/i._resolution,s=this.clampOffset/i._resolution;return a[0]=(e.frame.x+o+s)/i.width,a[1]=(e.frame.y+o+s)/i.height,a[2]=(e.frame.x+e.frame.width-o+s)/i.width,a[3]=(e.frame.y+e.frame.height-o+s)/i.height,this.uClampOffset[0]=this.clampOffset/i.pixelWidth,this.uClampOffset[1]=this.clampOffset/i.pixelHeight,this.isSimple=e.frame.width===i.width&&e.frame.height===i.height&&e.rotate===0,!0}}})),q,$o=s((()=>{ri(),Uo(),Pa(),ea(),oa(),Go(),Yo(),Po(),Qo(),q=class extends ni{constructor({source:e,label:t,frame:n,orig:r,trim:i,defaultAnchor:a,defaultBorders:o,rotate:s,dynamic:c}={}){if(super(),this.uid=Qi(`texture`),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new G,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=e?.source??new No,this.noFrame=!n,n)this.frame.copyFrom(n);else{let{width:e,height:t}=this._source;this.frame.width=e,this.frame.height=t}this.orig=r||this.frame,this.trim=i,this.rotate=s??0,this.defaultAnchor=a,this.defaultBorders=o,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off(`resize`,this.update,this),this._source=e,e.on(`resize`,this.update,this),this.emit(`update`,this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||=new Zo(this),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){let{uvs:e,frame:t}=this,{width:n,height:r}=this._source,i=t.x/n,a=t.y/r,o=t.width/n,s=t.height/r,c=this.rotate;if(c){let t=o/2,n=s/2,r=i+t,l=a+n;c=K.add(c,K.NW),e.x0=r+t*K.uX(c),e.y0=l+n*K.uY(c),c=K.add(c,2),e.x1=r+t*K.uX(c),e.y1=l+n*K.uY(c),c=K.add(c,2),e.x2=r+t*K.uX(c),e.y2=l+n*K.uY(c),c=K.add(c,2),e.x3=r+t*K.uX(c),e.y3=l+n*K.uY(c)}else e.x0=i,e.y0=a,e.x1=i+o,e.y1=a,e.x2=i+o,e.y2=a+s,e.x3=i,e.y3=a+s}destroy(e=!1){this._source&&(this._source.off(`resize`,this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit(`destroy`,this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit(`update`,this)}get baseTexture(){return H(V,`Texture.baseTexture is now Texture.source`),this._source}},q.EMPTY=new q({label:`EMPTY`,source:new No({label:`EMPTY`})}),q.EMPTY.destroy=Wo,q.WHITE=new q({source:new Jo({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:`premultiply-alpha-on-upload`,label:`WHITE`}),label:`WHITE`}),q.WHITE.destroy=Wo})),es,ts=s((()=>{es=class{constructor(){this._screenSizes=new Map,this._widths=[],this._heights=[]}get size(){return this._screenSizes.size}set(e,t,n){let r=this._screenSizes.get(e);return r&&r.pixelWidth===t&&r.pixelHeight===n?!1:(this._screenSizes.set(e,{pixelWidth:t,pixelHeight:n}),this._update(),!0)}remove(e){return this._screenSizes.delete(e)?(this._update(),!0):!1}getFittingWidth(e){return this._getFittingAxis(e,this._widths)}getFittingHeight(e){return this._getFittingAxis(e,this._heights)}hasWidth(e){return this._widths.includes(e)}hasHeight(e){return this._heights.includes(e)}_getFittingAxis(e,t){for(let n=0;n<t.length;n++){let r=t[n];if(r>=e)return r}}_update(){this._widths=[...this._screenSizes.values()].map(e=>e.pixelWidth).filter((e,t,n)=>n.indexOf(e)===t).sort((e,t)=>e-t),this._heights=[...this._screenSizes.values()].map(e=>e.pixelHeight).filter((e,t,n)=>n.indexOf(e)===t).sort((e,t)=>e-t)}}}));function ns(e){let t=cs[e];return t===void 0?cs[e]=ls++:t}function rs(e,t,n,r,i,a){return(e<<17)+(t<<2)+(!!r<<1)+ +!!n+ +(a===`nearest`)*os+ns(i)*ss}var is,as,os,ss,cs,ls,us,ds,fs=s((()=>{So(),oa(),W(),ua(),Po(),$o(),ko(),ts(),is=0,as=32767,os=4294967296,ss=8589934592,cs=Object.create(null),ls=0,us=class{constructor(e){this._buckets=new Map,this._poolKey=Object.create(null),this._poolStyle=Object.create(null),this._screens=new es,this._enableFullScreen=!1,this.textureOptions=e||{}}get textureStyle(){return H(ra,`TexturePool.textureStyle is no longer used, pooled textures carry their own style. Pass scaleMode in the request instead.`),this._textureStyle||=new Oo(this.textureOptions),this._textureStyle}set textureStyle(e){H(ra,`TexturePool.textureStyle is no longer used, pooled textures carry their own style. Pass scaleMode in the request instead.`),this._textureStyle=e}get enableFullScreen(){return H(ra,`TexturePool.enableFullScreen is no longer used, the pool sizes textures to the screens registered with setScreenSize.`),this._enableFullScreen}set enableFullScreen(e){H(ra,`TexturePool.enableFullScreen is no longer used, the pool sizes textures to the screens registered with setScreenSize.`),this._enableFullScreen=e}createTexture(...e){let t=e[0];typeof t==`number`&&(H(ra,`TexturePool.createTexture params are now an options object. See params: { width, height, antialias, autoGenerateMipmaps }`),t={width:t,height:e[1],antialias:e[2]??!1,autoGenerateMipmaps:e[3]??!1});let n=t.format??this.textureOptions.format??No.defaultOptions.format,r=t.scaleMode??this.textureOptions.scaleMode??Oo.defaultOptions.scaleMode,i=new No({...this.textureOptions,width:t.width,height:t.height,resolution:1,antialias:t.antialias??!1,autoGarbageCollect:!1,autoGenerateMipmaps:t.autoGenerateMipmaps??!1,format:n,scaleMode:r});return new q({source:i,label:`texturePool_${is++}`})}getOptimalTexture(...e){let t=e[0];typeof t==`number`&&(H(ra,`TexturePool.getOptimalTexture params are now an options object. See params: { width, height, resolution, antialias, autoGenerateMipmaps }`),t={width:t,height:e[1],resolution:e[2]??1,antialias:e[3]??!1,autoGenerateMipmaps:e[4]??!1});let n=t.width,r=t.height,i=t.resolution??1,a=t.antialias??!1,o=t.autoGenerateMipmaps??!1,s=t.format??this.textureOptions.format??No.defaultOptions.format,c=t.scaleMode??this.textureOptions.scaleMode??Oo.defaultOptions.scaleMode,{width:l,height:u}=this.getOptimalSize(n,r,i);(l>as||u>as)&&U(`TexturePool: ${l}x${u} is larger than the ${as}px pool key limit, textures of this size may be pooled together`);let d=rs(l,u,a,o,s,c),f=this._buckets.get(d);f||(f=[],this._buckets.set(d,f));let p=f.pop();return p||(p=this.createTexture({width:l,height:u,antialias:a,autoGenerateMipmaps:o,format:s,scaleMode:c}),this._poolStyle[p.uid]=p.source.style),p.source._resolution=i,p.source.width=l/i,p.source.height=u/i,p.source.pixelWidth=l,p.source.pixelHeight=u,p.frame.x=0,p.frame.y=0,p.frame.width=n,p.frame.height=r,p.updateUvs(),this._poolKey[p.uid]=d,p}getOptimalSize(e,t,n=1){let r=Math.ceil(e*n-1e-6),i=Math.ceil(t*n-1e-6),a=bo(r),o=this._screens.getFittingWidth(r),s=bo(i),c=this._screens.getFittingHeight(i);return{width:o===void 0?a:Math.min(o,a),height:c===void 0?s:Math.min(c,s)}}getSameSizeTexture(e,t=!1){let n=e.source;return this.getOptimalTexture({width:e.width,height:e.height,resolution:n._resolution,antialias:t})}returnTexture(e,t=!1){let n=e.uid,r=this._poolKey[n];if(r===void 0){U(`TexturePool: returnTexture was passed a texture that did not come from this pool, ignoring it`);return}let i=this._poolStyle[n];t&&e.source.style!==i&&(e.source.style=i);let a=this._buckets.get(r);a?a.push(e):(delete this._poolKey[n],delete this._poolStyle[n],e.destroy(!0))}setScreenSize(e,t,n){this._screens.set(e,t,n)&&this._pruneScreenTextures()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenTextures()}_pruneScreenTextures(){for(let[e,t]of this._buckets){let n=e>>>0,r=n>>>17,i=n>>>2&32767;(!xo(r)&&!this._screens.hasWidth(r)||!xo(i)&&!this._screens.hasHeight(i))&&(this._dropTextures(t,!0),this._buckets.delete(e))}}_dropTextures(e,t){for(let n=0;n<e.length;n++){let r=e[n];delete this._poolKey[r.uid],delete this._poolStyle[r.uid],t&&r.destroy(!0)}}clear(e){for(let t of this._buckets.values())this._dropTextures(t,e!==!1);this._buckets.clear()}},ds=new us,la.register(ds)})),ps,ms=s((()=>{B(),yo(),fs(),ps=class{constructor(){this.renderPipeId=`renderGroup`,this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new z,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new vo,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;let t=e.children;for(let e=0;e<t.length;e++){let n=t[e];n._updateFlags=15,this.addChild(n)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&=(ds.returnTexture(this.texture),null)}updateCacheTexture(){this.textureNeedsUpdate=!0;let e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(let e in this.childrenToUpdate){let t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){let t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.relativeRenderGroupDepth=e.parent===this.root?1:e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);let t=e.children;for(let e=0;e<t.length;e++)this.addChild(t[e])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}let t=e.children;for(let e=0;e<t.length;e++)this.removeChild(t[e])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]},t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.indexOf(e)===-1&&this._onRenderContainers.push(e)}removeOnRender(e){let t=this._onRenderContainers.indexOf(e);t!==-1&&this._onRenderContainers.splice(t,1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet?.destroy(),this.instructionSet=null}getChildren(e=[]){let t=this.root.children;for(let n=0;n<t.length;n++)this._getChildren(t[n],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;let n=e.children;for(let e=0;e<n.length;e++)this._getChildren(n[e],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return this._matrixDirty&1?(this._matrixDirty&=-2,this._inverseWorldTransform||=new z,this._inverseWorldTransform.copyFrom(this.worldTransform).invert()):this._inverseWorldTransform}get textureOffsetInverseTransform(){return this._matrixDirty&2?(this._matrixDirty&=-3,this._textureOffsetInverseTransform||=new z,this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y)):this._textureOffsetInverseTransform}get inverseParentTextureTransform(){if(!(this._matrixDirty&4))return this._inverseParentTextureTransform;this._matrixDirty&=-5;let e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||=new z,this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}}));function hs(e,t,n={}){for(let r in t)!n[r]&&t[r]!==void 0&&(e[r]=t[r])}var gs=s((()=>{})),_s,vs,ys,bs,J,xs=s((()=>{ri(),Ri(),Bi(),R(),B(),Wi(),Zi(),ea(),oa(),W(),ha(),_a(),xa(),Ca(),Aa(),Ma(),Ua(),to(),lo(),fo(),ho(),_o(),ms(),gs(),_s=new Xi(null),vs=new Xi(null),ys=new Xi(null,1,1),bs=new Xi(null),J=class e extends ni{constructor(e={}){super(),this.uid=Qi(`renderable`),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new z,this.relativeGroupTransform=new z,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Xi(this,0,0),this._scale=ys,this._pivot=vs,this._origin=bs,this._skew=_s,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode=`inherit`,this.groupBlendMode=`normal`,this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],hs(this,e,{children:!0,parent:!0,effects:!0}),e.children?.forEach(e=>this.addChild(e)),e.parent?.addChild(this)}static mixin(t){H(`8.8.0`,`Container.mixin is deprecated, please use extensions.mixin instead.`),L.mixin(e,t)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||H(V,`addChild: Only Containers will be allowed to add children in v8.0.0`),e.length>1){for(let t=0;t<e.length;t++)this.addChild(e[t]);return e[0]}let t=e[0],n=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),n&&(n.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,n&&n.addChild(t),this.emit(`childAdded`,t,this,this.children.length-1),t.emit(`added`,this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let t=0;t<e.length;t++)this.removeChild(e[t]);return e[0]}let t=e[0],n=this.children.indexOf(t);return n>-1&&(this._didViewChangeTick++,this.children.splice(n,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit(`childRemoved`,t,this,n),t.emit(`removed`,this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;let e=this.parentRenderGroup;e?.removeChild(this),this.renderGroup=ma.get(ps,this),this.groupTransform=z.IDENTITY,e?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;let e=this.parentRenderGroup;e?.removeChild(this),ma.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||=new z,this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*Hi}set angle(e){this.rotation=e*Ui}get pivot(){return this._pivot===vs&&(this._pivot=new Xi(this,0,0)),this._pivot}set pivot(e){this._pivot===vs&&(this._pivot=new Xi(this,0,0),this._origin!==bs&&U(`Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.`)),typeof e==`number`?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===_s&&(this._skew=new Xi(this,0,0)),this._skew}set skew(e){this._skew===_s&&(this._skew=new Xi(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===ys&&(this._scale=new Xi(this,1,1)),this._scale}set scale(e){this._scale===ys&&(this._scale=new Xi(this,0,0)),typeof e==`string`&&(e=parseFloat(e)),typeof e==`number`?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===bs&&(this._origin=new Xi(this,0,0)),this._origin}set origin(e){this._origin===bs&&(this._origin=new Xi(this,0,0),this._pivot!==vs&&U(`Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.`)),typeof e==`number`?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){let t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){let t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||={};let t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){let n=this.getLocalBounds();typeof e==`object`?(t=e.height??e.width,e=e.width):t??=e,e!==void 0&&this._setWidth(e,n.width),t!==void 0&&this._setHeight(t,n.height)}_updateSkew(){let e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x==`number`?e.x:this.position.x,typeof e.y==`number`?e.y:this.position.y),this.scale.set(typeof e.scaleX==`number`?e.scaleX:this.scale.x,typeof e.scaleY==`number`?e.scaleY:this.scale.y),this.rotation=typeof e.rotation==`number`?e.rotation:this.rotation,this.skew.set(typeof e.skewX==`number`?e.skewX:this.skew.x,typeof e.skewY==`number`?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX==`number`?e.pivotX:this.pivot.x,typeof e.pivotY==`number`?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX==`number`?e.originX:this.origin.x,typeof e.originY==`number`?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){let e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;let t=this.localTransform,n=this._scale,r=this._pivot,i=this._origin,a=this._position,o=n._x,s=n._y,c=r._x,l=r._y,u=-i._x,d=-i._y;t.a=this._cx*o,t.b=this._sx*o,t.c=this._cy*s,t.d=this._sy*s,t.tx=a._x-(c*t.a+l*t.c)+(u*t.a+d*t.c)-u,t.ty=a._y-(c*t.b+l*t.d)+(u*t.b+d*t.d)-d}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=1,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){let t=Li.shared.setValue(e??16777215).toBgrNumber();t!==this.localColor&&(this.localColor=t,this._updateFlags|=1,this._onUpdate())}get tint(){return $a(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=2,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){let t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=4,this.localDisplayStatus^=2,this._onUpdate(),this.emit(`visibleChanged`,e))}get culled(){return!(this.localDisplayStatus&4)}set culled(e){let t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=4,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){let t=+!!e;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=4,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit(`destroyed`,this),this.removeAllListeners(),(typeof e==`boolean`?e:e?.children)&&t)for(let n=0;n<t.length;++n)t[n].destroy(e);this.renderGroup?.destroy(),this.renderGroup=null}},L.mixin(J,ba,Ha,go,uo,co,ka,ja,mo,zi,ga,eo,Sa)})),Ss,Cs=s((()=>{Ss=(e=>(e[e.INTERACTION=50]=`INTERACTION`,e[e.HIGH=25]=`HIGH`,e[e.NORMAL=0]=`NORMAL`,e[e.LOW=-25]=`LOW`,e[e.UTILITY=-50]=`UTILITY`,e))(Ss||{})})),ws,Ts=s((()=>{ws=class{constructor(e,t=null,n=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=n,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));let t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);let t=this.next;return this.next=e?null:t,this.previous=null,t}}})),Es,Ds,Os=s((()=>{Cs(),Ts(),Es=class e{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new ws(null,null,1/0),this.deltaMS=1/e.targetFPMS,this.elapsedMS=1/e.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,n=Ss.NORMAL){return this._addListener(new ws(e,t,n))}addOnce(e,t,n=Ss.NORMAL){return this._addListener(new ws(e,t,n,!0))}_addListener(e){let t=this._head.next,n=this._head;if(!t)e.connect(n);else{for(;t;){if(e.priority>t.priority){e.connect(n);break}n=t,t=t.next}e.previous||e.connect(n)}return this._startIfPossible(),this}remove(e,t){let n=this._head.next;for(;n;)n=n.match(e,t)?n.destroy():n.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(t=performance.now()){let n;if(t>this.lastTime){if(n=this.elapsedMS=t-this.lastTime,n>this._maxElapsedMS&&(n=this._maxElapsedMS),n*=this.speed,this._minElapsedMS){let e=t-this._lastFrame|0;if(e<this._minElapsedMS)return;this._lastFrame=t-e%this._minElapsedMS}this.deltaMS=n,this.deltaTime=this.deltaMS*e.targetFPMS;let r=this._head,i=r.next;for(;i;)i=i.emit(this);r.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=t}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(t){let n=Math.min(Math.max(0,t)/1e3,e.targetFPMS);this._maxElapsedMS=1/n,this._minElapsedMS&&t>this.maxFPS&&(this.maxFPS=t)}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){e===0?this._minElapsedMS=0:(e<this.minFPS&&(this.minFPS=e),this._minElapsedMS=1/(e/1e3))}static get shared(){if(!e._shared){let t=e._shared=new e;t.autoStart=!0,t._protected=!0}return e._shared}static get system(){if(!e._system){let t=e._system=new e;t.autoStart=!0,t._protected=!0}return e._system}},Es.targetFPMS=.06,Ds=Es})),ks,As=s((()=>{Cs(),Os(),ks=class{constructor(e){this._lastTransform=``,this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;let e=this._canvas.getBoundingClientRect(),t=this._canvas.width,n=this._canvas.height,r=e.width/t*this._renderer.resolution,i=e.height/n*this._renderer.resolution,a=`translate(${e.left}px, ${e.top}px) scale(${r}, ${i})`;a!==this._lastTransform&&(this._domElement.style.transform=a,this._lastTransform=a)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){`ResizeObserver`in globalThis?(this._observer&&=(this._observer.disconnect(),null),this._observer=new ResizeObserver(e=>{for(let t of e){if(t.target!==this._canvas)continue;let e=this.canvas.width,n=this.canvas.height,r=t.contentRect.width/e*this._renderer.resolution,i=t.contentRect.height/n*this._renderer.resolution;(this._lastScaleX!==r||this._lastScaleY!==i)&&(this.updateTranslation(),this._lastScaleX=r,this._lastScaleY=i)}}),this._observer.observe(this._canvas)):this._tickerAttached||Ds.shared.add(this.updateTranslation,this,Ss.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&Ds.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform=``,this._lastScaleX=null,this._lastScaleY=null}}})),js,Ms=s((()=>{qi(),js=class e{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=e.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new Gi,this.page=new Gi,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,n){throw Error(`initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.`)}initUIEvent(e,t,n,r,i){throw Error(`initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.`)}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}}));function Ns(e){return function(t){return t.test(e)}}function Ps(e){var t={userAgent:``,platform:``,maxTouchPoints:0};!e&&typeof navigator<`u`?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof e==`string`?t.userAgent=e:e&&e.userAgent&&(t={userAgent:e.userAgent,platform:e.platform,maxTouchPoints:e.maxTouchPoints||0});var n=t.userAgent,r=n.split(`[FBAN`);r[1]!==void 0&&(n=r[0]),r=n.split(`Twitter`),r[1]!==void 0&&(n=r[0]);var i=Ns(n),a={apple:{phone:i(Fs)&&!i(Us),ipod:i(Is),tablet:!i(Fs)&&(i(Ls)||Xs(t))&&!i(Us),universal:i(Rs),device:(i(Fs)||i(Is)||i(Ls)||i(Rs)||Xs(t))&&!i(Us)},amazon:{phone:i(Vs),tablet:!i(Vs)&&i(Hs),device:i(Vs)||i(Hs)},android:{phone:!i(Us)&&i(Vs)||!i(Us)&&i(zs),tablet:!i(Us)&&!i(Vs)&&!i(zs)&&(i(Hs)||i(Bs)),device:!i(Us)&&(i(Vs)||i(Hs)||i(zs)||i(Bs))||i(/\bokhttp\b/i)},windows:{phone:i(Us),tablet:i(Ws),device:i(Us)||i(Ws)},other:{blackberry:i(Gs),blackberry10:i(Ks),opera:i(qs),firefox:i(Ys),chrome:i(Js),device:i(Gs)||i(Ks)||i(qs)||i(Ys)||i(Js)},any:!1,phone:!1,tablet:!1};return a.any=a.apple.device||a.android.device||a.windows.device||a.other.device,a.phone=a.apple.phone||a.android.phone||a.windows.phone,a.tablet=a.apple.tablet||a.android.tablet||a.windows.tablet,a}var Fs,Is,Ls,Rs,zs,Bs,Vs,Hs,Us,Ws,Gs,Ks,qs,Js,Ys,Xs,Zs=s((()=>{Fs=/iPhone/i,Is=/iPod/i,Ls=/iPad/i,Rs=/\biOS-universal(?:.+)Mac\b/i,zs=/\bAndroid(?:.+)Mobile\b/i,Bs=/Android/i,Vs=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Hs=/Silk/i,Us=/Windows Phone/i,Ws=/\bWindows(?:.+)ARM\b/i,Gs=/BlackBerry/i,Ks=/BB10/i,qs=/Opera Mini/i,Js=/\b(CriOS|Chrome)(?:.+)Mobile/i,Ys=/Mobile(?:.+)Firefox\b/i,Xs=function(e){return e!==void 0&&e.platform===`MacIntel`&&typeof e.maxTouchPoints==`number`&&e.maxTouchPoints>1&&typeof MSStream>`u`}})),Qs=s((()=>{Zs(),Zs()})),$s,ec=s((()=>{Qs(),$s=(Ps.default??Ps)(globalThis.navigator)})),tc,nc,rc,ic,ac,oc,sc,cc,lc,uc,dc,fc=s((()=>{As(),Ms(),R(),ec(),ya(),tc=9,nc=100,rc=0,ic=0,ac=2,oc=1,sc=-1e3,cc=-1e3,lc=2,uc=class e{constructor(e,t=$s){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){let e=document.createElement(`button`);e.style.width=`${oc}px`,e.style.height=`${oc}px`,e.style.position=`absolute`,e.style.top=`${sc}px`,e.style.left=`${cc}px`,e.style.zIndex=lc.toString(),e.style.backgroundColor=`#FF0000`,e.title=`select to enable accessibility for this content`,e.addEventListener(`focus`,()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&=(document.body.removeChild(this._hookDiv),null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement(`div`),this._div.style.position=`absolute`,this._div.style.top=`${rc}px`,this._div.style.left=`${ic}px`,this._div.style.pointerEvents=`none`,this._div.style.zIndex=ac.toString(),this._canvasObserver=new ks({domElement:this._div,renderer:this._renderer})),this._deactivateOnMouseMove&&globalThis.document.addEventListener(`mousemove`,this._boundOnMouseMove,!0);let e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{let t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){if(this._isActive&&!this._isMobileAccessibility){this._isActive=!1,globalThis.document.removeEventListener(`mousemove`,this._boundOnMouseMove,!0),this._renderer.runners.postrender.remove(this);for(let e of this._children)e._accessibleDiv?.parentNode&&(e._accessibleDiv.parentNode.removeChild(e._accessibleDiv),e._accessibleDiv=null),e._accessibleActive=!1;for(let e in this._pools)this._pools[e].forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),delete this._pools[e];this._div?.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);let t=e.children;if(t)for(let e=0;e<t.length;e++)this._updateAccessibleObjects(t[e])}init(t){let n={accessibilityOptions:{...e.defaultOptions,...t?.accessibilityOptions||{}}};this.debug=n.accessibilityOptions.debug,this._activateOnTab=n.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=n.accessibilityOptions.deactivateOnMouseMove,this._activateOnTab&&globalThis.addEventListener(`keydown`,this._boundOnKeyDown,!1),n.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){let e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;let t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(let e of this._children)e._renderId===this._renderId&&t.add(this._children.indexOf(e))}for(let e=this._children.length-1;e>=0;e--){let n=this._children[e];t.has(e)||(n._accessibleDiv&&n._accessibleDiv.parentNode&&(n._accessibleDiv.parentNode.removeChild(n._accessibleDiv),this._getPool(n.accessibleType).push(n._accessibleDiv),n._accessibleDiv=null),n._accessibleActive=!1,va(this._children,e,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let e=0;e<this._children.length;e++){let t=this._children[e];if(!t._accessibleActive||!t._accessibleDiv)continue;let n=t._accessibleDiv,r=t.hitArea||t.getBounds().rectangle;if(t.hitArea){let e=t.worldTransform;n.style.left=`${e.tx+r.x*e.a}px`,n.style.top=`${e.ty+r.y*e.d}px`,n.style.width=`${r.width*e.a}px`,n.style.height=`${r.height*e.d}px`}else this._capHitArea(r),n.style.left=`${r.x}px`,n.style.top=`${r.y}px`,n.style.width=`${r.width}px`,n.style.height=`${r.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);let{width:t,height:n}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>n&&(e.height=n-e.y)}_addChild(e){let t=this._getPool(e.accessibleType).pop();t?(t.innerHTML=``,t.removeAttribute(`title`),t.removeAttribute(`aria-label`),t.tabIndex=0):(e.accessibleType===`button`?(t=document.createElement(`button`),this.debug||(t.style.color=`transparent`)):(t=document.createElement(e.accessibleType),t.style.cssText=`
|
|
10
|
-
color: transparent;
|
|
11
|
-
pointer-events: none;
|
|
12
|
-
padding: 0;
|
|
13
|
-
margin: 0;
|
|
14
|
-
border: 0;
|
|
15
|
-
outline: 0;
|
|
16
|
-
background: transparent;
|
|
17
|
-
box-sizing: border-box;
|
|
18
|
-
user-select: none;
|
|
19
|
-
-webkit-user-select: none;
|
|
20
|
-
-moz-user-select: none;
|
|
21
|
-
-ms-user-select: none;
|
|
22
|
-
`),t.style.width=`${nc}px`,t.style.height=`${nc}px`,t.style.backgroundColor=this.debug?`rgba(255,255,255,0.5)`:`transparent`,t.style.position=`absolute`,t.style.zIndex=ac.toString(),t.style.borderStyle=`none`,navigator.userAgent.toLowerCase().includes(`chrome`)?t.setAttribute(`aria-live`,`off`):t.setAttribute(`aria-live`,`polite`),navigator.userAgent.match(/rv:.*Gecko\//)?t.setAttribute(`aria-relevant`,`additions`):t.setAttribute(`aria-relevant`,`text`),t.addEventListener(`click`,this._onClick.bind(this)),t.addEventListener(`focus`,this._onFocus.bind(this)),t.addEventListener(`focusout`,this._onFocusOut.bind(this))),t.style.pointerEvents=e.accessiblePointerEvents,t.type=e.accessibleType,e.accessibleText&&(t.innerText=e.accessibleText),e.accessibleTitle&&e.accessibleTitle!==null?t.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(t.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&t.setAttribute(`aria-label`,e.accessibleHint),e.interactive?t.tabIndex=e.tabIndex:t.tabIndex=0,this.debug&&this._updateDebugHTML(t),e._accessibleActive=!0,e._accessibleDiv=t,t.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){let{container:n}=e.target,r=this._renderer.events.rootBoundary,i=Object.assign(new js(r),{target:n});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(e=>r.dispatchEvent(i,e))}_onClick(e){this._dispatchEvent(e,[`click`,`pointertap`,`tap`])}_onFocus(e){e.target.getAttribute(`aria-live`)||e.target.setAttribute(`aria-live`,`assertive`),this._dispatchEvent(e,[`mouseover`])}_onFocusOut(e){e.target.getAttribute(`aria-live`)||e.target.setAttribute(`aria-live`,`polite`),this._dispatchEvent(e,[`mouseout`])}_onKeyDown(e){e.keyCode===tc&&this._activateOnTab&&this._activate()}_onMouseMove(e){(e.movementX!==0||e.movementY!==0)&&this._deactivate()}destroy(){this._deactivate(),this._destroyTouchHook(),this._canvasObserver?.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener(`keydown`,this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener(`mousemove`,this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(e){e?this._activate():this._deactivate()}_getPool(e){return this._pools[e]||(this._pools[e]=[]),this._pools[e]}},uc.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:`accessibility`},uc.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0},dc=uc})),pc,mc=s((()=>{pc={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:`button`,accessibleText:null,accessiblePointerEvents:`auto`,accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1}})),hc=s((()=>{R(),xs(),fc(),mc(),L.add(dc),L.mixin(J,pc)})),gc,_c=s((()=>{R(),As(),gc=class{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement(`div`),this._domElement.style.position=`absolute`,this._domElement.style.top=`0`,this._domElement.style.left=`0`,this._domElement.style.pointerEvents=`none`,this._domElement.style.zIndex=`1000`}init(){this._canvasObserver=new ks({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){let e=this._attachedDomElements;if(e.length===0)this._domElement.remove();else{this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){let n=e[t],r=n.element;if(!n.parent||n.globalDisplayStatus<7)r?.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position=`absolute`,r.style.pointerEvents=`auto`,this._domElement.appendChild(r));let e=n.worldTransform,t=n._anchor,i=n.width*t.x,a=n.height*t.y;r.style.transformOrigin=`${i}px ${a}px`,r.style.transform=`matrix(${e.a}, ${e.b}, ${e.c}, ${e.d}, ${e.tx-i}, ${e.ty-a})`,r.style.opacity=n.groupAlpha.toString()}}}}destroy(){this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)this._attachedDomElements[e].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}},gc.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`dom`}})),vc,yc=s((()=>{La(),xs(),vc=class extends J{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Ia(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty&&=(this.updateBounds(),!1),this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=+!!e}containsPoint(e){let t=this.bounds,{x:n,y:r}=e;return n>=t.minX&&n<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;let e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,n){let{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e);let i=r[this.renderPipeId];i?.addRenderable&&i.addRenderable(this,e),this.didViewUpdate=!1;let a=this.children,o=a.length;for(let r=0;r<o;r++)a[r].collectRenderables(e,t,n);r.blendMode.popBlendMode(e)}}})),bc=s((()=>{R(),_c(),As(),qi(),yc(),L.add(gc)})),xc,Sc,Cc=s((()=>{Cs(),Os(),xc=class{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){!this._tickerAdded&&this.domElement&&(Ds.system.add(this._tickerUpdate,this,Ss.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&=(Ds.system.remove(this._tickerUpdate,this),!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}let e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType===`touch`||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent(`pointermove`,{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent(`mousemove`,{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}},Sc=new xc})),wc,Tc=s((()=>{qi(),Ms(),wc=class extends js{constructor(){super(...arguments),this.client=new Gi,this.movement=new Gi,this.offset=new Gi,this.global=new Gi,this.screen=new Gi}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,n){return e.worldTransform.applyInverse(n||this.global,t)}getModifierState(e){return`getModifierState`in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m){throw Error(`Method not implemented.`)}}})),Ec,Dc=s((()=>{Tc(),Ec=class extends wc{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1,this.persistentDeviceId=0}getCoalescedEvents(){return this.type===`pointermove`||this.type===`mousemove`||this.type===`touchmove`?[this]:[]}getPredictedEvents(){throw Error(`getPredictedEvents is not supported!`)}}})),Oc,kc=s((()=>{Tc(),Oc=class extends wc{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}},Oc.DOM_DELTA_PIXEL=0,Oc.DOM_DELTA_LINE=1,Oc.DOM_DELTA_PAGE=2})),Ac,jc,Mc,Nc,Pc=s((()=>{ri(),qi(),W(),Cc(),Tc(),Dc(),kc(),Ac=2048,jc=new Gi,Mc=new Gi,Nc=class{constructor(e){this.dispatch=new ni,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mapContextMenu=this.mapContextMenu.bind(this),this.mappingTable={},this.addEventMapping(`pointerdown`,this.mapPointerDown),this.addEventMapping(`pointermove`,this.mapPointerMove),this.addEventMapping(`pointerout`,this.mapPointerOut),this.addEventMapping(`pointerleave`,this.mapPointerOut),this.addEventMapping(`pointerover`,this.mapPointerOver),this.addEventMapping(`pointerup`,this.mapPointerUp),this.addEventMapping(`pointerupoutside`,this.mapPointerUpOutside),this.addEventMapping(`wheel`,this.mapWheel),this.addEventMapping(`contextmenu`,this.mapContextMenu)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((e,t)=>e.priority-t.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;let t=this.mappingTable[e.type];if(t)for(let n=0,r=t.length;n<r;n++)t[n].fn(e);else U(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){Sc.pauseUpdate=!0;let n=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?`hitTestMoveRecursive`:`hitTestRecursive`,r=this[n](this.rootTarget,this.rootTarget.eventMode,jc.set(e,t),this.hitTestFn,this.hitPruneFn);return r&&r[0]}propagate(e,t){if(!e.target)return;let n=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,i=n.length-1;r<i;r++)if(e.currentTarget=n[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=n.length-2;r>=0;r--)if(e.currentTarget=n[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,n=this._allInteractiveElements){if(n.length===0)return;e.eventPhase=e.BUBBLING_PHASE;let r=Array.isArray(t)?t:[t];for(let t=n.length-1;t>=0;t--)r.forEach(r=>{e.currentTarget=n[t],this.notifyTarget(e,r)})}propagationPath(e){let t=[e];for(let n=0;n<Ac&&e!==this.rootTarget&&e.parent;n++){if(!e.parent)throw Error(`Cannot find propagation path to disconnected target`);t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,n,r,i,a=!1){let o=!1;if(this._interactivePrune(e))return null;if((e.eventMode===`dynamic`||t===`dynamic`)&&(Sc.pauseUpdate=!1),e.interactiveChildren&&e.children){let s=e.children;for(let c=s.length-1;c>=0;c--){let l=s[c],u=this.hitTestMoveRecursive(l,this._isInteractive(t)?t:l.eventMode,n,r,i,a||i(e,n));if(u){if(u.length>0&&!u[u.length-1].parent)continue;let t=e.isInteractive();(u.length>0||t)&&(t&&this._allInteractiveElements.push(e),u.push(e)),this._hitElements.length===0&&(this._hitElements=u),o=!0}}}let s=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),a||this._hitElements.length>0?null:o?this._hitElements:s&&!i(e,n)&&r(e,n)?c?[e]:[]:null}hitTestRecursive(e,t,n,r,i){if(this._interactivePrune(e)||i(e,n))return null;if((e.eventMode===`dynamic`||t===`dynamic`)&&(Sc.pauseUpdate=!1),e.interactiveChildren&&e.children){let a=e.children,o=n;for(let n=a.length-1;n>=0;n--){let s=a[n],c=this.hitTestRecursive(s,this._isInteractive(t)?t:s.eventMode,o,r,i);if(c){if(c.length>0&&!c[c.length-1].parent)continue;let t=e.isInteractive();return(c.length>0||t)&&c.push(e),c}}}let a=this._isInteractive(t),o=e.isInteractive();return a&&r(e,n)?o?[e]:[]:null}_isInteractive(e){return e===`static`||e===`dynamic`}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode===`none`||e.eventMode===`passive`&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,Mc),!e.hitArea.contains(Mc.x,Mc.y)))return!0;if(e.effects&&e.effects.length)for(let n=0;n<e.effects.length;n++){let r=e.effects[n];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e?.containsPoint?(e.worldTransform.applyInverse(t,Mc),e.containsPoint(Mc)):!1}notifyTarget(e,t){if(!e.currentTarget.isInteractive())return;t??=e.type;let n=`on${t}`;e.currentTarget[n]?.(e);let r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}let t=this.createPointerEvent(e);if(this.dispatchEvent(t,`pointerdown`),t.pointerType===`touch`)this.dispatchEvent(t,`touchstart`);else if(t.pointerType===`mouse`||t.pointerType===`pen`){let e=t.button===2;this.dispatchEvent(t,e?`rightdown`:`mousedown`)}let n=this.trackingData(e.pointerId);n.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;let t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;let n=t.pointerType===`mouse`||t.pointerType===`pen`,r=this.trackingData(e.pointerId),i=this.findMountedTarget(r.overTargets);if(r.overTargets?.length>0&&i!==t.target){let r=e.type===`mousemove`?`mouseout`:`pointerout`,a=this.createPointerEvent(e,r,i);if(this.dispatchEvent(a,`pointerout`),n&&this.dispatchEvent(a,`mouseout`),!t.composedPath().includes(i)){let r=this.createPointerEvent(e,`pointerleave`,i);for(r.eventPhase=r.AT_TARGET;r.target&&!t.composedPath().includes(r.target);)r.currentTarget=r.target,this.notifyTarget(r),n&&this.notifyTarget(r,`mouseleave`),r.target=r.target.parent;this.freeEvent(r)}this.freeEvent(a)}if(i!==t.target){let r=e.type===`mousemove`?`mouseover`:`pointerover`,a=this.clonePointerEvent(t,r);this.dispatchEvent(a,`pointerover`),n&&this.dispatchEvent(a,`mouseover`);let o=i?.parent;for(;o&&o!==this.rootTarget.parent&&o!==t.target;)o=o.parent;if(!o||o===this.rootTarget.parent){let e=this.clonePointerEvent(t,`pointerenter`);for(e.eventPhase=e.AT_TARGET;e.target&&e.target!==i&&e.target!==this.rootTarget.parent;)e.currentTarget=e.target,this.notifyTarget(e),n&&this.notifyTarget(e,`mouseenter`),e.target=e.target.parent;this.freeEvent(e)}this.freeEvent(a)}let a=[],o=this.enableGlobalMoveEvents??!0;this.moveOnAll?a.push(`pointermove`):this.dispatchEvent(t,`pointermove`),o&&a.push(`globalpointermove`),t.pointerType===`touch`&&(this.moveOnAll?a.splice(1,0,`touchmove`):this.dispatchEvent(t,`touchmove`),o&&a.push(`globaltouchmove`)),n&&(this.moveOnAll?a.splice(1,0,`mousemove`):this.dispatchEvent(t,`mousemove`),o&&a.push(`globalmousemove`),this.cursor=t.target?.cursor),a.length>0&&this.all(t,a),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}let t=this.trackingData(e.pointerId),n=this.createPointerEvent(e),r=n.pointerType===`mouse`||n.pointerType===`pen`;this.dispatchEvent(n,`pointerover`),r&&this.dispatchEvent(n,`mouseover`),n.pointerType===`mouse`&&(this.cursor=n.target?.cursor);let i=this.clonePointerEvent(n,`pointerenter`);for(i.eventPhase=i.AT_TARGET;i.target&&i.target!==this.rootTarget.parent;)i.currentTarget=i.target,this.notifyTarget(i),r&&this.notifyTarget(i,`mouseenter`),i.target=i.target.parent;t.overTargets=n.composedPath(),this.freeEvent(n),this.freeEvent(i)}mapPointerOut(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}let t=this.trackingData(e.pointerId);if(t.overTargets){let n=e.pointerType===`mouse`||e.pointerType===`pen`,r=this.findMountedTarget(t.overTargets),i=this.createPointerEvent(e,`pointerout`,r);this.dispatchEvent(i),n&&this.dispatchEvent(i,`mouseout`);let a=this.createPointerEvent(e,`pointerleave`,r);for(a.eventPhase=a.AT_TARGET;a.target&&a.target!==this.rootTarget.parent;)a.currentTarget=a.target,this.notifyTarget(a),n&&this.notifyTarget(a,`mouseleave`),a.target=a.target.parent;t.overTargets=null,this.freeEvent(i),this.freeEvent(a)}this.cursor=null}mapPointerUp(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}let t=performance.now(),n=this.createPointerEvent(e);if(this.dispatchEvent(n,`pointerup`),n.pointerType===`touch`)this.dispatchEvent(n,`touchend`);else if(n.pointerType===`mouse`||n.pointerType===`pen`){let e=n.button===2;this.dispatchEvent(n,e?`rightup`:`mouseup`)}let r=this.trackingData(e.pointerId),i=this.findMountedTarget(r.pressTargetsByButton[e.button]),a=i;if(i&&!n.composedPath().includes(i)){let t=i;for(;t&&!n.composedPath().includes(t);){if(n.currentTarget=t,this.notifyTarget(n,`pointerupoutside`),n.pointerType===`touch`)this.notifyTarget(n,`touchendoutside`);else if(n.pointerType===`mouse`||n.pointerType===`pen`){let e=n.button===2;this.notifyTarget(n,e?`rightupoutside`:`mouseupoutside`)}t=t.parent}delete r.pressTargetsByButton[e.button],a=t}if(a){let i=this.clonePointerEvent(n,`click`);i.target=a,i.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:i.target,timeStamp:t});let o=r.clicksByButton[e.button];if(o.target===i.target&&t-o.timeStamp<200?++o.clickCount:o.clickCount=1,o.target=i.target,o.timeStamp=t,i.detail=o.clickCount,i.pointerType===`mouse`){let e=i.button===2;this.dispatchEvent(i,e?`rightclick`:`click`)}else i.pointerType===`touch`&&this.dispatchEvent(i,`tap`);this.dispatchEvent(i,`pointertap`),this.freeEvent(i)}this.freeEvent(n)}mapPointerUpOutside(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}let t=this.trackingData(e.pointerId),n=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(n){let i=n;for(;i;)r.currentTarget=i,this.notifyTarget(r,`pointerupoutside`),r.pointerType===`touch`?this.notifyTarget(r,`touchendoutside`):(r.pointerType===`mouse`||r.pointerType===`pen`)&&this.notifyTarget(r,r.button===2?`rightupoutside`:`mouseupoutside`),i=i.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof Oc)){U(`EventBoundary cannot map a non-wheel event as a wheel event`);return}let t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}mapContextMenu(e){if(!(e instanceof Ec)){U(`EventBoundary cannot map a non-pointer event as a pointer event`);return}let t=this.createPointerEvent(e);this.dispatchEvent(t,`contextmenu`),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let n=1;n<e.length&&e[n].parent===t;n++)t=e[n];return t}createPointerEvent(e,t,n){let r=this.allocateEvent(Ec);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=n??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t==`string`&&(r.type=t),r}createWheelEvent(e){let t=this.allocateEvent(Oc);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){let n=this.allocateEvent(Ec);return n.nativeEvent=e.nativeEvent,n.originalEvent=e.originalEvent,this.copyPointerData(e,n),this.copyMouseData(e,n),this.copyData(e,n),n.target=e.target,n.path=e.composedPath().slice(),n.type=t??n.type,n}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof Ec&&t instanceof Ec&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,t.persistentDeviceId=e.persistentDeviceId)}copyMouseData(e,t){e instanceof wc&&t instanceof wc&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);let t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw Error(`It is illegal to free an event not managed by this EventBoundary!`);let t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){let n=e.currentTarget._events[t];if(n){if(`fn`in n)n.once&&e.currentTarget.removeListener(t,n.fn,void 0,!0),n.fn.call(n.context,e);else for(let r=0,i=n.length;r<i&&!e.propagationImmediatelyStopped;r++)n[r].once&&e.currentTarget.removeListener(t,n[r].fn,void 0,!0),n[r].fn.call(n[r].context,e)}}}})),Fc,Ic,Lc,Rc,zc=s((()=>{R(),Pc(),Cc(),Dc(),kc(),Fc=1,Ic={touchstart:`pointerdown`,touchend:`pointerup`,touchendoutside:`pointerupoutside`,touchmove:`pointermove`,touchcancel:`pointercancel`},Lc=class e{constructor(t){this.supportsTouchEvents=`ontouchstart`in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=t,this.rootBoundary=new Nc(null),Sc.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new Ec(null),this._rootWheelEvent=new Oc(null),this._rootContextMenuEvent=new Ec(null),this.cursorStyles={default:`inherit`,pointer:`pointer`},this.features=new Proxy({...e.defaultEventFeatures},{set:(e,t,n)=>(t===`globalMove`&&(this.rootBoundary.enableGlobalMoveEvents=n),e[t]=n,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(t){let{canvas:n,resolution:r}=this.renderer;this.setTargetElement(n),this.resolution=r,e._defaultEventMode=t.eventMode??`passive`,Object.assign(this.features,t.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){Sc.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||=`default`;let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;let n=this.cursorStyles[e];if(n)switch(typeof n){case`string`:t&&(this.domElement.style.cursor=n);break;case`function`:n(e);break;case`object`:t&&Object.assign(this.domElement.style,n)}else t&&typeof e==`string`&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!(`cancelable`in e))&&e.preventDefault();for(let e=0,n=t.length;e<n;e++){let n=t[e],r=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(r)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Sc.pointerMoved();let t=this._normalizeToPointerData(e);for(let e=0,n=t.length;e<n;e++){let n=this._bootstrapEvent(this._rootPointerEvent,t[e]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);let n=t===this.domElement?``:`outside`,r=this._normalizeToPointerData(e);for(let e=0,t=r.length;e<t;e++){let t=this._bootstrapEvent(this._rootPointerEvent,r[e]);t.type+=n,this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=this._normalizeToPointerData(e);for(let e=0,n=t.length;e<n;e++){let n=this._bootstrapEvent(this._rootPointerEvent,t[e]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onContextMenu(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=this._normalizeToPointerData(e);for(let e=0,n=t.length;e<n;e++){let n=this._bootstrapEvent(this._rootContextMenuEvent,t[e]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;let t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,Sc.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;Sc.addTickerListener();let e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming=`none`,e.msTouchAction=`none`):this.supportsPointerEvents&&(e.touchAction=`none`)),this.supportsPointerEvents?(globalThis.document.addEventListener(`pointermove`,this._onPointerMove,!0),this.domElement.addEventListener(`pointerdown`,this._onPointerDown,!0),this.domElement.addEventListener(`pointerleave`,this._onPointerOverOut,!0),this.domElement.addEventListener(`pointerover`,this._onPointerOverOut,!0),globalThis.addEventListener(`pointerup`,this._onPointerUp,!0)):(globalThis.document.addEventListener(`mousemove`,this._onPointerMove,!0),this.domElement.addEventListener(`mousedown`,this._onPointerDown,!0),this.domElement.addEventListener(`mouseout`,this._onPointerOverOut,!0),this.domElement.addEventListener(`mouseover`,this._onPointerOverOut,!0),globalThis.addEventListener(`mouseup`,this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener(`touchstart`,this._onPointerDown,!0),this.domElement.addEventListener(`touchend`,this._onPointerUp,!0),this.domElement.addEventListener(`touchmove`,this._onPointerMove,!0))),this.domElement.addEventListener(`wheel`,this.onWheel,{passive:!0,capture:!0}),this.domElement.addEventListener(`contextmenu`,this._onContextMenu,!0),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;Sc.removeTickerListener();let e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming=``,e.msTouchAction=``):this.supportsPointerEvents&&(e.touchAction=``)),this.supportsPointerEvents?(globalThis.document.removeEventListener(`pointermove`,this._onPointerMove,!0),this.domElement.removeEventListener(`pointerdown`,this._onPointerDown,!0),this.domElement.removeEventListener(`pointerleave`,this._onPointerOverOut,!0),this.domElement.removeEventListener(`pointerover`,this._onPointerOverOut,!0),globalThis.removeEventListener(`pointerup`,this._onPointerUp,!0)):(globalThis.document.removeEventListener(`mousemove`,this._onPointerMove,!0),this.domElement.removeEventListener(`mousedown`,this._onPointerDown,!0),this.domElement.removeEventListener(`mouseout`,this._onPointerOverOut,!0),this.domElement.removeEventListener(`mouseover`,this._onPointerOverOut,!0),globalThis.removeEventListener(`mouseup`,this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener(`touchstart`,this._onPointerDown,!0),this.domElement.removeEventListener(`touchend`,this._onPointerUp,!0),this.domElement.removeEventListener(`touchmove`,this._onPointerMove,!0))),this.domElement.removeEventListener(`wheel`,this.onWheel,!0),this.domElement.removeEventListener(`contextmenu`,this._onContextMenu,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,n){let r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{x:0,y:0,width:this.domElement.width,height:this.domElement.height,left:0,top:0},i=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*i,e.y=(n-r.top)*(this.domElement.height/r.height)*i}_normalizeToPointerData(e){let t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches[n];r.button===void 0&&(r.button=0),r.buttons===void 0&&(r.buttons=1),r.isPrimary===void 0&&(r.isPrimary=e.touches.length===1&&e.type===`touchstart`),r.width===void 0&&(r.width=r.radiusX||1),r.height===void 0&&(r.height=r.radiusY||1),r.tiltX===void 0&&(r.tiltX=0),r.tiltY===void 0&&(r.tiltY=0),r.pointerType===void 0&&(r.pointerType=`touch`),r.pointerId===void 0&&(r.pointerId=r.identifier||0),r.pressure===void 0&&(r.pressure=r.force||.5),r.twist===void 0&&(r.twist=0),r.tangentialPressure===void 0&&(r.tangentialPressure=0),r.layerX===void 0&&(r.layerX=r.offsetX=r.clientX),r.layerY===void 0&&(r.layerY=r.offsetY=r.clientY),r.isNormalized=!0,r.type=e.type,r.altKey??=e.altKey,r.ctrlKey??=e.ctrlKey,r.metaKey??=e.metaKey,r.shiftKey??=e.shiftKey,t.push(r)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){let n=e;n.isPrimary===void 0&&(n.isPrimary=!0),n.width===void 0&&(n.width=1),n.height===void 0&&(n.height=1),n.tiltX===void 0&&(n.tiltX=0),n.tiltY===void 0&&(n.tiltY=0),n.pointerType===void 0&&(n.pointerType=`mouse`),n.pointerId===void 0&&(n.pointerId=Fc),n.pressure===void 0&&(n.pressure=.5),n.twist===void 0&&(n.twist=0),n.tangentialPressure===void 0&&(n.tangentialPressure=0),n.isNormalized=!0,t.push(n)}else t.push(e);return t}normalizeWheelEvent(e){let t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type===`pointerleave`&&(e.type=`pointerout`),e.type.startsWith(`mouse`)&&(e.type=e.type.replace(`mouse`,`pointer`)),e.type.startsWith(`touch`)&&(e.type=Ic[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}},Lc.extension={name:`events`,type:[I.WebGLSystem,I.CanvasSystem,I.WebGPUSystem],priority:-1},Lc.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0},Rc=Lc})),Bc,Vc=s((()=>{zc(),Ms(),Bc={onclick:null,oncontextmenu:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode===`dynamic`||this.eventMode===`static`},set interactive(e){this.eventMode=e?`static`:`passive`},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Rc.defaultEventMode},set eventMode(e){this._internalEventMode=e},isInteractive(){return this.eventMode===`static`||this.eventMode===`dynamic`},interactiveChildren:!0,hitArea:null,addEventListener(e,t,n){let r=typeof n==`boolean`&&n||typeof n==`object`&&n.capture,i=typeof n==`object`?n.signal:void 0,a=typeof n==`object`&&n.once===!0,o=typeof t==`function`?void 0:t;e=r?`${e}capture`:e;let s=typeof t==`function`?t:t.handleEvent,c=this;i&&i.addEventListener(`abort`,()=>{c.off(e,s,o)}),a?c.once(e,s,o):c.on(e,s,o)},removeEventListener(e,t,n){let r=typeof n==`boolean`&&n||typeof n==`object`&&n.capture,i=typeof t==`function`?void 0:t;e=r?`${e}capture`:e,t=typeof t==`function`?t:t.handleEvent,this.off(e,t,i)},dispatchEvent(e){if(!(e instanceof js))throw Error(`Container cannot propagate events outside of the Federated Events API`);return e.defaultPrevented=!1,e.path=null,e.target=this,e.manager.dispatchEvent(e),!e.defaultPrevented}}})),Hc=s((()=>{R(),xs(),zc(),Vc(),L.add(Rc),L.mixin(J,Bc)})),Uc,Wc=s((()=>{Uc=(e=>(e[e.Low=0]=`Low`,e[e.Normal=1]=`Normal`,e[e.High=2]=`High`,e))(Uc||{})})),Gc,Kc=s((()=>{Gc={createCanvas:(e,t)=>{let n=document.createElement(`canvas`);return n.width=e,n.height=t,n},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(e,t)=>fetch(e,t),parseXML:e=>new DOMParser().parseFromString(e,`text/xml`)}})),qc,Y,Jc=s((()=>{Kc(),qc=Gc,Y={get(){return qc},set(e){qc=e}}}));function Yc(e){if(typeof e!=`string`)throw TypeError(`Path must be a string. Received ${JSON.stringify(e)}`)}function Xc(e){return e.split(`?`)[0].split(`#`)[0]}function Zc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Qc(e,t,n){return e.replace(new RegExp(Zc(t),`g`),n)}function $c(e,t){let n=``,r=0,i=-1,a=0,o=-1;for(let s=0;s<=e.length;++s){if(s<e.length)o=e.charCodeAt(s);else if(o===47)break;else o=47;if(o===47){if(i!==s-1&&a!==1){if(i!==s-1&&a===2){if(n.length<2||r!==2||n.charCodeAt(n.length-1)!==46||n.charCodeAt(n.length-2)!==46){if(n.length>2){let e=n.lastIndexOf(`/`);if(e!==n.length-1){e===-1?(n=``,r=0):(n=n.slice(0,e),r=n.length-1-n.lastIndexOf(`/`)),i=s,a=0;continue}}else if(n.length===2||n.length===1){n=``,r=0,i=s,a=0;continue}}t&&(n.length>0?n+=`/..`:n=`..`,r=2)}else n.length>0?n+=`/${e.slice(i+1,s)}`:n=e.slice(i+1,s),r=s-i-1}i=s,a=0}else o===46&&a!==-1?++a:a=-1}return n}var el,tl=s((()=>{Jc(),el={toPosix(e){return Qc(e,`\\`,`/`)},isUrl(e){return/^https?:/.test(this.toPosix(e))},isDataUrl(e){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(e)},isBlobUrl(e){return e.startsWith(`blob:`)},hasProtocol(e){return/^[^/:]+:/.test(this.toPosix(e))},getProtocol(e){Yc(e),e=this.toPosix(e);let t=/^file:\/\/\//.exec(e);if(t)return t[0];let n=/^[^/:]+:\/{0,2}/.exec(e);return n?n[0]:``},toAbsolute(e,t,n){if(Yc(e),this.isDataUrl(e)||this.isBlobUrl(e))return e;let r=Xc(this.toPosix(t??Y.get().getBaseUrl())),i=Xc(this.toPosix(n??this.rootname(r)));return e=this.toPosix(e),e.startsWith(`/`)?el.join(i,e.slice(1)):this.isAbsolute(e)?e:this.join(r,e)},normalize(e){if(Yc(e),e.length===0)return`.`;if(this.isDataUrl(e)||this.isBlobUrl(e))return e;e=this.toPosix(e);let t=``,n=e.startsWith(`/`);this.hasProtocol(e)&&(t=this.rootname(e),e=e.slice(t.length));let r=e.endsWith(`/`);return e=$c(e,!1),e.length>0&&r&&(e+=`/`),n?`/${e}`:t+e},isAbsolute(e){return Yc(e),e=this.toPosix(e),this.hasProtocol(e)?!0:e.startsWith(`/`)},join(...e){if(e.length===0)return`.`;let t;for(let n=0;n<e.length;++n){let r=e[n];if(Yc(r),r.length>0){if(t===void 0)t=r;else{let i=e[n-1]??``;this.joinExtensions.includes(this.extname(i).toLowerCase())?t+=`/../${r}`:t+=`/${r}`}}}return t===void 0?`.`:this.normalize(t)},dirname(e){if(Yc(e),e.length===0)return`.`;e=this.toPosix(e);let t=e.charCodeAt(0),n=t===47,r=-1,i=!0,a=this.getProtocol(e),o=e;e=e.slice(a.length);for(let n=e.length-1;n>=1;--n)if(t=e.charCodeAt(n),t===47){if(!i){r=n;break}}else i=!1;return r===-1?n?`/`:this.isUrl(o)?a+e:a:n&&r===1?`//`:a+e.slice(0,r)},rootname(e){Yc(e),e=this.toPosix(e);let t=``;if(t=e.startsWith(`/`)?`/`:this.getProtocol(e),this.isUrl(e)){let n=e.indexOf(`/`,t.length);t=n===-1?e:e.slice(0,n),t.endsWith(`/`)||(t+=`/`)}return t},basename(e,t){Yc(e),t&&Yc(t),e=Xc(this.toPosix(e));let n=0,r=-1,i=!0,a;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return``;let o=t.length-1,s=-1;for(a=e.length-1;a>=0;--a){let c=e.charCodeAt(a);if(c===47){if(!i){n=a+1;break}}else s===-1&&(i=!1,s=a+1),o>=0&&(c===t.charCodeAt(o)?--o===-1&&(r=a):(o=-1,r=s))}return n===r?r=s:r===-1&&(r=e.length),e.slice(n,r)}for(a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!i){n=a+1;break}}else r===-1&&(i=!1,r=a+1);return r===-1?``:e.slice(n,r)},extname(e){Yc(e),e=Xc(this.toPosix(e));let t=-1,n=0,r=-1,i=!0,a=0;for(let o=e.length-1;o>=0;--o){let s=e.charCodeAt(o);if(s===47){if(!i){n=o+1;break}}else r===-1&&(i=!1,r=o+1),s===46?t===-1?t=o:a!==1&&(a=1):t!==-1&&(a=-1)}return t===-1||r===-1||a===0||a===1&&t===r-1&&t===n+1?``:e.slice(t,r)},parse(e){Yc(e);let t={root:``,dir:``,base:``,ext:``,name:``};if(e.length===0)return t;e=Xc(this.toPosix(e));let n=e.charCodeAt(0),r=this.isAbsolute(e),i;t.root=this.rootname(e),i=r||this.hasProtocol(e)?1:0;let a=-1,o=0,s=-1,c=!0,l=e.length-1,u=0;for(;l>=i;--l)if(n=e.charCodeAt(l),n===47){if(!c){o=l+1;break}}else s===-1&&(c=!1,s=l+1),n===46?a===-1?a=l:u!==1&&(u=1):a!==-1&&(u=-1);return a===-1||s===-1||u===0||u===1&&a===s-1&&a===o+1?s!==-1&&(t.base=t.name=o===0&&r?e.slice(1,s):e.slice(o,s)):(o===0&&r?(t.name=e.slice(1,a),t.base=e.slice(1,s)):(t.name=e.slice(o,a),t.base=e.slice(o,s)),t.ext=e.slice(a,s)),t.dir=this.dirname(e),t},sep:`/`,delimiter:`:`,joinExtensions:[`.html`]}})),nl,rl=s((()=>{nl=(e,t,n=!1)=>(Array.isArray(e)||(e=[e]),t?e.map(e=>typeof e==`string`||n?t(e):e):e)}));function il(e,t,n,r,i){let a=t[n];for(let o=0;o<a.length;o++){let s=a[o];n<t.length-1?il(e.replace(r[n],s),t,n+1,r,i):i.push(e.replace(r[n],s))}}function al(e){let t=e.match(/\{(.*?)\}/g),n=[];if(t){let r=[];t.forEach(e=>{let t=e.substring(1,e.length-1).split(`,`);r.push(t)}),il(e,r,0,t,n)}else n.push(e);return n}var ol=s((()=>{})),sl,cl=s((()=>{sl=e=>!Array.isArray(e)}));function ll(e){return e.split(`.`).pop().split(`?`).shift().split(`#`).shift()}var ul,dl=s((()=>{W(),tl(),rl(),ol(),cl(),ul=class{constructor(){this._defaultBundleIdentifierOptions={connector:`-`,createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,``)},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle(`foo`,this._createBundleAssetId(`foo`,`bar`))!==`bar`)throw Error(`[Resolver] GenerateBundleAssetId are not working correctly`)}prefer(...e){e.forEach(e=>{this._preferredOrder.push(e),e.priority||=Object.keys(e.params)}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e==`string`)this._defaultSearchParams=e;else{let t=e;this._defaultSearchParams=Object.keys(t).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join(`&`)}}getAlias(e){let{alias:t,src:n}=e;return nl(t||n,e=>typeof e==`string`?e:Array.isArray(e)?e.map(e=>e?.src??e):e?.src?e.src:e,!0)}removeAlias(e,t){this._assetMap[e]&&(t&&t!==this._resolverHash[e]||(delete this._resolverHash[e],delete this._assetMap[e]))}addManifest(e){this._manifest&&U(`[Resolver] Manifest already exists, this will be overwritten`),this._manifest=e,e.bundles.forEach(e=>{this.addBundle(e.name,e.assets)})}addBundle(e,t){let n=[],r=t;Array.isArray(t)||(r=Object.entries(t).map(([e,t])=>typeof t==`string`||Array.isArray(t)?{alias:e,src:t}:{alias:e,...t})),r.forEach(t=>{let r=t.src,i=t.alias,a;if(typeof i==`string`){let t=this._createBundleAssetId(e,i);n.push(t),a=[i,t]}else{let t=i.map(t=>this._createBundleAssetId(e,t));n.push(...t),a=[...i,...t]}this.add({...t,alias:a,src:r})}),this._bundles[e]=n}add(e){let t=[];Array.isArray(e)?t.push(...e):t.push(e);let n=e=>{this.hasKey(e)&&U(`[Resolver] already has key: ${e} overwriting`)};nl(t).forEach(e=>{let{src:t}=e,{data:r,format:i,loadParser:a,parser:o}=e,s=nl(t).map(e=>typeof e==`string`?al(e):Array.isArray(e)?e:[e]),c=this.getAlias(e);Array.isArray(c)?c.forEach(n):n(c);let l=[],u=e=>({src:e,...this._parsers.find(t=>t.test(e))?.parse(e)});s.forEach(t=>{t.forEach(t=>{let n={};if(typeof t==`object`?(r=t.data??r,i=t.format??i,(t.loadParser||t.parser)&&(a=t.loadParser??a,o=t.parser??o),n={...u(t.src),...t}):n=u(t),!c)throw Error(`[Resolver] alias is undefined for this asset: ${n.src}`);n=this._buildResolvedAsset(n,{aliases:c,data:r,format:i,loadParser:a,parser:o,progressSize:e.progressSize}),l.push(n)})}),c.forEach(e=>{this._assetMap[e]=l})})}resolveBundle(e){let t=sl(e);e=nl(e);let n={};return e.forEach(e=>{let t=this._bundles[e];if(t){let r=this.resolve(t),i={};for(let t in r){let n=r[t];i[this._extractAssetIdFromBundle(e,t)]=n}n[e]=i}}),t?n[e[0]]:n}resolveUrl(e){let t=this.resolve(e);if(typeof e!=`string`){let e={};for(let n in t)e[n]=t[n].src;return e}return t.src}resolve(e){let t=sl(e);e=nl(e);let n={};return e.forEach(e=>{if(!this._resolverHash[e]){if(this._assetMap[e]){let t=this._assetMap[e],n=this._getPreferredOrder(t);n?.priority.forEach(e=>{n.params[e].forEach(n=>{let r=t.filter(t=>t[e]?t[e]===n:!1);r.length&&(t=r)})}),this._resolverHash[e]=t[0]}else this._resolverHash[e]=this._buildResolvedAsset({alias:[e],src:e},{})}n[e]=this._resolverHash[e]}),t?n[e[0]]:n}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){let n=e[t],r=this._preferredOrder.find(e=>e.params.format.includes(n.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){return this._defaultSearchParams?`${e}${/\?/.test(e)?`&`:`?`}${this._defaultSearchParams}`:e}_buildResolvedAsset(e,t){let{aliases:n,data:r,loadParser:i,parser:a,format:o,progressSize:s}=t;return(this._basePath||this._rootPath)&&(e.src=el.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=n??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=i??e.loadParser,e.parser=a??e.parser,e.format=o??e.format??ll(e.src),s!==void 0&&(e.progressSize=s),e}},ul.RETINA_PREFIX=/@([0-9\.]+)x/})),fl,pl=s((()=>{fl=(e,t)=>{let n=t.split(`?`)[1];return n&&(e+=`?${n}`),e}})),ml,hl,gl=s((()=>{Pa(),Po(),$o(),ml=class e{constructor(e,t){this.linkedSheets=[];let n=e;e?.source instanceof No&&(n={texture:e,data:t});let{texture:r,data:i,cachePrefix:a=``}=n;this.cachePrefix=a,this._texture=r instanceof q?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=i;let o=parseFloat(i.meta.scale);o?(this.resolution=o,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(t=>{this._callback=t,this._batchIndex=0,this._frameKeys.length<=e.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(t,n=!1){let r=t,i=n?1/0:e.BATCH_SIZE;for(;r-t<i&&r<this._frameKeys.length;){let e=this._frameKeys[r],t=this._frames[e],n=t.frame;if(n){let r=null,i=null,a=t.trimmed!==!1&&t.sourceSize?t.sourceSize:t.frame,o=new G(0,0,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution);r=t.rotated?new G(Math.floor(n.x)/this.resolution,Math.floor(n.y)/this.resolution,Math.floor(n.h)/this.resolution,Math.floor(n.w)/this.resolution):new G(Math.floor(n.x)/this.resolution,Math.floor(n.y)/this.resolution,Math.floor(n.w)/this.resolution,Math.floor(n.h)/this.resolution),t.trimmed!==!1&&t.spriteSourceSize&&(i=new G(Math.floor(t.spriteSourceSize.x)/this.resolution,Math.floor(t.spriteSourceSize.y)/this.resolution,Math.floor(n.w)/this.resolution,Math.floor(n.h)/this.resolution)),this.textures[e]=new q({source:this.textureSource,frame:r,orig:o,trim:i,rotate:t.rotated?2:0,defaultAnchor:t.anchor,defaultBorders:t.borders,label:e.toString()})}r++}}_processAnimations(){let e=this.data.animations||{};for(let t in e){this.animations[t]=[];for(let n=0;n<e[t].length;n++){let r=e[t][n];this.animations[t].push(this.textures[r])}}}_parseComplete(){let e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*e.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*e.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){for(let e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}},ml.BATCH_SIZE=1e3,hl=ml}));function _l(e,t,n){let r={};if(e.forEach(e=>{r[e]=t}),Object.keys(t.textures).forEach(e=>{r[`${t.cachePrefix}${e}`]=t.textures[e]}),!n){let n=el.dirname(e[0]);t.linkedSheets.forEach((e,i)=>{let a=_l([`${n}/${t.data.meta.related_multi_packs[i]}`],e,!0);Object.assign(r,a)})}return r}var vl,yl,bl=s((()=>{Wc(),dl(),pl(),R(),$o(),tl(),gl(),vl=[`jpg`,`png`,`jpeg`,`avif`,`webp`,`basis`,`etc2`,`bc7`,`bc6h`,`bc5`,`bc4`,`bc3`,`bc2`,`bc1`,`eac`,`astc`],yl={extension:I.Asset,cache:{test:e=>e instanceof hl,getCacheableAssets:(e,t)=>_l(e,t,!1)},resolver:{extension:{type:I.ResolveParser,name:`resolveSpritesheet`},test:e=>{let t=e.split(`?`)[0].split(`.`),n=t.pop(),r=t.pop();return n===`json`&&vl.includes(r)},parse:e=>{let t=e.split(`.`);return{resolution:parseFloat(ul.RETINA_PREFIX.exec(e)?.[1]??`1`),format:t[t.length-2],src:e}}},loader:{name:`spritesheetLoader`,id:`spritesheet`,extension:{type:I.LoadParser,priority:Uc.Normal,name:`spritesheetLoader`},async testParse(e,t){return el.extname(t.src).toLowerCase()===`.json`&&!!e.frames},async parse(e,t,n){let{texture:r,imageFilename:i,textureOptions:a,cachePrefix:o}=t?.data??{},s=el.dirname(t.src);s&&s.lastIndexOf(`/`)!==s.length-1&&(s+=`/`);let c;if(r instanceof q)c=r;else{let r=fl(s+(i??e.meta.image),t.src);c=(await n.load([{src:r,data:a}]))[r]}let l=new hl({texture:c.source,data:e,cachePrefix:o});await l.parse();let u=e?.meta?.related_multi_packs;if(Array.isArray(u)){let e=[];for(let r of u){if(typeof r!=`string`)continue;let i=s+r;t.data?.ignoreMultiPack||(i=fl(i,t.src),e.push(n.load({src:i,data:{textureOptions:a,ignoreMultiPack:!0}})))}let r=await Promise.all(e);l.linkedSheets=r,r.forEach(e=>{e.linkedSheets=[l].concat(l.linkedSheets.filter(t=>t!==e))})}return l},async unload(e,t,n){await n.unload(e.textureSource._sourceOrigin),e.destroy(!1)}}}})),xl=s((()=>{R(),bl(),L.add(yl)}));function Sl(e,t,n){let{width:r,height:i}=n.orig,a=n.trim;if(a){let n=a.width,o=a.height;e.minX=a.x-t._x*r,e.maxX=e.minX+n,e.minY=a.y-t._y*i,e.maxY=e.minY+o}else e.minX=-t._x*r,e.maxX=e.minX+r,e.minY=-t._y*i,e.maxY=e.minY+i}var Cl=s((()=>{})),wl,Tl=s((()=>{Zi(),$o(),Cl(),oa(),yc(),wl=class e extends vc{constructor(e=q.EMPTY){e instanceof q&&(e={texture:e});let{texture:t=q.EMPTY,anchor:n,roundPixels:r,width:i,height:a,...o}=e;super({label:`Sprite`,...o}),this.renderPipeId=`sprite`,this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new Xi({_onUpdate:()=>{this.onViewUpdate()}}),n?this.anchor=n:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,i!==void 0&&(this.width=i),a!==void 0&&(this.height=a)}static from(t,n=!1){return t instanceof q?new e(t):new e(q.from(t,n))}set texture(e){e||=q.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return Sl(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return H(`8.6.1`,`Sprite.sourceBounds is deprecated, use visualBounds instead.`),this.visualBounds}updateBounds(){let e=this._anchor,t=this._texture,n=this._bounds,{width:r,height:i}=t.orig;n.minX=-e._x*r,n.maxX=n.minX+r,n.minY=-e._y*i,n.maxY=n.minY+i}destroy(e=!1){if(super.destroy(e),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||={},e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e==`object`?(t=e.height??e.width,e=e.width):t??=e,e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}}));function El(e,t,n){let r=Dl;e.measurable=!0,Wa(e,n,r),t.addBoundsMask(r),e.measurable=!1}var Dl,Ol=s((()=>{La(),qa(),Dl=new Ia}));function kl(e,t,n){let r=za.get();e.measurable=!0;let i=Ra.get().identity();no(e,r,Al(e,n,i)),e.measurable=!1,t.addBoundsMask(r),Ra.return(i),za.return(r)}function Al(e,t,n){return e?(e!==t&&(Al(e.parent,t,n),e.updateLocalTransform(),n.append(e.localTransform)),n):(U(`Mask bounds, renderable is not inside the root container`),n)}var jl=s((()=>{io(),Ba(),W()})),Ml,Nl=s((()=>{R(),Tl(),Ol(),jl(),Ml=class{constructor(e){this.priority=0,this.inverse=!1,this.channel=`red`,this.pipe=`alphaMask`,e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof wl),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||El(this.mask,e,t)}addLocalBounds(e,t){kl(this.mask,e,t)}containsPoint(e,t){let n=this.mask;return t(n,e)}destroy(){this.reset()}static test(e){return e instanceof wl}},Ml.extension=I.MaskEffect})),Pl,Fl=s((()=>{R(),Pl=class{constructor(e){this.priority=0,this.pipe=`colorMask`,e?.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e==`number`}},Pl.extension=I.MaskEffect})),Il,Ll=s((()=>{R(),xs(),Ol(),jl(),Il=class{constructor(e){this.priority=0,this.pipe=`stencilMask`,e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){El(this.mask,e,t)}addLocalBounds(e,t){kl(this.mask,e,t)}containsPoint(e,t){let n=this.mask;return t(n,e)}destroy(){this.reset()}static test(e){return e instanceof J}},Il.extension=I.MaskEffect})),Rl,zl=s((()=>{Jc(),R(),Po(),Rl=class extends No{constructor(e){e.resource||=Y.get().createCanvas(),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId=`image`,this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&`style`in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,n=this._resolution){let r=super.resize(e,t,n);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||=this.resource.getContext(`2d`)}},Rl.extension=I.TextureSource})),Bl,Vl=s((()=>{R(),Po(),Bl=class extends No{constructor(e){super(e),this.uploadMethodId=`image`,this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}},Bl.extension=I.TextureSource}));async function Hl(){return Ul??=(async()=>{let e=Y.get().createCanvas(1,1).getContext(`webgl`);if(!e)return`premultiply-alpha-on-upload`;let t=await new Promise(e=>{let t=document.createElement(`video`);t.onloadeddata=()=>e(t),t.onerror=()=>e(null),t.autoplay=!1,t.crossOrigin=`anonymous`,t.preload=`auto`,t.src=`data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=`,t.load()});if(!t)return`premultiply-alpha-on-upload`;let n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);let i=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,i),e.deleteFramebuffer(r),e.deleteTexture(n),e.getExtension(`WEBGL_lose_context`)?.loseContext(),i[0]<=i[3]?`premultiplied-alpha`:`premultiply-alpha-on-upload`})(),Ul}var Ul,Wl=s((()=>{Jc()})),Gl,Kl,ql=s((()=>{R(),Os(),Wl(),Po(),Gl=class e extends No{constructor(t){super(t),this.isReady=!1,this.uploadMethodId=`video`,t={...e.defaultOptions,...t},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=t.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=t.autoPlay!==!1,this.alphaMode=t.alphaMode??`premultiply-alpha-on-upload`,this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),this._onLoadedMetadata=this._onLoadedMetadata.bind(this),t.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){let e=Ds.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this._videoFrameRequestCallbackHandle=this.destroyed?null:this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;let e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener(`play`,this._onPlayStart),e.addEventListener(`pause`,this._onPlayStop),e.addEventListener(`seeked`,this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener(`canplay`,this._onCanPlay),e.addEventListener(`canplaythrough`,this._onCanPlayThrough),e.addEventListener(`error`,this._onError,!0)),this.isValid||e.addEventListener(`loadedmetadata`,this._onLoadedMetadata),this.alphaMode=await Hl(),this._load=new Promise((n,r)=>{this.isValid?n(this):(this._resolve=n,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener(`error`,this._onError,!0),this.emit(`error`,e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){let e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onLoadedMetadata(){this.isValid&&this._mediaReady()}_onCanPlay(){this.resource.removeEventListener(`canplay`,this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener(`canplaythrough`,this._onCanPlayThrough),this._preloadTimeout&&=(clearTimeout(this._preloadTimeout),void 0),this._mediaReady()}_mediaReady(){let e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&this.isValid&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();let e=this.resource;e&&(e.removeEventListener(`play`,this._onPlayStart),e.removeEventListener(`pause`,this._onPlayStop),e.removeEventListener(`seeked`,this._onSeeked),e.removeEventListener(`canplay`,this._onCanPlay),e.removeEventListener(`canplaythrough`,this._onCanPlayThrough),e.removeEventListener(`loadedmetadata`,this._onLoadedMetadata),e.removeEventListener(`error`,this._onError,!0),e.pause(),e.src=``,e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(Ds.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Ds.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Ds.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}},Gl.extension=I.TextureSource,Gl.defaultOptions={...No.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},Gl.MIME_TYPES={ogv:`video/ogg`,mov:`video/quicktime`,m4v:`video/mp4`},Kl=Gl})),Jl,Yl,Xl=s((()=>{W(),rl(),Jl=class{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){let t=this._cache.get(e);return t||U(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){let n=nl(e),r;for(let e=0;e<this.parsers.length;e++){let i=this.parsers[e];if(i.test(t)){r=i.getCacheableAssets(n,t);break}}let i=new Map(Object.entries(r||{}));r||n.forEach(e=>{i.set(e,t)});let a=[...i.keys()],o={cacheKeys:a,keys:n};n.forEach(e=>{this._cacheMap.set(e,o)}),a.forEach(e=>{let n=r?r[e]:t;this._cache.has(e)&&this._cache.get(e)!==n&&U(`[Cache] already has key:`,e),this._cache.set(e,i.get(e))})}remove(e){if(!this._cacheMap.has(e)){U(`[Assets] Asset id ${e} was not found in the Cache`);return}let t=this._cacheMap.get(e);t.cacheKeys.forEach(e=>{this._cache.delete(e)}),t.keys.forEach(e=>{this._cacheMap.delete(e)})}get parsers(){return this._parsers}},Yl=new Jl}));function Zl(e={}){let t=e&&e.resource,n=t?e.resource:e,r=t?e:{resource:e};for(let e=0;e<eu.length;e++){let t=eu[e];if(t.test(n))return new t(r)}throw Error(`Could not find a source type for resource: ${r.resource}`)}function Ql(e={},t=!1){let n=e&&e.resource,r=n?e.resource:e,i=n?e:{resource:e};if(!t&&Yl.has(r))return Yl.get(r);let a=new q({source:Zl(i)});return a.on(`destroy`,()=>{Yl.has(r)&&Yl.remove(r)}),t||Yl.set(r,a),a}function $l(e,t=!1){return typeof e==`string`?Yl.get(e):e instanceof No?new q({source:e}):Ql(e,t)}var eu,tu=s((()=>{Xl(),R(),Po(),$o(),eu=[],L.handleByList(I.TextureSource,eu),q.from=$l,No.from=Zl})),nu=s((()=>{R(),Nl(),Fl(),Ll(),Yo(),zl(),Vl(),ql(),tu(),L.add(Ml,Pl,Il,Kl,Bl,Rl,Jo)}));function ru(e){let t=Y.get().createCanvas(6,1),n=t.getContext(`2d`);return n.fillStyle=e,n.fillRect(0,0,6,1),t}function iu(){if(au!==void 0)return au;try{let e=ru(`#ff00ff`),t=ru(`#ffff00`),n=Y.get().createCanvas(6,1).getContext(`2d`);n.globalCompositeOperation=`multiply`,n.drawImage(e,0,0),n.drawImage(t,2,0);let r=n.getImageData(2,0,1,1);if(!r)au=!1;else{let e=r.data;au=e[0]===255&&e[1]===0&&e[2]===0}}catch{au=!1}return au}var au,ou=s((()=>{Jc()})),X,su=s((()=>{Ri(),Jc(),Uo(),ou(),X={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:iu(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:e=>{let t=e.source,n=t?.resource;if(!n)return null;let r=t.alphaMode===`premultiplied-alpha`,i=t.resourceWidth??t.pixelWidth,a=t.resourceHeight??t.pixelHeight,o=i!==t.pixelWidth||a!==t.pixelHeight;if(r){if((n instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&n instanceof OffscreenCanvas)&&!o)return n;let e=X._unpremultipliedCache.get(t);if(e?.resourceId===t._resourceId)return e.canvas}if(n instanceof Uint8Array||n instanceof Uint8ClampedArray||n instanceof Int8Array||n instanceof Uint16Array||n instanceof Int16Array||n instanceof Uint32Array||n instanceof Int32Array||n instanceof Float32Array||n instanceof ArrayBuffer){let e=X._canvasSourceCache.get(t);if(e?.resourceId===t._resourceId)return e.canvas;let r=Y.get().createCanvas(t.pixelWidth,t.pixelHeight),i=r.getContext(`2d`),a=i.createImageData(t.pixelWidth,t.pixelHeight),o=a.data,s=n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength);if(t.format===`bgra8unorm`)for(let e=0;e<o.length&&e+3<s.length;e+=4)o[e]=s[e+2],o[e+1]=s[e+1],o[e+2]=s[e],o[e+3]=s[e+3];else o.set(s.subarray(0,o.length));return i.putImageData(a,0,0),X._canvasSourceCache.set(t,{canvas:r,resourceId:t._resourceId}),r}if(r){let e=Y.get().createCanvas(t.pixelWidth,t.pixelHeight),r=e.getContext(`2d`,{willReadFrequently:!0});e.width=t.pixelWidth,e.height=t.pixelHeight,r.drawImage(n,0,0);let i=r.getImageData(0,0,e.width,e.height),a=i.data;for(let e=0;e<a.length;e+=4){let t=a[e+3];if(t>0){let n=255/t;a[e]=Math.min(255,a[e]*n+.5),a[e+1]=Math.min(255,a[e+1]*n+.5),a[e+2]=Math.min(255,a[e+2]*n+.5)}}return r.putImageData(i,0,0),X._unpremultipliedCache.set(t,{canvas:e,resourceId:t._resourceId}),e}if(o){let e=X._canvasSourceCache.get(t);if(e?.resourceId===t._resourceId)return e.canvas;let r=Y.get().createCanvas(t.pixelWidth,t.pixelHeight),i=r.getContext(`2d`);return r.width=t.pixelWidth,r.height=t.pixelHeight,i.drawImage(n,0,0),X._canvasSourceCache.set(t,{canvas:r,resourceId:t._resourceId}),r}return n},getTintedCanvas:(e,t)=>{let n=e.texture,r=Li.shared.setValue(t).toHex(),i=n.tintCache||={},a=i[r],o=n.source._resourceId;if(a?.tintId===o)return a;let s=a&&`getContext`in a?a:Y.get().createCanvas();if(X.tintMethod(n,t,s),s.tintId=o,X.convertTintToImage&&s.toDataURL!==void 0){let e=Y.get().createImage();e.src=s.toDataURL(),e.tintId=o,i[r]=e}else i[r]=s;return i[r]},getTintedPattern:(e,t)=>{let n=Li.shared.setValue(t).toHex(),r=e.patternCache||={},i=e.source._resourceId,a=r[n];return a?.tintId===i||(X.canvas||(X.canvas=Y.get().createCanvas()),X.tintMethod(e,t,X.canvas),a=X.canvas.getContext(`2d`).createPattern(X.canvas,`repeat`),a.tintId=i,r[n]=a),a},applyPatternTransform:(e,t,n=!0)=>{if(!t)return;let r=e;if(!r.setTransform)return;let i=globalThis.DOMMatrix;if(!i)return;let a=new i([t.a,t.b,t.c,t.d,t.tx,t.ty]);r.setTransform(n?a.inverse():a)},tintWithMultiply:(e,t,n)=>{let r=n.getContext(`2d`),i=e.frame.clone(),a=e.source._resolution??e.source.resolution??1,o=e.rotate;i.x*=a,i.y*=a,i.width*=a,i.height*=a;let s=K.isVertical(o),c=s?i.height:i.width,l=s?i.width:i.height;n.width=Math.ceil(c),n.height=Math.ceil(l),r.save(),t!==16777215&&(r.fillStyle=Li.shared.setValue(t).toHex(),r.fillRect(0,0,c,l),r.globalCompositeOperation=`multiply`);let u=X.getCanvasSource(e);u&&(o&&X._applyInverseRotation(r,o,i.width,i.height),r.drawImage(u,i.x,i.y,i.width,i.height,0,0,i.width,i.height),t!==16777215&&(r.globalCompositeOperation=`destination-atop`,r.drawImage(u,i.x,i.y,i.width,i.height,0,0,i.width,i.height))),r.restore()},tintWithOverlay:(e,t,n)=>{let r=n.getContext(`2d`),i=e.frame.clone(),a=e.source._resolution??e.source.resolution??1,o=e.rotate;i.x*=a,i.y*=a,i.width*=a,i.height*=a;let s=K.isVertical(o),c=s?i.height:i.width,l=s?i.width:i.height;n.width=Math.ceil(c),n.height=Math.ceil(l),r.save(),r.globalCompositeOperation=`copy`,r.fillStyle=Li.shared.setValue(t).toHex(),r.fillRect(0,0,c,l),r.globalCompositeOperation=`destination-atop`;let u=X.getCanvasSource(e);u&&(o&&X._applyInverseRotation(r,o,i.width,i.height),r.drawImage(u,i.x,i.y,i.width,i.height,0,0,i.width,i.height)),r.restore()},tintWithPerPixel:(e,t,n)=>{let r=n.getContext(`2d`),i=e.frame.clone(),a=e.source._resolution??e.source.resolution??1,o=e.rotate;i.x*=a,i.y*=a,i.width*=a,i.height*=a;let s=K.isVertical(o),c=s?i.height:i.width,l=s?i.width:i.height;n.width=Math.ceil(c),n.height=Math.ceil(l),r.save(),r.globalCompositeOperation=`copy`;let u=X.getCanvasSource(e);if(!u){r.restore();return}o&&X._applyInverseRotation(r,o,i.width,i.height),r.drawImage(u,i.x,i.y,i.width,i.height,0,0,i.width,i.height),r.restore();let d=t>>16&255,f=t>>8&255,p=t&255,m=r.getImageData(0,0,c,l),h=m.data;for(let e=0;e<h.length;e+=4)h[e]=h[e]*d/255,h[e+1]=h[e+1]*f/255,h[e+2]=h[e+2]*p/255;r.putImageData(m,0,0)},_applyInverseRotation:(e,t,n,r)=>{let i=K.inv(t),a=K.uX(i),o=K.uY(i),s=K.vX(i),c=K.vY(i),l=-Math.min(0,a*n,s*r,a*n+s*r),u=-Math.min(0,o*n,c*r,o*n+c*r);e.transform(a,o,s,c,l,u)}},X.tintMethod=X.canUseMultiply?X.tintWithMultiply:X.tintWithPerPixel}));function cu(e,t){return(e<<17)+(t<<2)}var lu,uu,du,fu=s((()=>{Jc(),So(),oa(),W(),ua(),ts(),lu=32767,uu=class{constructor(e){this._buckets=new Map,this._screens=new es,this._enableFullScreen=!1,this.canvasOptions=e||{}}get enableFullScreen(){return H(ra,`CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize.`),this._enableFullScreen}set enableFullScreen(e){H(ra,`CanvasPool.enableFullScreen is no longer used, the pool sizes canvases to the screens registered with setScreenSize.`),this._enableFullScreen=e}_createCanvasAndContext(e,t){let n=Y.get().createCanvas();return n.width=e,n.height=t,{canvas:n,context:n.getContext(`2d`)}}getOptimalCanvasAndContext(e,t,n=1){let{width:r,height:i}=this.getOptimalSize(e,t,n);(r>lu||i>lu)&&U(`CanvasPool: ${r}x${i} is larger than the ${lu}px pool key limit, canvases of this size may be pooled together`);let a=cu(r,i),o=this._buckets.get(a);o||(o=[],this._buckets.set(a,o));let s=o.pop();return s||=this._createCanvasAndContext(r,i),s}getOptimalSize(e,t,n=1){let r=Math.ceil(e*n-1e-6),i=Math.ceil(t*n-1e-6),a=bo(r),o=this._screens.getFittingWidth(r),s=bo(i),c=this._screens.getFittingHeight(i);return{width:o===void 0?a:Math.min(o,a),height:c===void 0?s:Math.min(c,s)}}returnCanvasAndContext(e){let{width:t,height:n}=e.canvas,r=this._buckets.get(cu(t,n));r&&(e.context.resetTransform(),e.context.clearRect(0,0,t,n),r.push(e))}setScreenSize(e,t,n){this._screens.set(e,t,n)&&this._pruneScreenCanvases()}removeScreen(e){this._screens.remove(e)&&this._pruneScreenCanvases()}clear(){this._buckets.clear()}_pruneScreenCanvases(){for(let[e]of this._buckets){let t=e>>>17,n=e>>>2&32767;(!xo(t)&&!this._screens.hasWidth(t)||!xo(n)&&!this._screens.hasHeight(n))&&this._buckets.delete(e)}}},du=new uu,la.register(du)}));function pu(e){let t=e.length;if(t<6)return 1;let n=0;for(let r=0,i=e[t-2],a=e[t-1];r<t;r+=2){let t=e[r],o=e[r+1];n+=(t-i)*(o+a),i=t,a=o}return n<0?-1:1}var mu=s((()=>{}));function hu(e,t,n,r,i,a){let o=e-n,s=t-r,c=i-n,l=a-r,u=o*c+s*l,d=c*c+l*l,f=-1;d!==0&&(f=u/d);let p,m;f<0?(p=n,m=r):f>1?(p=i,m=a):(p=n+f*c,m=r+f*l);let h=e-p,g=t-m;return h*h+g*g}var gu=s((()=>{}));function _u(e,t,n,r,i,a,o,s){let c=o-n,l=s-r,u=i-n,d=a-r,f=e-n,p=t-r,m=c*c+l*l,h=c*u+l*d,g=c*f+l*p,_=u*u+d*d,v=u*f+d*p,y=1/(m*_-h*h),b=(_*g-h*v)*y,x=(m*v-h*g)*y;return b>=0&&x>=0&&b+x<1}var vu=s((()=>{})),yu,bu=s((()=>{Pa(),yu=class e{constructor(e=0,t=0,n=0){this.type=`circle`,this.x=e,this.y=t,this.radius=n}clone(){return new e(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;let n=this.radius*this.radius,r=this.x-e,i=this.y-t;return r*=r,i*=i,r+i<=n}strokeContains(e,t,n,r=.5){if(this.radius===0)return!1;let i=this.x-e,a=this.y-t,o=this.radius,s=(1-r)*n,c=Math.sqrt(i*i+a*a);return c<=o+s&&c>o-(n-s)}getBounds(e){return e||=new G,e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}})),xu,Su=s((()=>{Pa(),xu=class e{constructor(e=0,t=0,n=0,r=0){this.type=`ellipse`,this.x=e,this.y=t,this.halfWidth=n,this.halfHeight=r}clone(){return new e(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let n=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return n*=n,r*=r,n+r<=1}strokeContains(e,t,n,r=.5){let{halfWidth:i,halfHeight:a}=this;if(i<=0||a<=0)return!1;let o=n*(1-r),s=n-o,c=i-s,l=a-s,u=i+o,d=a+o,f=e-this.x,p=t-this.y;return f*f/(u*u)+p*p/(d*d)>1?!1:c<=0||l<=0||f*f/(c*c)+p*p/(l*l)>1}getBounds(e){return e||=new G,e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}})),Cu,wu,Tu,Eu=s((()=>{oa(),mu(),gu(),Pa(),Tu=class e{constructor(...e){this.type=`polygon`;let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!=`number`){let e=[];for(let n=0,r=t.length;n<r;n++)e.push(t[n].x,t[n].y);t=e}this.points=t,this.closePath=!0}isClockwise(){let e=0,t=this.points,n=t.length;for(let r=0;r<n;r+=2){let i=t[r],a=t[r+1],o=t[(r+2)%n],s=t[(r+3)%n];e+=(o-i)*(s+a)}return e<0}containsPolygon(e){let t=this.getBounds(Cu),n=e.getBounds(wu);if(!t.containsRect(n))return!1;let r=e.points;for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!this.contains(t,n))return!1}return!0}clone(){let t=this.points.slice(),n=new e(t);return n.closePath=this.closePath,n}contains(e,t){let n=!1,r=this.points.length/2;for(let i=0,a=r-1;i<r;a=i++){let r=this.points[i*2],o=this.points[i*2+1],s=this.points[a*2],c=this.points[a*2+1];o>t!=c>t&&e<(s-r)*((t-o)/(c-o))+r&&(n=!n)}return n}strokeContains(e,t,n,r=.5){let{points:i}=this,a=n*(r===.5?r:(r-.5)*pu(i)+.5),o=n-a,s=a*a,c=o*o,l=i.length-(this.closePath?0:2);for(let n=0;n<l;n+=2){let r=i[n],a=i[n+1],o=i[(n+2)%i.length],l=i[(n+3)%i.length];if(hu(e,t,r,a,o,l)<=(Math.sign((o-r)*(t-a)-(l-a)*(e-r))<0?s:c))return!0}return!1}getBounds(e){e||=new G;let t=this.points,n=1/0,r=-1/0,i=1/0,a=-1/0;for(let e=0,o=t.length;e<o;e+=2){let o=t[e],s=t[e+1];n=o<n?o:n,r=o>r?o:r,i=s<i?s:i,a=s>a?s:a}return e.x=n,e.width=r-n,e.y=i,e.height=a-i,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,``)}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return H(`8.11.0`,`Polygon.lastX is deprecated, please use Polygon.lastX instead.`),this.points[this.points.length-2]}get y(){return H(`8.11.0`,`Polygon.y is deprecated, please use Polygon.lastY instead.`),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}})),Du,Ou,ku=s((()=>{Pa(),Du=(e,t,n,r,i,a,o)=>{let s=e-n,c=t-r,l=Math.sqrt(s*s+c*c);return l>=i-a&&l<=i+o},Ou=class e{constructor(e=0,t=0,n=0,r=0,i=20){this.type=`roundedRectangle`,this.x=e,this.y=t,this.width=n,this.height=r,this.radius=i}getBounds(e){return e||=new G,e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new e(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){let n=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+n&&t<=this.y+this.height-n||e>=this.x+n&&e<=this.x+this.width-n)return!0;let r=e-(this.x+n),i=t-(this.y+n),a=n*n;if(r*r+i*i<=a||(r=e-(this.x+this.width-n),r*r+i*i<=a)||(i=t-(this.y+this.height-n),r*r+i*i<=a)||(r=e-(this.x+n),r*r+i*i<=a))return!0}return!1}strokeContains(e,t,n,r=.5){let{x:i,y:a,width:o,height:s,radius:c}=this,l=n*(1-r),u=n-l,d=i+c,f=a+c,p=o-c*2,m=s-c*2,h=i+o,g=a+s;return(e>=i-l&&e<=i+u||e>=h-u&&e<=h+l)&&t>=f&&t<=f+m||(t>=a-l&&t<=a+u||t>=g-u&&t<=g+l)&&e>=d&&e<=d+p||e<d&&t<f&&Du(e,t,d,f,c,u,l)||e>h-c&&t<f&&Du(e,t,h-c,f,c,u,l)||e>h-c&&t>g-c&&Du(e,t,h-c,g-c,c,u,l)||e<d&&t>g-c&&Du(e,t,d,g-c,c,u,l)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}}));function Au(e,t){t.clear();let n=t.matrix;for(let n=0;n<e.length;n++){let r=e[n];if(r.globalDisplayStatus<7)continue;let i=r.renderGroup??r.parentRenderGroup;t.matrix=i?.isCachedAsTexture?ju.copyFrom(i.textureOffsetInverseTransform).append(r.worldTransform):i?._parentCacheAsTextureRenderGroup?ju.copyFrom(i._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):r.worldTransform,t.addBounds(r.bounds)}return t.matrix=n,t}var ju,Mu=s((()=>{B(),ju=new z}));function Nu(e,t,n,r,i=!1,a){let o=Pu;o.minX=0,o.minY=0,o.maxX=e.width/r|0,o.maxY=e.height/r|0;let s=ds.getOptimalTexture({width:o.width,height:o.height,resolution:r,autoGenerateMipmaps:i,scaleMode:a});return s.source.uploadMethodId=`image`,s.source.resource=e,s.source.alphaMode=`premultiply-alpha-on-upload`,s.frame.width=t/r,s.frame.height=n/r,s.source.emit(`update`,s.source),s.updateUvs(),s}var Pu,Fu=s((()=>{fs(),La(),Pu=new Ia}));function Iu(e){return typeof e.getCanvasFilterString==`function`}var Lu,Ru,zu=s((()=>{R(),su(),fu(),La(),Mu(),Fu(),Lu=class{constructor(){this.skip=!1,this.useClip=!1,this.filters=null,this.container=null,this.bounds=new Ia,this.cssFilterString=``}},Ru=class{constructor(e){this._filterStack=[],this._filterStackIndex=0,this._savedStates=[],this._alphaMultiplier=1,this._warnedFilterTypes=new Set,this.renderer=e}push(e){let t=this._pushFilterFrame(),n=e.filterEffect.filters;if(t.skip=!1,t.useClip=!1,t.filters=n,t.container=e.container,t.cssFilterString=``,n.every(e=>!e.enabled)){t.skip=!0;return}let r=[];for(let e of n){if(!e.enabled)continue;if(!Iu(e)){this._warnUnsupportedFilter(e);continue}let t=e.getCanvasFilterString();t===null?this._warnUnsupportedFilter(e):t&&r.push(t)}if(r.length===0){t.skip=!0;return}t.cssFilterString=r.join(` `),this._calculateFilterArea(e,t.bounds),t.useClip=!!e.filterEffect.filterArea;let i=this.renderer.canvasContext.activeContext,a=i.filter||`none`;if(this._savedStates.push({filter:a,alphaMultiplier:this._alphaMultiplier}),t.useClip&&Number.isFinite(t.bounds.width)&&Number.isFinite(t.bounds.height)&&t.bounds.width>0&&t.bounds.height>0){let e=this.renderer.canvasContext.activeResolution||1;i.save(),i.setTransform(1,0,0,1,0,0),i.beginPath(),i.rect(t.bounds.x*e,t.bounds.y*e,t.bounds.width*e,t.bounds.height*e),i.clip()}else t.useClip=!1;t.cssFilterString&&(i.filter=a===`none`?t.cssFilterString:`${a} ${t.cssFilterString}`)}pop(){let e=this._popFilterFrame();if(e.skip)return;let t=this._savedStates.pop();if(!t)return;let n=this.renderer.canvasContext.activeContext;e.useClip?n.restore():n.filter=t.filter,this._alphaMultiplier=t.alphaMultiplier}generateFilteredTexture({texture:e,filters:t}){if(!t?.length||t.every(e=>!e.enabled))return e;let n=[];for(let e of t){if(!e.enabled)continue;if(!Iu(e)){this._warnUnsupportedFilter(e);continue}let t=e.getCanvasFilterString();t===null?this._warnUnsupportedFilter(e):t&&n.push(t)}if(n.length===0)return e;let r=X.getCanvasSource(e);if(!r)return e;let i=e.frame,a=e.source._resolution??e.source.resolution??1,o=i.width,s=i.height,{canvas:c,context:l}=du.getOptimalCanvasAndContext(o,s,a);l.setTransform(1,0,0,1,0,0),l.clearRect(0,0,c.width,c.height),n.length&&(l.filter=n.join(` `));let u=i.x*a,d=i.y*a,f=o*a,p=s*a;return l.drawImage(r,u,d,f,p,0,0,f,p),l.filter=`none`,l.globalAlpha=1,Nu(c,o,s,a)}_calculateFilterArea(e,t){if(e.renderables?Au(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){let n=(e.container.renderGroup||e.container.parentRenderGroup)?.cacheToLocalTransform;n&&t.applyMatrix(n)}}_warnUnsupportedFilter(e){let t=e?.constructor?.name||`Filter`;this._warnedFilterTypes.has(t)||(this._warnedFilterTypes.add(t),console.warn(`CanvasRenderer: filter "${t}" is not supported in Canvas2D and will be skipped.`))}get alphaMultiplier(){return this._alphaMultiplier}_pushFilterFrame(){let e=this._filterStack[this._filterStackIndex];return e||=this._filterStack[this._filterStackIndex]=new Lu,this._filterStackIndex++,e}_popFilterFrame(){return this._filterStackIndex<=0?this._filterStack[0]:(this._filterStackIndex--,this._filterStack[this._filterStackIndex])}destroy(){this._filterStack=null,this._savedStates=null,this._warnedFilterTypes=null,this._alphaMultiplier=1}},Ru.extension={type:[I.CanvasSystem],name:`filter`}})),Bu,Vu=s((()=>{R(),Bu=class{constructor(e){this._renderer=e}push(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`filter`,canBundle:!1,action:`pushFilter`,container:t,filterEffect:e})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`filter`,action:`popFilter`,canBundle:!1})}execute(e){e.action===`pushFilter`?this._renderer.filter.push(e):e.action===`popFilter`&&this._renderer.filter.pop()}destroy(){this._renderer=null}},Bu.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`filter`}}));function Hu(e,t){let n=Wu[e];return n===void 0&&(Uu[t]===void 0&&(Uu[t]=1),Wu[e]=n=Uu[t]++),n}var Uu,Wu,Gu=s((()=>{Uu=Object.create(null),Wu=Object.create(null)}));function Ku(){return(!qu||qu?.isContextLost())&&(qu=Y.get().createCanvas().getContext(`webgl`,{})),qu}var qu,Ju=s((()=>{Jc()}));function Yu(){if(!Xu){Xu=`mediump`;let e=Ku();e&&e.getShaderPrecisionFormat&&(Xu=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision?`highp`:`mediump`)}return Xu}var Xu,Zu=s((()=>{Ju()}));function Qu(e,t,n){return t?e:n?(e=e.replace(`out vec4 finalColor;`,``),`
|
|
23
|
-
|
|
24
|
-
#ifdef GL_ES // This checks if it is WebGL1
|
|
25
|
-
#define in varying
|
|
26
|
-
#define finalColor gl_FragColor
|
|
27
|
-
#define texture texture2D
|
|
28
|
-
#endif
|
|
29
|
-
${e}
|
|
30
|
-
`):`
|
|
31
|
-
|
|
32
|
-
#ifdef GL_ES // This checks if it is WebGL1
|
|
33
|
-
#define in attribute
|
|
34
|
-
#define out varying
|
|
35
|
-
#endif
|
|
36
|
-
${e}
|
|
37
|
-
`}var $u=s((()=>{}));function ed(e,t,n){let r=n?t.maxSupportedFragmentPrecision:t.maxSupportedVertexPrecision;if(e.substring(0,9)!==`precision`){let i=n?t.requestedFragmentPrecision:t.requestedVertexPrecision;i===`highp`&&r!==`highp`&&(i=`mediump`),e=`precision ${i} float;
|
|
38
|
-
${e}`}else r!==`highp`&&e.substring(0,15)===`precision highp`&&(e=e.replace(`precision highp`,`precision mediump`));let i=t.maxSupportedFragmentPrecision===`highp`?`highp`:`mediump`;return td(e,i)}function td(e,t){let n=new Set,r=``;for(let[,t]of e.matchAll(rd))n.add(t);for(let[,i]of e.matchAll(nd))n.has(i)||(n.add(i),r+=`precision ${id[i]??t} ${i};
|
|
39
|
-
`);return r+e}var nd,rd,id,ad=s((()=>{nd=/\buniform\s+([iu]?sampler\w+)/g,rd=/\bprecision\s+\w+\s+([iu]?sampler\w+)\s*;/g,id={sampler2D:`lowp`,samplerCube:`lowp`}}));function od(e,t){return t?`#version 300 es
|
|
40
|
-
${e}`:e}var sd=s((()=>{}));function cd(e,{name:t=`pixi-program`},n=!0){t=t.replace(/\s+/g,`-`),t+=n?`-fragment`:`-vertex`;let r=n?ld:ud;return r[t]?(r[t]++,t+=`-${r[t]}`):r[t]=1,e.indexOf(`#define SHADER_NAME`)===-1?`${`#define SHADER_NAME ${t}`}
|
|
41
|
-
${e}`:e}var ld,ud,dd=s((()=>{ld={},ud={}}));function fd(e,t){return t?e.replace(`#version 300 es`,``):e}var pd=s((()=>{})),md,hd,gd,_d,vd=s((()=>{Gu(),Zu(),$u(),ad(),sd(),dd(),pd(),md={stripVersion:fd,ensurePrecision:ed,addProgramDefines:Qu,setProgramName:cd,insertVersion:od},hd=Object.create(null),gd=class e{constructor(t){t={...e.defaultOptions,...t};let n=t.fragment.indexOf(`#version 300 es`)!==-1,r={stripVersion:n,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:`highp`,maxSupportedFragmentPrecision:Yu()},setProgramName:{name:t.name},addProgramDefines:n,insertVersion:n},i=t.fragment,a=t.vertex;Object.keys(md).forEach(e=>{let t=r[e];i=md[e](i,t,!0),a=md[e](a,t,!1)}),this.fragment=i,this.vertex=a,this.transformFeedbackVaryings=t.transformFeedbackVaryings,this._key=Hu(`${this.vertex}:${this.fragment}`,`gl-program`)}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,hd[this._cacheKey]=null}static from(t){let n=`${t.vertex}:${t.fragment}`;return hd[n]||(hd[n]=new e(t),hd[n]._cacheKey=n),hd[n]}},gd.defaultOptions={preferredVertexPrecision:`highp`,preferredFragmentPrecision:`mediump`},_d=gd}));function yd(e){return bd[e]??bd.float32}var bd,xd=s((()=>{bd={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}}}));function Sd(e,t){let n;for(;(n=Ed.exec(e))!==null;){let e=Td[n[3]]??`float32`;t[n[2]]={location:parseInt(n[1],10),format:e,stride:yd(e).stride,offset:0,instance:!1,start:0}}Ed.lastIndex=0}function Cd(e){return e.replace(/\/\/.*$/gm,``).replace(/\/\*[\s\S]*?\*\//g,``)}function wd({source:e,entryPoint:t}){let n={},r=Cd(e),i=r.indexOf(`fn ${t}(`);if(i===-1)return n;let a=r.indexOf(`->`,i);if(a===-1)return n;let o=r.substring(i,a);if(Sd(o,n),Object.keys(n).length===0){let e=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(e){let t=e[1],i=RegExp(`struct\\s+${t}\\s*\\{([^}]+)\\}`,`s`),a=r.match(i);a&&Sd(a[1],n)}}return n}var Td,Ed,Dd=s((()=>{xd(),Td={f32:`float32`,"vec2<f32>":`float32x2`,"vec3<f32>":`float32x3`,"vec4<f32>":`float32x4`,vec2f:`float32x2`,vec3f:`float32x3`,vec4f:`float32x4`,i32:`sint32`,"vec2<i32>":`sint32x2`,"vec3<i32>":`sint32x3`,"vec4<i32>":`sint32x4`,vec2i:`sint32x2`,vec3i:`sint32x3`,vec4i:`sint32x4`,u32:`uint32`,"vec2<u32>":`uint32x2`,"vec3<u32>":`uint32x3`,"vec4<u32>":`uint32x4`,vec2u:`uint32x2`,vec3u:`uint32x3`,vec4u:`uint32x4`,bool:`uint32`,"vec2<bool>":`uint32x2`,"vec3<bool>":`uint32x3`,"vec4<bool>":`uint32x4`},Ed=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g}));function Od(e){let t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,n=/@group\((\d+)\)/,r=/@binding\((\d+)\)/,i=/var(<[^>]+>)? (\w+)/,a=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,s=/(\w+)\s*:\s*([\w\<\>]+)/g,c=/struct\s+(\w+)/,l=e.match(t)?.map(e=>{let t=e.match(i),o=t?.[1]??``,s;return o===`<uniform>`?s=`uniform`:o.startsWith(`<storage`)&&(s=`storage`),{group:parseInt(e.match(n)[1],10),binding:parseInt(e.match(r)[1],10),name:t[2],accessMode:s,type:e.match(a)[1]}});return l?{groups:l,structs:e.match(o)?.map(e=>{let t=e.match(c)[1],n=e.match(s).reduce((e,t)=>{let[n,r]=t.split(`:`);return e[n.trim()]=r.trim(),e},{});return n?{name:t,members:n}:null}).filter(({name:e})=>l.some(t=>t.type===e||t.type.includes(`<${e}>`)))??[]}:{groups:[],structs:[]}}var kd=s((()=>{})),Ad,jd=s((()=>{Ad=(e=>(e[e.VERTEX=1]=`VERTEX`,e[e.FRAGMENT=2]=`FRAGMENT`,e[e.COMPUTE=4]=`COMPUTE`,e))(Ad||{})}));function Md(e){return e.endsWith(`<u32>`)?`uint`:e.endsWith(`<i32>`)?`sint`:`float`}function Nd({groups:e}){let t=[];for(let n=0;n<e.length;n++){let r=e[n];t[r.group]||(t[r.group]=[]),r.accessMode===`uniform`?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,buffer:{type:`uniform`}}):r.accessMode===`storage`?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,buffer:{type:`read-only-storage`}}):r.type===`sampler`?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,sampler:{type:`filtering`}}):r.type===`sampler_comparison`?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,sampler:{type:`comparison`}}):r.type===`texture_2d`||r.type.startsWith(`texture_2d<`)?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,texture:{sampleType:Md(r.type),viewDimension:`2d`,multisampled:!1}}):r.type===`texture_depth_2d`?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,texture:{sampleType:`depth`,viewDimension:`2d`,multisampled:!1}}):r.type===`texture_depth_2d_array`?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,texture:{sampleType:`depth`,viewDimension:`2d-array`,multisampled:!1}}):r.type===`texture_2d_array`||r.type.startsWith(`texture_2d_array<`)?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,texture:{sampleType:Md(r.type),viewDimension:`2d-array`,multisampled:!1}}):r.type===`texture_3d`||r.type.startsWith(`texture_3d<`)?t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,texture:{sampleType:Md(r.type),viewDimension:`3d`,multisampled:!1}}):(r.type===`texture_cube`||r.type.startsWith(`texture_cube<`))&&t[r.group].push({binding:r.binding,visibility:Ad.VERTEX|Ad.FRAGMENT,texture:{sampleType:Md(r.type),viewDimension:`cube`,multisampled:!1}})}for(let e=0;e<t.length;e++)t[e]||(t[e]=[]);return t}var Pd=s((()=>{jd()}));function Fd({groups:e}){let t=[];for(let n=0;n<e.length;n++){let r=e[n];t[r.group]||(t[r.group]={}),t[r.group][r.name]=r.binding}return t}var Id=s((()=>{}));function Ld(e,t){let n=new Set,r=new Set;return{structs:[...e.structs,...t.structs].filter(e=>!n.has(e.name)&&(n.add(e.name),!0)),groups:[...e.groups,...t.groups].filter(e=>{let t=`${e.name}-${e.binding}`;return!r.has(t)&&(r.add(t),!0)})}}var Rd=s((()=>{})),zd,Bd,Vd=s((()=>{Gu(),Dd(),kd(),Pd(),Id(),Rd(),zd=Object.create(null),Bd=class e{constructor(e){this._layoutKey=0,this._attributeLocationsKey=0;let{fragment:t,vertex:n,layout:r,gpuLayout:i,name:a}=e;if(this.name=a,this.fragment=t,this.vertex=n,t.source===n.source){let e=Od(t.source);this.structsAndGroups=e}else{let e=Od(n.source),r=Od(t.source);this.structsAndGroups=Ld(e,r)}this.layout=r??Fd(this.structsAndGroups),this.gpuLayout=i??Nd(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){let{vertex:e,fragment:t}=this,n=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=Hu(n,`program`)}get attributeData(){return this._attributeData??=wd(this.vertex),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,zd[this._cacheKey]=null}static from(t){let n=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return zd[n]||(zd[n]=new e(t),zd[n]._cacheKey=n),zd[n]}}})),Hd,Ud=s((()=>{W(),Hd=class{constructor(e){this.resources=Object.create(null),this._resourceKeysValue=null,this._dirty=!0;let t=0;for(let n in e){let r=e[n];this.setResource(r,t++)}}get _resourceKeys(){return this._resourceKeysValue??=Object.keys(this.resources).map(Number),this._resourceKeysValue}get _key(){if(this._dirty){this._dirty=!1;let e=[],t=0;for(let n in this.resources)e[t++]=this.resources[n]?this.resources[n]._resourceId:-1;this._keyValue=e.join(`|`)}return this._keyValue}setResource(e,t){let n=this.resources[t];e!==n&&(n&&n.off?.(`change`,this.onResourceChange,this),e.on?.(`change`,this.onResourceChange,this),n===void 0&&(this._resourceKeysValue=null),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e){let t=this.resources,n=this._resourceKeys;for(let r=0;r<n.length;r++){let i=t[n[r]];i&&(i._gcLastUsed=e)}}destroy(){let e=this.resources;for(let t in e)e[t]?.off?.(`change`,this.onResourceChange,this);this.resources=null,this._resourceKeysValue=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){let t=this.resources;for(let n in t)t[n]===e&&(t[n]=null);U(`[BindGroup] a '${e._resourceType}' was destroyed while still bound to a shader. Remove it from the shader before destroying it.`)}}}})),Wd,Gd=s((()=>{Wd=(e=>(e[e.WEBGL=1]=`WEBGL`,e[e.WEBGPU=2]=`WEBGPU`,e[e.CANVAS=4]=`CANVAS`,e[e.BOTH=3]=`BOTH`,e))(Wd||{})})),Kd,qd=s((()=>{Gu(),Kd=class e{constructor(e){this.data={...e};let t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join(`|`);this.id=Hu(t,`shader-overrides`)}static from(t){return t instanceof e?t:new e(t)}}})),Jd,Yd,Xd=s((()=>{Jd=[`f32`,`i32`,`u32`,`vec2<f32>`,`vec3<f32>`,`vec4<f32>`,`mat2x2<f32>`,`mat3x3<f32>`,`mat4x4<f32>`,`mat3x2<f32>`,`mat4x2<f32>`,`mat2x3<f32>`,`mat4x3<f32>`,`mat2x4<f32>`,`mat3x4<f32>`,`vec2<i32>`,`vec3<i32>`,`vec4<i32>`,`vec2<u32>`,`vec3<u32>`,`vec4<u32>`],Yd=Jd.reduce((e,t)=>(e[t]=!0,e),{})}));function Zd(e,t){switch(e){case`f32`:return 0;case`vec2<f32>`:return new Float32Array(2*t);case`vec3<f32>`:return new Float32Array(3*t);case`vec4<f32>`:return new Float32Array(4*t);case`mat2x2<f32>`:return new Float32Array([1,0,0,1]);case`mat3x3<f32>`:return new Float32Array([1,0,0,0,1,0,0,0,1]);case`mat4x4<f32>`:return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}var Qd=s((()=>{})),$d,ef,tf=s((()=>{ri(),ea(),Gu(),Xd(),Qd(),$d=class e extends ni{constructor(t,n){super(),this.uid=Qi(`uniform`),this._resourceType=`uniformGroup`,this._resourceId=Qi(`resource`),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,n={...e.defaultOptions,...n},this.uniformStructures=t;let r={};for(let e in t){let n=t[e];if(n.name=e,n.size=n.size??1,!Yd[n.type]){let e=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(e){let[,t,r]=e;throw Error(`Uniform type ${n.type} is not supported. Use type: '${t}', size: ${r} instead.`)}throw Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${Jd.join(`, `)}`)}n.value??=Zd(n.type,n.size),r[e]=n.value}this.uniforms=r,this._dirtyId=1,this.ubo=n.ubo,this.isStatic=n.isStatic,this._signature=Hu(Object.keys(r).map(e=>`${e}-${t[e].type}`).join(`-`),`uniform-group`)}get buffer(){return this._buffer}set buffer(e){this._buffer!==e&&(this._buffer?.off(`change`,this.onBufferChange,this),this._buffer=e,e?.on(`change`,this.onBufferChange,this))}get _gcLastUsed(){return this._buffer?._gcLastUsed??-1}set _gcLastUsed(e){this._buffer&&(this._buffer._gcLastUsed=e)}onBufferChange(){this._resourceId=Qi(`resource`),this.emit(`change`,this)}update(){this._dirtyId++}},$d.defaultOptions={ubo:!1,isStatic:!1},ef=$d})),nf,rf=s((()=>{ri(),ea(),W(),vd(),Ud(),Vd(),Gd(),qd(),tf(),nf=class e extends ni{constructor(e){super(),this.uid=Qi(`shader`),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:n,groups:r,resources:i,compatibleRenderers:a,groupMap:o,overrides:s}=e;this._overrides=s?Kd.from(s):null,this.gpuProgram=t,this.glProgram=n,a===void 0&&(a=0,t&&(a|=Wd.WEBGPU),n&&(a|=Wd.WEBGL)),this.compatibleRenderers=a;let c={};if(o)for(let e in o)for(let t in o[e]){let n=o[e][t];c[n]={group:e,binding:t,name:n}}if(!i&&!r&&(i={}),i&&r)throw Error(`[Shader] Cannot have both resources and groups`);if(!t&&r&&!o)throw Error(`[Shader] No group map or WebGPU shader provided - consider using resources instead.`);if(t&&r&&!o){let e=t.structsAndGroups.groups;o={},e.forEach(e=>{o[e.group]=o[e.group]||{},o[e.group][e.binding]=e.name,c[e.name]=e})}else if(i){r={},o||={},t&&t.structsAndGroups.groups.forEach(e=>{o[e.group]=o[e.group]||{},o[e.group][e.binding]=e.name,c[e.name]=e});let e=0;for(let a in i)c[a]||(t&&!n&&U(`[Shader] the resource '${a}' matches no binding in the WGSL source \u2014 is the name correct?`),r[99]||(r[99]=new Hd,this._ownedBindGroups.push(r[99])),c[a]={group:99,binding:e,name:a},o[99]=o[99]||{},o[99][e]=a,e++);for(let e in i){let t=e,n=i[e];!n.source&&!n._resourceType&&(n=new ef(n));let a=c[t];a&&(r[a.group]||(r[a.group]=new Hd,this._ownedBindGroups.push(r[a.group])),r[a.group].setResource(n,a.binding))}}this.groups=r,this._uniformBindMap=o,this.resources=this._buildResourceAccessor(r,c)}addResource(e,t,n){var r,i;(r=this._uniformBindMap)[t]||(r[t]={}),(i=this._uniformBindMap[t])[n]||(i[n]=e),this.groups[t]||(this.groups[t]=new Hd,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){let n={};for(let r in t){let i=t[r];Object.defineProperty(n,i.name,{get(){return e[i.group].getResource(i.binding)},set(t){e[i.group].setResource(t,i.binding)}})}return n}destroy(e=!1){this._destroyed||(this._destroyed=!0,this.emit(`destroy`,this),e&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(e=>{e.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null,this._overrides=null)}static from(t){let{gpu:n,gl:r,...i}=t,a,o;return n&&(a=Bd.from(n)),r&&(o=_d.from(r)),new e({gpuProgram:a,glProgram:o,...i})}}})),af,of,sf,cf,lf,uf,df,ff,pf,mf,hf=s((()=>{af={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},of={BLEND:0,OFFSET:1,CULLING:2,DEPTH_TEST:3,WINDING:4,DEPTH_MASK:5},{BLEND:sf,OFFSET:cf,CULLING:lf,DEPTH_TEST:uf,WINDING:df,DEPTH_MASK:ff}=of,pf=class e{constructor(){this.data=0,this.blendMode=`normal`,this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<sf)}set blend(e){!!(this.data&1<<sf)!==e&&(this.data^=1<<sf)}get offsets(){return!!(this.data&1<<cf)}set offsets(e){!!(this.data&1<<cf)!==e&&(this.data^=1<<cf)}set cullMode(e){e===`none`?this.culling=!1:(this.culling=!0,this.clockwiseFrontFace=e===`front`)}get cullMode(){return this.culling?this.clockwiseFrontFace?`front`:`back`:`none`}get culling(){return!!(this.data&1<<lf)}set culling(e){!!(this.data&1<<lf)!==e&&(this.data^=1<<lf)}get depthTest(){return!!(this.data&1<<uf)}set depthTest(e){!!(this.data&1<<uf)!==e&&(this.data^=1<<uf)}get depthMask(){return!!(this.data&1<<ff)}set depthMask(e){!!(this.data&1<<ff)!==e&&(this.data^=1<<ff)}get clockwiseFrontFace(){return!!(this.data&1<<df)}set clockwiseFrontFace(e){!!(this.data&1<<df)!==e&&(this.data^=1<<df)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!==`none`,this._blendMode=e,this._blendModeId=af[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){let t=new e;return t.depthTest=!1,t.depthMask=!1,t.blend=!0,t}},pf.default2d=pf.for2d(),mf=pf})),gf,_f,vf=s((()=>{vd(),Vd(),rf(),hf(),gf=class e extends nf{constructor(t){t={...e.defaultOptions,...t},super(t),this.enabled=!0,this._state=mf.for2d(),this.blendMode=t.blendMode,this.padding=t.padding,this.antialias=typeof t.antialias==`boolean`?t.antialias?`on`:`off`:t.antialias,this.resolution=t.resolution,this.blendRequired=t.blendRequired,this.clipToViewport=t.clipToViewport,this.addResource(`uTexture`,0,1),t.blendRequired&&this.addResource(`uBackTexture`,0,3)}apply(e,t,n,r){e.applyFilter(this,t,n,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(t){let{gpu:n,gl:r,...i}=t,a,o;return n&&(a=Bd.from(n)),r&&(o=_d.from(r)),new e({gpuProgram:a,glProgram:o,...i})}},gf.defaultOptions={blendMode:`normal`,resolution:1,padding:0,antialias:`off`,blendRequired:!1,clipToViewport:!0},_f=gf})),yf,bf=s((()=>{yf=`in vec2 aPosition;
|
|
42
|
-
out vec2 vTextureCoord;
|
|
43
|
-
|
|
44
|
-
uniform vec4 uInputSize;
|
|
45
|
-
uniform vec4 uOutputFrame;
|
|
46
|
-
uniform vec4 uOutputTexture;
|
|
47
|
-
|
|
48
|
-
vec4 filterVertexPosition( void )
|
|
49
|
-
{
|
|
50
|
-
vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
|
|
51
|
-
|
|
52
|
-
position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
|
|
53
|
-
position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
|
|
54
|
-
|
|
55
|
-
return vec4(position, 0.0, 1.0);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
vec2 filterTextureCoord( void )
|
|
59
|
-
{
|
|
60
|
-
return aPosition * (uOutputFrame.zw * uInputSize.zw);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
void main(void)
|
|
64
|
-
{
|
|
65
|
-
gl_Position = filterVertexPosition();
|
|
66
|
-
vTextureCoord = filterTextureCoord();
|
|
67
|
-
}
|
|
68
|
-
`})),xf,Sf=s((()=>{xf=`in vec2 vTextureCoord;
|
|
69
|
-
out vec4 finalColor;
|
|
70
|
-
uniform sampler2D uTexture;
|
|
71
|
-
void main() {
|
|
72
|
-
finalColor = texture(uTexture, vTextureCoord);
|
|
73
|
-
}
|
|
74
|
-
`})),Cf,wf=s((()=>{Cf=`struct GlobalFilterUniforms {
|
|
75
|
-
uInputSize: vec4<f32>,
|
|
76
|
-
uInputPixel: vec4<f32>,
|
|
77
|
-
uInputClamp: vec4<f32>,
|
|
78
|
-
uOutputFrame: vec4<f32>,
|
|
79
|
-
uGlobalFrame: vec4<f32>,
|
|
80
|
-
uOutputTexture: vec4<f32>,
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
@group(0) @binding(0) var <uniform> gfu: GlobalFilterUniforms;
|
|
84
|
-
@group(0) @binding(1) var uTexture: texture_2d<f32>;
|
|
85
|
-
@group(0) @binding(2) var uSampler: sampler;
|
|
86
|
-
|
|
87
|
-
struct VSOutput {
|
|
88
|
-
@builtin(position) position: vec4<f32>,
|
|
89
|
-
@location(0) uv: vec2<f32>
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
fn filterVertexPosition(aPosition: vec2<f32>) -> vec4<f32>
|
|
93
|
-
{
|
|
94
|
-
var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
|
|
95
|
-
|
|
96
|
-
position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
|
|
97
|
-
position.y = position.y * (2.0 * gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
|
|
98
|
-
|
|
99
|
-
return vec4(position, 0.0, 1.0);
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
fn filterTextureCoord(aPosition: vec2<f32>) -> vec2<f32>
|
|
103
|
-
{
|
|
104
|
-
return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
@vertex
|
|
108
|
-
fn mainVertex(
|
|
109
|
-
@location(0) aPosition: vec2<f32>,
|
|
110
|
-
) -> VSOutput {
|
|
111
|
-
return VSOutput(
|
|
112
|
-
filterVertexPosition(aPosition),
|
|
113
|
-
filterTextureCoord(aPosition)
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
@fragment
|
|
118
|
-
fn mainFragment(
|
|
119
|
-
@location(0) uv: vec2<f32>,
|
|
120
|
-
) -> @location(0) vec4<f32> {
|
|
121
|
-
return textureSample(uTexture, uSampler, uv);
|
|
122
|
-
}
|
|
123
|
-
`})),Tf,Ef=s((()=>{vd(),Vd(),vf(),bf(),Sf(),wf(),Tf=class extends _f{constructor(){let e=Bd.from({vertex:{source:Cf,entryPoint:`mainVertex`},fragment:{source:Cf,entryPoint:`mainFragment`},name:`passthrough-filter`}),t=_d.from({vertex:yf,fragment:xf,name:`passthrough-filter`});super({gpuProgram:e,glProgram:t})}}})),Df,Of=s((()=>{Df=(e=>(e[e.MAP_READ=1]=`MAP_READ`,e[e.MAP_WRITE=2]=`MAP_WRITE`,e[e.COPY_SRC=4]=`COPY_SRC`,e[e.COPY_DST=8]=`COPY_DST`,e[e.INDEX=16]=`INDEX`,e[e.VERTEX=32]=`VERTEX`,e[e.UNIFORM=64]=`UNIFORM`,e[e.STORAGE=128]=`STORAGE`,e[e.INDIRECT=256]=`INDIRECT`,e[e.QUERY_RESOLVE=512]=`QUERY_RESOLVE`,e[e.STATIC=1024]=`STATIC`,e))(Df||{})})),kf,Af=s((()=>{ri(),ea(),Of(),kf=class extends ni{constructor(e){let{data:t,size:n}=e,{usage:r,label:i,shrinkToFit:a}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=Qi(`buffer`),this._resourceType=`buffer`,this._resourceId=Qi(`resource`),this._updateID=1,this._updateOffset=0,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,n??=t?.byteLength;let o=!!t;this.descriptor={size:n,usage:r,mappedAtCreation:o,label:i},this.shrinkToFit=a??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||=new Int32Array(this.data.buffer),this._dataInt32}get static(){return!!(this.descriptor.usage&Df.STATIC)}set static(e){e?this.descriptor.usage|=Df.STATIC:this.descriptor.usage&=~Df.STATIC}setDataWithSize(e,t,n){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._updateOffset=0,this._data===e){n&&this.emit(`update`,this);return}let r=this._data;this._data=e,this._dataInt32=null,!r||r.length!==e.length?!this.shrinkToFit&&r&&e.byteLength<r.byteLength?n&&this.emit(`update`,this):(this.descriptor.size=e.byteLength,this._resourceId=Qi(`resource`),this.emit(`change`,this)):n&&this.emit(`update`,this)}update(e,t){this._updateSize=e??this._updateSize,this._updateOffset=t||0,this._updateID++,this.emit(`update`,this)}unload(){this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null),this.destroyed||(this._resourceId=Qi(`resource`),this.emit(`change`,this))}destroy(){this.destroyed=!0,this.unload(),this.emit(`destroy`,this),this.emit(`change`,this),this._data=null,this.descriptor=null,this.removeAllListeners()}}}));function jf(e,t){if(!(e instanceof kf)){let n=t?Df.INDEX:Df.VERTEX;e instanceof Array&&(t?(e=new Uint32Array(e),n=Df.INDEX|Df.COPY_DST):(e=new Float32Array(e),n=Df.VERTEX|Df.COPY_DST)),e=new kf({data:e,label:t?`index-mesh-buffer`:`vertex-mesh-buffer`,usage:n})}return e}var Mf=s((()=>{Af(),Of()}));function Nf(e,t,n){let r=e.getAttribute(t);if(!r)return n.minX=0,n.minY=0,n.maxX=0,n.maxY=0,n;let i=r.buffer.data,a=1/0,o=1/0,s=-1/0,c=-1/0,l=i.BYTES_PER_ELEMENT,u=(r.offset||0)/l,d=(r.stride||8)/l;for(let e=u;e<i.length;e+=d){let t=i[e],n=i[e+1];t>s&&(s=t),n>c&&(c=n),t<a&&(a=t),n<o&&(o=n)}return n.minX=a,n.minY=o,n.maxX=s,n.maxY=c,n}var Pf=s((()=>{}));function Ff(e){return(e instanceof kf||Array.isArray(e)||e.BYTES_PER_ELEMENT)&&(e={buffer:e}),e.buffer=jf(e.buffer,!1),e}var If,Lf=s((()=>{ri(),La(),ea(),oa(),Af(),Mf(),Pf(),If=class extends ni{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=Qi(`geometry`),this._layoutKey=0,this.instanceCount=1,this.indexCount=0,this._bounds=new Ia,this._boundsDirty=!0,this._vertexCount=0,this._vertexCountDirty=!0;let{attributes:t,indexBuffer:n,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(let e in t)this.addAttribute(e,t[e]);this.instanceCount=e.instanceCount??1,this.indexCount=e.indexCount??0,n&&this.addIndex(n),this.topology=r||`triangle-list`}onBufferUpdate(){this._boundsDirty=!0,this._vertexCountDirty=!0,this.emit(`update`,this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}get vertexCount(){if(!this._vertexCountDirty)return this._vertexCount;this._vertexCountDirty=!1;let e=this.attributes;for(let t in e){let n=e[t];if(n.instance)continue;let r=n.buffer;return this._vertexCount=r.data.length/(n.stride/4||n.size),this._vertexCount}return this._vertexCount=0,0}getSize(){return H(`8.20.0`,`Geometry.getSize is deprecated, please use Geometry.vertexCount instead.`),this.vertexCount}addAttribute(e,t){let n=Ff(t);this.buffers.indexOf(n.buffer)===-1&&(this.buffers.push(n.buffer),n.buffer.on(`update`,this.onBufferUpdate,this),n.buffer.on(`change`,this.onBufferUpdate,this)),this.attributes[e]=n,this._vertexCountDirty=!0}addIndex(e){this.indexBuffer=jf(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Nf(this,`aPosition`,this._bounds)):this._bounds}unload(){this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null)}destroy(e=!1){this.emit(`destroy`,this);for(let t of this.buffers)t.off(`update`,this.onBufferUpdate,this),t.off(`change`,this.onBufferUpdate,this),e&&t.destroy();this.unload(),this.removeAllListeners(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}})),Rf,zf,Bf,Vf=s((()=>{R(),Ef(),B(),Ud(),Lf(),tf(),$o(),fs(),Gd(),La(),Mu(),W(),Rf=new If({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:`float32x2`,stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])}),zf=class{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new Ia,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}},Bf=class{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new ef({uInputSize:{value:new Float32Array(4),type:`vec4<f32>`},uInputPixel:{value:new Float32Array(4),type:`vec4<f32>`},uInputClamp:{value:new Float32Array(4),type:`vec4<f32>`},uOutputFrame:{value:new Float32Array(4),type:`vec4<f32>`},uGlobalFrame:{value:new Float32Array(4),type:`vec4<f32>`},uOutputTexture:{value:new Float32Array(4),type:`vec4<f32>`}}),this._globalFilterBindGroup=new Hd({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){let t=this.renderer,n=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=n,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;let i=t.renderTarget.renderTarget.colorTexture.source,a=i.resolution,o=i.antialias;if(n.every(e=>!e.enabled)){r.skip=!0;return}let s=r.bounds;if(this._calculateFilterArea(e,s),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,o,a,1),r.skip)return;let c=this._getPreviousFilterData();this._setupFilterTextures(r,s,t,c)}generateFilteredTexture({texture:e,filters:t}){if(t.every(e=>!e.enabled))return e;let n=this._pushFilterData();this._activeFilterData=n,n.skip=!1,n.filters=t;let r=e.source,i=r.resolution,a=r.antialias,o=n.bounds;if(o.clear(),o.addRect(e.frame),this._calculateFilterBounds(n,o.rectangle,a,i,0),n.skip)return this._popFilterData(),e;n.outputRenderSurface=ds.getOptimalTexture({width:o.width,height:o.height,resolution:n.resolution,antialias:n.antialias}),n.backTexture=q.EMPTY,n.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(n,!0);let s=n.outputRenderSurface;return s.source.alphaMode=`premultiplied-alpha`,this._popFilterData(),s}pop(){let e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&ds.returnTexture(t.backTexture),ds.returnTexture(t.inputTexture))}getBackTexture(e,t,n){let r=e.colorTexture.source._resolution,i=ds.getOptimalTexture({width:t.width,height:t.height,resolution:r}),a=t.minX,o=t.minY;n&&(a-=n.minX,o-=n.minY),a=Math.floor(a*r),o=Math.floor(o*r);let s=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,i,{x:a,y:o},{width:s,height:c},{x:0,y:0}),i}applyFilter(e,t,n,r){let i=this.renderer,a=this._activeFilterData,o=a.outputRenderSurface===n,s=this._findClosestFilterData(),c=s?s.inputTexture.source._resolution:i.renderTarget.rootRenderTarget.colorTexture.source._resolution,l=0,u=0;o&&s&&(l=s.bounds.minX,u=s.bounds.minY),this._updateFilterUniforms(t,n,a,l,u,c,o,r);let d=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(d,t,i)}calculateSpriteMatrix(e,t){let n=this._activeFilterData,r=e.set(n.inputTexture._source.width,0,0,n.inputTexture._source.height,n.bounds.minX,n.bounds.minY),i=t.worldTransform.copyTo(z.shared),a=t.renderGroup||t.parentRenderGroup;return a&&a.cacheToLocalTransform&&i.prepend(a.cacheToLocalTransform),i.invert(),r.prepend(i),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){this._passthroughFilter?.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??=new Tf,this._passthroughFilter}_setupBindGroupsAndRender(e,t,n){if(n.renderPipes.uniformBatch){let e=n.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(e,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,n.encoder.draw({geometry:Rf,shader:e,state:e._state,topology:`triangle-list`}),n.type===Wd.WEBGL&&n.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,n,r){if(e.backTexture=q.EMPTY,e.inputTexture=ds.getOptimalTexture({width:t.width,height:t.height,resolution:e.resolution,antialias:e.antialias}),e.blendRequired){n.renderTarget.finishRenderPass();let i=n.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(i,t,r?.bounds)}n.renderTarget.bind({target:e.inputTexture,clear:!0}),n.globalUniforms.push({offset:t})}_updateFilterUniforms(e,t,n,r,i,a,o,s){let c=this._filterGlobalUniforms.uniforms,l=c.uOutputFrame,u=c.uInputSize,d=c.uInputPixel,f=c.uInputClamp,p=c.uGlobalFrame,m=c.uOutputTexture;o?(l[0]=n.bounds.minX-r,l[1]=n.bounds.minY-i):(l[0]=0,l[1]=0),l[2]=e.frame.width,l[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],d[0]=e.source.pixelWidth,d[1]=e.source.pixelHeight,d[2]=1/d[0],d[3]=1/d[1],f[0]=.5*d[2],f[1]=.5*d[3],f[2]=e.frame.width*u[2]-.5*d[2],f[3]=e.frame.height*u[3]-.5*d[3];let h=this.renderer.renderTarget.rootRenderTarget.colorTexture;p[0]=r*a,p[1]=i*a,p[2]=h.source.width*a,p[3]=h.source.height*a,t instanceof q&&(t.source.resource=null);let g=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind({target:t,clear:!!s}),t instanceof q?(m[0]=t.frame.width,m[1]=t.frame.height):(m[0]=g.width,m[1]=g.height),m[2]=g.isRoot?-1:1,this._filterGlobalUniforms.update()}_findClosestFilterData(){for(let e=this._filterStackIndex-1;e>=0;e--){let t=this._filterStack[e];if(!t.skip)return t}return null}_calculateFilterArea(e,t){if(e.renderables?Au(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){let n=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;n&&t.applyMatrix(n)}}_applyFiltersToTexture(e,t){let n=e.inputTexture,r=e.bounds,i=e.filters,a=e.firstEnabledIndex,o=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(n.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),a===o)i[a].apply(this,n,e.outputRenderSurface,t);else{let n=e.inputTexture,s=ds.getOptimalTexture({width:r.width,height:r.height,resolution:n.source._resolution}),c=s;for(let e=a;e<o;e++){let t=i[e];if(!t.enabled)continue;t.apply(this,n,c,!0);let r=n;n=c,c=r}i[o].apply(this,n,e.outputRenderSurface,t),ds.returnTexture(s)}}_calculateFilterBounds(e,t,n,r,i){let a=this.renderer,o=e.bounds,s=e.filters,c=1/0,l=0,u=!0,d=!1,f=!1,p=!0,m=-1,h=-1;for(let e=0;e<s.length;e++){let t=s[e];if(t.enabled){if(m===-1&&(m=e),h=e,c=Math.min(c,t.resolution===`inherit`?r:t.resolution),l+=t.padding,t.antialias===`off`?u=!1:t.antialias===`inherit`&&(u&&=n),t.clipToViewport||(p=!1),!(t.compatibleRenderers&a.type)){f=!1;break}if(t.blendRequired&&!(a.backBuffer?.useBackBuffer??!0)){U("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),f=!1;break}f=!0,d||=t.blendRequired}}f?(p&&o.fitBounds(0,t.width/r,0,t.height/r),o.scale(c).ceil().scale(1/c).pad((l|0)*i),o.isPositive?(e.antialias=u,e.resolution=c,e.blendRequired=d,e.firstEnabledIndex=m,e.lastEnabledIndex=h):e.skip=!0):e.skip=!0}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){for(let e=this._filterStackIndex-2;e>=0;e--){let t=this._filterStack[e];if(!t.skip)return t}return null}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||=this._filterStack[this._filterStackIndex]=new zf,this._filterStackIndex++,e}},Bf.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:`filter`}})),Hf=s((()=>{R(),zu(),Vu(),Vf(),L.add(Bf,Ru),L.add(Bu)})),Uf=l({}),Wf=s((()=>{hc(),bc(),Hc(),xl(),nu(),Hf()}));R();var Gf={extension:{type:I.Environment,name:`browser`,priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>(Wf(),Uf))}},Kf=l({}),qf=s((()=>{xl(),nu(),Hf()}));R();var Jf={extension:{type:I.Environment,name:`webworker`,priority:0},test:()=>typeof self<`u`&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>(qf(),Kf))}};async function Yf(e){if(!e)for(let e=0;e<Xf.length;e++){let t=Xf[e];if(t.value.test()){await t.value.load();return}}}var Xf,Zf=s((()=>{R(),Xf=[],L.handleByNamedList(I.Environment,Xf)}));function Qf(){if(typeof $f==`boolean`)return $f;try{$f=Function(`param1`,`param2`,`param3`,`return param1[param2] === param3;`)({a:`b`},`a`,`b`)===!0}catch{$f=!1}return $f}var $f,ep=s((()=>{}));function tp(e,t,n=2){let r=t&&t.length,i=r?t[0]*n:e.length;Rp.size&&Rp.clear();let a=np(e,0,i,n,!0),o=[];if(!a||a.next===a.prev)return o;let s=0,c=0,l=0;if(r&&(a=lp(e,t,a,n)),e.length>80*n){s=e[0],c=e[1];let t=s,r=c;for(let a=n;a<i;a+=n){let n=e[a],i=e[a+1];n<s&&(s=n),i<c&&(c=i),n>t&&(t=n),i>r&&(r=i)}l=Math.max(t-s,r-c),l=l===0?0:32767/l}return ip(a,o,s,c,l),o}function np(e,t,n,r,i){let a=null;if(i===Lp(e,t,n,r)>0)for(let i=t;i<n;i+=r)a=Pp(i/r|0,e[i],e[i+1],a);else for(let i=n-r;i>=t;i-=r)a=Pp(i/r|0,e[i],e[i+1],a);return a&&Dp(a,a.next)&&(Fp(a),a=a.next),a}function rp(e,t=e){let n=t===e,r=e,i;do i=!1,r!==r.next&&(Rp.size===0||!Rp.has(r))&&(Dp(r,r.next)||Ep(r.prev,r,r.next)===0)?((n||r===t)&&(t=r.prev),zp=!0,Fp(r),r=r.prev,i=!0):(n||r!==t)&&(r=r.next,i=!n);while(i||r!==t);return t}function ip(e,t,n,r,i){i&&yp(e,n,r,i);let a=e,o=!1;for(;e.prev!==e.next;){let s=e.prev,c=e.next;if(Ep(s,e,c)<0&&(i?op(e,n,r,i):ap(e)))t.push(s.i,e.i,c.i),Fp(e),e=c,a=c;else if(e=c,e===a){if(zp=!1,e=rp(e),zp){a=e;continue}if(!o){e=sp(e,t),a=e,o=!0;continue}cp(e,t,n,r,i);break}}}function ap(e){let t=e.prev,n=e,r=e.next,i=t.x,a=n.x,o=r.x,s=t.y,c=n.y,l=r.y,u=Math.min(i,a,o),d=Math.min(s,c,l),f=Math.max(i,a,o),p=Math.max(s,c,l),m=r.next;for(;m!==t;){if(m.x>=u&&m.x<=f&&m.y>=d&&m.y<=p&&(i!==m.x||s!==m.y)&&wp(i,s,a,c,o,l,m.x,m.y)&&Ep(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function op(e,t,n,r){let i=e.prev,a=e,o=e.next,s=i.x,c=a.x,l=o.x,u=i.y,d=a.y,f=o.y,p=Math.min(s,c,l),m=Math.min(u,d,f),h=Math.max(s,c,l),g=Math.max(u,d,f),_=Sp(p,m,t,n,r),v=Sp(h,g,t,n,r),y=e.prevZ;for(;y&&y.z>=_;){if(y.x>=p&&y.x<=h&&y.y>=m&&y.y<=g&&y!==o&&(s!==y.x||u!==y.y)&&wp(s,u,c,d,l,f,y.x,y.y)&&Ep(y.prev,y,y.next)>=0)return!1;y=y.prevZ}let b=e.nextZ;for(;b&&b.z<=v;){if(b.x>=p&&b.x<=h&&b.y>=m&&b.y<=g&&b!==o&&(s!==b.x||u!==b.y)&&wp(s,u,c,d,l,f,b.x,b.y)&&Ep(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function sp(e,t){let n=e,r=!1;do{let i=n.prev,a=n.next.next;Op(i,n,n.next,a,!1)&&jp(i,a)&&jp(a,i)&&(t.push(i.i,n.i,a.i),Fp(n),Fp(n.next),n=e=a,r=!0),n=n.next}while(n!==e);return r?rp(n):n}function cp(e,t,n,r,i){let a=e;do{let e=a.next.next;for(;e!==a.prev;){if(a.i!==e.i&&Tp(a,e)){let o=Np(a,e);a=rp(a,a.next),o=rp(o,o.next),ip(a,t,n,r,i),ip(o,t,n,r,i);return}e=e.next}a=a.next}while(a!==e)}function lp(e,t,n,r){let i=[];for(let n=0,a=t.length;n<a;n++){let o=np(e,t[n]*r,n<a-1?t[n+1]*r:e.length,r,!1);o===o.next&&Rp.add(o),i.push(Cp(o))}i.sort(up),fp(e.length/r,t.length),pp(n,n),Bp=!0;for(let e=0;e<i.length;e++)n=dp(i[e],n);return Bp=!1,rp(n)}function up(e,t){return e.x-t.x||e.y-t.y||(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)}function dp(e,t){let n=_p(e,t);if(!n)return t;let r=Np(n,e),i=r.next;return pp(n,i.next),rp(r,r.next),rp(n,n.next)}function fp(e,t){let n=Math.ceil((e+2*t)/Vp)+t+2;Hp.length<n*4&&(Hp=new Float64Array(n*4)),Up=0}function pp(e,t){let n=e;do{let e=Up++;Wp[e]=n;let r=n.x,i=n.y,a=n.x,o=n.y,s=0;do{let t=n.next;n.z=e,t.x<r&&(r=t.x),t.x>a&&(a=t.x),t.y<i&&(i=t.y),t.y>o&&(o=t.y),n=t}while(++s<Vp&&n!==t);Gp[e]=n;let c=e*4;Hp[c]=r,Hp[c+1]=i,Hp[c+2]=a,Hp[c+3]=o}while(n!==t)}function mp(e,t){let n=e.z*4;t.x<Hp[n]&&(Hp[n]=t.x),t.y<Hp[n+1]&&(Hp[n+1]=t.y),t.x>Hp[n+2]&&(Hp[n+2]=t.x),t.y>Hp[n+3]&&(Hp[n+3]=t.y)}function hp(e){let t=Gp[e];for(;t.prev.next!==t;)t=t.next;return Gp[e]=t,t}function gp(e){let t=Wp[e];for(;t.prev.next!==t;)t=t.next;return Wp[e]=t,t}function _p(e,t){let n=t,r=e.x,i=e.y,a=-1/0,o;if(Dp(e,n))return n;for(let t=0,s=0;t<Up;t++,s+=4){if(i<Hp[s+1]||i>Hp[s+3]||Hp[s]>r||Hp[s+2]<=a)continue;let c=hp(t);n=gp(t);do{if(n.prev.next===n){if(Dp(e,n.next))return n.next;if(i<=n.y&&i>=n.next.y&&n.next.y!==n.y){let e=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=r&&e>a&&(a=e,o=n.x<n.next.x?n:n.next,e===r))return o}}n=n.next}while(n!==c)}if(!o)return null;let s=o.x,c=o.y,l=Math.min(i,c),u=Math.max(i,c),d=1/0;for(let t=0,f=0;t<Up;t++,f+=4){if(Hp[f+2]<s||Hp[f]>r||Hp[f+3]<l||Hp[f+1]>u)continue;let p=hp(t);n=gp(t);do{if(n.prev.next===n&&r>=n.x&&n.x>=s&&r!==n.x&&wp(i<c?r:a,i,s,c,i<c?a:r,i,n.x,n.y)){let t=Math.abs(i-n.y)/(r-n.x);(jp(n,e)||n.y===i&&n.next.y===i&&n.next.x>r)&&(t<d||t===d&&(n.x>o.x||n.x===o.x&&vp(o,n)))&&(o=n,d=t)}n=n.next}while(n!==p)}return o}function vp(e,t){return Ep(e.prev,e,t.prev)<0&&Ep(t.next,e,e.next)<0}function yp(e,t,n,r){let i=e,a=0;do i.z=Sp(i.x,i.y,t,n,r),Kp[a++]=i,i=i.next;while(i!==e);bp(a);let o=null;for(let e=0;e<a;e++){let t=Kp[e];t.prevZ=o,o&&(o.nextZ=t),o=t}o.nextZ=null,Kp.fill(null,0,a),qp.fill(null,0,a)}function bp(e){if(e<=32)for(let t=1;t<e;t++){let e=Kp[t],n=e.z,r=t-1;for(;r>=0&&Kp[r].z>n;)Kp[r+1]=Kp[r],r--;Kp[r+1]=e}else{Jp.length<e&&(Jp=new Uint32Array(e),Yp=new Uint32Array(e),qp=Array(e));for(let t=0;t<e;t++)Jp[t]=Kp[t].z;xp(e,Kp,Jp,qp,Yp,0),xp(e,qp,Yp,Kp,Jp,8),xp(e,Kp,Jp,qp,Yp,16),xp(e,qp,Yp,Kp,Jp,24)}}function xp(e,t,n,r,i,a){Xp.fill(0);for(let t=0;t<e;t++)Xp[n[t]>>>a&255]++;let o=0;for(let e=0;e<256;e++){let t=Xp[e];Xp[e]=o,o+=t}for(let o=0;o<e;o++){let e=n[o],s=Xp[e>>>a&255]++;r[s]=t[o],i[s]=e}}function Sp(e,t,n,r,i){return e=(e-n)*i|0,t=(t-r)*i|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,e|t<<1}function Cp(e){let t=e,n=e;do(t.x<n.x||t.x===n.x&&t.y<n.y)&&(n=t),t=t.next;while(t!==e);return n}function wp(e,t,n,r,i,a,o,s){return(i-o)*(t-s)>=(e-o)*(a-s)&&(e-o)*(r-s)>=(n-o)*(t-s)&&(n-o)*(a-s)>=(i-o)*(r-s)}function Tp(e,t){let n=Dp(e,t)&&Ep(e.prev,e,e.next)>0&&Ep(t.prev,t,t.next)>0;return e.next.i!==t.i&&(n||jp(e,t)&&jp(t,e)&&(Ep(e.prev,e,t.prev)!==0||Ep(e,t.prev,t)!==0))&&!Ap(e,t)&&(n||Mp(e,t))}function Ep(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function Dp(e,t){return e.x===t.x&&e.y===t.y}function Op(e,t,n,r,i=!0){let a=Ep(e,t,n),o=Ep(e,t,r),s=Ep(n,r,e),c=Ep(n,r,t);return(a>0&&o<0||a<0&&o>0)&&(s>0&&c<0||s<0&&c>0)?!0:i?!!(a===0&&kp(e,n,t)||o===0&&kp(e,r,t)||s===0&&kp(n,e,r)||c===0&&kp(n,t,r)):!1}function kp(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function Ap(e,t){let n=Math.min(e.x,t.x),r=Math.max(e.x,t.x),i=Math.min(e.y,t.y),a=Math.max(e.y,t.y),o=e;do{let s=o.next;if(o.x>r&&s.x>r||o.x<n&&s.x<n||o.y>a&&s.y>a||o.y<i&&s.y<i)o=s;else{if(o.i!==e.i&&s.i!==e.i&&o.i!==t.i&&s.i!==t.i&&Op(o,s,e,t))return!0;o=s}}while(o!==e);return!1}function jp(e,t){return Ep(e.prev,e,e.next)<0?Ep(e,t,e.next)>=0&&Ep(e,e.prev,t)>=0:Ep(e,t,e.prev)<0||Ep(e,e.next,t)<0}function Mp(e,t){let n=e,r=!1,i=(e.x+t.x)/2,a=(e.y+t.y)/2;do{let e=n.next;n.y>a!=e.y>a&&i<(e.x-n.x)*(a-n.y)/(e.y-n.y)+n.x&&(r=!r),n=e}while(n!==e);return r}function Np(e,t){let n=Ip(e.i,e.x,e.y),r=Ip(t.i,t.x,t.y),i=e.next,a=t.prev;return e.next=t,t.prev=e,n.next=i,i.prev=n,r.next=n,n.prev=r,a.next=r,r.prev=a,r}function Pp(e,t,n,r){let i=Ip(e,t,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function Fp(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ),Bp&&mp(e.prev,e.next)}function Ip(e,t,n){return{i:e,x:t,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null}}function Lp(e,t,n,r){let i=0;for(let a=t,o=n-r;a<n;a+=r)i+=(e[o]-e[a])*(e[a+1]+e[o+1]),o=a;return i}var Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp=s((()=>{Rp=new Set,zp=!1,Bp=!1,Vp=16,Hp=new Float64Array,Up=0,Wp=[],Gp=[],Kp=[],qp=[],Jp=new Uint32Array,Yp=new Uint32Array,Xp=new Uint32Array(256)})),Qp,$p=s((()=>{Zp(),ri(),Qp=tp.default||tp})),em,tm=s((()=>{em=(e=>(e[e.NONE=0]=`NONE`,e[e.COLOR=16384]=`COLOR`,e[e.STENCIL=1024]=`STENCIL`,e[e.DEPTH=256]=`DEPTH`,e[e.COLOR_DEPTH=16640]=`COLOR_DEPTH`,e[e.COLOR_STENCIL=17408]=`COLOR_STENCIL`,e[e.DEPTH_STENCIL=1280]=`DEPTH_STENCIL`,e[e.ALL=17664]=`ALL`,e))(em||{})})),nm,rm=s((()=>{nm=class{constructor(e){this.items=[],this._name=e}emit(e,t,n,r,i,a,o,s){let{name:c,items:l}=this;for(let u=0,d=l.length;u<d;u++)l[u][c](e,t,n,r,i,a,o,s);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){let t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}})),im,am,om,sm=s((()=>{Ri(),Zf(),xs(),ep(),ea(),oa(),ua(),tm(),rm(),ri(),im=[`init`,`destroy`,`contextChange`,`resolutionChange`,`resetState`,`renderEnd`,`renderStart`,`render`,`update`,`postrender`,`prerender`],am=class e extends ni{constructor(e){super(),this.tick=0,this.uid=Qi(`renderer`),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;let t=[...im,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(t={}){let n=t.skipExtensionImports===!0||t.manageImports===!1;await Yf(n),!n&&this.config.loaders&&await Promise.all(this.config.loaders.map(e=>e.value.load())),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(let e in this._systemsHash)t={...this._systemsHash[e].constructor.defaultOptions,...t};t={...e.defaultOptions,...t},this._roundPixels=+!!t.roundPixels;for(let e=0;e<this.runners.init.items.length;e++)await this.runners.init.items[e].init(t);this._initOptions=t}render(e,t){this.tick++;let n=e;if(n instanceof J&&(n={container:n},t&&(H(V,`passing a second argument is deprecated, please use render options instead`),n.target=t.renderTexture)),n.target||(n.target=this.view.renderTarget),n.target===this.view.renderTarget&&(this._lastObjectRendered=n.container,n.clearColor??(n.clearColor=this.background.colorRgba),n.clear??(n.clear=this.background.clearBeforeRender)),n.clearColor){let e=Array.isArray(n.clearColor)&&n.clearColor.length===4;n.clearColor=e?n.clearColor:Li.shared.setValue(n.clearColor).toArray()}n.transform||(n.container.updateLocalTransform(),n.transform=n.container.localTransform),n.container.visible&&(n.container.enableRenderGroup(),this.runners.prerender.emit(n),this.runners.renderStart.emit(n),this.runners.render.emit(n),this.runners.renderEnd.emit(n),this.runners.postrender.emit(n))}resize(e,t,n){let r=this.view.resolution;this.view.resize(e,t,n),this.emit(`resize`,this.view.screen.width,this.view.screen.height,this.view.resolution),n!==void 0&&n!==r&&this.runners.resolutionChange.emit(n)}clear(e={}){let t=this;e.target||=t.renderTarget.renderTarget,e.clearColor||=this.background.colorRgba,e.clear??=em.ALL;let{clear:n,clearColor:r,target:i,mipLevel:a,layer:o}=e;Li.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(i,n,Li.shared.toArray(),a??0,o??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(e=>{this.runners[e]=new nm(e)})}_addSystems(e){let t;for(t in e){let n=e[t];this._addSystem(n.value,n.name)}}_addSystem(e,t){let n=new e(this);if(this[t])throw Error(`Whoops! The name "${t}" is already in use`);this[t]=n,this._systemsHash[t]=n;for(let e in this.runners)this.runners[e].add(n);return this}_addPipes(e,t){let n=t.reduce((e,t)=>(e[t.name]=t.value,e),{});e.forEach(e=>{let t=e.value,r=e.name,i=n[r];this.renderPipes[r]=new t(this,i?new i:null),this.runners.destroy.add(this.renderPipes[r])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e==`object`&&e.releaseGlobalResources)&&la.release(),Object.values(this.runners).forEach(e=>{e.destroy()}),this._systemsHash=null,this.renderPipes=null,this.removeAllListeners()}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Qf())throw Error(`Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.`)}resetState(){this.runners.resetState.emit()}},am.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1},om=am}));Jc(),sm();var cm;function lm(e){return cm===void 0&&(cm=(()=>{let t={stencil:!0,failIfMajorPerformanceCaveat:e??om.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Y.get().getWebGLRenderingContext())return!1;let e=Y.get().createCanvas().getContext(`webgl`,t),n=!!e?.getContextAttributes()?.stencil;if(e){let t=e.getExtension(`WEBGL_lose_context`);t&&t.loseContext()}return e=null,n}catch{return!1}})()),cm}Jc();var um;async function dm(e={}){return um===void 0&&(um=await(async()=>{let t=Y.get().getNavigator().gpu;if(!t)return!1;try{return await(await t.requestAdapter(e)).requestDevice(),!0}catch{return!1}})()),um}function fm(e,t,n){let r=2166136261;for(let n=0;n<t;n++)r^=e[n].uid,r=Math.imul(r,16777619),r>>>=0;return mm[r]||pm(e,t,r,n)}function pm(e,t,n,r){let i={},a=0;for(let n=0;n<r;n++){let r=n<t?e[n]:q.EMPTY.source;i[a++]=r.source,i[a++]=r.style}let o=new Hd(i);return mm[n]=o,o}var mm,hm=s((()=>{Ud(),$o(),mm={}}));function gm(e,t,n){if(e)for(let r in e){let i=t[r.toLocaleLowerCase()];if(i){let t=e[r];r===`header`&&(t=t.replace(/@in\s+[^;]+;\s*/g,``).replace(/@out\s+[^;]+;\s*/g,``)),n&&i.push(`//----${n}----//`),i.push(t)}else U(`${r} placement hook does not exist in shader`)}}var _m=s((()=>{W()}));function vm(e){let t={};return(e.match(ym)?.map(e=>e.replace(/[{()}]/g,``))??[]).forEach(e=>{t[e]=[]}),t}var ym,bm=s((()=>{ym=/\{\{(.*?)\}\}/g}));function xm(e,t){let n,r=/@in\s+([^;]+);/g;for(;(n=r.exec(e))!==null;)t.push(n[1])}function Sm(e,t,n=!1){let r=[];xm(t,r),e.forEach(e=>{e.header&&xm(e.header,r)});let i=r;n&&i.sort();let a=i.map((e,t)=>` @location(${t}) ${e},`).join(`
|
|
124
|
-
`),o=t.replace(/@in\s+[^;]+;\s*/g,``);return o=o.replace(`{{in}}`,`
|
|
125
|
-
${a}
|
|
126
|
-
`),o}var Cm=s((()=>{}));function wm(e,t){let n,r=/@out\s+([^;]+);/g;for(;(n=r.exec(e))!==null;)t.push(n[1])}function Tm(e){let t=/\b(\w+)\s*:/g.exec(e);return t?t[1]:``}function Em(e){return e.replace(/@.*?\s+/g,``)}function Dm(e,t){let n=[];wm(t,n),e.forEach(e=>{e.header&&wm(e.header,n)});let r=0,i=n.sort().map(e=>e.indexOf(`builtin`)>-1?e:`@location(${r++}) ${e}`).join(`,
|
|
127
|
-
`),a=n.sort().map(e=>` var ${Em(e)};`).join(`
|
|
128
|
-
`),o=`return VSOutput(
|
|
129
|
-
${n.sort().map(e=>` ${Tm(e)}`).join(`,
|
|
130
|
-
`)});`,s=t.replace(/@out\s+[^;]+;\s*/g,``);return s=s.replace(`{{struct}}`,`
|
|
131
|
-
${i}
|
|
132
|
-
`),s=s.replace(`{{start}}`,`
|
|
133
|
-
${a}
|
|
134
|
-
`),s=s.replace(`{{return}}`,`
|
|
135
|
-
${o}
|
|
136
|
-
`),s}var Om=s((()=>{}));function km(e,t){let n=e;for(let e in t){let r=t[e];n=r.join(`
|
|
137
|
-
`).length?n.replace(`{{${e}}}`,`//-----${e} START-----//
|
|
138
|
-
${r.join(`
|
|
139
|
-
`)}
|
|
140
|
-
//----${e} FINISH----//`):n.replace(`{{${e}}}`,``)}return n}var Am=s((()=>{}));function jm({template:e,bits:t}){let n=Pm(e,t);if(Im[n])return Im[n];let{vertex:r,fragment:i}=Nm(e,t);return Im[n]=Fm(r,i,t),Im[n]}function Mm({template:e,bits:t}){let n=Pm(e,t);return Im[n]||(Im[n]=Fm(e.vertex,e.fragment,t)),Im[n]}function Nm(e,t){let n=t.map(e=>e.vertex).filter(e=>!!e),r=t.map(e=>e.fragment).filter(e=>!!e),i=Sm(n,e.vertex,!0);i=Dm(n,i);let a=Sm(r,e.fragment,!0);return{vertex:i,fragment:a}}function Pm(e,t){return t.map(e=>(Lm.has(e)||Lm.set(e,Rm++),Lm.get(e))).sort((e,t)=>e-t).join(`-`)+e.vertex+e.fragment}function Fm(e,t,n){let r=vm(e),i=vm(t);return n.forEach(e=>{gm(e.vertex,r,e.name),gm(e.fragment,i,e.name)}),{vertex:km(e,r),fragment:km(t,i)}}var Im,Lm,Rm,zm=s((()=>{_m(),bm(),Cm(),Om(),Am(),Im=Object.create(null),Lm=new Map,Rm=0})),Bm,Vm,Hm,Um,Wm=s((()=>{Bm=`
|
|
141
|
-
@in aPosition: vec2<f32>;
|
|
142
|
-
@in aUV: vec2<f32>;
|
|
143
|
-
|
|
144
|
-
@out @builtin(position) vPosition: vec4<f32>;
|
|
145
|
-
@out vUV : vec2<f32>;
|
|
146
|
-
@out vColor : vec4<f32>;
|
|
147
|
-
|
|
148
|
-
{{header}}
|
|
149
|
-
|
|
150
|
-
struct VSOutput {
|
|
151
|
-
{{struct}}
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
@vertex
|
|
155
|
-
fn main( {{in}} ) -> VSOutput {
|
|
156
|
-
|
|
157
|
-
var worldTransformMatrix = globalUniforms.uWorldTransformMatrix;
|
|
158
|
-
var modelMatrix = mat3x3<f32>(
|
|
159
|
-
1.0, 0.0, 0.0,
|
|
160
|
-
0.0, 1.0, 0.0,
|
|
161
|
-
0.0, 0.0, 1.0
|
|
162
|
-
);
|
|
163
|
-
var position = aPosition;
|
|
164
|
-
var uv = aUV;
|
|
165
|
-
|
|
166
|
-
{{start}}
|
|
167
|
-
|
|
168
|
-
vColor = vec4<f32>(1., 1., 1., 1.);
|
|
169
|
-
|
|
170
|
-
{{main}}
|
|
171
|
-
|
|
172
|
-
vUV = uv;
|
|
173
|
-
|
|
174
|
-
var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix;
|
|
175
|
-
|
|
176
|
-
vPosition = vec4<f32>((modelViewProjectionMatrix * vec3<f32>(position, 1.0)).xy, 0.0, 1.0);
|
|
177
|
-
|
|
178
|
-
vColor *= globalUniforms.uWorldColorAlpha;
|
|
179
|
-
|
|
180
|
-
{{end}}
|
|
181
|
-
|
|
182
|
-
{{return}}
|
|
183
|
-
};
|
|
184
|
-
`,Vm=`
|
|
185
|
-
@in vUV : vec2<f32>;
|
|
186
|
-
@in vColor : vec4<f32>;
|
|
187
|
-
|
|
188
|
-
{{header}}
|
|
189
|
-
|
|
190
|
-
@fragment
|
|
191
|
-
fn main(
|
|
192
|
-
{{in}}
|
|
193
|
-
) -> @location(0) vec4<f32> {
|
|
194
|
-
|
|
195
|
-
{{start}}
|
|
196
|
-
|
|
197
|
-
var outColor:vec4<f32>;
|
|
198
|
-
|
|
199
|
-
{{main}}
|
|
200
|
-
|
|
201
|
-
var finalColor:vec4<f32> = outColor * vColor;
|
|
202
|
-
|
|
203
|
-
{{end}}
|
|
204
|
-
|
|
205
|
-
return finalColor;
|
|
206
|
-
};
|
|
207
|
-
`,Hm=`
|
|
208
|
-
in vec2 aPosition;
|
|
209
|
-
in vec2 aUV;
|
|
210
|
-
|
|
211
|
-
out vec4 vColor;
|
|
212
|
-
out vec2 vUV;
|
|
213
|
-
|
|
214
|
-
{{header}}
|
|
215
|
-
|
|
216
|
-
void main(void){
|
|
217
|
-
|
|
218
|
-
mat3 worldTransformMatrix = uWorldTransformMatrix;
|
|
219
|
-
mat3 modelMatrix = mat3(
|
|
220
|
-
1.0, 0.0, 0.0,
|
|
221
|
-
0.0, 1.0, 0.0,
|
|
222
|
-
0.0, 0.0, 1.0
|
|
223
|
-
);
|
|
224
|
-
vec2 position = aPosition;
|
|
225
|
-
vec2 uv = aUV;
|
|
226
|
-
|
|
227
|
-
{{start}}
|
|
228
|
-
|
|
229
|
-
vColor = vec4(1.);
|
|
230
|
-
|
|
231
|
-
{{main}}
|
|
232
|
-
|
|
233
|
-
vUV = uv;
|
|
234
|
-
|
|
235
|
-
mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix;
|
|
236
|
-
|
|
237
|
-
gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
|
|
238
|
-
|
|
239
|
-
vColor *= uWorldColorAlpha;
|
|
240
|
-
|
|
241
|
-
{{end}}
|
|
242
|
-
}
|
|
243
|
-
`,Um=`
|
|
244
|
-
|
|
245
|
-
in vec4 vColor;
|
|
246
|
-
in vec2 vUV;
|
|
247
|
-
|
|
248
|
-
out vec4 finalColor;
|
|
249
|
-
|
|
250
|
-
{{header}}
|
|
251
|
-
|
|
252
|
-
void main(void) {
|
|
253
|
-
|
|
254
|
-
{{start}}
|
|
255
|
-
|
|
256
|
-
vec4 outColor;
|
|
257
|
-
|
|
258
|
-
{{main}}
|
|
259
|
-
|
|
260
|
-
finalColor = outColor * vColor;
|
|
261
|
-
|
|
262
|
-
{{end}}
|
|
263
|
-
}
|
|
264
|
-
`})),Gm,Km,qm=s((()=>{Gm={name:`global-uniforms-bit`,vertex:{header:`
|
|
265
|
-
struct GlobalUniforms {
|
|
266
|
-
uProjectionMatrix:mat3x3<f32>,
|
|
267
|
-
uWorldTransformMatrix:mat3x3<f32>,
|
|
268
|
-
uWorldColorAlpha: vec4<f32>,
|
|
269
|
-
uResolution: vec2<f32>,
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
@group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
|
|
273
|
-
`}},Km={name:`global-uniforms-bit`,vertex:{header:`
|
|
274
|
-
uniform mat3 uProjectionMatrix;
|
|
275
|
-
uniform mat3 uWorldTransformMatrix;
|
|
276
|
-
uniform vec4 uWorldColorAlpha;
|
|
277
|
-
uniform vec2 uResolution;
|
|
278
|
-
`}}}));function Jm({bits:e,name:t}){let n=jm({template:{fragment:Vm,vertex:Bm},bits:[Gm,...e]});return Bd.from({name:t,vertex:{source:n.vertex,entryPoint:`main`},fragment:{source:n.fragment,entryPoint:`main`}})}function Ym({bits:e,name:t}){return new _d({name:t,...Mm({template:{vertex:Hm,fragment:Um},bits:[Km,...e]})})}var Xm=s((()=>{vd(),Vd(),zm(),Wm(),qm()})),Zm,Qm,$m=s((()=>{Zm={name:`color-bit`,vertex:{header:`
|
|
279
|
-
@in aColor: vec4<f32>;
|
|
280
|
-
`,main:`
|
|
281
|
-
vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
|
|
282
|
-
`}},Qm={name:`color-bit`,vertex:{header:`
|
|
283
|
-
in vec4 aColor;
|
|
284
|
-
`,main:`
|
|
285
|
-
vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
|
|
286
|
-
`}}}));function eh(e){let t=[];if(e===1)t.push(`@group(1) @binding(0) var textureSource1: texture_2d<f32>;`),t.push(`@group(1) @binding(1) var textureSampler1: sampler;`);else{let n=0;for(let r=0;r<e;r++)t.push(`@group(1) @binding(${n++}) var textureSource${r+1}: texture_2d<f32>;`),t.push(`@group(1) @binding(${n++}) var textureSampler${r+1}: sampler;`)}return t.join(`
|
|
287
|
-
`)}function th(e){let t=[];if(e===1)t.push(`outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);`);else{t.push(`switch vTextureId {`);for(let n=0;n<e;n++)n===e-1?t.push(` default:{`):t.push(` case ${n}:{`),t.push(` outColor = textureSampleGrad(textureSource${n+1}, textureSampler${n+1}, vUV, uvDx, uvDy);`),t.push(` break;}`);t.push(`}`)}return t.join(`
|
|
288
|
-
`)}function nh(e){return ah[e]||(ah[e]={name:`texture-batch-bit`,vertex:{header:`
|
|
289
|
-
@in aTextureIdAndRound: vec2<u32>;
|
|
290
|
-
@out @interpolate(flat) vTextureId : u32;
|
|
291
|
-
`,main:`
|
|
292
|
-
vTextureId = aTextureIdAndRound.y;
|
|
293
|
-
`,end:`
|
|
294
|
-
if(aTextureIdAndRound.x == 1)
|
|
295
|
-
{
|
|
296
|
-
vPosition = vec4<f32>(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
297
|
-
}
|
|
298
|
-
`},fragment:{header:`
|
|
299
|
-
@in @interpolate(flat) vTextureId: u32;
|
|
300
|
-
|
|
301
|
-
${eh(e)}
|
|
302
|
-
`,main:`
|
|
303
|
-
var uvDx = dpdx(vUV);
|
|
304
|
-
var uvDy = dpdy(vUV);
|
|
305
|
-
|
|
306
|
-
${th(e)}
|
|
307
|
-
`}}),ah[e]}function rh(e){let t=[];for(let n=0;n<e;n++)n>0&&t.push(`else`),n<e-1&&t.push(`if(vTextureId < ${n}.5)`),t.push(`{`),t.push(` outColor = texture(uTextures[${n}], vUV);`),t.push(`}`);return t.join(`
|
|
308
|
-
`)}function ih(e){return oh[e]||(oh[e]={name:`texture-batch-bit`,vertex:{header:`
|
|
309
|
-
in vec2 aTextureIdAndRound;
|
|
310
|
-
out float vTextureId;
|
|
311
|
-
|
|
312
|
-
`,main:`
|
|
313
|
-
vTextureId = aTextureIdAndRound.y;
|
|
314
|
-
`,end:`
|
|
315
|
-
if(aTextureIdAndRound.x == 1.)
|
|
316
|
-
{
|
|
317
|
-
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
318
|
-
}
|
|
319
|
-
`},fragment:{header:`
|
|
320
|
-
in float vTextureId;
|
|
321
|
-
|
|
322
|
-
uniform sampler2D uTextures[${e}];
|
|
323
|
-
|
|
324
|
-
`,main:`
|
|
325
|
-
|
|
326
|
-
${rh(e)}
|
|
327
|
-
`}}),oh[e]}var ah,oh,sh=s((()=>{ah={},oh={}})),ch,lh,uh,dh=s((()=>{ch={name:`local-uniform-bit`,vertex:{header:`
|
|
328
|
-
|
|
329
|
-
struct LocalUniforms {
|
|
330
|
-
uTransformMatrix:mat3x3<f32>,
|
|
331
|
-
uColor:vec4<f32>,
|
|
332
|
-
uRound:f32,
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
@group(1) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
336
|
-
`,main:`
|
|
337
|
-
vColor *= localUniforms.uColor;
|
|
338
|
-
modelMatrix *= localUniforms.uTransformMatrix;
|
|
339
|
-
`,end:`
|
|
340
|
-
if(localUniforms.uRound == 1)
|
|
341
|
-
{
|
|
342
|
-
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
343
|
-
}
|
|
344
|
-
`}},lh={...ch,vertex:{...ch.vertex,header:ch.vertex.header.replace(`group(1)`,`group(2)`)}},uh={name:`local-uniform-bit`,vertex:{header:`
|
|
345
|
-
|
|
346
|
-
uniform mat3 uTransformMatrix;
|
|
347
|
-
uniform vec4 uColor;
|
|
348
|
-
uniform float uRound;
|
|
349
|
-
`,main:`
|
|
350
|
-
vColor *= uColor;
|
|
351
|
-
modelMatrix = uTransformMatrix;
|
|
352
|
-
`,end:`
|
|
353
|
-
if(uRound == 1.)
|
|
354
|
-
{
|
|
355
|
-
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
356
|
-
}
|
|
357
|
-
`}}})),fh,ph,mh=s((()=>{fh={name:`round-pixels-bit`,vertex:{header:`
|
|
358
|
-
fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
|
|
359
|
-
{
|
|
360
|
-
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
361
|
-
}
|
|
362
|
-
`}},ph={name:`round-pixels-bit`,vertex:{header:`
|
|
363
|
-
vec2 roundPixels(vec2 position, vec2 targetSize)
|
|
364
|
-
{
|
|
365
|
-
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
366
|
-
}
|
|
367
|
-
`}}})),hh,gh=s((()=>{R(),B(),hm(),Xm(),$m(),sh(),dh(),mh(),rf(),tf(),hh=class{constructor(){this._maxTextures=0}contextChange(e){let t=new ef({uTransformMatrix:{value:new z,type:`mat3x3<f32>`},uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uRound:{value:0,type:`f32`}});this._maxTextures=e.limits.maxBatchableTextures;let n=Jm({name:`graphics`,bits:[Zm,nh(this._maxTextures),lh,fh]});this.shader=new nf({gpuProgram:n,resources:{localUniforms:t}})}execute(e,t){let n=t.context,r=n.customShader||this.shader,i=e.renderer,{batcher:a,instructions:o}=i.graphicsContext.getContextRenderData(n),s=i.encoder;s.setGeometry(a.geometry,r.gpuProgram);let c=i.globalUniforms.bindGroup;s.setBindGroup(0,c,r.gpuProgram);let l=i.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);s.setBindGroup(2,l,r.gpuProgram);let u=o.instructions,d=null;for(let t=0;t<o.instructionSize;t++){let n=u[t];if(n.topology!==d&&(d=n.topology,s.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,n.topology,r._overrides)),r.groups[1]=n.bindGroup,!n.gpuBindGroup){let e=n.textures;n.bindGroup=fm(e.textures,e.count,this._maxTextures),n.gpuBindGroup=i.bindGroup.getBindGroup(n.bindGroup,r.gpuProgram,1)}s.setBindGroup(1,n.bindGroup,r.gpuProgram),s.renderPassEncoder.drawIndexed(n.size,1,n.start)}}destroy(){this.shader.destroy(),this.shader=null}},hh.extension={type:[I.WebGPUPipesAdaptor],name:`graphics`}})),_h,vh,yh=s((()=>{_h={name:`texture-bit`,vertex:{header:`
|
|
368
|
-
|
|
369
|
-
struct TextureUniforms {
|
|
370
|
-
uTextureMatrix:mat3x3<f32>,
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
@group(2) @binding(2) var<uniform> textureUniforms : TextureUniforms;
|
|
374
|
-
`,main:`
|
|
375
|
-
uv = (textureUniforms.uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
376
|
-
`},fragment:{header:`
|
|
377
|
-
@group(2) @binding(0) var uTexture: texture_2d<f32>;
|
|
378
|
-
@group(2) @binding(1) var uSampler: sampler;
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
`,main:`
|
|
382
|
-
outColor = textureSample(uTexture, uSampler, vUV);
|
|
383
|
-
`}},vh={name:`texture-bit`,vertex:{header:`
|
|
384
|
-
uniform mat3 uTextureMatrix;
|
|
385
|
-
`,main:`
|
|
386
|
-
uv = (uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
387
|
-
`},fragment:{header:`
|
|
388
|
-
uniform sampler2D uTexture;
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
`,main:`
|
|
392
|
-
outColor = texture(uTexture, vUV);
|
|
393
|
-
`}}})),bh,xh=s((()=>{R(),B(),Xm(),dh(),mh(),yh(),rf(),$o(),W(),bh=class{init(){let e=Jm({name:`mesh`,bits:[ch,_h,fh]});this._shader=new nf({gpuProgram:e,resources:{uTexture:q.EMPTY._source,uSampler:q.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:`mat3x3<f32>`,value:new z}}}})}execute(e,t){let n=e.renderer,r=t._shader;if(!r)r=this._shader,r.groups[2]=n.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){U(`Mesh shader has no gpuProgram`,t.shader);return}let i=r.gpuProgram;if(i.autoAssignGlobalUniforms&&(r.groups[0]=n.globalUniforms.bindGroup),i.autoAssignLocalUniforms){let t=e.localUniforms;r.groups[1]=n.renderPipes.uniformBatch.getUniformBindGroup(t,!0)}n.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(),this._shader=null}},bh.extension={type:[I.WebGPUPipesAdaptor],name:`mesh`}})),Sh,Ch,wh=s((()=>{R(),hf(),hm(),Sh=mf.for2d(),Ch=class{start(e,t,n){let r=e.renderer,i=r.encoder,a=n.gpuProgram;this._shader=n,this._geometry=t,i.setGeometry(t,a),Sh.blendMode=`normal`,r.pipeline.getPipeline(t,a,Sh,void 0,n._overrides);let o=r.globalUniforms.bindGroup;i.resetBindGroup(1),i.setBindGroup(0,o,a)}execute(e,t){let n=this._shader.gpuProgram,r=e.renderer,i=r.encoder;if(!t.bindGroup){let e=t.textures;t.bindGroup=fm(e.textures,e.count,r.limits.maxBatchableTextures)}Sh.blendMode=t.blendMode;let a=r.bindGroup.getBindGroup(t.bindGroup,n,1),o=r.pipeline.getPipeline(this._geometry,n,Sh,t.topology,this._shader._overrides);t.bindGroup._touch(r.gc.now),i.setPipeline(o),i.renderPassEncoder.setBindGroup(1,a),i.renderPassEncoder.drawIndexed(t.size,1,t.start)}},Ch.extension={type:[I.WebGPUPipesAdaptor],name:`batch`}})),Th,Eh=s((()=>{R(),Th=class{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}},Th.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`customRender`}})),Dh,Oh=s((()=>{Dh=class{constructor(){this.batcherName=`default`,this.topology=`triangle-list`,this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}}));function kh(e,t){let n=e.instructionSet,r=n.instructions;for(let e=0;e<n.instructionSize;e++){let n=r[e];t[n.renderPipeId].execute(n)}}var Ah=s((()=>{})),jh,Mh=s((()=>{R(),B(),ha(),Oh(),Ah(),jh=class{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&=(ma.return(e._batchableRenderGroup),null),t.add(e)}_addRenderableCacheAsTexture(e,t){let n=e._batchableRenderGroup??=ma.get(Dh);n.renderable=e.root,n.transform=e.root.relativeGroupTransform,n.texture=e.texture,n.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(n,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;let t=new z().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push({target:e.texture,clear:!0,frame:e.texture.frame}),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),kh(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),kh(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}},jh.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`renderGroup`}}));function Nh(e,t){t||=0;for(let n=t;n<e.length&&e[n];n++)e[n]=null}var Ph=s((()=>{}));function Fh(e,t=!1){Ih(e);let n=e.childrenToUpdate,r=e.updateTick++;for(let t in n){let i=Number(t),a=n[t],o=a.list,s=a.index;for(let t=0;t<s;t++){let n=o[t];n.parentRenderGroup===e&&n.relativeRenderGroupDepth===i&&Lh(n,r,0)}Nh(o,s),a.index=0}if(t)for(let n=0;n<e.renderGroupChildren.length;n++)Fh(e.renderGroupChildren[n],t)}function Ih(e){let t=e.root,n;if(e.renderGroupParent){let r=e.renderGroupParent;e.worldTransform.appendFrom(t.relativeGroupTransform,r.worldTransform),e.worldColor=Xa(t.groupColor,r.worldColor),n=t.groupAlpha*r.worldAlpha}else e.worldTransform.copyFrom(t.localTransform),e.worldColor=t.localColor,n=t.localAlpha;n=n<0?0:n>1?1:n,e.worldAlpha=n,e.worldColorAlpha=e.worldColor+((n*255|0)<<24)}function Lh(e,t,n){if(t===e.updateTick)return;e.updateTick=t,e.didChange=!1;let r=e.localTransform;e.updateLocalTransform();let i=e.parent;if(i&&!i.renderGroup?(n|=e._updateFlags,e.relativeGroupTransform.appendFrom(r,i.relativeGroupTransform),n&Bh&&Rh(e,i,n)):(n=e._updateFlags,e.relativeGroupTransform.copyFrom(r),n&Bh&&Rh(e,zh,n)),!e.renderGroup){let r=e.children,i=r.length;for(let e=0;e<i;e++)Lh(r[e],t,n);let a=e.parentRenderGroup,o=e;o.renderPipeId&&!a.structureDidChange&&a.updateRenderable(o)}}function Rh(e,t,n){if(n&1){e.groupColor=Xa(e.localColor,t.groupColor);let n=e.localAlpha*t.groupAlpha;n=n<0?0:n>1?1:n,e.groupAlpha=n,e.groupColorAlpha=e.groupColor+((n*255|0)<<24)}n&2&&(e.groupBlendMode=e.localBlendMode===`inherit`?t.groupBlendMode:e.localBlendMode),n&4&&(e.globalDisplayStatus=e.localDisplayStatus&t.globalDisplayStatus),e._updateFlags=0}var zh,Bh,Vh=s((()=>{xs(),Ph(),Qa(),zh=new J,Bh=7}));function Hh(e,t){let{list:n}=e.childrenRenderablesToUpdate,r=!1;for(let i=0;i<e.childrenRenderablesToUpdate.index;i++){let e=n[i];if(r=t[e.renderPipeId].validateRenderable(e),r)break}return e.structureDidChange=r,r}var Uh=s((()=>{})),Wh,Gh,Kh=s((()=>{R(),B(),fs(),La(),Ph(),Ah(),Vh(),Uh(),Wh=new z,Gh=class{constructor(e){this._renderer=e}render({container:e,transform:t}){let n=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;let i=this._renderer,a=Wh;t&&(a.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));let o=i.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),i.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),kh(e.renderGroup,o),o.uniformBatch&&o.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(a),e.parent=n,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let n=e.renderGroupChildren.length-1;n>=0;n--)this._updateCachedRenderGroups(e.renderGroupChildren[n],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){let t=e.root.getLocalBounds(),n=this._renderer,r=e.textureOptions.resolution||n.view.resolution,i=e.textureOptions.antialias??n.view.antialias,a=e.textureOptions.scaleMode??`linear`,o=e.texture;t.ceil(),e.texture&&ds.returnTexture(e.texture),e.texture=ds.getOptimalTexture({width:t.width,height:t.height,resolution:r,antialias:i,scaleMode:a}),e._textureBounds||=new Ia,e._textureBounds.copyFrom(t),o!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&=(ds.returnTexture(e.texture),null)}_updateRenderGroups(e){let t=this._renderer,n=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=n,e.structureDidChange?Nh(e.childrenRenderablesToUpdate.list,0):Hh(e,n),Fh(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!e.isCachedAsTexture||e.textureNeedsUpdate)for(let t=0;t<e.renderGroupChildren.length;t++)this._updateRenderGroups(e.renderGroupChildren[t])}_updateRenderables(e){let{list:t,index:n}=e.childrenRenderablesToUpdate;for(let r=0;r<n;r++){let n=t[r];n.didViewUpdate&&e.updateRenderable(n)}Nh(t,n)}_buildInstructions(e,t){let n=e.root,r=e.instructionSet;r.reset();let i=t.renderPipes?t:t.batch.renderer,a=i.renderPipes;a.batch.buildStart(r),a.blendMode.buildStart(),a.colorMask.buildStart(),n.sortableChildren&&n.sortChildren(),n.collectRenderablesWithEffects(r,i,null),a.batch.buildEnd(r),a.blendMode.buildEnd(r)}},Gh.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`renderGroup`}})),qh,Jh=s((()=>{R(),Oh(),qh=class{constructor(e){this._renderer=e}addRenderable(e,t){let n=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,n),this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){let t=new Dh;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}},qh.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`sprite`}})),Yh,Xh=s((()=>{ri(),Yh=`8.22.0`})),Zh,Qh,$h=s((()=>{R(),Xh(),Zh=class{static init(){globalThis.__PIXI_APP_INIT__?.(this,Yh)}static destroy(){}},Zh.extension=I.Application,Qh=class{constructor(e){this._renderer=e}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,Yh)}destroy(){this._renderer=null}},Qh.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:`initHook`,priority:-10}})),eg,tg=s((()=>{eg=class{constructor(e){this.rawBinaryData=typeof e==`number`?new ArrayBuffer(e):e instanceof Uint8Array?e.buffer:e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||=new Int8Array(this.rawBinaryData),this._int8View}get uint8View(){return this._uint8View||=new Uint8Array(this.rawBinaryData),this._uint8View}get int16View(){return this._int16View||=new Int16Array(this.rawBinaryData),this._int16View}get int32View(){return this._int32View||=new Int32Array(this.rawBinaryData),this._int32View}get float64View(){return this._float64Array||=new Float64Array(this.rawBinaryData),this._float64Array}get bigUint64View(){return this._bigUint64Array||=new BigUint64Array(this.rawBinaryData),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case`int8`:case`uint8`:return 1;case`int16`:case`uint16`:return 2;case`int32`:case`uint32`:case`float32`:return 4;default:throw Error(`${e} isn't a valid view type`)}}}}));function ng(e,t,n,r){if(n??=0,r??=Math.min(e.byteLength-n,t.byteLength),!(n&7)&&!(r&7)){let i=r/8;new Float64Array(t,0,i).set(new Float64Array(e,n,i))}else if(!(n&3)&&!(r&3)){let i=r/4;new Float32Array(t,0,i).set(new Float32Array(e,n,i))}else new Uint8Array(t).set(new Uint8Array(e,n,r))}var rg=s((()=>{})),ig,ag,og=s((()=>{ig={normal:`normal-npm`,add:`add-npm`,screen:`screen-npm`},ag=(e=>(e[e.DISABLED=0]=`DISABLED`,e[e.RENDERING_MASK_ADD=1]=`RENDERING_MASK_ADD`,e[e.MASK_ACTIVE=2]=`MASK_ACTIVE`,e[e.INVERSE_MASK_ACTIVE=3]=`INVERSE_MASK_ACTIVE`,e[e.RENDERING_MASK_REMOVE=4]=`RENDERING_MASK_REMOVE`,e[e.NONE=5]=`NONE`,e))(ag||{})}));function sg(e,t){return t.alphaMode===`no-premultiply-alpha`&&ig[e]||e}var cg=s((()=>{og()}));function lg(e){let t=``;for(let n=0;n<e;++n)n>0&&(t+=`
|
|
394
|
-
else `),n<e-1&&(t+=`if(test == ${n}.0){}`);return t}function ug(e,t){if(e===0)throw Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");let n=t.createShader(t.FRAGMENT_SHADER);try{for(;;){let r=dg.replace(/%forloop%/gi,lg(e));if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))e=e/2|0;else break}}finally{t.deleteShader(n)}return e}var dg,fg=s((()=>{dg=[`precision mediump float;`,`void main(void){`,`float test = 0.1;`,`%forloop%`,`gl_FragColor = vec4(0.0);`,`}`].join(`
|
|
395
|
-
`)}));function pg(){if(mg)return mg;let e=Ku();return mg=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),mg=ug(mg,e),e.getExtension(`WEBGL_lose_context`)?.loseContext(),mg}var mg,hg=s((()=>{Ju(),fg(),mg=null})),gg,_g=s((()=>{gg=class{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){let t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}}));function vg(){return Sg>0?xg[--Sg]:new bg}function yg(e){e.elements=null,xg[Sg++]=e}var bg,xg,Sg,Cg,wg,Tg,Eg=s((()=>{ea(),tg(),oa(),ua(),rg(),cg(),hg(),_g(),bg=class{constructor(){this.renderPipeId=`batch`,this.action=`startBatch`,this.start=0,this.size=0,this.textures=new gg,this.blendMode=`normal`,this.topology=`triangle-strip`,this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}},xg=[],Sg=0,la.register({clear:()=>{if(xg.length>0)for(let e of xg)e&&e.destroy();xg.length=0,Sg=0}}),Cg=0,wg=class e{constructor(t){this.uid=Qi(`batcher`),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],t={...e.defaultOptions,...t},t.maxTextures||(H(`v8.8.0`,`maxTextures is a required option for Batcher now, please pass it in the options`),t.maxTextures=pg());let{maxTextures:n,attributesInitialSize:r,indicesInitialSize:i}=t;this.attributeBuffer=new eg(r*4),this.indexBuffer=new Uint16Array(i),this.maxTextures=n}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)yg(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){let n=e._batch.textures.ids[t._source.uid];return!n&&n!==0?!1:(e._textureId=n,e.texture=t,!0)}updateElement(e){this.dirty=!0;let t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){let t=this._elements;if(!t[this.elementStart])return;let n=vg(),r=n.textures;r.clear();let i=t[this.elementStart],a=sg(i.blendMode,i.texture._source),o=i.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);let s=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,l=this.indexBuffer,u=this._batchIndexSize,d=this._batchIndexStart,f=`startBatch`,p=[],m=this.maxTextures;for(let i=this.elementStart;i<this.elementSize;++i){let h=t[i];t[i]=null;let g=h.texture._source,_=sg(h.blendMode,g),v=a!==_||o!==h.topology;g._batchTick===Cg&&!v?(h._textureId=g._textureBindLocation,u+=h.indexSize,h.packAsQuad?(this.packQuadAttributes(h,s,c,h._attributeStart,h._textureId),this.packQuadIndex(l,h._indexStart,h._attributeStart/this.vertexSize)):(this.packAttributes(h,s,c,h._attributeStart,h._textureId),this.packIndex(h,l,h._indexStart,h._attributeStart/this.vertexSize)),h._batch=n,p.push(h)):(g._batchTick=Cg,(r.count>=m||v)&&(this._finishBatch(n,d,u-d,r,a,o,e,f,p),f=`renderBatch`,d=u,a=_,o=h.topology,n=vg(),r=n.textures,r.clear(),p=[],++Cg),h._textureId=g._textureBindLocation=r.count,r.ids[g.uid]=r.count,r.textures[r.count++]=g,h._batch=n,p.push(h),u+=h.indexSize,h.packAsQuad?(this.packQuadAttributes(h,s,c,h._attributeStart,h._textureId),this.packQuadIndex(l,h._indexStart,h._attributeStart/this.vertexSize)):(this.packAttributes(h,s,c,h._attributeStart,h._textureId),this.packIndex(h,l,h._indexStart,h._attributeStart/this.vertexSize)))}r.count>0&&(this._finishBatch(n,d,u-d,r,a,o,e,f,p),d=u,++Cg),this.elementStart=this.elementSize,this._batchIndexStart=d,this._batchIndexSize=u}_finishBatch(e,t,n,r,i,a,o,s,c){e.gpuBindGroup=null,e.bindGroup=null,e.action=s,e.batcher=this,e.textures=r,e.blendMode=i,e.topology=a,e.start=t,e.size=n,e.elements=c,++Cg,this.batches[this.batchIndex++]=e,o.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){let t=Math.max(e,this.attributeBuffer.size*2),n=new eg(t);ng(this.attributeBuffer.rawBinaryData,n.rawBinaryData),this.attributeBuffer=n}_resizeIndexBuffer(e){let t=this.indexBuffer,n=Math.max(e,t.length*1.5);n+=n%2;let r=n>65535?new Uint32Array(n):new Uint16Array(n);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let e=0;e<t.length;e++)r[e]=t[e];else ng(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,n){e[t]=n+0,e[t+1]=n+1,e[t+2]=n+2,e[t+3]=n+0,e[t+4]=n+2,e[t+5]=n+3}packIndex(e,t,n,r){let i=e.indices,a=e.indexSize,o=e.indexOffset,s=e.attributeOffset;for(let e=0;e<a;e++)t[n++]=r+i[e+o]-s}destroy(e={}){if(this.batches!==null){for(let e=0;e<this.batchIndex;e++)yg(this.batches[e]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&(this.shader?.destroy(),this.shader=null);for(let e=0;e<this._elements.length;e++)this._elements[e]&&(this._elements[e]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}},wg.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6},Tg=wg})),Dg,Og,kg,Ag=s((()=>{Af(),Of(),Lf(),Dg=new Float32Array(1),Og=new Uint32Array(1),kg=class extends If{constructor(){let e=new kf({data:Dg,label:`attribute-batch-buffer`,usage:Df.VERTEX|Df.COPY_DST,shrinkToFit:!1}),t=new kf({data:Og,label:`index-batch-buffer`,usage:Df.INDEX|Df.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:e,format:`float32x2`,stride:24,offset:0},aUV:{buffer:e,format:`float32x2`,stride:24,offset:8},aColor:{buffer:e,format:`unorm8x4`,stride:24,offset:16},aTextureIdAndRound:{buffer:e,format:`uint16x2`,stride:24,offset:20}},indexBuffer:t})}}}));function jg(e){let t=Mg[e];if(t)return t;let n=new Int32Array(e);for(let t=0;t<e;t++)n[t]=t;return t=Mg[e]=new ef({uTextures:{value:n,type:`i32`,size:e}},{isStatic:!0}),t}var Mg,Ng=s((()=>{tf(),Mg={}})),Pg,Fg=s((()=>{Xm(),$m(),sh(),mh(),Ng(),rf(),Pg=class extends nf{constructor(e){let t=Ym({name:`batch`,bits:[Qm,ih(e),ph]}),n=Jm({name:`batch`,bits:[Zm,nh(e),fh]});super({glProgram:t,gpuProgram:n,resources:{batchSamplers:jg(e)}}),this.maxTextures=e}}})),Ig,Lg,Rg,zg=s((()=>{R(),Eg(),Ag(),Fg(),Ig=null,Lg=class e extends Tg{constructor(t){super(t),this.geometry=new kg,this.name=e.extension.name,this.vertexSize=6,Ig??=new Pg(t.maxTextures),this.shader=Ig}packAttributes(e,t,n,r,i){let a=i<<16|e.roundPixels&65535,o=e.transform,s=o.a,c=o.b,l=o.c,u=o.d,d=o.tx,f=o.ty,{positions:p,uvs:m}=e,h=e.color,g=e.attributeOffset,_=g+e.attributeSize;for(let e=g;e<_;e++){let i=e*2,o=p[i],g=p[i+1];t[r++]=s*o+l*g+d,t[r++]=u*g+c*o+f,t[r++]=m[i],t[r++]=m[i+1],n[r++]=h,n[r++]=a}}packQuadAttributes(e,t,n,r,i){let a=e.texture,o=e.transform,s=o.a,c=o.b,l=o.c,u=o.d,d=o.tx,f=o.ty,p=e.bounds,m=p.maxX,h=p.minX,g=p.maxY,_=p.minY,v=a.uvs,y=e.color,b=i<<16|e.roundPixels&65535;t[r+0]=s*h+l*_+d,t[r+1]=u*_+c*h+f,t[r+2]=v.x0,t[r+3]=v.y0,n[r+4]=y,n[r+5]=b,t[r+6]=s*m+l*_+d,t[r+7]=u*_+c*m+f,t[r+8]=v.x1,t[r+9]=v.y1,n[r+10]=y,n[r+11]=b,t[r+12]=s*m+l*g+d,t[r+13]=u*g+c*m+f,t[r+14]=v.x2,t[r+15]=v.y2,n[r+16]=y,n[r+17]=b,t[r+18]=s*h+l*g+d,t[r+19]=u*g+c*h+f,t[r+20]=v.x3,t[r+21]=v.y3,n[r+22]=y,n[r+23]=b}_updateMaxTextures(e){this.shader.maxTextures!==e&&(Ig=new Pg(e),this.shader=Ig)}destroy(){this.shader=null,super.destroy()}},Lg.extension={type:[I.Batcher],name:`default`},Rg=Lg})),Bg,Vg,Hg=s((()=>{R(),hf(),zg(),Bg=class e{constructor(e,t){this.state=mf.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init?.(this)}static getBatcher(e,t){return new this._availableBatchers[e]({maxTextures:t})}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new Rg({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(let e in this._activeBatches)this._activeBatches[e].begin()}addToBatch(t,n){if(this._activeBatch.name!==t.batcherName){this._activeBatch.break(n);let r=this._activeBatches[t.batcherName];r||(r=this._activeBatches[t.batcherName]=e.getBatcher(t.batcherName,this.renderer.limits.maxBatchableTextures),r.begin()),this._activeBatch=r}this._activeBatch.add(t)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);let t=this._activeBatches;for(let e in t){let n=t[e],r=n.geometry;r.indexBuffer.setDataWithSize(n.indexBuffer,n.indexSize,!0),r.buffers[0].setDataWithSize(n.attributeBuffer.float32View,n.attributeSize,!1)}}upload(e){let t=this._batchersByInstructionSet[e.uid];for(let e in t){let n=t[e],r=n.geometry;n.dirty&&(n.dirty=!1,r.buffers[0].update(n.attributeSize*4))}}execute(e){if(e.action===`startBatch`){let t=e.batcher,n=t.geometry,r=t.shader;this._adaptor.start(this,n,r)}this._adaptor.execute(this,e)}destroyInstructionSet(e){let t=this._batchersByInstructionSet[e.uid];if(t){for(let e in t)t[e].destroy();delete this._batchersByInstructionSet[e.uid],this._activeBatches===t&&(this._activeBatches=Object.create(null),this._activeBatch=null)}}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(let e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}},Bg.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`batch`},Bg._availableBatchers=Object.create(null),Vg=Bg,L.handleByMap(I.Batcher,Vg._availableBatchers),L.add(Rg)})),Ug,Wg=s((()=>{Ug=`in vec2 vMaskCoord;
|
|
396
|
-
in vec2 vTextureCoord;
|
|
397
|
-
|
|
398
|
-
uniform sampler2D uTexture;
|
|
399
|
-
uniform sampler2D uMaskTexture;
|
|
400
|
-
|
|
401
|
-
uniform float uAlpha;
|
|
402
|
-
uniform vec4 uMaskClamp;
|
|
403
|
-
uniform float uInverse;
|
|
404
|
-
uniform float uChannel;
|
|
405
|
-
|
|
406
|
-
out vec4 finalColor;
|
|
407
|
-
|
|
408
|
-
void main(void)
|
|
409
|
-
{
|
|
410
|
-
float clip = step(3.5,
|
|
411
|
-
step(uMaskClamp.x, vMaskCoord.x) +
|
|
412
|
-
step(uMaskClamp.y, vMaskCoord.y) +
|
|
413
|
-
step(vMaskCoord.x, uMaskClamp.z) +
|
|
414
|
-
step(vMaskCoord.y, uMaskClamp.w));
|
|
415
|
-
|
|
416
|
-
// TODO look into why this is needed
|
|
417
|
-
float npmAlpha = uAlpha;
|
|
418
|
-
vec4 original = texture(uTexture, vTextureCoord);
|
|
419
|
-
vec4 masky = texture(uMaskTexture, vMaskCoord);
|
|
420
|
-
|
|
421
|
-
float a;
|
|
422
|
-
if (uChannel == 1.0) {
|
|
423
|
-
a = masky.a * npmAlpha * clip;
|
|
424
|
-
} else {
|
|
425
|
-
float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);
|
|
426
|
-
a = alphaMul * masky.r * npmAlpha * clip;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
if (uInverse == 1.0) {
|
|
430
|
-
a = 1.0 - a;
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
finalColor = original * a;
|
|
434
|
-
}
|
|
435
|
-
`})),Gg,Kg=s((()=>{Gg=`in vec2 aPosition;
|
|
436
|
-
|
|
437
|
-
out vec2 vTextureCoord;
|
|
438
|
-
out vec2 vMaskCoord;
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
uniform vec4 uInputSize;
|
|
442
|
-
uniform vec4 uOutputFrame;
|
|
443
|
-
uniform vec4 uOutputTexture;
|
|
444
|
-
uniform mat3 uFilterMatrix;
|
|
445
|
-
|
|
446
|
-
vec4 filterVertexPosition( vec2 aPosition )
|
|
447
|
-
{
|
|
448
|
-
vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
|
|
449
|
-
|
|
450
|
-
position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
|
|
451
|
-
position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
|
|
452
|
-
|
|
453
|
-
return vec4(position, 0.0, 1.0);
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
vec2 filterTextureCoord( vec2 aPosition )
|
|
457
|
-
{
|
|
458
|
-
return aPosition * (uOutputFrame.zw * uInputSize.zw);
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
vec2 getFilterCoord( vec2 aPosition )
|
|
462
|
-
{
|
|
463
|
-
return ( uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
void main(void)
|
|
467
|
-
{
|
|
468
|
-
gl_Position = filterVertexPosition(aPosition);
|
|
469
|
-
vTextureCoord = filterTextureCoord(aPosition);
|
|
470
|
-
vMaskCoord = getFilterCoord(aPosition);
|
|
471
|
-
}
|
|
472
|
-
`})),qg,Jg=s((()=>{qg=`struct GlobalFilterUniforms {
|
|
473
|
-
uInputSize:vec4<f32>,
|
|
474
|
-
uInputPixel:vec4<f32>,
|
|
475
|
-
uInputClamp:vec4<f32>,
|
|
476
|
-
uOutputFrame:vec4<f32>,
|
|
477
|
-
uGlobalFrame:vec4<f32>,
|
|
478
|
-
uOutputTexture:vec4<f32>,
|
|
479
|
-
};
|
|
480
|
-
|
|
481
|
-
struct MaskUniforms {
|
|
482
|
-
uFilterMatrix:mat3x3<f32>,
|
|
483
|
-
uMaskClamp:vec4<f32>,
|
|
484
|
-
uAlpha:f32,
|
|
485
|
-
uInverse:f32,
|
|
486
|
-
uChannel:f32,
|
|
487
|
-
};
|
|
488
|
-
|
|
489
|
-
@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
|
|
490
|
-
@group(0) @binding(1) var uTexture: texture_2d<f32>;
|
|
491
|
-
@group(0) @binding(2) var uSampler : sampler;
|
|
492
|
-
|
|
493
|
-
@group(1) @binding(0) var<uniform> filterUniforms : MaskUniforms;
|
|
494
|
-
@group(1) @binding(1) var uMaskTexture: texture_2d<f32>;
|
|
495
|
-
|
|
496
|
-
struct VSOutput {
|
|
497
|
-
@builtin(position) position: vec4<f32>,
|
|
498
|
-
@location(0) uv : vec2<f32>,
|
|
499
|
-
@location(1) filterUv : vec2<f32>,
|
|
500
|
-
};
|
|
501
|
-
|
|
502
|
-
fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
|
|
503
|
-
{
|
|
504
|
-
var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
|
|
505
|
-
|
|
506
|
-
position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
|
|
507
|
-
position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
|
|
508
|
-
|
|
509
|
-
return vec4(position, 0.0, 1.0);
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
|
|
513
|
-
{
|
|
514
|
-
return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
|
|
518
|
-
{
|
|
519
|
-
return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
fn getFilterCoord(aPosition:vec2<f32> ) -> vec2<f32>
|
|
523
|
-
{
|
|
524
|
-
return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
fn getSize() -> vec2<f32>
|
|
528
|
-
{
|
|
529
|
-
return gfu.uGlobalFrame.zw;
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
@vertex
|
|
533
|
-
fn mainVertex(
|
|
534
|
-
@location(0) aPosition : vec2<f32>,
|
|
535
|
-
) -> VSOutput {
|
|
536
|
-
return VSOutput(
|
|
537
|
-
filterVertexPosition(aPosition),
|
|
538
|
-
filterTextureCoord(aPosition),
|
|
539
|
-
getFilterCoord(aPosition)
|
|
540
|
-
);
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
@fragment
|
|
544
|
-
fn mainFragment(
|
|
545
|
-
@location(0) uv: vec2<f32>,
|
|
546
|
-
@location(1) filterUv: vec2<f32>,
|
|
547
|
-
@builtin(position) position: vec4<f32>
|
|
548
|
-
) -> @location(0) vec4<f32> {
|
|
549
|
-
|
|
550
|
-
var maskClamp = filterUniforms.uMaskClamp;
|
|
551
|
-
var uAlpha = filterUniforms.uAlpha;
|
|
552
|
-
|
|
553
|
-
var clip = step(3.5,
|
|
554
|
-
step(maskClamp.x, filterUv.x) +
|
|
555
|
-
step(maskClamp.y, filterUv.y) +
|
|
556
|
-
step(filterUv.x, maskClamp.z) +
|
|
557
|
-
step(filterUv.y, maskClamp.w));
|
|
558
|
-
|
|
559
|
-
var mask = textureSample(uMaskTexture, uSampler, filterUv);
|
|
560
|
-
var source = textureSample(uTexture, uSampler, uv);
|
|
561
|
-
|
|
562
|
-
var a: f32;
|
|
563
|
-
if (filterUniforms.uChannel == 1.0) {
|
|
564
|
-
a = mask.a * uAlpha * clip;
|
|
565
|
-
} else {
|
|
566
|
-
var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);
|
|
567
|
-
a = alphaMul * mask.r * uAlpha * clip;
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
if (filterUniforms.uInverse == 1.0) {
|
|
571
|
-
a = 1.0 - a;
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
return source * a;
|
|
575
|
-
}
|
|
576
|
-
`})),Yg,Xg=s((()=>{B(),vd(),Vd(),tf(),$o(),Qo(),W(),vf(),Wg(),Kg(),Jg(),Yg=class extends _f{constructor(e){let{sprite:t,...n}=e,r=new Zo(t.texture),i=new ef({uFilterMatrix:{value:new z,type:`mat3x3<f32>`},uMaskClamp:{value:r.uClampFrame,type:`vec4<f32>`},uAlpha:{value:1,type:`f32`},uInverse:{value:+!!e.inverse,type:`f32`},uChannel:{value:+(e.channel===`alpha`),type:`f32`}}),a=Bd.from({vertex:{source:qg,entryPoint:`mainVertex`},fragment:{source:qg,entryPoint:`mainFragment`}}),o=_d.from({vertex:Gg,fragment:Ug,name:`mask-filter`});super({...n,gpuProgram:a,glProgram:o,clipToViewport:!1,resources:{filterUniforms:i,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}setSprite(e){this.sprite=e;let t=this._getSafeTexture();this._textureMatrix.texture=t,this.resources.uMaskTexture=t.source}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=+!!e}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}set channel(e){this.resources.filterUniforms.uniforms.uChannel=+(e===`alpha`)}get channel(){return this.resources.filterUniforms.uniforms.uChannel===1?`alpha`:`red`}apply(e,t,n,r){let i=this._getSafeTexture();this._textureMatrix.texture=i,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=i.source,e.applyFilter(this,t,n,r)}_getSafeTexture(){let e=this.sprite.texture;return e.destroyed||!e.source||e.source.destroyed?(U(`[MaskFilter] The mask texture was destroyed while the mask is still in use. Remove the mask before destroying its texture.`),q.EMPTY):e}destroy(e=!1){this._textureMatrix.destroy(),super.destroy(e)}}})),Zg,Qg,$g,e_=s((()=>{R(),Ta(),Xg(),La(),qa(),Tl(),ha(),$o(),fs(),Gd(),Zg=new Ia,Qg=class extends wa{constructor(){super(),this._placeholderSprite=new wl(q.EMPTY),this.filters=[new Yg({sprite:this._placeholderSprite,inverse:!1,resolution:`inherit`,antialias:`inherit`})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].setSprite(e)}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}get channel(){return this.filters[0].channel}set channel(e){this.filters[0].channel=e}reset(){this._placeholderSprite.texture=q.EMPTY,this.sprite=this._placeholderSprite}},$g=class{constructor(e){this._activeMaskStage=[],this._usedEffects=[],this._renderer=e,e.runners.postrender.add(this)}push(e,t,n){let r=this._renderer;if(r.renderPipes.batch.break(n),n.add({renderPipeId:`alphaMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.channel=t._maskOptions.channel??`red`,e.renderMaskToTexture){let t=e.mask;t.includeInBuild=!0,t.collectRenderables(n,r,null),t.includeInBuild=!1}r.renderPipes.batch.break(n),n.add({renderPipeId:`alphaMask`,action:`pushMaskEnd`,mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`alphaMask`,action:`popMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){let t=this._renderer,n=e.mask.renderMaskToTexture;if(e.action===`pushMaskBegin`){let r=ma.get(Qg);if(r.inverse=e.inverse,r.channel=e.mask.channel,n){e.mask.mask.measurable=!0;let n=Wa(e.mask.mask,!0,Zg);e.mask.mask.measurable=!1,n.ceil();let i=t.renderTarget.renderTarget.colorTexture.source,a=ds.getOptimalTexture({width:n.width,height:n.height,resolution:i._resolution,antialias:i.antialias});t.renderTarget.push({target:a,clear:!0}),t.globalUniforms.push({offset:n,worldColor:4294967295});let o=r.sprite;o.texture=a,o.worldTransform.tx=n.minX,o.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer,filterTexture:a})}else r.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:r,maskedContainer:e.maskedContainer})}else if(e.action===`pushMaskEnd`){let e=this._activeMaskStage[this._activeMaskStage.length-1];n&&(t.type===Wd.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:`filter`,action:`pushFilter`,container:e.maskedContainer,filterEffect:e.filterEffect,canBundle:!1})}else if(e.action===`popMaskEnd`){t.filter.pop();let e=this._activeMaskStage.pop();n&&ds.returnTexture(e.filterTexture),this._usedEffects.push(e.filterEffect)}}postrender(){let e=this._usedEffects;for(let t=0;t<e.length;t++)ma.return(e[t]);e.length=0}destroy(){this.postrender(),this._renderer.runners.postrender.remove(this),this._renderer=null,this._activeMaskStage=null,this._usedEffects=null}},$g.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`alphaMask`}})),t_,n_=s((()=>{R(),t_=class{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;let i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;this._colorStackIndex--;let i=r[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}},t_.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`colorMask`}})),r_,i_=s((()=>{R(),tm(),og(),r_=class{constructor(e){this._maskHash=new WeakMap,this._renderer=e}push(e,t,n){let r=e,i=this._renderer;i.renderPipes.batch.break(n),i.renderPipes.blendMode.setBlendMode(r.mask,`none`,n),n.add({renderPipeId:`stencilMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1});let a=r.mask;a.includeInBuild=!0,this._maskHash.has(r)||this._maskHash.set(r,{instructionsStart:0,instructionsLength:0});let o=this._maskHash.get(r);o.instructionsStart=n.instructionSize,a.collectRenderables(n,i,null),a.includeInBuild=!1,i.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`pushMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1}),o.instructionsLength=n.instructionSize-o.instructionsStart-1}pop(e,t,n){let r=e,i=this._renderer;i.renderPipes.batch.break(n),i.renderPipes.blendMode.setBlendMode(r.mask,`none`,n),n.add({renderPipeId:`stencilMask`,action:`popMaskBegin`,inverse:t._maskOptions.inverse,canBundle:!1});let a=this._maskHash.get(e);for(let e=0;e<a.instructionsLength;e++)n.instructions[n.instructionSize++]=n.instructions[a.instructionsStart++];n.add({renderPipeId:`stencilMask`,action:`popMaskEnd`,canBundle:!1})}execute(e){let t=this._renderer,n=t.renderTarget.getGpuRenderTarget(t.renderTarget.renderTarget),r=n.maskStackIndex;e.action===`pushMaskBegin`?(t.renderTarget.ensureDepthStencil(),t.stencil.setStencilMode(ag.RENDERING_MASK_ADD,r),r++,t.colorMask.setMask(0)):e.action===`pushMaskEnd`?(e.inverse?t.stencil.setStencilMode(ag.INVERSE_MASK_ACTIVE,r):t.stencil.setStencilMode(ag.MASK_ACTIVE,r),t.colorMask.setMask(15)):e.action===`popMaskBegin`?(t.colorMask.setMask(0),r===0?(t.renderTarget.clear(null,em.STENCIL),t.stencil.setStencilMode(ag.DISABLED,r)):t.stencil.setStencilMode(ag.RENDERING_MASK_REMOVE,r),r--):e.action===`popMaskEnd`&&(e.inverse?t.stencil.setStencilMode(ag.INVERSE_MASK_ACTIVE,r):t.stencil.setStencilMode(ag.MASK_ACTIVE,r),t.colorMask.setMask(15)),n.maskStackIndex=r}destroy(){this._renderer=null,this._maskHash=null}},r_.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`stencilMask`}})),a_,o_,s_=s((()=>{Ri(),R(),W(),a_=class e{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new Li(0),this.color=this._backgroundColor,this.alpha=1}init(t){t={...e.defaultOptions,...t},this.clearBeforeRender=t.clearBeforeRender,this.color=t.background||t.backgroundColor||this._backgroundColor,this.alpha=t.backgroundAlpha,this._backgroundColor.setAlpha(t.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){Li.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&U(`Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application.`),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}},a_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`background`,priority:0},a_.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0},o_=a_})),c_,l_,u_=s((()=>{R(),Ta(),ms(),W(),c_={},L.handle(I.BlendMode,e=>{if(!e.name)throw Error(`BlendMode extension must have a name property`);c_[e.name]=e.ref},e=>{delete c_[e.name]}),l_=class{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode=`normal`,this._isAdvanced=!1}pushBlendMode(e,t,n){this._blendModeStack.push(t),this.setBlendMode(e,t,n)}popBlendMode(e){this._blendModeStack.pop();let t=this._blendModeStack[this._activeBlendMode.length-1]??`normal`;this.setBlendMode(null,t,e)}setBlendMode(e,t,n){let r=e instanceof ps;this._activeBlendMode===t?this._isAdvanced&&e&&!r&&this._renderableList?.push(e):(this._isAdvanced&&this._endAdvancedBlendMode(n),this._activeBlendMode=t,e&&(this._isAdvanced=!!c_[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,n)))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);let n=this._activeBlendMode;if(!c_[n]){U(`Unable to assign BlendMode: '${n}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}let r=this._ensureFilterEffect(n),i=e instanceof ps,a={renderPipeId:`filter`,action:`pushFilter`,filterEffect:r,renderables:i?null:[e],container:i?e.root:null,canBundle:!1};this._renderableList=a.renderables,t.add(a)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new wa,t.filters=[new c_[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:`filter`,action:`popFilter`,canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(let e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}},l_.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`blendMode`}})),d_,f_,p_,m_=s((()=>{Jc(),R(),xs(),$o(),d_={png:`image/png`,jpg:`image/jpeg`,webp:`image/webp`},f_=class e{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof J||e instanceof q?{target:e,...t}:{...t,...e}}async image(e){let t=Y.get().createImage();return t.src=await this.base64(e),t}async base64(t){t=this._normalizeOptions(t,e.defaultImageOptions);let{format:n,quality:r}=t,i=this.canvas(t);if(i.toBlob!==void 0)return new Promise((e,t)=>{i.toBlob(n=>{if(!n){t(Error(`ICanvas.toBlob failed!`));return}let r=new FileReader;r.onload=()=>e(r.result),r.onerror=t,r.readAsDataURL(n)},d_[n],r)});if(i.toDataURL!==void 0)return i.toDataURL(d_[n],r);if(i.convertToBlob!==void 0){let e=await i.convertToBlob({type:d_[n],quality:r});return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(e)})}throw Error(`Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented`)}canvas(e){e=this._normalizeOptions(e);let t=e.target,n=this._renderer;if(t instanceof q)return n.texture.generateCanvas(t);let r=n.textureGenerator.generateTexture(e),i=n.texture.generateCanvas(r);return r.destroy(!0),i}pixels(e){e=this._normalizeOptions(e);let t=e.target,n=this._renderer,r=t instanceof q?t:n.textureGenerator.generateTexture(e),i=n.texture.getPixels(r);return t instanceof J&&r.destroy(!0),i}texture(e){return e=this._normalizeOptions(e),e.target instanceof q?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);let t=this.canvas(e),n=document.createElement(`a`);n.download=e.filename??`image.png`,n.href=t.toDataURL(`image/png`),document.body.appendChild(n),n.click(),document.body.removeChild(n)}log(e){let t=e.width??200;e=this._normalizeOptions(e);let n=this.canvas(e),r=n.toDataURL();console.log(`[Pixi Texture] ${n.width}px ${n.height}px`);let i=[`font-size: 1px;`,`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,`background-size: contain;`].join(` `);console.log(`%c `,i)}destroy(){this._renderer=null}},f_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`extract`},f_.defaultImageOptions={format:`png`,quality:1},p_=f_})),h_,g_=s((()=>{Po(),$o(),h_=class e extends q{static create(t){let{dynamic:n,textureOptions:r,...i}=t;return new e({...r,source:new No(i),dynamic:n??!1})}resize(e,t,n){return this.source.resize(e,t,n),this}}})),__,v_,y_,b_,x_=s((()=>{Ri(),R(),B(),Pa(),La(),io(),xs(),g_(),__=new G,v_=new Ia,y_=[0,0,0,0],b_=class{constructor(e){this._renderer=e}generateTexture(e){e instanceof J&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});let t=e.resolution||this._renderer.resolution,n=e.antialias||this._renderer.view.antialias,r=e.target,i=e.clearColor;i=i?Array.isArray(i)&&i.length===4?i:Li.shared.setValue(i).toArray():y_;let a=e.frame?.copyTo(__)||no(r,v_).rectangle,o=e.defaultAnchor&&{defaultAnchor:e.defaultAnchor};a.width=Math.max(a.width,1/t)|0,a.height=Math.max(a.height,1/t)|0;let s=h_.create({...e.textureSourceOptions,width:a.width,height:a.height,resolution:t,antialias:n,textureOptions:o}),c=z.shared.translate(-a.x,-a.y);return this._renderer.render({container:r,transform:c,target:s,clearColor:i}),s.source.updateMipmaps(),s}destroy(){this._renderer=null}},b_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`textureGenerator`}}));function S_(e){let t=!1;for(let n in e)if(e[n]==null){t=!0;break}if(!t)return e;let n=Object.create(null);for(let t in e){let r=e[t];r&&(n[t]=r)}return n}function C_(e){let t=0;for(let n=0;n<e.length;n++)e[n]==null?t++:e[n-t]=e[n];return e.length-=t,e}var w_=s((()=>{})),T_,E_,D_=s((()=>{R(),w_(),T_=class e{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._running=!1,this._renderer=e}init(t){t={...e.defaultOptions,...t},this.maxUnusedTime=t.gcMaxUnusedTime,this._frequency=t.gcFrequency,this.enabled=t.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(let e of this._managedCollections){let{context:t,collection:n,type:r}=e;t[n]=r===`hash`?S_(t[n]):C_(t[n])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){this._ready&&this.enabled&&(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(let n of e.renderGroupChildren)this._updateInstructionGCTick(n,t)}addCollection(e,t,n){this._managedCollections.push({context:e,collection:t,type:n})}addResource(e,t){e._gcLastUsed===-1?(e._gcData={index:this._managedResources.length,type:t},e._gcLastUsed=this.now,e._onTouch?.(this.now),e.once(`unload`,this.removeResource,this),this._managedResources.push(e)):(e._gcLastUsed=this.now,e._onTouch?.(this.now))}removeResource(e){let t=e._gcData;if(!t)return;let n=t.index,r=this._managedResources.length-1;if(this._running)this._managedResources[n]=null;else{if(n!==r){let e=this._managedResources[r];this._managedResources[n]=e,e._gcData.index=n}this._managedResources.length--}e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,n,r=0){this._managedResourceHashes.push({context:e,hash:t,type:n,priority:r}),this._managedResourceHashes.sort((e,t)=>e.priority-t.priority)}run(){if(this._running)return;let e=performance.now(),t=this._managedResourceHashes,n=this._managedResources;this._running=!0;try{for(let n of t)this.runOnHash(n,e);let r=n.length;for(let t=0;t<r;t++){let r=n[t];r&&this.runOnResource(r,e)}}finally{let e=0;for(let t=0;t<n.length;t++){let r=n[t];r&&(e!==t&&(n[e]=r,r._gcData.index=e),e++)}n.length=e,this._running=!1}}updateRenderableGCTick(e,t){let n=e.renderGroup??e.parentRenderGroup,r=n?.instructionSet?.gcTick??-1;(n?.gcTick??0)===r&&(e._gcLastUsed=t,e._onTouch?.(t))}runOnResource(e,t){e._gcData.type===`renderable`&&this.updateRenderableGCTick(e,t),!(t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect)&&(e.off(`unload`,this.removeResource,this),e.unload(),this.removeResource(e))}_createHashClone(e,t){let n=Object.create(null);for(let r in e){if(r===t)break;e[r]!==null&&(n[r]=e[r])}return n}runOnHash(e,t){let{context:n,hash:r,type:i}=e,a=n[r],o=null,s=0;for(let e in a){let n=a[e];if(n===null)s++,s===1e4&&!o&&(o=this._createHashClone(a,e));else if(n._gcLastUsed===-1)n._gcLastUsed=t,n._onTouch?.(t),o&&(o[e]=n);else if(i===`renderable`&&this.updateRenderableGCTick(n,t),!(t-n._gcLastUsed<this.maxUnusedTime)&&n.autoGarbageCollect){if(i===`renderable`){let e=n,t=e.renderGroup??e.parentRenderGroup;t&&(t.structureDidChange=!0)}n.unload(),n._gcData=null,n._gcLastUsed=-1,o||(s+1===1e4?o=this._createHashClone(a,e):(a[e]=null,s++))}else o&&(o[e]=n)}o&&(n[r]=o)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e?.off(`unload`,this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}},T_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`gc`,priority:0},T_.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4},E_=T_}));function O_(e,t,n){let r=(e>>24&255)/255;t[n++]=(e&255)/255*r,t[n++]=(e>>8&255)/255*r,t[n++]=(e>>16&255)/255*r,t[n++]=r}var k_=s((()=>{})),A_,j_=s((()=>{R(),B(),qi(),k_(),Ud(),Gd(),tf(),A_=class{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:n,worldColor:r,offset:i}){let a=this._renderer.renderTarget.renderTarget,o=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{projectionData:a,worldTransformMatrix:new z,worldColor:4294967295,offset:new Gi},s={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||a.size,worldTransformMatrix:n||o.worldTransformMatrix,worldColor:r||o.worldColor,offset:i||o.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);let l=c.uniforms;l.uProjectionMatrix=s.projectionMatrix,l.uResolution=s.resolution,l.uWorldTransformMatrix.copyFrom(s.worldTransformMatrix),l.uWorldTransformMatrix.tx-=s.offset.x,l.uWorldTransformMatrix.ty-=s.offset.y,O_(s.worldColor,l.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Hd,this._activeBindGroups.push(u),u.setResource(c,0)),s.bindGroup=u,this._currentGlobalUniformData=s}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===Wd.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new ef({uProjectionMatrix:{value:new z,type:`mat3x3<f32>`},uWorldTransformMatrix:{value:new z,type:`mat3x3<f32>`},uWorldColorAlpha:{value:new Float32Array(4),type:`vec4<f32>`},uResolution:{value:[0,0],type:`vec2<f32>`}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}},A_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`globalUniforms`}})),M_,N_,P_=s((()=>{R(),Os(),M_=1,N_=class{constructor(){this._tasks=[],this._offset=0}init(){Ds.system.add(this._update,this)}repeat(e,t,n=!0){let r=M_++,i=0;return n&&(this._offset+=1e3,i=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:i,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){let e=performance.now();for(let t=0;t<this._tasks.length;t++){let n=this._tasks[t];if(e-n.offset-n.last>=n.duration){let t=e-n.start;n.func(t),n.last=e}}}destroy(){Ds.system.remove(this._update,this),this._tasks.length=0}},N_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`scheduler`,priority:0}}));function F_(e){if(!I_){if(Y.get().getNavigator().userAgent.toLowerCase().indexOf(`chrome`)>-1){let t=[`%c %c %c %c %c PixiJS %c v${Yh} (${e}) http://www.pixijs.com/
|
|
577
|
-
|
|
578
|
-
`,`background: #E72264; padding:5px 0;`,`background: #6CA2EA; padding:5px 0;`,`background: #B5D33D; padding:5px 0;`,`background: #FED23F; padding:5px 0;`,`color: #FFFFFF; background: #E72264; padding:5px 0;`,`color: #E72264; background: #FFFFFF; padding:5px 0;`];globalThis.console.log(...t)}else globalThis.console&&globalThis.console.log(`PixiJS ${Yh} - ${e} - http://www.pixijs.com/`);I_=!0}}var I_,L_=s((()=>{Jc(),Xh(),I_=!1})),R_,z_=s((()=>{R(),L_(),Gd(),R_=class{constructor(e){this._renderer=e}init(e){if(e.hello){let e=this._renderer.name;this._renderer.type===Wd.WEBGL&&(e+=` ${this._renderer.context.webGLVersion}`),F_(e)}}},R_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`hello`,priority:-2},R_.defaultOptions={hello:!1}})),B_,V_,H_=s((()=>{R(),oa(),B_=class e{constructor(e){this._renderer=e}init(t){t={...e.defaultOptions,...t},this.maxUnusedTime=t.renderableGCMaxUnusedTime}get enabled(){return H(`8.15.0`,`RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead.`),this._renderer.gc.enabled}set enabled(e){H(`8.15.0`,`RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead.`),this._renderer.gc.enabled=e}addManagedHash(e,t){H(`8.15.0`,`RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead.`),this._renderer.gc.addCollection(e,t,`hash`)}addManagedArray(e,t){H(`8.15.0`,`RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead.`),this._renderer.gc.addCollection(e,t,`array`)}addRenderable(e){H(`8.15.0`,`RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead.`),this._renderer.gc.addResource(e,`renderable`)}run(){H(`8.15.0`,`RenderableGCSystem.run is deprecated, please use the GCSystem instead.`),this._renderer.gc.run()}destroy(){this._renderer=null}},B_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`renderableGC`,priority:0},B_.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4},V_=B_})),U_,W_,G_=s((()=>{R(),oa(),U_=class e{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){H(`8.15.0`,`TextureGCSystem.run is deprecated, please use the GCSystem instead.`),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){H(`8.15.0`,`TextureGCSystem.run is deprecated, please use the GCSystem instead.`),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){H(`8.15.0`,`TextureGCSystem.run is deprecated, please use the GCSystem instead.`)}get active(){return this._renderer.gc.enabled}set active(e){H(`8.15.0`,`TextureGCSystem.run is deprecated, please use the GCSystem instead.`),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(t){t.textureGCActive!==e.defaultOptions.textureGCActive&&(this.active=t.textureGCActive),t.textureGCMaxIdle!==e.defaultOptions.textureGCMaxIdle&&(this.maxIdle=t.textureGCMaxIdle),t.textureGCCheckCountMax!==e.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=t.textureGCCheckCountMax)}run(){H(`8.15.0`,`TextureGCSystem.run is deprecated, please use the GCSystem instead.`),this._renderer.gc.run()}destroy(){this._renderer=null}},U_.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:`textureGC`},U_.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600},W_=U_})),K_,q_,J_=s((()=>{ri(),ea(),Po(),$o(),K_=class e extends ni{constructor(e={}){super(),this.uid=Qi(`renderTarget`),this.colorAttachments=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,this._depth=!1,this._stencil=!1,this._colorTextures=null;let t=`colorAttachments`in e?e:this._normalizeOptions(e);if(this.isRoot=t.isRoot??!1,this.label=t.label,this.colorAttachments=t.colorAttachments,this.depthStencilAttachment=t.depthStencilAttachment,this.depthStencilAttachment){let e=this.depthStencilAttachment.texture.format;this._depth||=e.includes(`depth`),this._stencil||=e.includes(`stencil`)}if(this.colorAttachments.length===0&&!this.depthStencilAttachment)throw Error(`[RenderTarget] no color textures or depth textures were provided. Provide a depthStencilTexture or set depth/stencil to true when using colorTextures: 0.`);if(this.colorAttachments.length>0){let e=this.colorTexture;this.resize(e.width,e.height,e._resolution)}this.sizeSource&&this.sizeSource.on(`resize`,this.onSourceResize,this)}_normalizeOptions(t){let n={...e.defaultOptions,...t},r=[],i;if(typeof n.colorTextures==`number`){if(n.colorTextures>0){this._managedColorTextures=!0;for(let e=0;e<n.colorTextures;e++)r.push({texture:new No({width:n.width,height:n.height,resolution:n.resolution,antialias:n.antialias}),loadOp:`clear`,storeOp:`store`})}}else n.colorTextures.forEach(e=>{r.push({texture:e.source,loadOp:`clear`,storeOp:`store`})});let a=n.depthStencilTexture===!0;if(this._depth=!!(n.depth||a),this._stencil=!!(n.stencil||a),n.depthStencilTexture instanceof q||n.depthStencilTexture instanceof No){if(n.isRoot)throw Error(`[RenderTarget] cannot attach a depth-stencil texture to the screen — the canvas owns its own depth/stencil buffers. Render to a texture target instead.`);i={texture:n.depthStencilTexture.source}}else(a&&!n.isRoot||(n.stencil||n.depth)&&r.length===0)&&(i=this._createDepthStencilTexture(n.width,n.height,n.resolution));return{colorAttachments:r,depthStencilAttachment:i,isRoot:n.isRoot,label:n.label}}get size(){let e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.sizeSource.width}get height(){return this.sizeSource.height}get pixelWidth(){return this.sizeSource.pixelWidth}get pixelHeight(){return this.sizeSource.pixelHeight}get resolution(){return this.sizeSource._resolution}get colorTextures(){return this._colorTextures||=this.colorAttachments.map(e=>e.texture),this._colorTextures}get depthStencilTexture(){return this.depthStencilAttachment?.texture??null}get depth(){return this._depth}get stencil(){return this._stencil}get colorTexture(){return this.colorAttachments[0]?.texture}get sizeSource(){return this.colorAttachments[0]?.texture??this.depthStencilAttachment?.texture}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this._createDepthStencilTexture(this.sizeSource.width,this.sizeSource.height,this.sizeSource._resolution),this._depth=!0,this._stencil=!0}resize(e,t,n=this.resolution,r=!1){if(this.dirtyId++,this.colorAttachments.forEach((i,a)=>{r&&a===0||i.texture.resize(e,t,n)}),this.depthStencilAttachment){if(r&&this.colorAttachments.length===0)return;this.depthStencilAttachment.texture.resize(e,t,n)}}destroy(){(this.colorAttachments||this.depthStencilAttachment)&&(this.emit(`destroy`,this),this.sizeSource.off(`resize`,this.onSourceResize,this),this._managedColorTextures&&this.colorAttachments.forEach(e=>{e.texture.destroy()}),this.depthStencilAttachment&&(this.depthStencilAttachment.texture.destroy(),delete this.depthStencilAttachment),this.colorAttachments=null,this._colorTextures=null,this.removeAllListeners())}_createDepthStencilTexture(e,t,n){return this.depthStencilAttachment??={texture:new No({width:e,height:t,resolution:n,format:`depth24plus-stencil8`,autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1})},this.depthStencilAttachment}},K_.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1},q_=K_}));function Y_(e,t){if(!X_.has(e)){let n=new q({source:new Rl({resource:e,...t})}),r=()=>{X_.get(e)===n&&X_.delete(e)};n.once(`destroy`,r),n.source.once(`destroy`,r),X_.set(e,n)}return X_.get(e)}var X_,Z_=s((()=>{ua(),zl(),$o(),X_=new Map,la.register(X_)})),Q_,$_,ev=s((()=>{Jc(),R(),Pa(),oa(),J_(),fu(),fs(),Z_(),Q_=class e{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}constructor(e){this._renderer=e}init(t){t={...e.defaultOptions,...t},t.view&&(H(V,`ViewSystem.view has been renamed to ViewSystem.canvas`),t.canvas=t.view),this.screen=new G(0,0,t.width,t.height),this.canvas=t.canvas||Y.get().createCanvas(),this.antialias=!!t.antialias;let{depth:n,...r}=t;this.texture=Y_(this.canvas,r),this.renderTarget=new q_({colorTextures:[this.texture],depth:!!n,isRoot:!0}),this.texture.source.transparent=t.backgroundAlpha<1,this.texture.source.on(`resize`,this._updateScreenSize,this),this.resolution=t.resolution,this._updateScreenSize()}resize(e,t,n){this.texture.source.resize(e,t,n),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e==`boolean`?e:e?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.source.off(`resize`,this._updateScreenSize,this),ds.removeScreen(this._renderer.uid),du.removeScreen(this._renderer.uid),this.texture.destroy()}_updateScreenSize(){let{pixelWidth:e,pixelHeight:t}=this.texture.source,n=this._renderer.uid;ds.setScreenSize(n,e,t),du.setScreenSize(n,e,t)}},Q_.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`view`,priority:0},Q_.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1},$_=Q_})),tv,nv,rv=s((()=>{Eh(),Mh(),Kh(),Jh(),$h(),Hg(),e_(),n_(),i_(),s_(),u_(),m_(),x_(),D_(),j_(),P_(),z_(),H_(),G_(),ev(),tv=[o_,A_,R_,$_,Gh,E_,W_,b_,p_,Qh,V_,N_],nv=[l_,Vg,qh,jh,$g,r_,t_,Th]})),iv,av,ov=s((()=>{R(),iv=class{constructor(e,t){this.autoGarbageCollect=!0,this._gpuData=null,this.gpuBindGroup=e,this._gcLastUsed=t}unload(){this.gpuBindGroup=null}},av=class{constructor(e){this._hash=Object.create(null),this._renderer=e,e.gc.addResourceHash(this,`_hash`,`resource`),e.gc.addCollection(this,`_hash`,`hash`)}contextChange(e){this._gpu=e,this._hash=Object.create(null)}getBindGroup(e,t,n){let r=`${e._key}:${t._layoutKey<<4|n}`,i=this._hash[r];return i?(i._gcLastUsed=this._renderer.gc.now,i.gpuBindGroup):this._createBindGroup(r,e,t,n)}_createBindGroup(e,t,n,r){let i=this._gpu.device,a=n.layout[r],o=[],s=this._renderer;for(let e in a){let n=t.resources[e]??t.resources[a[e]];if(!n||n.destroyed)throw Error(`[BindGroup] the resource bound as '${e}' was destroyed while a shader still uses it. Remove it from the shader before destroying it.`);let r;if(n._resourceType===`uniformGroup`){let e=n;s.ubo.updateUniformGroup(e);let t=e.buffer;r={buffer:s.buffer.getGPUBuffer(t),offset:0,size:t.descriptor.size}}else if(n._resourceType===`buffer`){let e=n;r={buffer:s.buffer.getGPUBuffer(e),offset:0,size:e.descriptor.size}}else if(n._resourceType===`bufferResource`){let e=n;r={buffer:s.buffer.getGPUBuffer(e.buffer),offset:e.offset,size:e.size??e.buffer.descriptor.size}}else if(n._resourceType===`textureSampler`){let e=n;r=s.texture.getGpuSampler(e)}else if(n._resourceType===`textureSource`){let e=n;r=s.texture.getTextureView(e)}else if(n._resourceType===`textureView`){let e=n;r=s.texture.getTextureView(e.source,e.viewDescriptor)}o.push({binding:a[e],resource:r})}let c=s.shader.getProgramData(n).bindGroups[r],l=i.createBindGroup({layout:c,entries:o});return this._hash[e]=new iv(l,s.gc.now),l}destroy(){this._hash=null,this._renderer=null}},av.extension={type:[I.WebGPUSystem],name:`bindGroup`}})),sv,cv=s((()=>{sv=class{constructor(e){this.items=Object.create(null);let{renderer:t,type:n,onUnload:r,priority:i,name:a}=e;this._renderer=t,t.gc.addResourceHash(this,`items`,n,i??0),this._onUnload=r,this.name=a}add(e){return!this.items[e.uid]&&(this.items[e.uid]=e,e.once(`unload`,this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){if(!this.items[e.uid])return;let n=e._gpuData[this._renderer.uid];n&&(this._onUnload?.(e,...t),e.off(`unload`,this.remove,this),n.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}})),lv,uv,dv=s((()=>{R(),cv(),rg(),lv=class{constructor(e){this.gpuBuffer=e}destroy(){this.gpuBuffer.destroy(),this.gpuBuffer=null}},uv=class{constructor(e){this._renderer=e,this._managedBuffers=new sv({renderer:e,type:`resource`,onUnload:this.onBufferUnload.bind(this),name:`gpuBuffer`})}contextChange(e){this._gpu=e,this.destroyAll()}getGPUBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.gpuBuffer||this.createGPUBuffer(e)}updateBuffer(e){let t=this.getGPUBuffer(e),n=e.data;return e._updateID&&n&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,e._updateOffset,n.buffer,n.byteOffset+e._updateOffset,(e._updateSize||n.byteLength)+3&-4)),t}destroyAll(){this._managedBuffers.removeAll()}onBufferUnload(e){e.off(`update`,this.updateBuffer,this),e.off(`change`,this.onBufferChange,this)}createGPUBuffer(e){let t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e.data&&(ng(e.data.buffer,t.getMappedRange(),e.data.byteOffset,e.data.byteLength),t.unmap()),e._gpuData[this._renderer.uid]=new lv(t),this._managedBuffers.add(e)&&(e.on(`update`,this.updateBuffer,this),e.on(`change`,this.onBufferChange,this)),t}onBufferChange(e){this._managedBuffers.remove(e),e._updateID=0,this.createGPUBuffer(e)}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gpu=null}},uv.extension={type:[I.WebGPUSystem],name:`buffer`}})),fv,pv=s((()=>{R(),fv=class{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}},fv.extension={type:[I.WebGPUSystem],name:`colorMask`}})),mv,hv,gv=s((()=>{Jc(),R(),W(),mv=new Set([`apple`,`arm`,`qualcomm`,`img-tec`]),hv=class{constructor(e){this._renderer=e}async init(e){return this._initPromise||=(this._options=e,(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(e=>this._setGpu(e))),this._initPromise}_setGpu(e){this.gpu=e,this.extensions={transientAttachment:typeof GPUTextureUsage.TRANSIENT_ATTACHMENT==`number`,tileBased:mv.has(e.adapter?.info?.vendor)},this._options.gpu||e.device.lost.then(()=>this._restoreDevice()).catch(e=>U(`WebGPU device was lost and could not be restored`,e)),this._renderer.runners.contextChange.emit(this.gpu)}async _restoreDevice(){if(!this._renderer)return;let e=await this._createDeviceAndAdaptor(this._options);this._renderer?this._setGpu(e):e.device.destroy()}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){let t=await Y.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter});if(!t)throw Error(`WebGPU not supported. No GPU adapter was returned by navigator.gpu.requestAdapter().`);let n=[`texture-compression-bc`,`texture-compression-astc`,`texture-compression-etc2`,`indirect-first-instance`,`bgra8unorm-storage`,`texture-formats-tier1`].filter(e=>t.features.has(e));return{adapter:t,device:await t.requestDevice({requiredFeatures:n,requiredLimits:{maxSampledTexturesPerShaderStage:t.limits.maxSampledTexturesPerShaderStage,maxSamplersPerShaderStage:t.limits.maxSamplersPerShaderStage}})}}destroy(){this._options?.gpu||this.gpu?.device.destroy(),this.gpu=null,this.extensions=null,this._renderer=null}},hv.extension={type:[I.WebGPUSystem],name:`device`},hv.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1}})),_v,vv=s((()=>{_v=class{constructor(e,t,n,r){this.gpuBundle=e,this.stateKey=t,this.device=n,this.label=r}}})),yv,bv=s((()=>{R(),W(),vv(),yv=class{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e;for(let e=0;e<16;e++)this._boundBindGroup[e]={bindGroup:null,program:null,key:null}}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){return this.endRenderPass(),this._clearCache(),this._passEncoder=this.commandEncoder.beginRenderPass(e.descriptor),this.renderPassEncoder=this._passEncoder,this._passEncoder}endRenderPass(){this._passEncoder&&this._passEncoder.end(),this.renderPassEncoder=null,this._passEncoder=null}beginBundle(e){if(this._passEncoder!==this.renderPassEncoder)throw Error(`Cannot begin a new render bundle while one is already being recorded.`);this._clearCache();let t=this._renderer.pipeline,n=t.getBundleDescriptor();n.label=e,this._bundleStateKey=t.bundleStateKey,this._bundleLabel=e,this.renderPassEncoder=this._gpu.device.createRenderBundleEncoder(n)}endBundle(){let e=this.renderPassEncoder;if(!e||!(`finish`in e))throw Error(`endBundle called without an active render bundle.`);let t=e.finish({label:this._bundleLabel});return this.renderPassEncoder=this._passEncoder,this._clearCache(),new _v(t,this._bundleStateKey,this._gpu.device,this._bundleLabel)}isBundleValid(e){return e?.stateKey===this._renderer.pipeline.bundleStateKey&&e.device===this._gpu.device}executeBundle(e){let t=[];if(Array.isArray(e))for(let n=0;n<e.length;n++)t[n]=this._getGpuBundle(e[n]);else t[0]=this._getGpuBundle(e);this._clearCache(),this._passEncoder.executeBundles(t)}_getGpuBundle(e){return this.isBundleValid(e)||U(`Render bundle ${e?.label??`(unlabeled)`} was recorded against a different render target state or on a lost device. Re-record it \u2014 replaying it will either be rejected by WebGPU or draw with the wrong winding. Check encoder.isBundleValid(bundle) before executing.`),e.gpuBundle}setViewport(e){this._passEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setStencilReference(e){this._passEncoder.setStencilReference(e)}setPipelineFromGeometryProgramAndState(e,t,n,r,i){let a=this._renderer.pipeline.getPipeline(e,t,n,r,i);this.setPipeline(a)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;let t=e.data.BYTES_PER_ELEMENT===2?`uint16`:`uint32`;this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){let t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=null}setBindGroup(e,t,n){let r=this._boundBindGroup[e];if(r.bindGroup===t&&r.program===n&&r.key===t._key)return;r.bindGroup=t,r.program=n,r.key=t._key,t._touch(this._renderer.gc.now);let i=this._renderer.bindGroup.getBindGroup(t,n,e);this.renderPassEncoder.setBindGroup(e,i)}setGeometry(e,t){let n=this._renderer.pipeline.getBufferNamesToBind(e,t);for(let t=0;t<n.length;t++)this._setVertexBuffer(t,e.attributes[n[t]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){let n=e.gpuProgram,r=n.layout;for(let i=0;i<r.length;i++){let a=e.groups[i];r[i]&&a&&(t||this._syncBindGroup(a),this.setBindGroup(i,a,n))}}_syncBindGroup(e){let t=e.resources,n=e._resourceKeys;for(let e=0;e<n.length;e++){let r=t[n[e]];r&&r.isUniformGroup&&this._renderer.ubo.updateUniformGroup(r)}}draw(e){let{geometry:t,shader:n,state:r,topology:i,size:a,start:o,baseVertex:s,instanceCount:c,skipSync:l,firstInstance:u}=e;this.setPipelineFromGeometryProgramAndState(t,n.gpuProgram,r,i,n._overrides),this.setGeometry(t,n.gpuProgram),this._setShaderBindGroups(n,l),t.indexBuffer?this.renderPassEncoder.drawIndexed(a||t.indexCount||t.indexBuffer.data.length,c??t.instanceCount,o||0,s||0,u||0):this.renderPassEncoder.draw(a||t.vertexCount,c??t.instanceCount,o||0,u||0)}drawIndirect(e){let{geometry:t,shader:n,state:r,topology:i,skipSync:a,indirectBuffer:o,indirectOffset:s}=e;this.setPipelineFromGeometryProgramAndState(t,n.gpuProgram,r,i,n._overrides),this.setGeometry(t,n.gpuProgram),this._setShaderBindGroups(n,a),t.indexBuffer?this.renderPassEncoder.drawIndexedIndirect(o,s):this.renderPassEncoder.drawIndirect(o,s)}finishRenderPass(){this._passEncoder&&=(this._passEncoder.end(),this.renderPassEncoder=null,null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}_clearCache(){for(let e=0;e<16;e++){let t=this._boundBindGroup[e];t.bindGroup=null,t.program=null,t.key=null,this._boundVertexBuffer[e]=null}this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null,this.renderPassEncoder=null,this._passEncoder=null}contextChange(e){this._gpu=e}},yv.extension={type:[I.WebGPUSystem],name:`encoder`,priority:1}})),xv,Sv=s((()=>{R(),xv=class{constructor(e){this.supportsOverrideConstants=!1,this._renderer=e}contextChange(){let e=this._renderer.device.gpu.device;this.maxTextures=Math.min(e.limits.maxSampledTexturesPerShaderStage,e.limits.maxSamplersPerShaderStage),this.maxBatchableTextures=this.maxTextures,this._detectOverrideConstantsSupport(e)}_detectOverrideConstantsSupport(e){e.pushErrorScope(`validation`);let t=e.createShaderModule({code:`override TEST_VALUE: f32 = 0.0;
|
|
579
|
-
@compute @workgroup_size(1) fn main() {}`});e.createComputePipeline({layout:`auto`,compute:{module:t,entryPoint:`main`,constants:{TEST_VALUE:1}}}),e.popErrorScope().then(e=>{this.supportsOverrideConstants=!e})}destroy(){}},xv.extension={type:[I.WebGPUSystem],name:`limits`}})),Cv,wv=s((()=>{R(),Cv=class{constructor(e){this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}contextChange(){this._activeGpuRenderTarget=null}onRenderTargetChange(e){let t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeRenderTarget=e,this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){let n=this._activeGpuRenderTarget??=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget);n.stencilMode=e,n.stencilReference=t;let r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}},Cv.extension={type:[I.WebGPUSystem],name:`stencil`}})),Tv,Ev=s((()=>{ep(),Af(),Of(),Tv=class{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!Qf())throw Error(`Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.`)}ensureUniformGroup(e){let t=this.getUniformGroupData(e);e.buffer||=new kf({data:new Float32Array(t.layout.size/4),usage:Df.UNIFORM|Df.COPY_DST})}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){let t=e._signature,n=this._syncFunctionHash[t];if(!n){let r=Object.keys(e.uniformStructures).map(t=>e.uniformStructures[t]),i=this._adaptor.createUboElements(r),a=this._generateUboSync(i.uboElements);n=this._syncFunctionHash[t]={layout:i,syncFunction:a}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,n){let r=this.getUniformGroupData(e);e.buffer||=new kf({data:new Float32Array(r.layout.size/4),usage:Df.UNIFORM|Df.COPY_DST});let i=null;return t||(t=e.buffer.data,i=e.buffer.dataInt32),n||=0,r.syncFunction(e.uniforms,t,i,n),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;let t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}}));function Dv(e){let t=e.map(e=>({data:e,offset:0,size:0})),n=0;for(let e=0;e<t.length;e++){let r=t[e],i=Ov[r.data.type].size,a=Ov[r.data.type].align;if(!Ov[r.data.type])throw Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(i=Math.max(i,a)*r.data.size),n=Math.ceil(n/a)*a,r.size=i,r.offset=n,n+=i}return n=Math.ceil(n/16)*16,{uboElements:t,size:n}}var Ov,kv=s((()=>{Ov={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}}})),Av,jv=s((()=>{Av=[{type:`mat3x3<f32>`,test:e=>e.value.a!==void 0,ubo:`
|
|
580
|
-
var matrix = uv[name].toArray(true);
|
|
581
|
-
data[offset] = matrix[0];
|
|
582
|
-
data[offset + 1] = matrix[1];
|
|
583
|
-
data[offset + 2] = matrix[2];
|
|
584
|
-
data[offset + 4] = matrix[3];
|
|
585
|
-
data[offset + 5] = matrix[4];
|
|
586
|
-
data[offset + 6] = matrix[5];
|
|
587
|
-
data[offset + 8] = matrix[6];
|
|
588
|
-
data[offset + 9] = matrix[7];
|
|
589
|
-
data[offset + 10] = matrix[8];
|
|
590
|
-
`,uniform:`
|
|
591
|
-
gl.uniformMatrix3fv(ud[name].location, false, uv[name].toArray(true));
|
|
592
|
-
`},{type:`vec4<f32>`,test:e=>e.type===`vec4<f32>`&&e.size===1&&e.value.width!==void 0,ubo:`
|
|
593
|
-
v = uv[name];
|
|
594
|
-
data[offset] = v.x;
|
|
595
|
-
data[offset + 1] = v.y;
|
|
596
|
-
data[offset + 2] = v.width;
|
|
597
|
-
data[offset + 3] = v.height;
|
|
598
|
-
`,uniform:`
|
|
599
|
-
cv = ud[name].value;
|
|
600
|
-
v = uv[name];
|
|
601
|
-
if (cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height) {
|
|
602
|
-
cv[0] = v.x;
|
|
603
|
-
cv[1] = v.y;
|
|
604
|
-
cv[2] = v.width;
|
|
605
|
-
cv[3] = v.height;
|
|
606
|
-
gl.uniform4f(ud[name].location, v.x, v.y, v.width, v.height);
|
|
607
|
-
}
|
|
608
|
-
`},{type:`vec2<f32>`,test:e=>e.type===`vec2<f32>`&&e.size===1&&e.value.x!==void 0,ubo:`
|
|
609
|
-
v = uv[name];
|
|
610
|
-
data[offset] = v.x;
|
|
611
|
-
data[offset + 1] = v.y;
|
|
612
|
-
`,uniform:`
|
|
613
|
-
cv = ud[name].value;
|
|
614
|
-
v = uv[name];
|
|
615
|
-
if (cv[0] !== v.x || cv[1] !== v.y) {
|
|
616
|
-
cv[0] = v.x;
|
|
617
|
-
cv[1] = v.y;
|
|
618
|
-
gl.uniform2f(ud[name].location, v.x, v.y);
|
|
619
|
-
}
|
|
620
|
-
`},{type:`vec4<f32>`,test:e=>e.type===`vec4<f32>`&&e.size===1&&e.value.red!==void 0,ubo:`
|
|
621
|
-
v = uv[name];
|
|
622
|
-
data[offset] = v.red;
|
|
623
|
-
data[offset + 1] = v.green;
|
|
624
|
-
data[offset + 2] = v.blue;
|
|
625
|
-
data[offset + 3] = v.alpha;
|
|
626
|
-
`,uniform:`
|
|
627
|
-
cv = ud[name].value;
|
|
628
|
-
v = uv[name];
|
|
629
|
-
if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha) {
|
|
630
|
-
cv[0] = v.red;
|
|
631
|
-
cv[1] = v.green;
|
|
632
|
-
cv[2] = v.blue;
|
|
633
|
-
cv[3] = v.alpha;
|
|
634
|
-
gl.uniform4f(ud[name].location, v.red, v.green, v.blue, v.alpha);
|
|
635
|
-
}
|
|
636
|
-
`},{type:`vec3<f32>`,test:e=>e.type===`vec3<f32>`&&e.size===1&&e.value.red!==void 0,ubo:`
|
|
637
|
-
v = uv[name];
|
|
638
|
-
data[offset] = v.red;
|
|
639
|
-
data[offset + 1] = v.green;
|
|
640
|
-
data[offset + 2] = v.blue;
|
|
641
|
-
`,uniform:`
|
|
642
|
-
cv = ud[name].value;
|
|
643
|
-
v = uv[name];
|
|
644
|
-
if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue) {
|
|
645
|
-
cv[0] = v.red;
|
|
646
|
-
cv[1] = v.green;
|
|
647
|
-
cv[2] = v.blue;
|
|
648
|
-
gl.uniform3f(ud[name].location, v.red, v.green, v.blue);
|
|
649
|
-
}
|
|
650
|
-
`}]}));function Mv(e,t,n){let r=[`
|
|
651
|
-
var v = null;
|
|
652
|
-
var v2 = null;
|
|
653
|
-
var t = 0;
|
|
654
|
-
var index = 0;
|
|
655
|
-
var name = null;
|
|
656
|
-
var arrayOffset = null;
|
|
657
|
-
`],i=0;for(let a=0;a<e.length;a++){let o=e[a],s=o.data.name,c=!1,l=0;for(let e=0;e<Av.length;e++)if(Av[e].test(o.data)){l=o.offset/4,r.push(`name = "${s}";`,`offset += ${l-i};`,Av[e].ubo),c=!0;break}if(!c){if(o.data.size>1)l=o.offset/4,r.push(n(o,l-i));else{let e=t[o.data.type];l=o.offset/4,r.push(`
|
|
658
|
-
v = uv.${s};
|
|
659
|
-
offset += ${l-i};
|
|
660
|
-
${e};
|
|
661
|
-
`)}}i=l}let a=r.join(`
|
|
662
|
-
`);return Function(`uv`,`data`,`dataInt32`,`offset`,a)}var Nv=s((()=>{jv()}));function Pv(e,t){return`
|
|
663
|
-
for (let i = 0; i < ${e*t}; i++) {
|
|
664
|
-
data[offset + (((i / ${e})|0) * 4) + (i % ${e})] = v[i];
|
|
665
|
-
}
|
|
666
|
-
`}var Fv,Iv,Lv=s((()=>{Fv={f32:`
|
|
667
|
-
data[offset] = v;`,i32:`
|
|
668
|
-
dataInt32[offset] = v;`,u32:`
|
|
669
|
-
dataInt32[offset] = v;`,"vec2<f32>":`
|
|
670
|
-
data[offset] = v[0];
|
|
671
|
-
data[offset + 1] = v[1];`,"vec3<f32>":`
|
|
672
|
-
data[offset] = v[0];
|
|
673
|
-
data[offset + 1] = v[1];
|
|
674
|
-
data[offset + 2] = v[2];`,"vec4<f32>":`
|
|
675
|
-
data[offset] = v[0];
|
|
676
|
-
data[offset + 1] = v[1];
|
|
677
|
-
data[offset + 2] = v[2];
|
|
678
|
-
data[offset + 3] = v[3];`,"vec2<i32>":`
|
|
679
|
-
dataInt32[offset] = v[0];
|
|
680
|
-
dataInt32[offset + 1] = v[1];`,"vec3<i32>":`
|
|
681
|
-
dataInt32[offset] = v[0];
|
|
682
|
-
dataInt32[offset + 1] = v[1];
|
|
683
|
-
dataInt32[offset + 2] = v[2];`,"vec4<i32>":`
|
|
684
|
-
dataInt32[offset] = v[0];
|
|
685
|
-
dataInt32[offset + 1] = v[1];
|
|
686
|
-
dataInt32[offset + 2] = v[2];
|
|
687
|
-
dataInt32[offset + 3] = v[3];`,"vec2<u32>":`
|
|
688
|
-
dataInt32[offset] = v[0];
|
|
689
|
-
dataInt32[offset + 1] = v[1];`,"vec3<u32>":`
|
|
690
|
-
dataInt32[offset] = v[0];
|
|
691
|
-
dataInt32[offset + 1] = v[1];
|
|
692
|
-
dataInt32[offset + 2] = v[2];`,"vec4<u32>":`
|
|
693
|
-
dataInt32[offset] = v[0];
|
|
694
|
-
dataInt32[offset + 1] = v[1];
|
|
695
|
-
dataInt32[offset + 2] = v[2];
|
|
696
|
-
dataInt32[offset + 3] = v[3];`,"mat2x2<f32>":`
|
|
697
|
-
data[offset] = v[0];
|
|
698
|
-
data[offset + 1] = v[1];
|
|
699
|
-
data[offset + 4] = v[2];
|
|
700
|
-
data[offset + 5] = v[3];`,"mat3x3<f32>":`
|
|
701
|
-
data[offset] = v[0];
|
|
702
|
-
data[offset + 1] = v[1];
|
|
703
|
-
data[offset + 2] = v[2];
|
|
704
|
-
data[offset + 4] = v[3];
|
|
705
|
-
data[offset + 5] = v[4];
|
|
706
|
-
data[offset + 6] = v[5];
|
|
707
|
-
data[offset + 8] = v[6];
|
|
708
|
-
data[offset + 9] = v[7];
|
|
709
|
-
data[offset + 10] = v[8];`,"mat4x4<f32>":`
|
|
710
|
-
for (let i = 0; i < 16; i++) {
|
|
711
|
-
data[offset + i] = v[i];
|
|
712
|
-
}`,"mat3x2<f32>":Pv(3,2),"mat4x2<f32>":Pv(4,2),"mat2x3<f32>":Pv(2,3),"mat4x3<f32>":Pv(4,3),"mat2x4<f32>":Pv(2,4),"mat3x4<f32>":Pv(3,4)},Iv={...Fv,"mat2x2<f32>":`
|
|
713
|
-
data[offset] = v[0];
|
|
714
|
-
data[offset + 1] = v[1];
|
|
715
|
-
data[offset + 2] = v[2];
|
|
716
|
-
data[offset + 3] = v[3];
|
|
717
|
-
`}}));function Rv(e,t){let{size:n,align:r}=Ov[e.data.type],i=(Math.max(n,r)-n)/4,a=e.data.type.indexOf(`i32`)>=0?`dataInt32`:`data`;return`
|
|
718
|
-
v = uv.${e.data.name};
|
|
719
|
-
${t===0?``:`offset += ${t};`}
|
|
720
|
-
|
|
721
|
-
arrayOffset = offset;
|
|
722
|
-
|
|
723
|
-
t = 0;
|
|
724
|
-
|
|
725
|
-
for(var i=0; i < ${e.data.size}; i++)
|
|
726
|
-
{
|
|
727
|
-
for(var j = 0; j < ${n/4}; j++)
|
|
728
|
-
{
|
|
729
|
-
${a}[arrayOffset++] = v[t++];
|
|
730
|
-
}
|
|
731
|
-
${i===0?``:`arrayOffset += ${i};`}
|
|
732
|
-
}
|
|
733
|
-
`}var zv=s((()=>{kv()}));function Bv(e){return Mv(e,Iv,Rv)}var Vv=s((()=>{Nv(),Lv(),zv()})),Hv,Uv=s((()=>{R(),Ev(),kv(),Vv(),Hv=class extends Tv{constructor(){super({createUboElements:Dv,generateUboSync:Bv})}},Hv.extension={type:[I.WebGPUSystem],name:`ubo`}})),Wv,Gv=s((()=>{ri(),ea(),Wv=class extends ni{constructor({buffer:e,offset:t,size:n}){super(),this.uid=Qi(`buffer`),this._resourceType=`bufferResource`,this._resourceId=Qi(`resource`),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=n,this.buffer.on(`change`,this.onBufferChange,this)}get _gcLastUsed(){return this.buffer?._gcLastUsed??-1}set _gcLastUsed(e){this.buffer&&(this.buffer._gcLastUsed=e)}onBufferChange(){this._resourceId=Qi(`resource`),this.emit(`change`,this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit(`change`,this),this.buffer=null,this.removeAllListeners()}}})),Kv,qv=s((()=>{Kv=class{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw Error(`UniformBufferBatch: array is too large: ${e*4}`);let t=this.byteIndex,n=t+e*4;if(n=Math.ceil(n/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,n>this.data.length*4)throw Error(`UniformBufferBatch: ubo batch got too big`);return this.byteIndex=n,t}addGroup(e){let t=this.addEmptyGroup(e.length);for(let n=0;n<e.length;n++)this.data[t/4+n]=e[n];return t}destroy(){this.data=null}}})),Jv,Yv,Xv=s((()=>{R(),Af(),Gv(),Of(),qv(),Ud(),Jv=128,Yv=class{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._batchBuffer=new Kv({minUniformOffsetAlignment:Jv});let t=256/Jv;for(let e=0;e<t;e++){let t=Df.UNIFORM|Df.COPY_DST;e===0&&(t|=Df.COPY_SRC),this._buffers.push(new kf({data:this._batchBuffer.data,usage:t}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){this._bindGroupHash=Object.create(null),this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);let n=e.buffer.data,r=this._batchBuffer.addEmptyGroup(n.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Jv),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);let t=e.buffer.data,n=this._batchBuffer.addGroup(t);return this._getBufferResource(n/Jv)}getArrayBindGroup(e){let t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Jv)}getArrayBufferResource(e){let t=this._batchBuffer.addGroup(e)/Jv;return this._getBufferResource(t)}_getBufferResource(e){if(!this._bufferResources[e]){let t=this._buffers[e%2];this._bufferResources[e]=new Wv({buffer:t,offset:(e/2|0)*256,size:Jv})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){let t=new Hd({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){let e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);let n=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){let i=this._buffers[r];n.copyBufferToBuffer(e.getGPUBuffer(t),Jv,e.getGPUBuffer(i),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([n.finish()])}destroy(){for(let e=0;e<this._bindGroups.length;e++)this._bindGroups[e]?.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let e=0;e<this._buffers.length;e++)this._buffers[e].destroy();this._buffers=null;for(let e=0;e<this._bufferResources.length;e++)this._bufferResources[e].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._renderer=null}},Yv.extension={type:[I.WebGPUPipes],name:`uniformBatch`}}));function Zv(e,t){for(let n in e.attributes){let r=e.attributes[n],i=t[n];i?(r.format??=i.format,r.offset??=i.offset,r.instance??=i.instance):r.format||U(`Attribute ${n} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Qv(e)}function Qv(e){let{buffers:t,attributes:n}=e,r={},i={};for(let e in t){let n=t[e];r[n.uid]=0,i[n.uid]=0}for(let e in n){let t=n[e];r[t.buffer.uid]+=yd(t.format).stride}for(let e in n){let t=n[e];t.stride??=r[t.buffer.uid],t.start??=i[t.buffer.uid],i[t.buffer.uid]+=yd(t.format).stride}}var $v=s((()=>{W(),xd()})),ey,ty=s((()=>{og(),ey=[],ey[ag.NONE]=void 0,ey[ag.DISABLED]={stencilWriteMask:0,stencilReadMask:0},ey[ag.RENDERING_MASK_ADD]={stencilFront:{compare:`equal`,passOp:`increment-clamp`},stencilBack:{compare:`equal`,passOp:`increment-clamp`}},ey[ag.RENDERING_MASK_REMOVE]={stencilFront:{compare:`equal`,passOp:`decrement-clamp`},stencilBack:{compare:`equal`,passOp:`decrement-clamp`}},ey[ag.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:`equal`,passOp:`keep`},stencilBack:{compare:`equal`,passOp:`keep`}},ey[ag.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:`not-equal`,passOp:`keep`},stencilBack:{compare:`not-equal`,passOp:`keep`}}}));function ny(e,t){for(let[n,r]of Object.entries(t)){let t=RegExp(`override\\s+${n}\\s*:\\s*(\\w+)\\s*(?:=[^;]*)?;`);e=e.replace(t,(e,t)=>{let i;return i=t===`u32`?`${Math.trunc(r)}u`:t===`i32`?`${Math.trunc(r)}`:Number.isInteger(r)?`${r}.0`:`${r}`,`const ${n}: ${t} = ${i};`})}return e}function ry(e,t,n,r,i,a){return e*35184372088832+t*536870912+a*16384+(n<<8)+(r<<3)+i}function iy(e){let t=dy[e];return t===void 0&&(t=dy[e]=fy++),t}function ay(e,t,n,r,i,a,o,s){return s<<20|a<<16|i<<13|n<<9|e<<6|o<<5|r<<1|t}function oy(e,t,n,r,i,a,o){return o<<11|a<<10|i<<9|r<<8|n<<5|t<<1|e}var sy,cy,ly,uy,dy,fy,py,my=s((()=>{R(),W(),$v(),qd(),og(),Gu(),ty(),sy={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4},cy=new Kd({}),ly={"depth24plus-stencil8":{depth:!0,stencil:!0,index:1},depth24plus:{depth:!0,stencil:!1,index:2},depth32float:{depth:!0,stencil:!1,index:3},"depth32float-stencil8":{depth:!0,stencil:!0,index:4},depth16unorm:{depth:!0,stencil:!1,index:5},stencil8:{depth:!1,stencil:!0,index:6}},uy={depth:!1,stencil:!1,index:0},dy=Object.create(null),fy=0,py=class{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=new Map,this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._colorTargetCount=1,this._colorFormat=`bgra8unorm`,this._colorFormatId=iy(`bgra8unorm`),this._depthStencilFormat=`depth24plus-stencil8`,this._depthStencilFormatData=uy,this._depthReadOnly=!1,this._stencilReadOnly=!1,this._invertFrontFace=!1,this._renderer=e}contextChange(e){this._gpu=e,this._moduleCache=Object.create(null),this._pipeStateCaches=Object.create(null),this.setStencilMode(ag.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){let t=e.colorAttachments[0]?.texture;this._multisampleCount=t?.source.antialias?4:1,this._colorTargetCount=e.colorAttachments.length,this._colorFormat=t?.format??`bgra8unorm`,this._colorFormatId=iy(this._colorFormat),this._depthStencilFormat=e.depthStencilAttachment?.texture.format,this._depthStencilFormatData=ly[this._depthStencilFormat]||uy,this._depthReadOnly=e.depthStencilAttachment?.depthReadOnly??!1,this._stencilReadOnly=e.depthStencilAttachment?.stencilReadOnly??this._depthReadOnly,this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=ey[e],this._updatePipeHash())}get bundleStateKey(){let e=this._depthStencilFormatData;return oy(this._multisampleCount===1?0:1,this._colorTargetCount,e.index,e.depth&&this._depthReadOnly?1:0,e.stencil&&this._stencilReadOnly?1:0,+!!this._invertFrontFace,this._colorFormatId)}getBundleDescriptor(){let e=[];for(let t=0;t<this._colorTargetCount;t++)e.push(this._colorFormat);let t={colorFormats:e,sampleCount:this._multisampleCount},n=this._depthStencilFormatData;return(n.depth||n.stencil)&&(t.depthStencilFormat=this._depthStencilFormat,n.depth&&this._depthReadOnly&&(t.depthReadOnly=!0),n.stencil&&this._stencilReadOnly&&(t.stencilReadOnly=!0)),t}setPipeline(e,t,n,r){let i=this.getPipeline(e,t,n);r.setPipeline(i)}getPipelineKey(e,t,n,r,i){return e._layoutKey||(Zv(e,t.attributeData),this._generateBufferKey(e)),ry(e._layoutKey,t._layoutKey,n.data,n._blendModeId,sy[r],i.id)}getPipeline(e,t,n,r,i){e._layoutKey||(Zv(e,t.attributeData),this._generateBufferKey(e)),r||=e.topology,i||=cy;let a=ry(e._layoutKey,t._layoutKey,n.data,n._blendModeId,sy[r],i.id),o=this._pipeCache.get(a);return o||(o=this._createPipeline(e,t,n,r,i),this._pipeCache.set(a,o)),o}_createPipeline(e,t,n,r,i){let a=this._gpu.device,o=this._createVertexBufferLayouts(e,t),s=this._renderer.state.getColorTargets(n,this._colorTargetCount,this._colorFormat),c=this._stencilMode===ag.RENDERING_MASK_ADD?0:this._colorMask;for(let e=0;e<s.length;e++)s[e].writeMask=c;let l=this._renderer.shader.getProgramData(t).pipeline,u=Object.keys(i.data).length>0,d=t.vertex.source,f=t.fragment.source,p;u&&(this._renderer.limits.supportsOverrideConstants?p=i.data:(d=ny(d,i.data),f=ny(f,i.data)));let m={vertex:{module:this._getModule(d),entryPoint:t.vertex.entryPoint,constants:p,buffers:o},fragment:{module:this._getModule(f),entryPoint:t.fragment.entryPoint,targets:s,constants:p},primitive:{topology:r,cullMode:n.culling?`back`:`none`,frontFace:n.clockwiseFrontFace===this._invertFrontFace?`ccw`:`cw`},layout:l,multisample:{count:this._multisampleCount},label:t.name?`PIXI Pipeline (${t.name})`:`PIXI Pipeline`};if(this._depthStencilFormatData.depth||this._depthStencilFormatData.stencil){let e=this._depthStencilFormatData;m.depthStencil={...this._stencilState,format:this._depthStencilFormat,depthWriteEnabled:e.depth?n.depthMask&&!this._depthReadOnly:!1,depthCompare:e.depth&&n.depthTest?`less`:`always`}}return a.createRenderPipeline(m)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){let t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){let t=[],n=0,r=Object.keys(e.attributes).sort();for(let i=0;i<r.length;i++){let a=e.attributes[r[i]];t[n++]=a.offset,t[n++]=a.format,t[n++]=a.stride,t[n++]=a.instance}return e._layoutKey=Hu(t.join(`|`),`geometry`),e._layoutKey}_generateAttributeLocationsKey(e){let t=[],n=0,r=Object.keys(e.attributeData).sort();for(let i=0;i<r.length;i++){let a=e.attributeData[r[i]];t[n++]=a.location}return e._attributeLocationsKey=Hu(t.join(`|`),`programAttributes`),e._attributeLocationsKey}getBufferNamesToBind(e,t){let n=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[n])return this._bindingNamesCache[n];let r=this._createVertexBufferLayouts(e,t),i=[],a=t.attributeData;for(let e=0;e<r.length;e++){let t=Object.values(r[e].attributes)[0].shaderLocation;for(let n in a)if(a[n].location===t){i[e]=n;break}}return this._bindingNamesCache[n]=i,i}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);let n=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[n])return this._bufferLayoutsCache[n];let r=[];return e.buffers.forEach(n=>{let i={arrayStride:0,stepMode:`vertex`,attributes:[]},a=i.attributes;for(let r in t.attributeData){let o=e.attributes[r];(o.divisor??1)!==1&&U(`Attribute ${r} has an invalid divisor value of '${o.divisor}'. WebGPU only supports a divisor value of 1`),o.buffer===n&&(i.arrayStride=o.stride,i.stepMode=o.instance?`instance`:`vertex`,a.push({shaderLocation:t.attributeData[r].location,offset:o.offset,format:o.format}))}a.length&&r.push(i)}),this._bufferLayoutsCache[n]=r,r}_updatePipeHash(){var e;let t=ay(this._stencilMode,this._multisampleCount===1?0:1,this._colorMask,this._colorTargetCount,this._depthStencilFormatData.index,this._colorFormatId,+!!this._depthReadOnly,+!!this._invertFrontFace);this._pipeCache=(e=this._pipeStateCaches)[t]??(e[t]=new Map)}destroy(){this._bufferLayoutsCache=null,this._pipeCache=null,this._gpu=null,this._renderer=null,this._bindingNamesCache=null,this._pipeStateCaches=null,this._moduleCache=null}},py.extension={type:[I.WebGPUSystem],name:`pipeline`}}));function hy(e,t,n,r,i,a){let o=a?1:-1;return e.identity(),e.a=1/r*2,e.d=o*(1/i*2),e.tx=-1-t*e.a,e.ty=-o-n*e.d,e}var gy=s((()=>{}));function _y(e){if(e.colorAttachments.length===0)return!1;let t=e.colorTexture.resource;return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement&&document.body.contains(t)}var vy=s((()=>{})),yy,by=s((()=>{B(),Pa(),oa(),W(),tm(),gy(),Gd(),rm(),zl(),Po(),$o(),Z_(),vy(),J_(),yy=class{constructor(e){this.rootViewPort=new G,this.viewport=new G,this.onRenderTargetChange=new nm(`onRenderTargetChange`),this.projectionMatrix=new z,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._bindState={target:null,frame:void 0,mipLevel:0,layer:0,flipY:!1},this._bindFrame=new G,this._renderer=e,e.gc.addCollection(this,`_gpuRenderTargetHash`,`hash`)}get renderSurface(){return this._bindState.target}get mipLevel(){return this._bindState.mipLevel}get layer(){return this._bindState.layer}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart(e){this._renderTargetStack.length=0,this.push(e),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=_y(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(e,t=!0,n,r,i=0,a=0,o){let s;`target`in e?s=e:(H(`8.20.0`,`RenderTargetSystem.bind: positional arguments are deprecated, please use an options object instead: bind({ target, clear, clearColor, frame, mipLevel, layer, flipY })`),s={target:e,clear:t,clearColor:n,frame:r,mipLevel:i,layer:a,flipY:o});let c=s.target;t=s.clear??!0,n=s.clearColor,i=(s.mipLevel??0)|0,a=(s.layer??0)|0,o=s.flipY,r=s.frame;let l=this.getRenderTarget(c),u=this.renderTarget!==l||!!l.flipY!=!!o;this.renderTarget=l;let d=this.getGpuRenderTarget(l);(l.pixelWidth!==d.width||l.pixelHeight!==d.height)&&(this.adaptor.resizeGpuRenderTarget(l),d.width=l.pixelWidth,d.height=l.pixelHeight);let f=l.colorAttachments[0]?.texture||l.depthStencilAttachment?.texture,p=this.viewport,m=f.dimension===`3d`?Math.max(f.depth>>i,1):f.depthOrArrayLayers;if(a<0||a>=m)throw Error(`[RenderTargetSystem] layer ${a} is out of bounds (layer count=${m}).`);let h=this._bindState;h.target=c,h.frame=r?this._bindFrame.copyFrom(r):void 0,h.mipLevel=i,h.layer=a,h.flipY=o;let g=Math.max(f.pixelWidth>>i,1),_=Math.max(f.pixelHeight>>i,1);if(!r&&c instanceof q&&(r=c.frame),r){let e=f._resolution,t=1<<Math.max(i,0),n=r.x*e+.5|0,a=r.y*e+.5|0,o=r.width*e+.5|0,s=r.height*e+.5|0,c=Math.floor(n/t),l=Math.floor(a/t),u=Math.ceil(o/t),d=Math.ceil(s/t);c<0&&(u+=c,c=0),l<0&&(d+=l,l=0),c=Math.min(c,g-1),l=Math.min(l,_-1),u=Math.min(u,g-c),d=Math.min(d,_-l),u=Math.max(u,1),d=Math.max(d,1),p.x=c,p.y=l,p.width=u,p.height=d}else p.x=0,p.y=0,p.width=g,p.height=_;return l.flipY=o,hy(this.projectionMatrix,0,0,p.width/f.resolution,p.height/f.resolution,!l.isRoot!=!!l.flipY),this.adaptor.startRenderPass(l,t,n,p,i,a),u&&this.onRenderTargetChange.emit(l),l}getBindState(e){if(!this.renderTarget)throw Error(`[RenderTargetSystem] getBindState is only valid while a render surface is bound`);let t=this._bindState;return e??={},e.target=t.target,e.clear=em.NONE,e.clearColor=void 0,t.frame?e.frame?e.frame.copyFrom(t.frame):e.frame=t.frame.clone():e.frame=void 0,e.mipLevel=t.mipLevel,e.layer=t.layer,e.flipY=!!t.flipY,e}isFrontFaceInverted(e,t){if(!e){if(e=this.renderTarget,!e)return!1;t=e.flipY}return!!t!=(this._renderer.type===Wd.WEBGL&&!e.isRoot)}get frontFaceInverted(){return H(ra,`RenderTargetSystem.frontFaceInverted is deprecated, use isFrontFaceInverted() instead`),this.isFrontFaceInverted()}clear(e,t=em.ALL,n,r=this.mipLevel,i=this.layer){t&&(e&&=this.getRenderTarget(e),this.adaptor.clear(e||this.renderTarget,t,n,this.viewport,r,i))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=em.ALL,n,r,i=0,a=0,o){let s;`target`in e?s=e:(H(`8.20.0`,`RenderTargetSystem.push: positional arguments are deprecated, please use an options object instead: push({ target, clear, clearColor, frame, mipLevel, layer, flipY })`),s={target:e,clear:t,clearColor:n,frame:r,mipLevel:i,layer:a,flipY:o});let c=this.bind(s);return this._renderTargetStack.push({target:s.target,clear:!1,clearColor:void 0,frame:s.frame?s.frame.clone():void 0,mipLevel:s.mipLevel,layer:s.layer,flipY:s.flipY}),c}pop(){this._renderTargetStack.pop();let e=this._renderTargetStack[this._renderTargetStack.length-1];if(!e)throw Error(`[RenderTargetSystem] pop: no previous binding to restore (unbalanced pop)`);return this.bind(e)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,n,r,i){let a=this.getRenderTarget(e);n.x<0&&(r.width+=n.x,i.x-=n.x,n.x=0),n.y<0&&(r.height+=n.y,i.y-=n.y,n.y=0);let{pixelWidth:o,pixelHeight:s}=a;return r.width=Math.min(r.width,o-n.x),r.height=Math.min(r.height,s-n.y),this.adaptor.copyToTexture(a,t,n,r,i)}copyDepthTexture(e,t,n,r,i={x:0,y:0}){let a=this.getRenderTarget(e);if(!a.depthStencilAttachment){U(`[RenderTargetSystem] copyDepthTexture: the source render target has no depth attachment to copy from`);return}let o=t.source;if(!o.format.includes(`depth`)&&!o.format.includes(`stencil`)){U(`[RenderTargetSystem] copyDepthTexture: the destination texture must have a depth/stencil format (got '${o.format}')`);return}let s=n.x,c=n.y,l=i.x,u=i.y,d=r.width,f=r.height;s<0&&(d+=s,l-=s,s=0),c<0&&(f+=c,u-=c,c=0),d=Math.min(d,a.pixelWidth-s),f=Math.min(f,a.pixelHeight-c),d=Math.min(d,o.pixelWidth-l),f=Math.min(f,o.pixelHeight-u),!(d<=0||f<=0)&&this.adaptor.copyDepthTexture(a,t,{x:s,y:c},{width:d,height:f},{x:l,y:u})}ensureDepthStencil(){if(!this.renderTarget.stencil){if(this.renderTarget.depthStencilTexture){U(`[RenderTargetSystem] a stencil mask is being used, but the render target's depthStencilTexture format '${this.renderTarget.depthStencilTexture.format}' has no stencil aspect, so masking cannot work here. Use a 'depth24plus-stencil8' texture instead.`);return}this.renderTarget._depth=!0,this.renderTarget._stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer)}}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e===t?e.off(`destroy`,this._onRenderTargetDestroy,this):this._releaseRenderTarget(t,e)}),this._renderSurfaceToRenderTargetHash.clear();for(let e of Object.values(this._gpuRenderTargetHash))e&&this.adaptor.destroyGpuRenderTarget(e);this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;if(Rl.test(e)&&(e=Y_(e).source),e instanceof q_)t=e,e.once(`destroy`,this._onRenderTargetDestroy,this);else if(e instanceof No){let n=e.format;t=n.includes(`depth`)||n.includes(`stencil`)?new q_({colorTextures:0,depthStencilTexture:e}):new q_({colorTextures:[e]}),e.source instanceof Rl&&(t.isRoot=!0),e.once(`destroy`,this._onRenderSurfaceDestroy,this)}return this._renderSurfaceToRenderTargetHash.set(e,t),t}_onRenderSurfaceDestroy(e){let t=this._renderSurfaceToRenderTargetHash.get(e);t&&this._releaseRenderTarget(e,t)}_onRenderTargetDestroy(e){this._renderSurfaceToRenderTargetHash.delete(e),this._releaseGpuRenderTarget(e)}_releaseRenderTarget(e,t){t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e),e.off(`destroy`,this._onRenderSurfaceDestroy,this),this._releaseGpuRenderTarget(t)}_releaseGpuRenderTarget(e){let t=this._gpuRenderTargetHash[e.uid];t&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(t))}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this._bindState.target=null}}})),xy,Sy=s((()=>{Po(),xy=class{constructor(e){this._pipelines=Object.create(null),this._modules=Object.create(null),this._bindGroups=new WeakMap,this._renderer=e,this._device=e.gpu.device,this._layout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:`unfilterable-float`}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._layout]})}copy(e,t,n,r){var i;let a=this._renderer.renderTarget.getGpuRenderTarget(t),o=t.colorAttachments[n].texture;(i=a.msaaBackTextures)[n]??(i[n]=new No({label:`msaa-back-texture`,width:o.width,height:o.height,resolution:o._resolution,format:a.msaaTextures[n].format,autoGenerateMipmaps:!1,autoGarbageCollect:!0}));let s=this._renderer.texture.getGpuSource(a.msaaBackTextures[n]);e.copyTextureToTexture({texture:r},{texture:s},{width:Math.min(r.width,s.width),height:Math.min(r.height,s.height)})}draw(e,t,n){var r;let i=this._renderer.renderTarget.getGpuRenderTarget(t),a=this._renderer.texture.getGpuSource(i.msaaBackTextures[n]),o=t.depthStencilAttachment?.texture.format??``;for(let e of t.colorAttachments)o+=`|${e.texture.format}`;let s=(r=this._pipelines)[o]??(r[o]=[]),c=this._bindGroups.get(a);c||(c=this._device.createBindGroup({layout:this._layout,entries:[{binding:0,resource:a.createView()}]}),this._bindGroups.set(a,c)),e.setPipeline(s[n]??(s[n]=this._createPipeline(t,n))),e.setBindGroup(0,c),e.draw(3)}_getModule(e){var t;return(t=this._modules)[e]??(t[e]=this._device.createShaderModule({label:`msaa-restore`,code:`
|
|
734
|
-
@group(0) @binding(0) var resolved: texture_2d<f32>;
|
|
735
|
-
|
|
736
|
-
@vertex
|
|
737
|
-
fn vertexMain(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
|
738
|
-
let pos = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
|
|
739
|
-
|
|
740
|
-
return vec4<f32>(pos[i], 0.0, 1.0);
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
@fragment
|
|
744
|
-
fn fragmentMain(@builtin(position) position: vec4<f32>) -> @location(${e}) vec4<f32> {
|
|
745
|
-
return textureLoad(resolved, vec2<i32>(position.xy), 0);
|
|
746
|
-
}
|
|
747
|
-
`})),this._modules[e]}_createPipeline(e,t){let n=e.depthStencilAttachment?.texture.format,r;n&&(r={format:n},n.includes(`depth`)&&(r.depthWriteEnabled=!1,r.depthCompare=`always`));let i=this._getModule(t);return this._device.createRenderPipeline({label:`msaa-restore`,layout:this._pipelineLayout,vertex:{module:i,entryPoint:`vertexMain`},fragment:{module:i,entryPoint:`fragmentMain`,targets:e.colorAttachments.map((e,n)=>({format:e.texture.format,writeMask:n===t?GPUColorWrite.ALL:0}))},depthStencil:r,multisample:{count:4}})}}})),Cy,wy=s((()=>{og(),Cy=class{constructor(){this.contexts=[],this.canvasTextures=[],this.msaaTextures=[],this.transient=!1,this.msaaSamples=1,this.msaaBackTextures=[],this.stencilMode=ag.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}}));function Ty(e){if(Ey[e])return e;let t=navigator.gpu.getPreferredCanvasFormat();return U(`[WebGPU] CanvasSource format '${e}' is not a valid GPUCanvasContext format. Falling back to '${t}'. Allowed formats are: bgra8unorm, rgba8unorm, rgba16float.`),t}var Ey,Dy,Oy=s((()=>{W(),tm(),zl(),Po(),Sy(),wy(),Ey={bgra8unorm:!0,rgba8unorm:!0,rgba16float:!0},Dy=class{constructor(){this._activePass=null}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this),e.runners.destroy.add(this)}contextChange(){this._msaaRestore=null}destroy(){this._msaaRestore=null}copyToTexture(e,t,n,r,i){let a=this._renderer;this.finishRenderPass();let o=this._getGpuColorTexture(e),s=a.texture.getGpuSource(t.source);return a.encoder.commandEncoder.copyTextureToTexture({texture:o,origin:n},{texture:s,origin:i},r),t}copyDepthTexture(e,t,n,r,i){let a=this._renderer;this.finishRenderPass();let o=e.depthStencilAttachment.texture,s=a.texture.getGpuSource(o),c=a.texture.getGpuSource(t.source),l=a.encoder.commandEncoder===null,u=l?a.gpu.device.createCommandEncoder():a.encoder.commandEncoder;u.copyTextureToTexture({texture:s,origin:n},{texture:c,origin:i},{width:r.width,height:r.height}),l&&a.gpu.device.queue.submit([u.finish()])}startRenderPass(e,t=!0,n,r,i=0,a=0){let o=this._renderTargetSystem.getGpuRenderTarget(e);if(a!==0&&o.msaaTextures?.length)throw Error(`[RenderTargetSystem] Rendering to array layers is not supported with MSAA render targets.`);if(i>0&&o.msaaTextures?.length)throw Error(`[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.`);let s=t;typeof s==`boolean`&&(s=s?em.ALL:em.NONE),(e.stencil||e.depth)&&!e.depthStencilAttachment&&e.ensureDepthStencilTexture();let c=!!e.depthStencilAttachment,l=this._activePass,u=l!==null&&l.renderTarget===e&&l.mipLevel===i&&l.layer===a&&l.depthStencil===c&&this._renderer.encoder.renderPassEncoder!==null&&s===em.NONE;if(this._renderer.pipeline.setRenderTarget(e),u){this._renderer.encoder.setViewport(r);return}let{descriptor:d,restore:f}=this._buildDescriptor(e,t,n,i,a);o.descriptor=d;let p=this._renderer.encoder;f?(p.endRenderPass(),this._beginRestoredPass(e,f,p.commandEncoder,()=>p.beginRenderPass(o))):p.beginRenderPass(o),p.setViewport(r),this._activePass={renderTarget:e,mipLevel:i,layer:a,depthStencil:c}}finishRenderPass(){this._renderer.encoder.endRenderPass(),this._activePass=null}_beginRestoredPass(e,t,n,r){let i=this._msaaRestore??=new xy(this._renderer);for(let r of t)i.copy(n,e,r,this._getGpuColorTexture(e,r));let a=r();for(let n of t)i.draw(a,e,n);return a}_getGpuColorTexture(e,t=0){if(e.colorAttachments.length===0)throw Error(`[GpuRenderTargetAdaptor] cannot get gpu color texture from a depth-only render target`);let n=e.colorAttachments[t].texture;return n instanceof Rl&&n._gpuContext?n._gpuContext.getCurrentTexture():this._renderer.texture.getGpuSource(n)}getDescriptor(e,t,n,r=0,i=0){return this._buildDescriptor(e,t,n,r,i).descriptor}_buildDescriptor(e,t,n,r=0,i=0){let a=null;typeof t==`boolean`&&(t=t?em.ALL:em.NONE);let o=this._renderTargetSystem,s=o.getGpuRenderTarget(e),c=e.colorAttachments.map((e,c)=>{let l=e.texture,u=l instanceof Rl?l._gpuContext:null,d,f,p=!1;if(u){if(i!==0)throw Error(`[RenderTargetSystem] Rendering to array layers is not supported for canvas targets.`);let t=u.getCurrentTexture();p=s.canvasTextures[c]!==t,s.canvasTextures[c]=t,d=t.createView(e.viewDescriptor)}else d=this._renderer.texture.getTextureRenderTargetView(e.texture,r,i,e.viewDescriptor);let m=s.msaaTextures[c];m&&(f=d,d=this._renderer.texture.getTextureView(m));let h=e.loadOp;t!==void 0&&(h=t&em.COLOR?`clear`:`load`),n??=o.defaultClearColor;let g=!!m?.transient,_=g&&h!==`clear`,v=_&&!p;_&&(h=`clear`,v&&(a??=[]).push(c));let y={view:d,resolveTarget:f,storeOp:g?`discard`:e.storeOp??`store`,loadOp:h};l.dimension===`3d`&&(y.depthSlice=i),_?y.clearValue=[0,0,0,0]:h===`clear`&&(n??=e.clearValue??o.defaultClearColor,y.clearValue=n);for(let t in e)t!==`texture`&&t!==`viewDescriptor`&&t!==`clearValue`&&t!==`loadOp`&&t!==`storeOp`&&(y[t]=e[t]);return y}),l;if(e.depthStencilAttachment){this._prepareDepthStencil(e,s);let n=e.depthStencilAttachment,a=n.texture.format.includes(`stencil`),o=n.texture.format.includes(`depth`),c=s.transient?`discard`:`store`,u=s.transient?`clear`:`load`;l={view:this._renderer.texture.getTextureRenderTargetView(n.texture,r,i,n.viewDescriptor)};let d=n.depthReadOnly??!1,f=n.stencilReadOnly??d;a&&!f?(l.stencilLoadOp=t&em.STENCIL?`clear`:n.stencilLoadOp??u,l.stencilStoreOp=n.stencilStoreOp??c,l.stencilLoadOp===`clear`&&(l.stencilClearValue=n.stencilClearValue??0)):a&&f&&(l.stencilReadOnly=!0),o&&!d?(l.depthLoadOp=t&em.DEPTH?`clear`:n.depthLoadOp??u,l.depthStoreOp=n.depthStoreOp??c,l.depthLoadOp===`clear`&&(l.depthClearValue=n.depthClearValue??1)):o&&d&&(l.depthReadOnly=!0);for(let e in n)e!==`texture`&&e!==`viewDescriptor`&&e!==`stencilLoadOp`&&e!==`stencilStoreOp`&&e!==`stencilClearValue`&&e!==`stencilReadOnly`&&e!==`depthLoadOp`&&e!==`depthStoreOp`&&e!==`depthClearValue`&&e!==`depthReadOnly`&&(l[e]=n[e])}return{descriptor:{colorAttachments:c,depthStencilAttachment:l,label:e.label},restore:a}}clear(e,t=!0,n,r,i=0,a=0){if(!t)return;let{gpu:o,encoder:s}=this._renderer,c=o.device;if(s.commandEncoder===null){let o=c.createCommandEncoder(),{descriptor:s,restore:l}=this._buildDescriptor(e,t,n,i,a),u=()=>o.beginRenderPass(s),d=l?this._beginRestoredPass(e,l,o,u):u();d.setViewport(r.x,r.y,r.width,r.height,0,1),d.end();let f=o.finish();c.queue.submit([f])}else this.startRenderPass(e,t,n,r,i,a)}initGpuRenderTarget(e){e.isRoot=!0;let t=new Cy;return t.transient=!!e.colorTexture?.antialias&&!!e.colorTexture.transient,e.colorAttachments.forEach((e,n)=>{let r=e.texture;if(r instanceof Rl){let e=r._gpuContext??=r.resource.getContext(`webgpu`),i=r.transparent?`premultiplied`:`opaque`,a=Ty(r.format);try{e.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:a,alphaMode:i,...a===`rgba16float`?{toneMapping:{mode:`extended`}}:{}})}catch(e){console.error(e)}t.contexts[n]=e}if(t.msaa=r.source.antialias,r.antialias){let e=new No({width:0,height:0,sampleCount:4,autoGenerateMipmaps:!1,transient:this._renderer.device.extensions.tileBased||t.transient,arrayLayerCount:r.arrayLayerCount,format:r.format});t.msaaTextures[n]=e}}),t.msaa&&(t.msaaSamples=4),t}_prepareDepthStencil(e,t){let n=e.depthStencilAttachment?.texture;n&&t.msaa&&(n.sampleCount=4,n.transient=t.transient)}destroyGpuRenderTarget(e){e.contexts.forEach(e=>{e.unconfigure()}),e.msaaTextures.forEach(e=>{e.destroy()}),e.msaaBackTextures.forEach(e=>{e?.destroy()}),e.msaaTextures.length=0,e.msaaBackTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){this._prepareDepthStencil(e,this._renderTargetSystem.getGpuRenderTarget(e))}resizeGpuRenderTarget(e){let t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorAttachments.forEach((e,n)=>{let r=e.texture;t.msaaTextures[n]?.resize(r.width,r.height,r._resolution),t.msaaBackTextures[n]?.resize(r.width,r.height,r._resolution)})}}})),ky,Ay=s((()=>{R(),by(),Oy(),ky=class extends yy{constructor(e){super(e),this.adaptor=new Dy,this.adaptor.init(e,this)}},ky.extension={type:[I.WebGPUSystem],name:`renderTarget`}})),jy,My=s((()=>{R(),jy=class{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e,this._gpuProgramData=Object.create(null)}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){let t=this._gpu.device,n=e.gpuLayout.map(e=>t.createBindGroupLayout({entries:e})),r={bindGroupLayouts:n};return this._gpuProgramData[e._layoutKey]={bindGroups:n,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}},jy.extension={type:[I.WebGPUSystem],name:`shader`}})),Ny,Py=s((()=>{Ny={},Ny.normal={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`}},Ny.add={alpha:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`one`,dstFactor:`one`,operation:`add`}},Ny.multiply={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`dst`,dstFactor:`one-minus-src-alpha`,operation:`add`}},Ny.screen={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`one`,dstFactor:`one-minus-src`,operation:`add`}},Ny.overlay={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`one`,dstFactor:`one-minus-src`,operation:`add`}},Ny.none={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`zero`,dstFactor:`zero`,operation:`add`}},Ny[`normal-npm`]={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`,operation:`add`}},Ny[`add-npm`]={alpha:{srcFactor:`one`,dstFactor:`one`,operation:`add`},color:{srcFactor:`src-alpha`,dstFactor:`one`,operation:`add`}},Ny[`screen-npm`]={alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src`,operation:`add`}},Ny.erase={alpha:{srcFactor:`zero`,dstFactor:`one-minus-src-alpha`,operation:`add`},color:{srcFactor:`zero`,dstFactor:`one-minus-src`,operation:`add`}},Ny.min={alpha:{srcFactor:`one`,dstFactor:`one`,operation:`min`},color:{srcFactor:`one`,dstFactor:`one`,operation:`min`}},Ny.max={alpha:{srcFactor:`one`,dstFactor:`one`,operation:`max`},color:{srcFactor:`one`,dstFactor:`one`,operation:`max`}}})),Fy,Iy=s((()=>{R(),hf(),Py(),Fy=class{constructor(){this.defaultState=new mf,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e,t,n){let r=e.blend?Ny[e.blendMode]||Ny.normal:void 0,i=[];for(let e=0;e<t;e++)i[e]={format:n,writeMask:0,blend:r};return i}destroy(){this.gpu=null}},Fy.extension={type:[I.WebGPUSystem],name:`state`}}));function Ly(e,t,n,r,i){if(e=Math.max(0,e),t=Math.min(t,n*r),e>=t)return 0;let a=Math.floor(e/n),o=e-a*n,s=Math.floor(t/n),c=t-s*n;if(a===s)return i[0].set(o,a,c-o,1),1;let l=0,u=a;return o>0&&(i[l++].set(o,a,n-o,1),u++),s>u&&i[l++].set(0,u,n,s-u),c>0&&i[l++].set(0,s,c,1),l}var Ry=s((()=>{})),zy,By,Vy=s((()=>{Pa(),Ry(),zy=[new G,new G,new G],By={type:`image`,upload(e,t,n,r=0){let i=e.resource,a=e.pixelWidth|0,o=e.pixelHeight|0,s=e.depthOrArrayLayers,c=i.byteLength/(a*o*s);if(s>1){n.device.queue.writeTexture({texture:t,origin:{x:0,y:0,z:r}},i,{offset:0,rowsPerImage:o,bytesPerRow:a*c},{width:a,height:o,depthOrArrayLayers:s});return}let l=Ly(e._updateStart,e._updateEnd,a,o,zy);for(let e=0;e<l;e++){let o=zy[e];n.device.queue.writeTexture({texture:t,origin:{x:o.x,y:o.y,z:r}},i,{offset:(o.y*a+o.x)*c,rowsPerImage:o.height,bytesPerRow:a*c},{width:o.width,height:o.height,depthOrArrayLayers:1})}}}})),Hy,Uy,Wy,Gy=s((()=>{Hy={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},Uy={blockBytes:4,blockWidth:1,blockHeight:1},Wy={type:`compressed`,upload(e,t,n,r=0){let i=e.pixelWidth,a=e.pixelHeight,o=Hy[e.format]||Uy;for(let s=0;s<e.resource.length;s++){let c=e.resource[s],l=Math.ceil(i/o.blockWidth)*o.blockBytes;n.device.queue.writeTexture({texture:t,mipLevel:s,origin:{x:0,y:0,z:r}},c,{offset:0,bytesPerRow:l},{width:Math.ceil(i/o.blockWidth)*o.blockWidth,height:Math.ceil(a/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),i=Math.max(i>>1,1),a=Math.max(a>>1,1)}}}}));function Ky(e){return{type:`cube`,upload(t,n,r){let i=t.faces;for(let t=0;t<qy.length;t++){let a=i[qy[t]];(e[a.uploadMethodId]||e.image).upload(a,n,r,t)}}}}var qy,Jy=s((()=>{qy=[`right`,`left`,`top`,`bottom`,`front`,`back`]})),Yy,Xy=s((()=>{Jc(),W(),Yy={type:`image`,upload(e,t,n,r=0){let i=e.resource;if(!i)return;if(globalThis.HTMLImageElement&&i instanceof HTMLImageElement){let t=Y.get().createCanvas(i.width,i.height);t.getContext(`2d`).drawImage(i,0,0,i.width,i.height),e.resource=t,U(`ImageSource: Image element passed, converting to canvas and replacing resource.`)}let a=Math.min(t.width,e.resourceWidth||e.pixelWidth),o=Math.min(t.height,e.resourceHeight||e.pixelHeight),s=e.alphaMode===`premultiply-alpha-on-upload`;n.device.queue.copyExternalImageToTexture({source:i},{texture:t,origin:{x:0,y:0,z:r},premultipliedAlpha:s},{width:a,height:o})}}})),Zy,Qy=s((()=>{Xy(),Zy={type:`video`,upload(e,t,n,r){Yy.upload(e,t,n,r)}}}));function $y(e,t){if(!t)throw Error(`[Gpu3dMipmapGenerator] generating mipmaps for a 3D texture needs storage: true.`);if(!eb.includes(e))throw Error(`[Gpu3dMipmapGenerator] format '${e}' can't be downsampled. Use ${eb.join(`, `)}.`)}var eb,tb,nb,rb=s((()=>{eb=[`rgba8unorm`,`rgba16float`],tb=4,nb=class{constructor(e){this._pipelines={},this._device=e,this._sampler=e.createSampler({magFilter:`linear`,minFilter:`linear`})}_getMipmapPipeline(e){var t;return(t=this._pipelines)[e]??(t[e]=this._device.createComputePipeline({layout:`auto`,compute:{module:this._device.createShaderModule({code:`
|
|
748
|
-
@group(0) @binding(0) var srcSampler : sampler;
|
|
749
|
-
@group(0) @binding(1) var src : texture_3d<f32>;
|
|
750
|
-
@group(0) @binding(2) var dst : texture_storage_3d<${e}, write>;
|
|
751
|
-
|
|
752
|
-
@compute @workgroup_size(${tb}, ${tb}, ${tb})
|
|
753
|
-
fn main(@builtin(global_invocation_id) gid : vec3<u32>) {
|
|
754
|
-
let dstSize = textureDimensions(dst);
|
|
755
|
-
|
|
756
|
-
if (gid.x >= dstSize.x || gid.y >= dstSize.y || gid.z >= dstSize.z) {
|
|
757
|
-
return;
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
// centre of the 2x2x2 footprint in the previous mip. When a dimension is
|
|
761
|
-
// odd its last texel, row or slice is never sampled, as in the 2D generator
|
|
762
|
-
let uv = (vec3<f32>(gid) * 2.0 + 1.0) / vec3<f32>(textureDimensions(src));
|
|
763
|
-
|
|
764
|
-
textureStore(dst, gid, textureSampleLevel(src, srcSampler, uv, 0.0));
|
|
765
|
-
}
|
|
766
|
-
`}),entryPoint:`main`}})),this._pipelines[e]}generateMipmap(e){if(e.dimension!==`3d`)throw Error(`[Gpu3dMipmapGenerator] generateMipmap expects a 3D texture.`);if(e.mipLevelCount<2)return;$y(e.format,(e.usage&GPUTextureUsage.STORAGE_BINDING)!==0);let t=this._getMipmapPipeline(e.format),n=t.getBindGroupLayout(0),r=this._device.createCommandEncoder({label:`Gpu3dMipmapGenerator`}),i=r.beginComputePass();i.setPipeline(t);let a=e.width,o=e.height,s=e.depthOrArrayLayers,c=e.createView({dimension:`3d`,baseMipLevel:0,mipLevelCount:1});for(let t=1;t<e.mipLevelCount;t++){a=Math.max(1,a>>1),o=Math.max(1,o>>1),s=Math.max(1,s>>1);let r=e.createView({dimension:`3d`,baseMipLevel:t,mipLevelCount:1});i.setBindGroup(0,this._device.createBindGroup({layout:n,entries:[{binding:0,resource:this._sampler},{binding:1,resource:c},{binding:2,resource:r}]})),i.dispatchWorkgroups(Math.ceil(a/tb),Math.ceil(o/tb),Math.ceil(s/tb)),c=r}i.end(),this._device.queue.submit([r.finish()])}}})),ib,ab=s((()=>{ib=class{constructor(e){this._pipelines={},this._device=e,this._sampler=e.createSampler({minFilter:`linear`})}_getMipmapPipeline(e){let t=this._pipelines[e];return t||(this._mipmapShaderModule||=this._device.createShaderModule({code:`
|
|
767
|
-
var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
|
|
768
|
-
vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
|
|
769
|
-
|
|
770
|
-
struct VertexOutput {
|
|
771
|
-
@builtin(position) position : vec4<f32>,
|
|
772
|
-
@location(0) texCoord : vec2<f32>,
|
|
773
|
-
};
|
|
774
|
-
|
|
775
|
-
@vertex
|
|
776
|
-
fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput {
|
|
777
|
-
var output : VertexOutput;
|
|
778
|
-
output.texCoord = pos[vertexIndex] * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);
|
|
779
|
-
output.position = vec4<f32>(pos[vertexIndex], 0.0, 1.0);
|
|
780
|
-
return output;
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
@group(0) @binding(0) var imgSampler : sampler;
|
|
784
|
-
@group(0) @binding(1) var img : texture_2d<f32>;
|
|
785
|
-
|
|
786
|
-
@fragment
|
|
787
|
-
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
788
|
-
return textureSample(img, imgSampler, texCoord);
|
|
789
|
-
}
|
|
790
|
-
`}),t=this._device.createRenderPipeline({layout:`auto`,vertex:{module:this._mipmapShaderModule,entryPoint:`vertexMain`},fragment:{module:this._mipmapShaderModule,entryPoint:`fragmentMain`,targets:[{format:e}]}}),this._pipelines[e]=t),t}generateMipmap(e){if(e.dimension===`3d`)throw Error(`[GpuMipmapGenerator] a 3D texture uses Gpu3dMipmapGenerator.`);if(e.dimension===`1d`)throw Error(`Generating mipmaps for 1d textures is currently unsupported!`);let t=this._getMipmapPipeline(e.format),n=e,r=e.depthOrArrayLayers||1,i=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!i){let t={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};n=this._device.createTexture(t)}let a=this._device.createCommandEncoder({}),o=t.getBindGroupLayout(0);for(let s=0;s<r;++s){let r=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:`2d`,baseArrayLayer:s,arrayLayerCount:1}),c=+!!i;for(let i=1;i<e.mipLevelCount;++i){let e=n.createView({baseMipLevel:c++,mipLevelCount:1,dimension:`2d`,baseArrayLayer:s,arrayLayerCount:1}),i=a.beginRenderPass({colorAttachments:[{view:e,storeOp:`store`,loadOp:`clear`,clearValue:{r:0,g:0,b:0,a:0}}]}),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:this._sampler},{binding:1,resource:r}]});i.setPipeline(t),i.setBindGroup(0,l),i.draw(3,1,0,0),i.end(),r=e}}if(!i){let t={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let r=1;r<e.mipLevelCount;++r)a.copyTextureToTexture({texture:n,mipLevel:r-1},{texture:e,mipLevel:r},t),t.width=Math.ceil(t.width/2),t.height=Math.ceil(t.height/2)}return this._device.queue.submit([a.finish()]),i||n.destroy(),e}}}));function ob(e){return lb.test(e)?[`${e}-srgb`]:void 0}function sb(e){return`${e.format||``}.${e.dimension||``}.${e.aspect||``}.${e.baseMipLevel||0}.${e.mipLevelCount||``}.${e.baseArrayLayer||0}.${e.arrayLayerCount||``}`}var cb,lb,ub,db,fb=s((()=>{Jc(),R(),cv(),tf(),fu(),Ud(),Vy(),Gy(),Jy(),Xy(),Qy(),rb(),ab(),cb=class{constructor(e){this.textureView=null,this.textureViews=Object.create(null),this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.textureViews=null,this.gpuTexture=null}},lb=/^(rgba8|bgra8|bc[1237]-rgba-|etc2-rgb8|etc2-rgb8a1|etc2-rgba8|astc-\d+x\d+-)unorm$/,ub=class e{constructor(t){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=t,t.gc.addCollection(this,`_bindGroupHash`,`hash`),this._managedTextures=new sv({renderer:t,type:`resource`,onUnload:this.onSourceUnload.bind(this),name:`gpuTextureSource`});let n={image:Yy,buffer:By,video:Zy,compressed:Wy,...e.uploadExtensions};this._uploads={...n,cube:Ky(n)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e,this._managedTextures.removeAll(),this._gpuSamplers=Object.create(null),this._mipmapGenerator=null,this._mipmap3dGenerator=null}initSource(e){return e._gpuData[this._renderer.uid]?.gpuTexture||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){e.dimension===`3d`&&$y(e.format,e.storage);let t=Math.max(e.pixelWidth,e.pixelHeight,e.depth);e.mipLevelCount=Math.floor(Math.log2(t))+1}let t,n;e.sampleCount>1?(t=GPUTextureUsage.RENDER_ATTACHMENT,e.transient&&this._renderer.device.extensions.transientAttachment&&(t|=GPUTextureUsage.TRANSIENT_ATTACHMENT)):(t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST,e.uploadMethodId!==`compressed`&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC),e.storage&&(t|=GPUTextureUsage.STORAGE_BINDING),n=ob(e.format));let r=Hy[e.format]||{blockBytes:4,blockWidth:1,blockHeight:1},i=Math.ceil(e.pixelWidth/r.blockWidth)*r.blockWidth,a=Math.ceil(e.pixelHeight/r.blockHeight)*r.blockHeight,o={label:e.label,size:{width:i,height:a,depthOrArrayLayers:e.depthOrArrayLayers},format:e.format,viewFormats:n,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},s=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new cb(s),this._managedTextures.add(e)&&(e.on(`update`,this.onSourceUpdate,this),e.on(`resize`,this.onSourceResize,this),e.on(`updateMipmaps`,this.onUpdateMipmaps,this)),this.onSourceUpdate(e),s}onSourceUpdate(e){let t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){let t=this.getGpuSource(e);e.dimension===`3d`?(this._mipmap3dGenerator??=new nb(this._gpu.device),this._mipmap3dGenerator.generateMipmap(t)):(this._mipmapGenerator??=new ib(this._gpu.device),this._mipmapGenerator.generateMipmap(t))}onSourceUnload(e){e.off(`update`,this.onSourceUpdate,this),e.off(`resize`,this.onSourceResize,this),e.off(`updateMipmaps`,this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;let t=e._gpuData[this._renderer.uid],n=t?.gpuTexture;n?(n.width!==e.pixelWidth||n.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]?.gpuTexture||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){let t=e.source;return this._bindGroupHash[e.uid]=new Hd({0:t,1:t.style,2:new ef({uTextureMatrix:{type:`mat3x3<f32>`,value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e,t){var n;let r=e.source;r._gcLastUsed=this._renderer.gc.now;let i=r._gpuData[this._renderer.uid];i||=(this.initSource(r),r._gpuData[this._renderer.uid]);let a=t?sb(t):0;return(n=i.textureViews)[a]||(n[a]=i.gpuTexture.createView({dimension:r.viewDimension,...t})),i.textureViews[a]}getTextureRenderTargetView(e,t=0,n=0,r){var i;let a=e.source;a._gcLastUsed=this._renderer.gc.now;let o=a._gpuData[this._renderer.uid];o||=(this.initSource(a),a._gpuData[this._renderer.uid]);let s=a.dimension===`3d`;s&&(n=0);let c=n*(a.mipLevelCount||1)+t+1;return r&&(c=`${c}.${sb(r)}`),(i=o.textureViews)[c]||(i[c]=o.gpuTexture.createView({dimension:s?`3d`:`2d`,baseMipLevel:t,mipLevelCount:1,baseArrayLayer:n,arrayLayerCount:1,...r})),o.textureViews[c]}generateCanvas(e){let t=this._renderer,n=t.gpu.device.createCommandEncoder(),r=Y.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;let i=r.getContext(`webgpu`);return i.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:Y.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:`premultiplied`}),n.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:i.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([n.finish()]),r}getPixels(e){let t=this.generateCanvas(e),n=du.getOptimalCanvasAndContext(t.width,t.height),r=n.context;r.drawImage(t,0,0);let{width:i,height:a}=t,o=r.getImageData(0,0,i,a),s=new Uint8ClampedArray(o.data.buffer);return du.returnCanvasAndContext(n),{pixels:s,width:i,height:a}}destroy(){this._managedTextures.destroy();for(let e of Object.keys(this._bindGroupHash)){let t=Number(e);this._bindGroupHash[t]?.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._mipmap3dGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}},ub.extension={type:[I.WebGPUSystem],name:`texture`},ub.uploadExtensions=Object.create(null),db=ub,L.handleByMap(I.TextureUploaderWebGPU,db.uploadExtensions)})),pb=l({WebGPURenderer:()=>xb}),mb,hb,gb,_b,vb,yb,bb,xb,Sb=s((()=>{R(),gh(),xh(),wh(),sm(),rv(),Gd(),ov(),dv(),pv(),gv(),bv(),Sv(),wv(),Uv(),Xv(),my(),Ay(),My(),Iy(),fb(),mb=[...tv,Hv,yv,hv,xv,uv,db,ky,jy,Fy,py,fv,Cv,av],hb=[...nv,Yv],gb=[Ch,bh,hh],_b=[],vb=[],yb=[],bb=[],L.handleByNamedList(I.WebGPUSystem,_b),L.handleByNamedList(I.WebGPUPipes,vb),L.handleByNamedList(I.WebGPUPipesAdaptor,yb),L.handleByNamedList(I.WebGPULoader,bb),L.add(...mb,...hb,...gb),xb=class extends om{constructor(){let e={name:`webgpu`,type:Wd.WEBGPU,systems:_b,renderPipes:vb,renderPipeAdaptors:yb,loaders:bb};super(e)}}})),Cb,wb=s((()=>{R(),B(),Xm(),$m(),sh(),dh(),mh(),Ng(),rf(),tf(),Cb=class{contextChange(e){let t=new ef({uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uTransformMatrix:{value:new z,type:`mat3x3<f32>`},uRound:{value:0,type:`f32`}}),n=e.limits.maxBatchableTextures,r=Ym({name:`graphics`,bits:[Qm,ih(n),uh,ph]});this.shader=new nf({glProgram:r,resources:{localUniforms:t,batchSamplers:jg(n)}})}execute(e,t){let n=t.context,r=n.customShader||this.shader,i=e.renderer,{batcher:a,instructions:o}=i.graphicsContext.getContextRenderData(n);r.groups[0]=i.globalUniforms.bindGroup,i.state.set(e.state),i.shader.bind(r),i.geometry.bind(a.geometry,r.glProgram);let s=o.instructions;for(let e=0;e<o.instructionSize;e++){let t=s[e];if(t.size){for(let e=0;e<t.textures.count;e++)i.texture.bind(t.textures.textures[e],e);i.texture.unbindIntegerTextures(t.textures.count),i.geometry.draw(t.topology,t.size,t.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}},Cb.extension={type:[I.WebGLPipesAdaptor],name:`graphics`}})),Tb,Eb=s((()=>{R(),B(),Xm(),dh(),mh(),yh(),rf(),$o(),W(),Tb=class{init(){let e=Ym({name:`mesh`,bits:[uh,vh,ph]});this._shader=new nf({glProgram:e,resources:{uTexture:q.EMPTY.source,textureUniforms:{uTextureMatrix:{type:`mat3x3<f32>`,value:new z}}}})}execute(e,t){let n=e.renderer,r=t._shader;if(!r){r=this._shader;let e=t.texture,n=e.source;r.resources.uTexture=n,r.resources.uSampler=n.style,r.resources.textureUniforms.uniforms.uTextureMatrix=e.textureMatrix.mapCoord}else if(!r.glProgram){U(`Mesh shader has no glProgram`,t.shader);return}r.groups[100]=n.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,n.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}},Tb.extension={type:[I.WebGLPipesAdaptor],name:`mesh`}})),Db,Ob=s((()=>{R(),hf(),Db=class{constructor(){this._tempState=mf.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,n){let r=e.renderer,i=this._didUploadHash[n.uid];r.shader.bind(n,i),i||(this._didUploadHash[n.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,n.glProgram)}execute(e,t){let n=e.renderer;this._tempState.blendMode=t.blendMode,n.state.set(this._tempState);let r=t.textures.textures;for(let e=0;e<t.textures.count;e++)n.texture.bind(r[e],e);n.texture.unbindIntegerTextures(t.textures.count),n.geometry.draw(t.topology,t.size,t.start)}},Db.extension={type:[I.WebGLPipesAdaptor],name:`batch`}})),kb,Ab=s((()=>{kb=(e=>(e[e.ELEMENT_ARRAY_BUFFER=34963]=`ELEMENT_ARRAY_BUFFER`,e[e.ARRAY_BUFFER=34962]=`ARRAY_BUFFER`,e[e.UNIFORM_BUFFER=35345]=`UNIFORM_BUFFER`,e))(kb||{})})),jb,Mb=s((()=>{jb=class{constructor(e,t){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=e||null,this.updateID=-1,this.byteLength=-1,this.type=t}destroy(){this.buffer=null,this.updateID=-1,this.byteLength=-1,this.type=-1,this._lastBindBaseLocation=-1,this._lastBindCallId=-1}}})),Nb,Pb=s((()=>{R(),cv(),Of(),Ab(),Mb(),Nb=class{constructor(e){this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=e,this._managedBuffers=new sv({renderer:e,type:`resource`,onUnload:this.onBufferUnload.bind(this),name:`glBuffer`})}destroy(){this._managedBuffers.destroy(),this._renderer=null,this._gl=null,this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this.destroyAll(!0),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this.createGLBuffer(e)}bind(e){let{_gl:t}=this,n=this.getGlBuffer(e);t.bindBuffer(n.type,n.buffer)}bindBufferBase(e,t){let{_gl:n}=this;this._boundBufferBases[t]!==e&&(this._boundBufferBases[t]=e,e._lastBindBaseLocation=t,n.bindBufferBase(n.UNIFORM_BUFFER,t,e.buffer))}nextBindBase(e){this._bindCallId++,this._minBaseLocation=0,e&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(e){let t=this.getLastBindBaseLocation(e);if(t>=this._minBaseLocation)return e._lastBindCallId=this._bindCallId,t;let n=0,r=this._nextBindBaseIndex;for(;n<2;){r>=this._maxBindings&&(r=this._minBaseLocation,n++);let e=this._boundBufferBases[r];if(e&&e._lastBindCallId===this._bindCallId)r++;else break}return t=r,this._nextBindBaseIndex=r+1,n>=2?-1:(e._lastBindCallId=this._bindCallId,this._boundBufferBases[t]=null,t)}getLastBindBaseLocation(e){let t=e._lastBindBaseLocation;return this._boundBufferBases[t]===e?t:-1}bindBufferRange(e,t,n,r){let{_gl:i}=this;n||=0,t||=0,this._boundBufferBases[t]=null,i.bindBufferRange(i.UNIFORM_BUFFER,t||0,e.buffer,n*256,r||256)}updateBuffer(e){let{_gl:t}=this,n=this.getGlBuffer(e);if(e._updateID===n.updateID)return n;n.updateID=e._updateID,t.bindBuffer(n.type,n.buffer);let r=e.data,i=e.descriptor.usage&Df.STATIC?t.STATIC_DRAW:t.DYNAMIC_DRAW;return r?n.byteLength>=r.byteLength?t.bufferSubData(n.type,e._updateOffset,r,e._updateOffset/r.BYTES_PER_ELEMENT,(e._updateSize||r.byteLength)/r.BYTES_PER_ELEMENT):(n.byteLength=r.byteLength,t.bufferData(n.type,r,i)):(n.byteLength=e.descriptor.size,t.bufferData(n.type,n.byteLength,i)),n}destroyAll(e=!1){this._managedBuffers.removeAll(e)}onBufferUnload(e,t=!1){let n=e._gpuData[this._renderer.uid];n&&(t||this._gl.deleteBuffer(n.buffer))}createGLBuffer(e){let{_gl:t}=this,n=kb.ARRAY_BUFFER;e.descriptor.usage&Df.INDEX?n=kb.ELEMENT_ARRAY_BUFFER:e.descriptor.usage&Df.UNIFORM&&(n=kb.UNIFORM_BUFFER);let r=new jb(t.createBuffer(),n);return e._gpuData[this._renderer.uid]=r,this._managedBuffers.add(e),r}resetState(){this._boundBufferBases=Object.create(null)}},Nb.extension={type:[I.WebGLSystem],name:`buffer`}})),Fb,Ib,Lb=s((()=>{Jc(),R(),W(),Fb=class e{constructor(e){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=e,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(e){this.gl=e,this._renderer.gl=e}init(t){t={...e.defaultOptions,...t};let n=this.multiView=t.multiView;if(t.context&&n&&(U(`Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together.`),n=!1),this.canvas=n?Y.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this._renderer.view.canvas,t.context)this.initFromContext(t.context);else{let e=this._renderer.background.alpha<1,n=t.premultipliedAlpha??!0,r=t.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(t.preferWebGLVersion,{alpha:e,premultipliedAlpha:n,antialias:r,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference??`default`})}}ensureCanvasSize(e){if(!this.multiView){e!==this.canvas&&U(`multiView is disabled, but targetCanvas is not the main canvas`);return}let{canvas:t}=this;(t.width<e.width||t.height<e.height)&&(t.width=Math.max(e.width,e.width),t.height=Math.max(e.height,e.height))}initFromContext(e){this.gl=e,this.webGLVersion=e instanceof Y.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(e),this._renderer.runners.contextChange.emit(e);let t=this._renderer.view.canvas;t.addEventListener(`webglcontextlost`,this.handleContextLost,!1),t.addEventListener(`webglcontextrestored`,this.handleContextRestored,!1)}createContext(e,t){let n,r=this.canvas;if(e===2&&(n=r.getContext(`webgl2`,t)),!n&&(n=r.getContext(`webgl`,t),!n))throw Error(`This browser does not support WebGL. Try using the canvas renderer`);this.gl=n,this.initFromContext(this.gl)}getExtensions(){let{gl:e}=this,t={anisotropicFiltering:e.getExtension(`EXT_texture_filter_anisotropic`),floatTextureLinear:e.getExtension(`OES_texture_float_linear`),s3tc:e.getExtension(`WEBGL_compressed_texture_s3tc`),s3tc_sRGB:e.getExtension(`WEBGL_compressed_texture_s3tc_srgb`),etc:e.getExtension(`WEBGL_compressed_texture_etc`),etc1:e.getExtension(`WEBGL_compressed_texture_etc1`),pvrtc:e.getExtension(`WEBGL_compressed_texture_pvrtc`)||e.getExtension(`WEBKIT_WEBGL_compressed_texture_pvrtc`),atc:e.getExtension(`WEBGL_compressed_texture_atc`),astc:e.getExtension(`WEBGL_compressed_texture_astc`),bptc:e.getExtension(`EXT_texture_compression_bptc`),rgtc:e.getExtension(`EXT_texture_compression_rgtc`),loseContext:e.getExtension(`WEBGL_lose_context`)};if(this.webGLVersion===1)this.extensions={...t,drawBuffers:e.getExtension(`WEBGL_draw_buffers`),depthTexture:e.getExtension(`WEBGL_depth_texture`),vertexArrayObject:e.getExtension(`OES_vertex_array_object`)||e.getExtension(`MOZ_OES_vertex_array_object`)||e.getExtension(`WEBKIT_OES_vertex_array_object`),uint32ElementIndex:e.getExtension(`OES_element_index_uint`),floatTexture:e.getExtension(`OES_texture_float`),floatTextureLinear:e.getExtension(`OES_texture_float_linear`),textureHalfFloat:e.getExtension(`OES_texture_half_float`),textureHalfFloatLinear:e.getExtension(`OES_texture_half_float_linear`),vertexAttribDivisorANGLE:e.getExtension(`ANGLE_instanced_arrays`),srgb:e.getExtension(`EXT_sRGB`)};else{this.extensions={...t,colorBufferFloat:e.getExtension(`EXT_color_buffer_float`)};let n=e.getExtension(`WEBGL_provoking_vertex`);n&&n.provokingVertexWEBGL(n.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(e){e.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext?.restoreContext()},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){let e=this._renderer.view.canvas;this._renderer=null,e.removeEventListener(`webglcontextlost`,this.handleContextLost),e.removeEventListener(`webglcontextrestored`,this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext?.loseContext()}forceContextLoss(){this.extensions.loseContext?.loseContext(),this._contextLossForced=!0}validateContext(e){let t=e.getContextAttributes();t&&!t.stencil&&U(`Provided WebGL context does not have a stencil buffer, masks may not render correctly`);let n=this.supports,r=this.webGLVersion===2,i=this.extensions;n.uint32Indices=r||!!i.uint32ElementIndex,n.uniformBufferObject=r,n.vertexArrayObject=r||!!i.vertexArrayObject,n.srgbTextures=r||!!i.srgb,n.nonPowOf2wrapping=r,n.nonPowOf2mipmaps=r,n.msaa=r,n.uint32Indices||U(`Provided WebGL context does not support 32 index buffer, large scenes may not render correctly`)}},Fb.extension={type:[I.WebGLSystem],name:`context`},Fb.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1},Ib=Fb})),Rb,zb,Bb,Vb=s((()=>{Rb=(e=>(e[e.RGBA=6408]=`RGBA`,e[e.RGB=6407]=`RGB`,e[e.RG=33319]=`RG`,e[e.RED=6403]=`RED`,e[e.RGBA_INTEGER=36249]=`RGBA_INTEGER`,e[e.RGB_INTEGER=36248]=`RGB_INTEGER`,e[e.RG_INTEGER=33320]=`RG_INTEGER`,e[e.RED_INTEGER=36244]=`RED_INTEGER`,e[e.ALPHA=6406]=`ALPHA`,e[e.LUMINANCE=6409]=`LUMINANCE`,e[e.LUMINANCE_ALPHA=6410]=`LUMINANCE_ALPHA`,e[e.DEPTH_COMPONENT=6402]=`DEPTH_COMPONENT`,e[e.DEPTH_STENCIL=34041]=`DEPTH_STENCIL`,e))(Rb||{}),zb=(e=>(e[e.TEXTURE_2D=3553]=`TEXTURE_2D`,e[e.TEXTURE_CUBE_MAP=34067]=`TEXTURE_CUBE_MAP`,e[e.TEXTURE_2D_ARRAY=35866]=`TEXTURE_2D_ARRAY`,e[e.TEXTURE_3D=32879]=`TEXTURE_3D`,e[e.TEXTURE_CUBE_MAP_POSITIVE_X=34069]=`TEXTURE_CUBE_MAP_POSITIVE_X`,e[e.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]=`TEXTURE_CUBE_MAP_NEGATIVE_X`,e[e.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]=`TEXTURE_CUBE_MAP_POSITIVE_Y`,e[e.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]=`TEXTURE_CUBE_MAP_NEGATIVE_Y`,e[e.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]=`TEXTURE_CUBE_MAP_POSITIVE_Z`,e[e.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]=`TEXTURE_CUBE_MAP_NEGATIVE_Z`,e))(zb||{}),Bb=(e=>(e[e.UNSIGNED_BYTE=5121]=`UNSIGNED_BYTE`,e[e.UNSIGNED_SHORT=5123]=`UNSIGNED_SHORT`,e[e.UNSIGNED_SHORT_5_6_5=33635]=`UNSIGNED_SHORT_5_6_5`,e[e.UNSIGNED_SHORT_4_4_4_4=32819]=`UNSIGNED_SHORT_4_4_4_4`,e[e.UNSIGNED_SHORT_5_5_5_1=32820]=`UNSIGNED_SHORT_5_5_5_1`,e[e.UNSIGNED_INT=5125]=`UNSIGNED_INT`,e[e.UNSIGNED_INT_10F_11F_11F_REV=35899]=`UNSIGNED_INT_10F_11F_11F_REV`,e[e.UNSIGNED_INT_2_10_10_10_REV=33640]=`UNSIGNED_INT_2_10_10_10_REV`,e[e.UNSIGNED_INT_24_8=34042]=`UNSIGNED_INT_24_8`,e[e.UNSIGNED_INT_5_9_9_9_REV=35902]=`UNSIGNED_INT_5_9_9_9_REV`,e[e.BYTE=5120]=`BYTE`,e[e.SHORT=5122]=`SHORT`,e[e.INT=5124]=`INT`,e[e.FLOAT=5126]=`FLOAT`,e[e.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]=`FLOAT_32_UNSIGNED_INT_24_8_REV`,e[e.HALF_FLOAT=36193]=`HALF_FLOAT`,e))(Bb||{})}));function Hb(e){return Ub[e]??Ub.float32}var Ub,Wb=s((()=>{Vb(),Ub={uint8x2:Bb.UNSIGNED_BYTE,uint8x4:Bb.UNSIGNED_BYTE,sint8x2:Bb.BYTE,sint8x4:Bb.BYTE,unorm8x2:Bb.UNSIGNED_BYTE,unorm8x4:Bb.UNSIGNED_BYTE,snorm8x2:Bb.BYTE,snorm8x4:Bb.BYTE,uint16x2:Bb.UNSIGNED_SHORT,uint16x4:Bb.UNSIGNED_SHORT,sint16x2:Bb.SHORT,sint16x4:Bb.SHORT,unorm16x2:Bb.UNSIGNED_SHORT,unorm16x4:Bb.UNSIGNED_SHORT,snorm16x2:Bb.SHORT,snorm16x4:Bb.SHORT,float16x2:Bb.HALF_FLOAT,float16x4:Bb.HALF_FLOAT,float32:Bb.FLOAT,float32x2:Bb.FLOAT,float32x3:Bb.FLOAT,float32x4:Bb.FLOAT,uint32:Bb.UNSIGNED_INT,uint32x2:Bb.UNSIGNED_INT,uint32x3:Bb.UNSIGNED_INT,uint32x4:Bb.UNSIGNED_INT,sint32:Bb.INT,sint32x2:Bb.INT,sint32x3:Bb.INT,sint32x4:Bb.INT}})),Gb,Kb,qb,Jb=s((()=>{R(),cv(),xd(),$v(),Wb(),Gb={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5},Kb=class{constructor(){this.vaoCache=Object.create(null)}destroy(){this.vaoCache=Object.create(null)}},qb=class{constructor(e){this._renderer=e,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._managedGeometries=new sv({renderer:e,type:`resource`,onUnload:this.onGeometryUnload.bind(this),name:`glGeometry`})}contextChange(){let e=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw Error(`[PixiJS] Vertex Array Objects are not supported on this device`);this.destroyAll(!0);let t=this._renderer.context.extensions.vertexArrayObject;t&&(e.createVertexArray=()=>t.createVertexArrayOES(),e.bindVertexArray=e=>t.bindVertexArrayOES(e),e.deleteVertexArray=e=>t.deleteVertexArrayOES(e));let n=this._renderer.context.extensions.vertexAttribDivisorANGLE;n&&(e.drawArraysInstanced=(e,t,r,i)=>{n.drawArraysInstancedANGLE(e,t,r,i)},e.drawElementsInstanced=(e,t,r,i,a)=>{n.drawElementsInstancedANGLE(e,t,r,i,a)},e.vertexAttribDivisor=(e,t)=>n.vertexAttribDivisorANGLE(e,t)),this._activeGeometry=null,this._activeVao=null}bind(e,t){let n=this.gl;this._activeGeometry=e;let r=this.getVao(e,t);this._activeVao!==r&&(this._activeVao=r,n.bindVertexArray(r)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){let e=this._activeGeometry,t=this._renderer.buffer;for(let n=0;n<e.buffers.length;n++){let r=e.buffers[n];t.updateBuffer(r)}e._gcLastUsed=this._renderer.gc.now}checkCompatibility(e,t){let n=e.attributes,r=t._attributeData;for(let e in r)if(!n[e])throw Error(`shader and geometry incompatible, geometry missing the "${e}" attribute`)}getSignature(e,t){let n=e.attributes,r=t._attributeData,i=[`g`,e.uid];for(let e in n)r[e]&&i.push(e,r[e].location);return i.join(`-`)}getVao(e,t){return e._gpuData[this._renderer.uid]?.vaoCache[t._key]||this.initGeometryVao(e,t)}initGeometryVao(e,t,n=!0){let r=this._renderer.gl,i=this._renderer.buffer;this._renderer.shader._getProgramData(t),this.checkCompatibility(e,t);let a=this.getSignature(e,t),o=e._gpuData[this._renderer.uid];o||(o=new Kb,e._gpuData[this._renderer.uid]=o,this._managedGeometries.add(e));let s=o.vaoCache,c=s[a];if(c)return s[t._key]=c,c;Zv(e,t._attributeData);let l=e.buffers;c=r.createVertexArray(),r.bindVertexArray(c);for(let e=0;e<l.length;e++){let t=l[e];i.bind(t)}return this.activateVao(e,t),s[t._key]=c,s[a]=c,r.bindVertexArray(null),c}onGeometryUnload(e,t=!1){let n=e._gpuData[this._renderer.uid];if(!n)return;let r=n.vaoCache;if(!t)for(let e in r)this._activeVao===r[e]&&this.resetState(),this.gl.deleteVertexArray(r[e])}destroyAll(e=!1){this._managedGeometries.removeAll(e)}activateVao(e,t){let n=this._renderer.gl,r=this._renderer.buffer,i=e.attributes;e.indexBuffer&&r.bind(e.indexBuffer);let a=null;for(let e in i){let o=i[e],s=o.buffer,c=r.getGlBuffer(s),l=t._attributeData[e];if(l){a!==c&&(r.bind(s),a=c);let e=l.location;n.enableVertexAttribArray(e);let t=yd(o.format),i=Hb(o.format);if(l.format?.substring(1,4)===`int`?n.vertexAttribIPointer(e,t.size,i,o.stride,o.offset):n.vertexAttribPointer(e,t.size,i,t.normalised,o.stride,o.offset),o.instance){if(this.hasInstance){let t=o.divisor??1;n.vertexAttribDivisor(e,t)}else throw Error(`geometry error, GPU Instancing is not supported on this device`)}}}}draw(e,t,n,r){let{gl:i}=this._renderer,a=this._activeGeometry,o=Gb[e||a.topology];if(r??=a.instanceCount,a.indexBuffer){let e=a.indexBuffer.data.BYTES_PER_ELEMENT,s=e===2?i.UNSIGNED_SHORT:i.UNSIGNED_INT,c=t||a.indexCount||a.indexBuffer.data.length,l=(n||0)*e;r===1?i.drawElements(o,c,s,l):i.drawElementsInstanced(o,c,s,l,r)}else r===1?i.drawArrays(o,n||0,t||a.vertexCount):i.drawArraysInstanced(o,n||0,t||a.vertexCount,r);return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._managedGeometries.destroy(),this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null}},qb.extension={type:[I.WebGLSystem],name:`geometry`}})),Yb,Xb,Zb,Qb=s((()=>{R(),W(),Lf(),rf(),hf(),Po(),$o(),vd(),Yb=new If({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Xb=class e{constructor(e){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=e}init(t={}){let{useBackBuffer:n,antialias:r}={...e.defaultOptions,...t};this.useBackBuffer=n,this._antialias=r,this._renderer.context.supports.msaa||(U(`antialiasing, is not supported on when using the back buffer`),this._antialias=!1),this._state=mf.for2d();let i=new _d({vertex:`
|
|
791
|
-
attribute vec2 aPosition;
|
|
792
|
-
out vec2 vUv;
|
|
793
|
-
|
|
794
|
-
void main() {
|
|
795
|
-
gl_Position = vec4(aPosition, 0.0, 1.0);
|
|
796
|
-
|
|
797
|
-
vUv = (aPosition + 1.0) / 2.0;
|
|
798
|
-
|
|
799
|
-
// flip dem UVs
|
|
800
|
-
vUv.y = 1.0 - vUv.y;
|
|
801
|
-
}`,fragment:`
|
|
802
|
-
in vec2 vUv;
|
|
803
|
-
out vec4 finalColor;
|
|
804
|
-
|
|
805
|
-
uniform sampler2D uTexture;
|
|
806
|
-
|
|
807
|
-
void main() {
|
|
808
|
-
finalColor = texture(uTexture, vUv);
|
|
809
|
-
}`,name:`big-triangle`});this._bigTriangleShader=new nf({glProgram:i,resources:{uTexture:q.WHITE.source}})}renderStart(e){let t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){let t=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=t.colorTexture,e.target=this._getBackBufferTexture(t.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){let e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind({target:this._targetTexture,clear:!1}),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:Yb,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new q({source:new No({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&=(this._backBufferTexture.destroy(),null)}},Xb.extension={type:[I.WebGLSystem],name:`backBuffer`,priority:1},Xb.defaultOptions={useBackBuffer:!1},Zb=Xb})),$b,ex=s((()=>{R(),$b=class{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}},$b.extension={type:[I.WebGLSystem],name:`colorMask`}})),tx,nx=s((()=>{R(),tx=class{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){let t=this._renderer,{geometry:n,shader:r,state:i,skipSync:a,topology:o,size:s,start:c,instanceCount:l}=e;t.shader.bind(r,a),t.geometry.bind(n,t.shader._activeProgram),i&&t.state.set(i),t.geometry.draw(o,s,c,l??n.instanceCount)}destroy(){this._renderer=null}},tx.extension={type:[I.WebGLSystem],name:`encoder`}})),rx,ix=s((()=>{R(),fg(),rx=class{constructor(e){this._renderer=e}contextChange(){let e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=ug(this.maxTextures,e);let t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}},rx.extension={type:[I.WebGLSystem],name:`limits`}})),ax,ox=s((()=>{R(),ty(),og(),ax=class{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:ag.NONE},this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this._activeGpuRenderTarget=null,this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let t=this._renderer.renderTarget.getGpuRenderTarget(e);this._activeGpuRenderTarget=t,this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=ag.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){let n=this._activeGpuRenderTarget??=this._renderer.renderTarget.getGpuRenderTarget(this._activeRenderTarget),r=this._gl,i=ey[e],a=this._stencilCache;n.stencilMode=e,n.stencilReference=t,e===ag.DISABLED?this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST)):(this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(e!==a.stencilMode||a.stencilReference!==t)&&(a.stencilMode=e,a.stencilReference=t,r.stencilFunc(this._comparisonFuncMapping[i.stencilBack.compare],t,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[i.stencilBack.passOp])))}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._gl=null,this._activeRenderTarget=null,this._activeGpuRenderTarget=null}},ax.extension={type:[I.WebGLSystem],name:`stencil`}}));function sx(e){let t=e.map(e=>({data:e,offset:0,size:0})),n=0,r=0;for(let e=0;e<t.length;e++){let i=t[e];if(n=cx[i.data.type],!n)throw Error(`Unknown type ${i.data.type}`);i.data.size>1&&(n=Math.max(n,16)*i.data.size);let a=n===12?16:n;i.size=n;let o=r%16;o>0&&16-o<a?r+=(16-o)%16:r+=(n-o%n)%n,i.offset=r,r+=n}return r=Math.ceil(r/16)*16,{uboElements:t,size:r}}var cx,lx=s((()=>{cx={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,u32:4,"vec2<u32>":8,"vec3<u32>":12,"vec4<u32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64}}));function ux(e,t){let n=Math.max(cx[e.data.type]/16,1),r=e.data.value.length/e.data.size,i=(4-r%4)%4,a=e.data.type.indexOf(`i32`)>=0?`dataInt32`:`data`;return`
|
|
810
|
-
v = uv.${e.data.name};
|
|
811
|
-
offset += ${t};
|
|
812
|
-
|
|
813
|
-
arrayOffset = offset;
|
|
814
|
-
|
|
815
|
-
t = 0;
|
|
816
|
-
|
|
817
|
-
for(var i=0; i < ${e.data.size*n}; i++)
|
|
818
|
-
{
|
|
819
|
-
for(var j = 0; j < ${r}; j++)
|
|
820
|
-
{
|
|
821
|
-
${a}[arrayOffset++] = v[t++];
|
|
822
|
-
}
|
|
823
|
-
${i===0?``:`arrayOffset += ${i};`}
|
|
824
|
-
}
|
|
825
|
-
`}var dx=s((()=>{lx()}));function fx(e){return Mv(e,Fv,ux)}var px=s((()=>{Nv(),Lv(),dx()})),mx,hx=s((()=>{R(),Ev(),lx(),px(),mx=class extends Tv{constructor(){super({createUboElements:sx,generateUboSync:fx})}},mx.extension={type:[I.WebGLSystem],name:`ubo`}})),gx,_x=s((()=>{og(),gx=class{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this._attachedMipLevel=0,this._attachedLayer=0,this.msaaRenderBuffer=[],this.stencilMode=ag.DISABLED,this.stencilReference=0,this.maskStackIndex=0}}})),vx,yx=s((()=>{Pa(),W(),zl(),tm(),_x(),vx=class{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new G,this._boundFramebuffer=void 0}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new G,this._boundFramebuffer=void 0;let e=this._renderer.gl;this._drawBuffersCache=[];for(let t=1;t<=16;t++)this._drawBuffersCache[t]=Array.from({length:t},(t,n)=>e.COLOR_ATTACHMENT0+n)}copyToTexture(e,t,n,r,i){let a=this._renderTargetSystem,o=this._renderer,s=a.getGpuRenderTarget(e),c=o.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,s.resolveTargetFramebuffer),this._boundFramebuffer=s.resolveTargetFramebuffer,o.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,i.x,i.y,n.x,n.y,r.width,r.height),t}copyDepthTexture(e,t,n,r,i){let a=this._renderTargetSystem,o=this._renderer.gl;this.finishRenderPass(e);let s=a.getRenderTarget(t),c=a.getGpuRenderTarget(e),l=a.getGpuRenderTarget(s);o.bindFramebuffer(o.READ_FRAMEBUFFER,c.framebuffer),o.bindFramebuffer(o.DRAW_FRAMEBUFFER,l.framebuffer),this._boundFramebuffer=void 0,o.blitFramebuffer(n.x,n.y,n.x+r.width,n.y+r.height,i.x,i.y,i.x+r.width,i.y+r.height,o.DEPTH_BUFFER_BIT,o.NEAREST)}startRenderPass(e,t=!0,n,r,i=0,a=0){let o=this._renderTargetSystem.getGpuRenderTarget(e);if(a!==0&&this._renderer.context.webGLVersion<2)throw Error(`[RenderTargetSystem] Rendering to array layers requires WebGL2.`);if(i>0){if(o.msaa)throw Error(`[RenderTargetSystem] Rendering to mip levels is not supported with MSAA render targets.`);if(this._renderer.context.webGLVersion<2)throw Error(`[RenderTargetSystem] Rendering to mip levels requires WebGL2.`)}e.colorAttachments.forEach(e=>{this._renderer.texture.unbind(e.texture)});let s=this._renderer.gl;this.bindFramebuffer(o.framebuffer),!e.isRoot&&e.colorAttachments.length>0&&(o._attachedMipLevel!==i||o._attachedLayer!==a)&&(e.colorAttachments.forEach((e,t)=>{let n=e.texture,r=this._renderer.texture.getGlSource(n);if(r.target===s.TEXTURE_2D){if(a!==0)throw Error(`[RenderTargetSystem] layer must be 0 when rendering to 2D textures in WebGL.`);s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+t,s.TEXTURE_2D,r.texture,i)}else if(r.target===s.TEXTURE_2D_ARRAY||r.target===s.TEXTURE_3D)s.framebufferTextureLayer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+t,r.texture,i,a);else if(r.target===s.TEXTURE_CUBE_MAP){if(a<0||a>5)throw Error(`[RenderTargetSystem] Cube map layer must be between 0 and 5.`);s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+t,s.TEXTURE_CUBE_MAP_POSITIVE_X+a,r.texture,i)}else throw Error(`[RenderTargetSystem] Unsupported texture target for render-to-layer in WebGL.`)}),o._attachedMipLevel=i,o._attachedLayer=a),o.framebuffer&&(e.depthStencilAttachment?this._attachDepthStencilTexture(e,i,a):!o.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(o)),e.colorAttachments.length>1&&this._setDrawBuffers(e,s);let c=r.y;e.isRoot&&(c=e.pixelHeight-r.height-r.y);let l=this._viewPortCache;(l.x!==r.x||l.y!==c||l.width!==r.width||l.height!==r.height)&&(l.x=r.x,l.y=c,l.width=r.width,l.height=r.height,s.viewport(r.x,c,r.width,r.height)),this.clear(e,t,n)}finishRenderPass(e){let t=this._renderTargetSystem.getGpuRenderTarget(e);if(!t.msaa||e.colorAttachments.length===0)return;let n=this._renderer.gl;n.bindFramebuffer(n.FRAMEBUFFER,t.resolveTargetFramebuffer),n.bindFramebuffer(n.READ_FRAMEBUFFER,t.framebuffer),n.blitFramebuffer(0,0,t.width,t.height,0,0,t.width,t.height,n.COLOR_BUFFER_BIT,n.NEAREST),n.bindFramebuffer(n.FRAMEBUFFER,t.framebuffer),this._boundFramebuffer=t.framebuffer}initGpuRenderTarget(e){let t=this._renderer.gl,n=new gx;n._attachedMipLevel=0,n._attachedLayer=0;let r=e.colorTexture;return r instanceof Rl?(this._renderer.context.ensureCanvasSize(r.resource),n.framebuffer=null,n):(n.width=e.pixelWidth,n.height=e.pixelHeight,e.colorAttachments.length===0?this._initDepth(e,n):this._initColor(e,n),e.depthStencilAttachment&&this._attachDepthStencilTexture(e,0,0),t.bindFramebuffer(t.FRAMEBUFFER,null),this._boundFramebuffer=null,n)}destroyGpuRenderTarget(e){let t=this._renderer.gl;e.framebuffer&&=(t.deleteFramebuffer(e.framebuffer),null),e.resolveTargetFramebuffer&&=(t.deleteFramebuffer(e.resolveTargetFramebuffer),null),e.depthStencilRenderBuffer&&=(t.deleteRenderbuffer(e.depthStencilRenderBuffer),null),e.msaaRenderBuffer.forEach(e=>{t.deleteRenderbuffer(e)}),e.msaaRenderBuffer.length=0}clear(e,t,n,r,i=0,a=0){if(!t)return;if(a!==0)throw Error(`[RenderTargetSystem] Clearing array layers is not supported in WebGL renderer.`);let o=this._renderTargetSystem;if(typeof t==`boolean`&&(t=t?em.ALL:em.NONE),e.colorAttachments.length===0&&(t&=~em.COLOR,!t))return;let s=this._renderer.gl,c=!!(t&em.DEPTH)&&!this._renderer.state.depthMaskEnabled;if(t&em.COLOR){n??=o.defaultClearColor;let e=this._clearColorCache,t=n;(e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3])&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],s.clearColor(t[0],t[1],t[2],t[3]))}c&&s.depthMask(!0),s.clear(t),c&&s.depthMask(!1)}resizeGpuRenderTarget(e){if(e.isRoot)return;let t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.pixelWidth,t.height=e.pixelHeight,e.colorAttachments.length>0&&this._resizeColor(e,t),t.depthStencilRenderBuffer&&this._resizeStencil(t),this._boundFramebuffer=void 0}_initColor(e,t){let n=this._renderer,r=n.gl,i=r.createFramebuffer();if(t.resolveTargetFramebuffer=i,r.bindFramebuffer(r.FRAMEBUFFER,i),e.colorAttachments.forEach((e,i)=>{let a=e.texture;a.antialias&&(n.context.supports.msaa?t.msaa=!0:U(`[RenderTexture] Antialiasing on textures is not supported in WebGL1`)),n.texture.bindSource(a,0);let o=n.texture.getGlSource(a),s=o.texture;if(o.target===r.TEXTURE_2D)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+i,r.TEXTURE_2D,s,0);else if(o.target===r.TEXTURE_2D_ARRAY||o.target===r.TEXTURE_3D)r.framebufferTextureLayer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+i,s,0,0);else if(o.target===r.TEXTURE_CUBE_MAP)r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+i,r.TEXTURE_CUBE_MAP_POSITIVE_X,s,0);else throw Error(`[RenderTargetSystem] Unsupported texture target for framebuffer attachment.`)}),t.msaa){let n=r.createFramebuffer();t.framebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),e.colorAttachments.forEach((e,n)=>{let i=r.createRenderbuffer();t.msaaRenderBuffer[n]=i})}else t.framebuffer=i;this._resizeColor(e,t)}_initDepth(e,t){let n=this._renderer;if(n.context.webGLVersion<2)throw Error(`[RenderTargetSystem] Depth-only render targets require WebGL2.`);let r=n.gl,i=r.createFramebuffer();t.resolveTargetFramebuffer=i,t.framebuffer=i,r.bindFramebuffer(r.FRAMEBUFFER,i),r.drawBuffers([r.NONE]),r.readBuffer(r.NONE)}_resizeColor(e,t){let n=e.colorAttachments[0].texture;if(t._attachedMipLevel=0,t._attachedLayer=0,e.colorAttachments.forEach((e,t)=>{t!==0&&e.texture.resize(n.width,n.height,n._resolution)}),t.msaa){let n=this._renderer,r=n.gl,i=t.framebuffer;r.bindFramebuffer(r.FRAMEBUFFER,i),e.colorAttachments.forEach((e,i)=>{let a=e.texture;n.texture.bindSource(a,0);let o=n.texture.getGlSource(a).internalFormat,s=t.msaaRenderBuffer[i];r.bindRenderbuffer(r.RENDERBUFFER,s),r.renderbufferStorageMultisample(r.RENDERBUFFER,4,o,a.pixelWidth,a.pixelHeight),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+i,r.RENDERBUFFER,s)})}}_attachDepthStencilTexture(e,t,n){let r=this._renderer,i=r.gl,a=e.depthStencilAttachment.texture,o=r.texture.getGlSource(a),s=o.texture,c=a.format,l;l=c===`depth24plus-stencil8`||c===`depth32float-stencil8`?i.DEPTH_STENCIL_ATTACHMENT:c===`stencil8`?i.STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,o.target===i.TEXTURE_2D?i.framebufferTexture2D(i.FRAMEBUFFER,l,i.TEXTURE_2D,s,t):o.target===i.TEXTURE_2D_ARRAY||o.target===i.TEXTURE_3D?i.framebufferTextureLayer(i.FRAMEBUFFER,l,s,t,n):o.target===i.TEXTURE_CUBE_MAP&&i.framebufferTexture2D(i.FRAMEBUFFER,l,i.TEXTURE_CUBE_MAP_POSITIVE_X+n,s,t)}_initStencil(e){if(e.framebuffer===null)return;let t=this._renderer.gl,n=t.createRenderbuffer();e.depthStencilRenderBuffer=n,t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,n),this._resizeStencil(e)}_resizeStencil(e){let t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){if(e.colorAttachments.length===0)return;let t=e.colorAttachments[0].texture.resource;this._renderer.context.multiView&&Rl.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(!this._renderer.context.multiView||e.colorAttachments.length===0)return;let t=e.colorAttachments[0].texture;if(Rl.test(t.resource)){let e=this._renderer.context.canvas,n=t;n.context2D.drawImage(e,0,n.pixelHeight-e.height)}}_setDrawBuffers(e,t){let n=e.colorAttachments.length,r=this._drawBuffersCache[n];if(this._renderer.context.webGLVersion===1){let e=this._renderer.context.extensions.drawBuffers;e?e.drawBuffersWEBGL(r):U(`[RenderTexture] This WebGL1 context does not support rendering to multiple targets`)}else t.drawBuffers(r)}resetState(){this._boundFramebuffer=void 0,this._viewPortCache=new G,this._clearColorCache=[0,0,0,0]}bindFramebuffer(e){this._boundFramebuffer!==e&&(this._boundFramebuffer=e,this._renderer.gl.bindFramebuffer(this._renderer.gl.FRAMEBUFFER,e))}}})),bx,xx=s((()=>{R(),by(),yx(),bx=class extends yy{constructor(e){super(e),this.adaptor=new vx,this.adaptor.init(e,this)}resetState(){this.adaptor.resetState()}},bx.extension={type:[I.WebGLSystem],name:`renderTarget`}})),Sx,Cx=s((()=>{ri(),ea(),Sx=class extends ni{constructor(e,t){super(),this._resourceType=`textureView`,this._resourceId=Qi(`resource`),this.source=e,this.viewDescriptor=t,this._onChange=this._onChange.bind(this),this._onDestroy=this._onDestroy.bind(this),this.source.on(`change`,this._onChange),this.source.on(`destroy`,this._onDestroy)}_onChange(){this.emit(`change`,this)}_onDestroy(){this.destroy()}get destroyed(){return this.source.destroyed}destroy(){this.source&&(this.source.off(`change`,this._onChange),this.source.off(`destroy`,this._onDestroy)),this.emit(`destroy`,this),this.removeAllListeners()}}}));function wx(e,t){let n=[],r=[`
|
|
826
|
-
var g = s.groups;
|
|
827
|
-
var sS = r.shader;
|
|
828
|
-
var p = s.glProgram;
|
|
829
|
-
var ugS = r.uniformGroup;
|
|
830
|
-
var resources;
|
|
831
|
-
`],i=!1,a=0,o=t._getProgramData(e.glProgram);for(let s in e.groups){let c=e.groups[s];n.push(`
|
|
832
|
-
resources = g[${s}].resources;
|
|
833
|
-
`);for(let l in c.resources){let u=c.resources[l];if(u instanceof ef){if(u.ubo){let t=e._uniformBindMap[s][Number(l)];n.push(`
|
|
834
|
-
sS.bindUniformBlock(
|
|
835
|
-
resources[${l}],
|
|
836
|
-
'${t}',
|
|
837
|
-
${e.glProgram._uniformBlockData[t].index}
|
|
838
|
-
);
|
|
839
|
-
`)}else n.push(`
|
|
840
|
-
ugS.updateUniformGroup(resources[${l}], p, sD);
|
|
841
|
-
`)}else if(u instanceof Wv){let t=e._uniformBindMap[s][Number(l)];n.push(`
|
|
842
|
-
sS.bindUniformBlock(
|
|
843
|
-
resources[${l}],
|
|
844
|
-
'${t}',
|
|
845
|
-
${e.glProgram._uniformBlockData[t].index}
|
|
846
|
-
);
|
|
847
|
-
`)}else if(u instanceof No||u instanceof Sx){let c=e._uniformBindMap[s][l],u=o.uniformData[c];u&&(i||(i=!0,r.push(`
|
|
848
|
-
var tS = r.texture;
|
|
849
|
-
`)),t._gl.uniform1i(u.location,a),n.push(`
|
|
850
|
-
tS.bind(resources[${l}], ${a});
|
|
851
|
-
`),a++)}}}let s=[...r,...n].join(`
|
|
852
|
-
`);return Function(`r`,`s`,`sD`,s)}var Tx=s((()=>{Gv(),tf(),Po(),Cx()})),Ex,Dx=s((()=>{Ex=class{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}}));function Ox(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var kx=s((()=>{}));function Ax(e){let t=Array(e);for(let e=0;e<t.length;e++)t[e]=!1;return t}function jx(e,t){switch(e){case`float`:return 0;case`vec2`:return new Float32Array(2*t);case`vec3`:return new Float32Array(3*t);case`vec4`:return new Float32Array(4*t);case`int`:case`uint`:case`sampler2D`:case`sampler2DArray`:case`sampler3D`:return 0;case`ivec2`:return new Int32Array(2*t);case`ivec3`:return new Int32Array(3*t);case`ivec4`:return new Int32Array(4*t);case`uvec2`:return new Uint32Array(2*t);case`uvec3`:return new Uint32Array(3*t);case`uvec4`:return new Uint32Array(4*t);case`bool`:return!1;case`bvec2`:return Ax(2*t);case`bvec3`:return Ax(3*t);case`bvec4`:return Ax(4*t);case`mat2`:return new Float32Array([1,0,0,1]);case`mat3`:return new Float32Array([1,0,0,0,1,0,0,0,1]);case`mat4`:return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}var Mx=s((()=>{}));function Nx(e,t){if(!Fx){let t=Object.keys(Ix);Fx={};for(let n=0;n<t.length;++n){let r=t[n];Fx[e[r]]=Ix[r]}}return Fx[t]}function Px(e,t){let n=Nx(e,t);return Lx[n]||`float32`}var Fx,Ix,Lx,Rx=s((()=>{Fx=null,Ix={FLOAT:`float`,FLOAT_VEC2:`vec2`,FLOAT_VEC3:`vec3`,FLOAT_VEC4:`vec4`,INT:`int`,INT_VEC2:`ivec2`,INT_VEC3:`ivec3`,INT_VEC4:`ivec4`,UNSIGNED_INT:`uint`,UNSIGNED_INT_VEC2:`uvec2`,UNSIGNED_INT_VEC3:`uvec3`,UNSIGNED_INT_VEC4:`uvec4`,BOOL:`bool`,BOOL_VEC2:`bvec2`,BOOL_VEC3:`bvec3`,BOOL_VEC4:`bvec4`,FLOAT_MAT2:`mat2`,FLOAT_MAT3:`mat3`,FLOAT_MAT4:`mat4`,SAMPLER_2D:`sampler2D`,INT_SAMPLER_2D:`sampler2D`,UNSIGNED_INT_SAMPLER_2D:`sampler2D`,SAMPLER_2D_SHADOW:`sampler2DShadow`,SAMPLER_CUBE:`samplerCube`,INT_SAMPLER_CUBE:`samplerCube`,UNSIGNED_INT_SAMPLER_CUBE:`samplerCube`,SAMPLER_CUBE_SHADOW:`samplerCubeShadow`,SAMPLER_2D_ARRAY:`sampler2DArray`,INT_SAMPLER_2D_ARRAY:`sampler2DArray`,UNSIGNED_INT_SAMPLER_2D_ARRAY:`sampler2DArray`,SAMPLER_2D_ARRAY_SHADOW:`sampler2DArrayShadow`,SAMPLER_3D:`sampler3D`,INT_SAMPLER_3D:`sampler3D`,UNSIGNED_INT_SAMPLER_3D:`sampler3D`},Lx={float:`float32`,vec2:`float32x2`,vec3:`float32x3`,vec4:`float32x4`,int:`sint32`,ivec2:`sint32x2`,ivec3:`sint32x3`,ivec4:`sint32x4`,uint:`uint32`,uvec2:`uint32x2`,uvec3:`uint32x3`,uvec4:`uint32x4`,bool:`uint32`,bvec2:`uint32x2`,bvec3:`uint32x3`,bvec4:`uint32x4`}}));function zx(e,t,n=!1){let r={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let n=0;n<i;n++){let i=t.getActiveAttrib(e,n);if(i.name.startsWith(`gl_`))continue;let a=Px(t,i.type);r[i.name]={location:0,format:a,stride:yd(a).stride,offset:0,instance:!1,start:0}}let a=Object.keys(r);if(n){a.sort((e,t)=>e>t?1:-1);for(let n=0;n<a.length;n++)r[a[n]].location=n,t.bindAttribLocation(e,n,a[n]);t.linkProgram(e)}else for(let n=0;n<a.length;n++)r[a[n]].location=t.getAttribLocation(e,a[n]);return r}var Bx=s((()=>{xd(),Rx()}));function Vx(e,t){if(!t.ACTIVE_UNIFORM_BLOCKS)return{};let n={},r=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let i=0;i<r;i++){let r=t.getActiveUniformBlockName(e,i);n[r]={name:r,index:t.getUniformBlockIndex(e,r),size:t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_DATA_SIZE)}}return n}var Hx=s((()=>{}));function Ux(e,t){let n={},r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS);for(let i=0;i<r;i++){let r=t.getActiveUniform(e,i),a=r.name.replace(/\[.*?\]$/,``),o=!!r.name.match(/\[.*?\]$/),s=Nx(t,r.type);n[a]={name:a,index:i,type:s,size:r.size,isArray:o,value:jx(s,r.size)}}return n}var Wx=s((()=>{Mx(),Rx()}));function Gx(e,t){let n=e.getShaderSource(t);if(n===null){console.error(`PixiJS Error: Could not retrieve shader source (WebGL context may be lost).`);return}let r=n.split(`
|
|
853
|
-
`).map((e,t)=>`${t}: ${e}`),i=e.getShaderInfoLog(t)??``,a=i.split(`
|
|
854
|
-
`),o={},s=a.map(e=>parseFloat(e.replace(/^ERROR\: 0\:([\d]+)\:.*$/,`$1`))).filter(e=>e&&!o[e]?(o[e]=!0,!0):!1),c=[``];s.forEach(e=>{r[e-1]=`%c${r[e-1]}%c`,c.push(`background: #FF0000; color:#FFFFFF; font-size: 10px`,`font-size: 10px`)}),c[0]=r.join(`
|
|
855
|
-
`),console.error(i),console.groupCollapsed(`click to view full shader code`),console.warn(...c),console.groupEnd()}function Kx(e,t,n,r){e.getProgramParameter(t,e.LINK_STATUS)||(e.getShaderParameter(n,e.COMPILE_STATUS)||Gx(e,n),e.getShaderParameter(r,e.COMPILE_STATUS)||Gx(e,r),console.error(`PixiJS Error: Could not initialize shader.`),e.getProgramInfoLog(t)!==``&&console.warn(`PixiJS Warning: gl.getProgramInfoLog()`,e.getProgramInfoLog(t)))}var qx=s((()=>{}));function Jx(e,t){let n=Ox(e,e.VERTEX_SHADER,t.vertex),r=Ox(e,e.FRAGMENT_SHADER,t.fragment),i=e.createProgram();e.attachShader(i,n),e.attachShader(i,r);let a=t.transformFeedbackVaryings;a&&(typeof e.transformFeedbackVaryings==`function`?e.transformFeedbackVaryings(i,a.names,a.bufferMode===`separate`?e.SEPARATE_ATTRIBS:e.INTERLEAVED_ATTRIBS):U(`TransformFeedback is not supported but TransformFeedbackVaryings are given.`)),e.linkProgram(i),e.getProgramParameter(i,e.LINK_STATUS)||Kx(e,i,n,r),t._attributeData=zx(i,e,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(t.vertex)),t._uniformData=Ux(i,e),t._uniformBlockData=Vx(i,e),e.deleteShader(n),e.deleteShader(r);let o={};for(let n in t._uniformData){let r=t._uniformData[n];o[n]={location:e.getUniformLocation(i,n),value:jx(r.type,r.size)}}return new Ex(i,o)}var Yx=s((()=>{W(),Dx(),kx(),Mx(),Bx(),Hx(),Wx(),qx()})),Xx,Zx,Qx=s((()=>{R(),Tx(),Yx(),Xx={textureCount:0,blockIndex:0},Zx=class{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;Xx.textureCount=0,Xx.blockIndex=0;let n=this._shaderSyncFunctions[e.glProgram._key];n||=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),n(this._renderer,e,Xx)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,Xx)}bindUniformBlock(e,t,n=0){let r=this._renderer.buffer,i=this._getProgramData(this._activeProgram),a=e._bufferResource;a||this._renderer.ubo.updateUniformGroup(e);let o=e.buffer,s=r.updateBuffer(o),c=r.freeLocationForBufferBase(s);if(a){let{offset:t,size:n}=e;t===0&&n===o.data.byteLength?r.bindBufferBase(s,c):r.bindBufferRange(s,c,t)}else r.getLastBindBaseLocation(s)!==c&&r.bindBufferBase(s,c);let l=this._activeProgram._uniformBlockData[t].index;i.uniformBlockBindings[n]!==c&&(i.uniformBlockBindings[n]=c,this._renderer.gl.uniformBlockBinding(i.program,l,c))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;let t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){let t=e._key;return this._programDataHash[t]=Jx(this._gl,e),this._programDataHash[t]}destroy(){for(let e of Object.keys(this._programDataHash))this._programDataHash[e].destroy();this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return wx(e,t)}resetState(){this._activeProgram=null}},Zx.extension={type:[I.WebGLSystem],name:`shader`}})),$x,eS,tS=s((()=>{$x={f32:`if (cv !== v) {
|
|
856
|
-
cu.value = v;
|
|
857
|
-
gl.uniform1f(location, v);
|
|
858
|
-
}`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
859
|
-
cv[0] = v[0];
|
|
860
|
-
cv[1] = v[1];
|
|
861
|
-
gl.uniform2f(location, v[0], v[1]);
|
|
862
|
-
}`,"vec3<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
863
|
-
cv[0] = v[0];
|
|
864
|
-
cv[1] = v[1];
|
|
865
|
-
cv[2] = v[2];
|
|
866
|
-
gl.uniform3f(location, v[0], v[1], v[2]);
|
|
867
|
-
}`,"vec4<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
868
|
-
cv[0] = v[0];
|
|
869
|
-
cv[1] = v[1];
|
|
870
|
-
cv[2] = v[2];
|
|
871
|
-
cv[3] = v[3];
|
|
872
|
-
gl.uniform4f(location, v[0], v[1], v[2], v[3]);
|
|
873
|
-
}`,i32:`if (cv !== v) {
|
|
874
|
-
cu.value = v;
|
|
875
|
-
gl.uniform1i(location, v);
|
|
876
|
-
}`,"vec2<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
877
|
-
cv[0] = v[0];
|
|
878
|
-
cv[1] = v[1];
|
|
879
|
-
gl.uniform2i(location, v[0], v[1]);
|
|
880
|
-
}`,"vec3<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
881
|
-
cv[0] = v[0];
|
|
882
|
-
cv[1] = v[1];
|
|
883
|
-
cv[2] = v[2];
|
|
884
|
-
gl.uniform3i(location, v[0], v[1], v[2]);
|
|
885
|
-
}`,"vec4<i32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
886
|
-
cv[0] = v[0];
|
|
887
|
-
cv[1] = v[1];
|
|
888
|
-
cv[2] = v[2];
|
|
889
|
-
cv[3] = v[3];
|
|
890
|
-
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
891
|
-
}`,u32:`if (cv !== v) {
|
|
892
|
-
cu.value = v;
|
|
893
|
-
gl.uniform1ui(location, v);
|
|
894
|
-
}`,"vec2<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
895
|
-
cv[0] = v[0];
|
|
896
|
-
cv[1] = v[1];
|
|
897
|
-
gl.uniform2ui(location, v[0], v[1]);
|
|
898
|
-
}`,"vec3<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
899
|
-
cv[0] = v[0];
|
|
900
|
-
cv[1] = v[1];
|
|
901
|
-
cv[2] = v[2];
|
|
902
|
-
gl.uniform3ui(location, v[0], v[1], v[2]);
|
|
903
|
-
}`,"vec4<u32>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
904
|
-
cv[0] = v[0];
|
|
905
|
-
cv[1] = v[1];
|
|
906
|
-
cv[2] = v[2];
|
|
907
|
-
cv[3] = v[3];
|
|
908
|
-
gl.uniform4ui(location, v[0], v[1], v[2], v[3]);
|
|
909
|
-
}`,bool:`if (cv !== v) {
|
|
910
|
-
cu.value = v;
|
|
911
|
-
gl.uniform1i(location, v);
|
|
912
|
-
}`,"vec2<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
913
|
-
cv[0] = v[0];
|
|
914
|
-
cv[1] = v[1];
|
|
915
|
-
gl.uniform2i(location, v[0], v[1]);
|
|
916
|
-
}`,"vec3<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) {
|
|
917
|
-
cv[0] = v[0];
|
|
918
|
-
cv[1] = v[1];
|
|
919
|
-
cv[2] = v[2];
|
|
920
|
-
gl.uniform3i(location, v[0], v[1], v[2]);
|
|
921
|
-
}`,"vec4<bool>":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) {
|
|
922
|
-
cv[0] = v[0];
|
|
923
|
-
cv[1] = v[1];
|
|
924
|
-
cv[2] = v[2];
|
|
925
|
-
cv[3] = v[3];
|
|
926
|
-
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
927
|
-
}`,"mat2x2<f32>":`gl.uniformMatrix2fv(location, false, v);`,"mat3x3<f32>":`gl.uniformMatrix3fv(location, false, v);`,"mat4x4<f32>":`gl.uniformMatrix4fv(location, false, v);`},eS={f32:`gl.uniform1fv(location, v);`,"vec2<f32>":`gl.uniform2fv(location, v);`,"vec3<f32>":`gl.uniform3fv(location, v);`,"vec4<f32>":`gl.uniform4fv(location, v);`,"mat2x2<f32>":`gl.uniformMatrix2fv(location, false, v);`,"mat3x3<f32>":`gl.uniformMatrix3fv(location, false, v);`,"mat4x4<f32>":`gl.uniformMatrix4fv(location, false, v);`,i32:`gl.uniform1iv(location, v);`,"vec2<i32>":`gl.uniform2iv(location, v);`,"vec3<i32>":`gl.uniform3iv(location, v);`,"vec4<i32>":`gl.uniform4iv(location, v);`,u32:`gl.uniform1iv(location, v);`,"vec2<u32>":`gl.uniform2iv(location, v);`,"vec3<u32>":`gl.uniform3iv(location, v);`,"vec4<u32>":`gl.uniform4iv(location, v);`,bool:`gl.uniform1iv(location, v);`,"vec2<bool>":`gl.uniform2iv(location, v);`,"vec3<bool>":`gl.uniform3iv(location, v);`,"vec4<bool>":`gl.uniform4iv(location, v);`}}));function nS(e,t){let n=[`
|
|
928
|
-
var v = null;
|
|
929
|
-
var cv = null;
|
|
930
|
-
var cu = null;
|
|
931
|
-
var t = 0;
|
|
932
|
-
var gl = renderer.gl;
|
|
933
|
-
var name = null;
|
|
934
|
-
`];for(let r in e.uniforms){if(!t[r]){e.uniforms[r]instanceof ef?e.uniforms[r].ubo?n.push(`
|
|
935
|
-
renderer.shader.bindUniformBlock(uv.${r}, "${r}");
|
|
936
|
-
`):n.push(`
|
|
937
|
-
renderer.shader.updateUniformGroup(uv.${r});
|
|
938
|
-
`):e.uniforms[r]instanceof Wv&&n.push(`
|
|
939
|
-
renderer.shader.bindBufferResource(uv.${r}, "${r}");
|
|
940
|
-
`);continue}let i=e.uniformStructures[r],a=!1;for(let e=0;e<Av.length;e++){let t=Av[e];if(i.type===t.type&&t.test(i)){n.push(`name = "${r}";`,Av[e].uniform),a=!0;break}}if(!a){let e=(i.size===1?$x:eS)[i.type].replace(`location`,`ud["${r}"].location`);n.push(`
|
|
941
|
-
cu = ud["${r}"];
|
|
942
|
-
cv = cu.value;
|
|
943
|
-
v = uv["${r}"];
|
|
944
|
-
${e};`)}}return Function(`ud`,`uv`,`renderer`,`syncData`,n.join(`
|
|
945
|
-
`))}var rS=s((()=>{Gv(),tf(),jv(),tS()})),iS,aS=s((()=>{R(),rS(),iS=class{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,n){let r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,n))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){let n=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,`u`);return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),n[t._key]=this._cache[r],n[t._key]}_generateUniformsSync(e,t){return nS(e,t)}_getSignature(e,t,n){let r=e.uniforms,i=[`${n}-`];for(let e in r)i.push(e),t[e]&&i.push(t[e].type);return i.join(`-`)}destroy(){this._renderer=null,this._cache=null}},iS.extension={type:[I.WebGLSystem],name:`uniformGroup`}}));function oS(e){let t={};if(t.normal=[e.ONE,e.ONE_MINUS_SRC_ALPHA],t.add=[e.ONE,e.ONE],t.multiply=[e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.screen=[e.ONE,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t[`normal-npm`]=[e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA],t[`add-npm`]=[e.SRC_ALPHA,e.ONE,e.ONE,e.ONE],t[`screen-npm`]=[e.SRC_ALPHA,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA],t.erase=[e.ZERO,e.ONE_MINUS_SRC_ALPHA],!(e instanceof Y.get().getWebGLRenderingContext()))t.min=[e.ONE,e.ONE,e.ONE,e.ONE,e.MIN,e.MIN],t.max=[e.ONE,e.ONE,e.ONE,e.ONE,e.MAX,e.MAX];else{let n=e.getExtension(`EXT_blend_minmax`);n&&(t.min=[e.ONE,e.ONE,e.ONE,e.ONE,n.MIN_EXT,n.MIN_EXT],t.max=[e.ONE,e.ONE,e.ONE,e.ONE,n.MAX_EXT,n.MAX_EXT])}return t}var sS=s((()=>{Jc()})),cS,lS,uS,dS,fS,pS,mS,hS,gS=s((()=>{R(),hf(),sS(),{BLEND:cS,OFFSET:lS,CULLING:uS,DEPTH_TEST:dS,WINDING:fS,DEPTH_MASK:pS}=of,mS=class e{constructor(e){this._invertFrontFace=!1,this._renderer=e,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=`none`,this._blendEq=!1,this.map=[],this.map[cS]=this.setBlend,this.map[lS]=this.setOffset,this.map[uS]=this.setCullFace,this.map[dS]=this.setDepthTest,this.map[fS]=this.setFrontFace,this.map[pS]=this.setDepthMask,this.checks=[],this.defaultState=mf.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=this._renderer.renderTarget.isFrontFaceInverted(e,e.flipY),this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=oS(e),this.resetState()}set(e){if(e||=this.defaultState,this.stateId!==e.data){let t=this.stateId^e.data,n=0;for(;t;)t&1&&this.map[n].call(this,!!(e.data&1<<n)),t>>=1,n++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||=this.defaultState;for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(t){this._updateCheck(e._checkBlendMode,t),this.gl[t?`enable`:`disable`](this.gl.BLEND)}setOffset(t){this._updateCheck(e._checkPolygonOffset,t),this.gl[t?`enable`:`disable`](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?`enable`:`disable`](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}get depthMaskEnabled(){return!!(this.stateId&1<<pS)}setCullFace(e){this._cullFace=e,this.gl[e?`enable`:`disable`](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;let t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?`CW`:`CCW`]))}setBlendMode(e){if(this.blendModesMap[e]||(e=`normal`),e===this.blendMode)return;this.blendMode=e;let t=this.blendModesMap[e],n=this.gl;t.length===2?n.blendFunc(t[0],t[1]):n.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,n.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,n.blendEquationSeparate(n.FUNC_ADD,n.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=``,this.setBlendMode(`normal`)}_updateCheck(e,t){let n=this.checks.indexOf(e);t&&n===-1?this.checks.push(e):!t&&n!==-1&&this.checks.splice(n,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0,this._renderer=null}},mS.extension={type:[I.WebGLSystem],name:`state`},hS=mS})),_S,vS=s((()=>{Vb(),_S=class{constructor(e){this.target=zb.TEXTURE_2D,this._layerInitMask=0,this.texture=e,this.width=-1,this.height=-1,this.type=Bb.UNSIGNED_BYTE,this.internalFormat=Rb.RGBA,this.format=Rb.RGBA,this.samplerType=0}destroy(){}}})),yS,bS,xS=s((()=>{Pa(),Ry(),Vb(),yS=[new G,new G,new G],bS={id:`buffer`,upload(e,t,n,r,i,a=!1){let o=i||t.target,s=e.resource;if(o===zb.TEXTURE_3D||o===zb.TEXTURE_2D_ARRAY){a||t.width!==e.width||t.height!==e.height?n.texImage3D(o,0,t.internalFormat,e.width,e.height,e.depthOrArrayLayers,0,t.format,t.type,s):n.texSubImage3D(o,0,0,0,0,e.width,e.height,e.depthOrArrayLayers,t.format,t.type,s),t.width=e.width,t.height=e.height;return}let c=e.width*e.height,l=a||t.width!==e.width||t.height!==e.height,u=e._updateStart>0||e._updateEnd<c;if(l)n.texImage2D(o,0,t.internalFormat,e.width,e.height,0,t.format,t.type,s);else if(u){let r=s.length/c,i=Ly(e._updateStart,e._updateEnd,e.width,e.height,yS);for(let a=0;a<i;a++){let i=yS[a],c=(i.y*e.width+i.x)*r;n.texSubImage2D(o,0,i.x,i.y,i.width,i.height,t.format,t.type,s.subarray(c,c+i.width*i.height*r))}}else n.texSubImage2D(o,0,0,0,e.width,e.height,t.format,t.type,s);t.width=e.width,t.height=e.height}}})),SS,CS,wS=s((()=>{SS={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},CS={id:`compressed`,upload(e,t,n,r,i,a){let o=i??t.target;n.pixelStorei(n.UNPACK_ALIGNMENT,4);let s=e.pixelWidth,c=e.pixelHeight,l=!!SS[e.format];for(let r=0;r<e.resource.length;r++){let i=e.resource[r];l?n.compressedTexImage2D(o,r,t.internalFormat,s,c,0,i):n.texImage2D(o,r,t.internalFormat,s,c,0,t.format,t.type,i),s=Math.max(s>>1,1),c=Math.max(c>>1,1)}}}}));function TS(e){return{id:`cube`,upload(t,n,r,i){let a=t.faces;for(let t=0;t<ES.length;t++){let o=a[ES[t]];o.resource&&((e[o.uploadMethodId]||e.image).upload(o,n,r,i,zb.TEXTURE_CUBE_MAP_POSITIVE_X+t,!(n._layerInitMask&1<<t)),n._layerInitMask|=1<<t)}n.width=t.pixelWidth,n.height=t.pixelHeight}}}var ES,DS=s((()=>{Vb(),ES=[`right`,`left`,`top`,`bottom`,`front`,`back`]}));function OS(e,t,n,r,i,a,o,s,c,l){l?c?e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,s):e.texSubImage2D(t,0,0,0,n.format,n.type,s):(c&&e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,null),e.texSubImage2D(t,0,0,0,a,o,n.format,n.type,s))}function kS(e,t,n,r,i,a,o,s,c,l){l?c?e.texImage2D(t,0,n.internalFormat,n.format,n.type,s):e.texSubImage2D(t,0,0,0,n.format,n.type,s):(c&&e.texImage2D(t,0,n.internalFormat,r,i,0,n.format,n.type,null),e.texSubImage2D(t,0,0,0,n.format,n.type,s))}var AS,jS=s((()=>{AS={id:`image`,upload(e,t,n,r,i,a=!1){let o=i||t.target,s=e.pixelWidth,c=e.pixelHeight,l=e.resourceWidth,u=e.resourceHeight,d=r===2,f=a||t.width!==s||t.height!==c,p=l>=s&&u>=c,m=e.resource;(d?OS:kS)(n,o,t,s,c,l,u,m,f,p),t.width=s,t.height=c}}}));function MS(){let{userAgent:e}=Y.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(e)}var NS=s((()=>{Jc()})),PS,FS,IS=s((()=>{NS(),jS(),PS=MS(),FS={id:`video`,upload(e,t,n,r,i,a=PS){if(e.isValid)AS.upload(e,t,n,r,i,a);else{let e=i??t.target;n.texImage2D(e,0,t.internalFormat,1,1,0,t.format,t.type,null)}}}})),LS,RS,zS,BS,VS=s((()=>{LS={linear:9729,nearest:9728},RS={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},zS={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},BS={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519}}));function HS(e,t,n,r,i,a,o,s){let c=a;if(!s||e.addressModeU!==`repeat`||e.addressModeV!==`repeat`||e.addressModeW!==`repeat`){let n=zS[o?`clamp-to-edge`:e.addressModeU],r=zS[o?`clamp-to-edge`:e.addressModeV],a=zS[o?`clamp-to-edge`:e.addressModeW];t[i](c,t.TEXTURE_WRAP_S,n),t[i](c,t.TEXTURE_WRAP_T,r),t.TEXTURE_WRAP_R&&t[i](c,t.TEXTURE_WRAP_R,a)}if((!s||e.magFilter!==`linear`)&&t[i](c,t.TEXTURE_MAG_FILTER,LS[e.magFilter]),n){if(!s||e.mipmapFilter!==`linear`){let n=RS[e.minFilter][e.mipmapFilter];t[i](c,t.TEXTURE_MIN_FILTER,n)}}else t[i](c,t.TEXTURE_MIN_FILTER,LS[e.minFilter]);if(r&&e.maxAnisotropy>1){let n=Math.min(e.maxAnisotropy,t.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[i](c,r.TEXTURE_MAX_ANISOTROPY_EXT,n)}e.compare?(t[i](c,t.TEXTURE_COMPARE_FUNC,BS[e.compare]),t[i](c,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE)):s||t[i](c,t.TEXTURE_COMPARE_MODE,t.NONE)}var US=s((()=>{VS()}));function WS(e){return{r8unorm:e.RED,r8snorm:e.RED,r8uint:e.RED_INTEGER,r8sint:e.RED_INTEGER,r16uint:e.RED_INTEGER,r16sint:e.RED_INTEGER,r16float:e.RED,rg8unorm:e.RG,rg8snorm:e.RG,rg8uint:e.RG_INTEGER,rg8sint:e.RG_INTEGER,r32uint:e.RED_INTEGER,r32sint:e.RED_INTEGER,r32float:e.RED,rg16uint:e.RG_INTEGER,rg16sint:e.RG_INTEGER,rg16float:e.RG,rgba8unorm:e.RGBA,"rgba8unorm-srgb":e.RGBA,rgba8snorm:e.RGBA,rgba8uint:e.RGBA_INTEGER,rgba8sint:e.RGBA_INTEGER,bgra8unorm:e.RGBA,"bgra8unorm-srgb":e.RGBA,rgb9e5ufloat:e.RGB,rgb10a2unorm:e.RGBA,rg11b10ufloat:e.RGB,rg32uint:e.RG_INTEGER,rg32sint:e.RG_INTEGER,rg32float:e.RG,rgba16uint:e.RGBA_INTEGER,rgba16sint:e.RGBA_INTEGER,rgba16float:e.RGBA,rgba32uint:e.RGBA_INTEGER,rgba32sint:e.RGBA_INTEGER,rgba32float:e.RGBA,stencil8:e.STENCIL_INDEX8,depth16unorm:e.DEPTH_COMPONENT,depth24plus:e.DEPTH_COMPONENT,"depth24plus-stencil8":e.DEPTH_STENCIL,depth32float:e.DEPTH_COMPONENT,"depth32float-stencil8":e.DEPTH_STENCIL}}var GS=s((()=>{}));function KS(e,t){let n={},r=e.RGBA;return e instanceof Y.get().getWebGLRenderingContext()?t.srgb&&(n={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(n={"rgba8unorm-srgb":e.SRGB8_ALPHA8,"bgra8unorm-srgb":e.SRGB8_ALPHA8},r=e.RGBA8),{r8unorm:e.R8,r8snorm:e.R8_SNORM,r8uint:e.R8UI,r8sint:e.R8I,r16uint:e.R16UI,r16sint:e.R16I,r16float:e.R16F,rg8unorm:e.RG8,rg8snorm:e.RG8_SNORM,rg8uint:e.RG8UI,rg8sint:e.RG8I,r32uint:e.R32UI,r32sint:e.R32I,r32float:e.R32F,rg16uint:e.RG16UI,rg16sint:e.RG16I,rg16float:e.RG16F,rgba8unorm:e.RGBA,...n,rgba8snorm:e.RGBA8_SNORM,rgba8uint:e.RGBA8UI,rgba8sint:e.RGBA8I,bgra8unorm:r,rgb9e5ufloat:e.RGB9_E5,rgb10a2unorm:e.RGB10_A2,rg11b10ufloat:e.R11F_G11F_B10F,rg32uint:e.RG32UI,rg32sint:e.RG32I,rg32float:e.RG32F,rgba16uint:e.RGBA16UI,rgba16sint:e.RGBA16I,rgba16float:e.RGBA16F,rgba32uint:e.RGBA32UI,rgba32sint:e.RGBA32I,rgba32float:e.RGBA32F,stencil8:e.STENCIL_INDEX8,depth16unorm:e.DEPTH_COMPONENT16,depth24plus:e.DEPTH_COMPONENT24,"depth24plus-stencil8":e.DEPTH24_STENCIL8,depth32float:e.DEPTH_COMPONENT32F,"depth32float-stencil8":e.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}var qS=s((()=>{Jc()}));function JS(e){return{r8unorm:e.UNSIGNED_BYTE,r8snorm:e.BYTE,r8uint:e.UNSIGNED_BYTE,r8sint:e.BYTE,r16uint:e.UNSIGNED_SHORT,r16sint:e.SHORT,r16float:e.HALF_FLOAT,rg8unorm:e.UNSIGNED_BYTE,rg8snorm:e.BYTE,rg8uint:e.UNSIGNED_BYTE,rg8sint:e.BYTE,r32uint:e.UNSIGNED_INT,r32sint:e.INT,r32float:e.FLOAT,rg16uint:e.UNSIGNED_SHORT,rg16sint:e.SHORT,rg16float:e.HALF_FLOAT,rgba8unorm:e.UNSIGNED_BYTE,"rgba8unorm-srgb":e.UNSIGNED_BYTE,rgba8snorm:e.BYTE,rgba8uint:e.UNSIGNED_BYTE,rgba8sint:e.BYTE,bgra8unorm:e.UNSIGNED_BYTE,"bgra8unorm-srgb":e.UNSIGNED_BYTE,rgb9e5ufloat:e.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:e.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:e.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:e.UNSIGNED_INT,rg32sint:e.INT,rg32float:e.FLOAT,rgba16uint:e.UNSIGNED_SHORT,rgba16sint:e.SHORT,rgba16float:e.HALF_FLOAT,rgba32uint:e.UNSIGNED_INT,rgba32sint:e.INT,rgba32float:e.FLOAT,stencil8:e.UNSIGNED_BYTE,depth16unorm:e.UNSIGNED_SHORT,depth24plus:e.UNSIGNED_INT,"depth24plus-stencil8":e.UNSIGNED_INT_24_8,depth32float:e.FLOAT,"depth32float-stencil8":e.FLOAT_32_UNSIGNED_INT_24_8_REV}}var YS=s((()=>{}));function XS(e){return{"2d":e.TEXTURE_2D,cube:e.TEXTURE_CUBE_MAP,"1d":null,"3d":e?.TEXTURE_3D||null,"2d-array":e?.TEXTURE_2D_ARRAY||null,"cube-array":e?.TEXTURE_CUBE_MAP_ARRAY||null}}var ZS=s((()=>{})),QS,$S,eC,tC=s((()=>{Jc(),R(),cv(),$o(),qo(),vS(),xS(),wS(),DS(),jS(),IS(),US(),GS(),qS(),YS(),ZS(),QS=4,$S=class e{constructor(t){this._glSamplers=Object.create(null),this._boundTextures=[],this._integerUnits=0,this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._managedTextures=new sv({renderer:t,type:`resource`,onUnload:this.onSourceUnload.bind(this),name:`glTexture`});let n={image:AS,buffer:bS,video:FS,compressed:CS,...e.uploadExtensions};this._uploads={...n,cube:TS(n)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=KS(e,this._renderer.context.extensions),this._mapFormatToType=JS(e),this._mapFormatToFormat=WS(e),this._mapViewDimensionToGlTarget=XS(e)),this._managedTextures.removeAll(!0),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind(q.EMPTY,e)}initSource(e){this.bind(e)}bind(e,t=0){let n=e.source;e?(this.bindSource(n,t),this._useSeparateSamplers&&this._bindSampler(n.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){let n=this._gl;if(e._gcLastUsed=this._renderer.gc.now,this._boundTextures[t]!==e){this._setBoundTexture(t,e),this._activateLocation(t),e||=q.EMPTY.source;let r=this.getGlSource(e);n.bindTexture(r.target,r.texture)}}unbindIntegerTextures(e){if(e>=32)return;let t=this._integerUnits>>>e<<e;for(;t;){let e=31-Math.clz32(t);t&=~(1<<e),this.bind(q.EMPTY,e)}}_setBoundTexture(e,t){this._boundTextures[e]=t,!(e<0||e>31)&&t&&t.viewDimension===`2d`&&(Ko(t.format)?this._integerUnits|=1<<e:this._integerUnits&=~(1<<e))}_bindSampler(e,t=0){let n=this._gl;if(!e){this._boundSamplers[t]=null,n.bindSampler(t,null);return}let r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,n.bindSampler(t,r))}unbind(e){let t=e.source,n=this._boundTextures,r=this._gl;for(let e=0;e<n.length;e++)if(n[e]===t){this._activateLocation(e);let n=this.getGlSource(t);r.bindTexture(n.target,null),this._setBoundTexture(e,null)}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){let t=this._gl,n=new _S(t.createTexture());if(n.type=this._mapFormatToType[e.format],n.internalFormat=this._mapFormatToInternalFormat[e.format],n.format=this._mapFormatToFormat[e.format],n.target=this._mapViewDimensionToGlTarget[e.viewDimension],n.target===null)throw Error(`Unsupported view dimension: ${e.viewDimension} with this webgl version: ${this._renderer.context.webGLVersion}`);if(e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){let t=Math.max(e.width,e.height,e.depth);e.mipLevelCount=Math.floor(Math.log2(t))+1}return e._gpuData[this._renderer.uid]=n,this._managedTextures.add(e)&&(e.on(`update`,this.onSourceUpdate,this),e.on(`resize`,this.onSourceUpdate,this),e.on(`styleChange`,this.onStyleChange,this),e.on(`updateMipmaps`,this.onUpdateMipmaps,this)),this.onSourceUpdate(e),this.updateStyle(e,!1),n}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){let n=this._gl,r=this.getGlSource(e);n.bindTexture(r.target,r.texture),this._setBoundTexture(this._activeTextureLocation,e),HS(e.style,n,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,`texParameteri`,r.target,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e,t=!1){let n=e._gpuData[this._renderer.uid];n&&(t||(this.unbind(e),this._gl.deleteTexture(n.texture)),e.off(`update`,this.onSourceUpdate,this),e.off(`resize`,this.onSourceUpdate,this),e.off(`styleChange`,this.onStyleChange,this),e.off(`updateMipmaps`,this.onUpdateMipmaps,this))}onSourceUpdate(e){let t=this._gl,n=this.getGlSource(e);t.bindTexture(n.target,n.texture),this._setBoundTexture(this._activeTextureLocation,e);let r=e.alphaMode===`premultiply-alpha-on-upload`&&!Ko(e.format)&&n.target!==t.TEXTURE_3D&&n.target!==t.TEXTURE_2D_ARRAY;if(this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId])this._uploads[e.uploadMethodId].upload(e,n,t,this._renderer.context.webGLVersion);else if(n.target===t.TEXTURE_2D)this._initEmptyTexture2D(n,e);else if(n.target===t.TEXTURE_2D_ARRAY||n.target===t.TEXTURE_3D)this._initEmptyTexture3D(n,e);else if(n.target===t.TEXTURE_CUBE_MAP)this._initEmptyTextureCube(n,e);else throw Error(`[GlTextureSystem] Unsupported texture target for empty allocation.`);this._applyMipRange(n,e),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);let n=this.getGlSource(e);this._gl.generateMipmap(n.target)}_initEmptyTexture2D(e,t){let n=this._gl;n.texImage2D(n.TEXTURE_2D,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++)n.texImage2D(n.TEXTURE_2D,a,e.internalFormat,r,i,0,e.format,e.type,null),r=Math.max(r>>1,1),i=Math.max(i>>1,1)}_initEmptyTexture3D(e,t){let n=this._gl,r=e.target===n.TEXTURE_3D,i=t.pixelWidth,a=t.pixelHeight,o=t.depthOrArrayLayers;for(let s=0;s<t.mipLevelCount;s++)n.texImage3D(e.target,s,e.internalFormat,i,a,o,0,e.format,e.type,null),i=Math.max(i>>1,1),a=Math.max(a>>1,1),r&&(o=Math.max(o>>1,1))}_initEmptyTextureCube(e,t){let n=this._gl;for(let r=0;r<6;r++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,e.internalFormat,t.pixelWidth,t.pixelHeight,0,e.format,e.type,null);let r=Math.max(t.pixelWidth>>1,1),i=Math.max(t.pixelHeight>>1,1);for(let a=1;a<t.mipLevelCount;a++){for(let t=0;t<6;t++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,a,e.internalFormat,r,i,0,e.format,e.type,null);r=Math.max(r>>1,1),i=Math.max(i>>1,1)}}_applyMipRange(e,t){if(this._renderer.context.webGLVersion!==2||t.mipLevelCount<=1)return;let n=this._gl,r=Math.max((t.mipLevelCount|0)-1,0);n.texParameteri(e.target,n.TEXTURE_BASE_LEVEL,0),n.texParameteri(e.target,n.TEXTURE_MAX_LEVEL,r)}_initSampler(e){let t=this._gl,n=this._gl.createSampler();return this._glSamplers[e._resourceId]=n,HS(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,`samplerParameteri`,n,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return e._gcLastUsed=this._renderer.gc.now,e._gpuData[this._renderer.uid]||this._initSource(e)}generateCanvas(e){let{pixels:t,width:n,height:r}=this.getPixels(e),i=Y.get().createCanvas();i.width=n,i.height=r;let a=i.getContext(`2d`);if(a){let e=a.createImageData(n,r);e.data.set(t),a.putImageData(e,0,0)}return i}getPixels(e){let t=e.source.resolution,n=e.frame,r=Math.max(Math.round(n.width*t),1),i=Math.max(Math.round(n.height*t),1),a=new Uint8Array(QS*r*i),o=this._renderer,s=o.renderTarget.getRenderTarget(e),c=o.renderTarget.getGpuRenderTarget(s),l=o.gl;return o.renderTarget.adaptor.bindFramebuffer(c.resolveTargetFramebuffer),l.readPixels(Math.round(n.x*t),Math.round(n.y*t),r,i,l.RGBA,l.UNSIGNED_BYTE,a),{pixels:new Uint8ClampedArray(a.buffer),width:r,height:i}}destroy(){this._managedTextures.destroy(),this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){let e=this._renderer.limits.maxTextures;this._activeTextureLocation=-1,this._boundTextures.fill(null),this._integerUnits=e>=32?-1:(1<<e)-1,this._boundSamplers=Object.create(null);let t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}},$S.extension={type:[I.WebGLSystem],name:`texture`},$S.uploadExtensions=Object.create(null),eC=$S,L.handleByMap(I.TextureUploaderWebGL,eC.uploadExtensions)})),nC=l({WebGLRenderer:()=>uC}),rC,iC,aC,oC,sC,cC,lC,uC,dC=s((()=>{R(),wb(),Eb(),Ob(),sm(),rv(),Gd(),Pb(),Lb(),Jb(),Qb(),ex(),nx(),ix(),ox(),hx(),xx(),Qx(),aS(),gS(),tC(),rC=[...tv,mx,Zb,Ib,rx,Nb,eC,bx,qb,iS,Zx,tx,hS,ax,$b],iC=[...nv],aC=[Db,Tb,Cb],oC=[],sC=[],cC=[],lC=[],L.handleByNamedList(I.WebGLSystem,oC),L.handleByNamedList(I.WebGLPipes,sC),L.handleByNamedList(I.WebGLPipesAdaptor,cC),L.handleByNamedList(I.WebGLLoader,lC),L.add(...rC,...iC,...aC),uC=class extends om{constructor(){let e={name:`webgl`,type:Wd.WEBGL,systems:oC,renderPipes:sC,renderPipeAdaptors:cC,loaders:lC};super(e)}}})),fC,pC,mC=s((()=>{fC=1e-4,pC=1e-4}));function hC(e,t,n,r,i,a,o,s){let c=e-n*i,l=t-r*i,u=e+n*a,d=t+r*a,f,p;o?(f=r,p=-n):(f=-r,p=n);let m=c+f,h=l+p,g=u+f,_=d+p;return s.push(m,h),s.push(g,_),2}function gC(e,t,n,r,i,a,o,s){let c=n-e,l=r-t,u=Math.atan2(c,l),d=Math.atan2(i-e,a-t);s&&u<d?u+=Math.PI*2:!s&&u>d&&(d+=Math.PI*2);let f=u,p=d-u,m=Math.abs(p),h=Math.sqrt(c*c+l*l),g=(15*m*Math.sqrt(h)/Math.PI|0)+1,_=p/g;if(f+=_,s){o.push(e,t),o.push(n,r);for(let n=1,r=f;n<g;n++,r+=_)o.push(e,t),o.push(e+Math.sin(r)*h,t+Math.cos(r)*h);o.push(e,t),o.push(i,a)}else{o.push(n,r),o.push(e,t);for(let n=1,r=f;n<g;n++,r+=_)o.push(e+Math.sin(r)*h,t+Math.cos(r)*h),o.push(e,t);o.push(i,a),o.push(e,t)}return g*2}function _C(e,t,n,r,i,a){let o=fC;if(e.length===0)return;let s=t,c=s.alignment;if(t.alignment!==.5){let t=pu(e);n&&(t*=-1),c=(c-.5)*t+.5}let l=new Gi(e[0],e[1]),u=new Gi(e[e.length-2],e[e.length-1]),d=r,f=Math.abs(l.x-u.x)<o&&Math.abs(l.y-u.y)<o;if(d){e=e.slice(),f&&(e.pop(),e.pop(),u.set(e[e.length-2],e[e.length-1]));let t=(l.x+u.x)*.5,n=(u.y+l.y)*.5;e.unshift(t,n),e.push(t,n)}let p=i,m=e.length/2,h=e.length,g=p.length/2,_=s.width/2,v=_*_,y=s.miterLimit*s.miterLimit,b=e[0],x=e[1],S=e[2],C=e[3],ee=0,w=0,T=-(x-C),E=b-S,te=0,D=0,O=Math.sqrt(T*T+E*E);T/=O,E/=O,T*=_,E*=_;let ne=c,k=(1-ne)*2,A=ne*2;d||(s.cap===`round`?h+=gC(b-T*(k-A)*.5,x-E*(k-A)*.5,b-T*k,x-E*k,b+T*A,x+E*A,p,!0)+2:s.cap===`square`&&(h+=hC(b,x,T,E,k,A,!0,p))),p.push(b-T*k,x-E*k),p.push(b+T*A,x+E*A);for(let t=1;t<m-1;++t){b=e[(t-1)*2],x=e[(t-1)*2+1],S=e[t*2],C=e[t*2+1],ee=e[(t+1)*2],w=e[(t+1)*2+1],T=-(x-C),E=b-S,O=Math.sqrt(T*T+E*E),T/=O,E/=O,T*=_,E*=_,te=-(C-w),D=S-ee,O=Math.sqrt(te*te+D*D),te/=O,D/=O,te*=_,D*=_;let n=S-b,r=x-C,i=S-ee,a=w-C,o=n*i+r*a,c=r*i-a*n,l=c<0;if(Math.abs(c)<.001*Math.abs(o)){p.push(S-T*k,C-E*k),p.push(S+T*A,C+E*A),o>=0&&(s.join===`round`?h+=gC(S,C,S-T*k,C-E*k,S-te*k,C-D*k,p,!1)+4:h+=2,p.push(S-te*A,C-D*A),p.push(S+te*k,C+D*k));continue}let u=(-T+b)*(-E+C)-(-T+S)*(-E+x),d=(-te+ee)*(-D+C)-(-te+S)*(-D+w),f=(n*d-i*u)/c,m=(a*u-r*d)/c,g=(f-S)*(f-S)+(m-C)*(m-C),ne=S+(f-S)*k,re=C+(m-C)*k,ie=S-(f-S)*A,ae=C-(m-C)*A,oe=Math.min(n*n+r*r,i*i+a*a),se=l?k:A;g<=oe+se*se*v?s.join===`bevel`||g/v>y?(l?(p.push(ne,re),p.push(S+T*A,C+E*A),p.push(ne,re),p.push(S+te*A,C+D*A)):(p.push(S-T*k,C-E*k),p.push(ie,ae),p.push(S-te*k,C-D*k),p.push(ie,ae)),h+=2):s.join===`round`?l?(p.push(ne,re),p.push(S+T*A,C+E*A),h+=gC(S,C,S+T*A,C+E*A,S+te*A,C+D*A,p,!0)+4,p.push(ne,re),p.push(S+te*A,C+D*A)):(p.push(S-T*k,C-E*k),p.push(ie,ae),h+=gC(S,C,S-T*k,C-E*k,S-te*k,C-D*k,p,!1)+4,p.push(S-te*k,C-D*k),p.push(ie,ae)):(p.push(ne,re),p.push(ie,ae)):(p.push(S-T*k,C-E*k),p.push(S+T*A,C+E*A),s.join===`round`?h+=l?gC(S,C,S+T*A,C+E*A,S+te*A,C+D*A,p,!0)+2:gC(S,C,S-T*k,C-E*k,S-te*k,C-D*k,p,!1)+2:s.join===`miter`&&g/v<=y&&(l?(p.push(ie,ae),p.push(ie,ae)):(p.push(ne,re),p.push(ne,re)),h+=2),p.push(S-te*k,C-D*k),p.push(S+te*A,C+D*A),h+=2)}b=e[(m-2)*2],x=e[(m-2)*2+1],S=e[(m-1)*2],C=e[(m-1)*2+1],T=-(x-C),E=b-S,O=Math.sqrt(T*T+E*E),T/=O,E/=O,T*=_,E*=_,p.push(S-T*k,C-E*k),p.push(S+T*A,C+E*A),d||(s.cap===`round`?h+=gC(S-T*(k-A)*.5,C-E*(k-A)*.5,S-T*k,C-E*k,S+T*A,C+E*A,p,!1)+2:s.cap===`square`&&(h+=hC(S,C,T,E,k,A,!1,p)));let re=pC*pC;for(let e=g;e<h+g-2;++e)b=p[e*2],x=p[e*2+1],S=p[(e+1)*2],C=p[(e+1)*2+1],ee=p[(e+2)*2],w=p[(e+2)*2+1],!(Math.abs(b*(C-w)+S*(w-x)+ee*(x-C))<re)&&a.push(e,e+1,e+2)}var vC=s((()=>{mu(),qi(),mC()}));function yC(e,t){for(let n=0;n<t.length;n++){let r=t[n];e.addColorStop(r.offset,r.color)}}function bC(e,t){let n=Y.get().createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`)}}function xC(e){let t=e[0]??{};return(typeof t==`number`||e[1])&&(H(`8.5.2`,`use options object instead`),t={type:`linear`,start:{x:e[0],y:e[1]},end:{x:e[2],y:e[3]},textureSpace:e[4],textureSize:e[5]??wC.defaultLinearOptions.textureSize}),t}var SC,CC,wC,TC=s((()=>{Ri(),Jc(),B(),Vl(),$o(),ea(),oa(),wo(),SC=[{offset:0,color:`white`},{offset:1,color:`black`}],CC=class e{constructor(...t){this.uid=Qi(`fillGradient`),this._tick=0,this.type=`linear`,this.colorStops=[];let n=xC(t);n={...n.type===`radial`?e.defaultRadialOptions:e.defaultLinearOptions,...Co(n)},this._textureSize=n.textureSize,this._wrapMode=n.wrapMode,n.type===`radial`?(this.center=n.center,this.outerCenter=n.outerCenter??this.center,this.innerRadius=n.innerRadius,this.outerRadius=n.outerRadius,this.scale=n.scale,this.rotation=n.rotation):(this.start=n.start,this.end=n.end),this.textureSpace=n.textureSpace,this.type=n.type,n.colorStops.forEach(e=>{this.addColorStop(e.offset,e.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:Li.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:n,y:r}=this.end,i=n-e,a=r-t,o=i<0||a<0;if(this._wrapMode===`clamp-to-edge`){if(i<0){let t=e;e=n,n=t,i*=-1}if(a<0){let e=t;t=r,r=e,a*=-1}}let s=this.colorStops.length?this.colorStops:SC,c=this._textureSize,{canvas:l,context:u}=bC(c,1),d=o?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);yC(d,s),u.fillStyle=d,u.fillRect(0,0,c,1),this.texture=new q({source:new Bl({resource:l,addressMode:this._wrapMode})});let f=Math.sqrt(i*i+a*a),p=Math.atan2(a,i),m=new z;m.scale(f/c,1),m.rotate(p),m.translate(e,t),this.textureSpace===`local`&&m.scale(c,c),this.transform=m}buildGradient(){this.texture||this._tick++,this.type===`linear`?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;let e=this.colorStops.length?this.colorStops:SC,t=this._textureSize,{canvas:n,context:r}=bC(t,t),{x:i,y:a}=this.center,{x:o,y:s}=this.outerCenter,c=this.innerRadius,l=this.outerRadius,u=o-l,d=s-l,f=t/(l*2),p=(i-u)*f,m=(a-d)*f,h=r.createRadialGradient(p,m,c*f,(o-u)*f,(s-d)*f,l*f);yC(h,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=h,r.translate(p,m),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-p,-m),r.fillRect(0,0,t,t),this.texture=new q({source:new Bl({resource:n,addressMode:this._wrapMode})});let g=new z;this.textureSpace===`local`?g.scale(2*l,2*l):g.scale(1/f,1/f),g.translate(u,d),this.transform=g}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}},CC.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:`local`,type:`linear`,textureSize:256,wrapMode:`clamp-to-edge`},CC.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,rotation:0,textureSpace:`local`,type:`radial`,textureSize:256,wrapMode:`clamp-to-edge`},wC=CC}));function EC(e){return e.texture!==void 0}var DC,OC,kC=s((()=>{B(),ea(),DC={repeat:{addressModeU:`repeat`,addressModeV:`repeat`},"repeat-x":{addressModeU:`repeat`,addressModeV:`clamp-to-edge`},"repeat-y":{addressModeU:`clamp-to-edge`,addressModeV:`repeat`},"no-repeat":{addressModeU:`clamp-to-edge`,addressModeV:`clamp-to-edge`}},OC=class{constructor(e,t){this.uid=Qi(`fillPattern`),this._tick=0,this.transform=new z;let n=EC(e)?e:{texture:e,repetition:t};this.texture=n.texture,this.textureSpace=n.textureSpace??`global`;let r=n.repetition;r&&(this.texture.source.style.addressModeU=DC[r].addressModeU,this.texture.source.style.addressModeV=DC[r].addressModeV)}setTransform(e){if(e){if(this.transform.equals(e))return;this.transform.copyFrom(e)}else{if(this.transform.isIdentity())return;this.transform.identity()}this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}}));function AC(e,t,n,r,i,a,o,s=null){let c=0;n*=t,i*=a;let l=s.a,u=s.b,d=s.c,f=s.d,p=s.tx,m=s.ty;for(;c<o;){let o=e[n],s=e[n+1];r[i]=l*o+d*s+p,r[i+1]=u*o+f*s+m,i+=a,n+=t,c++}}function jC(e,t,n,r){let i=0;for(t*=n;i<r;)e[t]=0,e[t+1]=0,t+=n,i++}var MC=s((()=>{}));function NC(e,t,n,r,i){let a=t.a,o=t.b,s=t.c,c=t.d,l=t.tx,u=t.ty;n||=0,r||=2,i||=e.length/r-n;let d=n*r;for(let t=0;t<i;t++){let t=e[d],n=e[d+1];e[d]=a*t+s*n+l,e[d+1]=o*t+c*n+u,d+=r}}var PC=s((()=>{})),FC,IC,LC=s((()=>{B(),Ya(),FC=new z,IC=class{constructor(){this.packAsQuad=!1,this.batcherName=`default`,this.topology=`triangle-list`,this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:`normal`}get color(){let e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,n=this.renderable;return n?Ja(t,n.groupColor)+(this.alpha*n.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||FC}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology=`triangle-list`}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}})),RC,zC,BC,VC=s((()=>{R(),RC={extension:{type:I.ShapeBuilder,name:`circle`},build(e,t){let n,r,i,a,o,s;if(e.type===`circle`){let t=e;if(o=s=t.radius,o<=0)return!1;n=t.x,r=t.y,i=a=0}else if(e.type===`ellipse`){let t=e;if(o=t.halfWidth,s=t.halfHeight,o<=0||s<=0)return!1;n=t.x,r=t.y,i=a=0}else{let t=e,c=t.width/2,l=t.height/2;n=t.x+c,r=t.y+l,o=s=Math.max(0,Math.min(t.radius,Math.min(c,l))),i=c-o,a=l-s}if(i<0||a<0)return!1;let c=Math.ceil(2.3*Math.sqrt(o+s)),l=c*8+(i?4:0)+(a?4:0);if(l===0)return!1;if(c===0)return t[0]=t[6]=n+i,t[1]=t[3]=r+a,t[2]=t[4]=n-i,t[5]=t[7]=r-a,!0;let u=0,d=c*4+(i?2:0)+2,f=d,p=l,m=i+o,h=a,g=n+m,_=n-m,v=r+h;if(t[u++]=g,t[u++]=v,t[--d]=v,t[--d]=_,a){let e=r-h;t[f++]=_,t[f++]=e,t[--p]=e,t[--p]=g}for(let e=1;e<c;e++){let l=Math.PI/2*(e/c),m=i+Math.cos(l)*o,h=a+Math.sin(l)*s,g=n+m,_=n-m,v=r+h,y=r-h;t[u++]=g,t[u++]=v,t[--d]=v,t[--d]=_,t[f++]=_,t[f++]=y,t[--p]=y,t[--p]=g}m=i,h=a+s,g=n+m,_=n-m,v=r+h;let y=r-h;return t[u++]=g,t[u++]=v,t[--p]=y,t[--p]=g,i&&(t[u++]=_,t[u++]=v,t[--p]=y,t[--p]=_),!0},triangulate(e,t,n,r,i,a){if(e.length===0)return;let o=0,s=0;for(let t=0;t<e.length;t+=2)o+=e[t],s+=e[t+1];o/=e.length/2,s/=e.length/2;let c=r;t[c*n]=o,t[c*n+1]=s;let l=c++;for(let r=0;r<e.length;r+=2)t[c*n]=e[r],t[c*n+1]=e[r+1],r>0&&(i[a++]=c,i[a++]=l,i[a++]=c-1),c++;i[a++]=l+1,i[a++]=l,i[a++]=c-1}},zC={...RC,extension:{...RC.extension,name:`ellipse`}},BC={...RC,extension:{...RC.extension,name:`roundedRectangle`}}}));function HC(e,t,n,r){let i=fC;if(e.length===0)return;let a=e[0],o=e[1],s=e[e.length-2],c=e[e.length-1],l=t||Math.abs(a-s)<i&&Math.abs(o-c)<i,u=n,d=e.length/2,f=u.length/2;for(let t=0;t<d;t++)u.push(e[t*2]),u.push(e[t*2+1]);for(let e=0;e<d-1;e++)r.push(f+e,f+e+1);l&&r.push(f+d-1,f)}var UC=s((()=>{mC()}));function WC(e,t,n,r,i,a,o){let s=Qp(e,t,2);if(!s)return;for(let e=0;e<s.length;e+=3)a[o++]=s[e]+i,a[o++]=s[e+1]+i,a[o++]=s[e+2]+i;let c=i*r;for(let t=0;t<e.length;t+=2)n[c]=e[t],n[c+1]=e[t+1],c+=r}var GC=s((()=>{$p()})),KC,qC,JC=s((()=>{R(),GC(),KC=[],qC={extension:{type:I.ShapeBuilder,name:`polygon`},build(e,t){for(let n=0;n<e.points.length;n++)t[n]=e.points[n];return!0},triangulate(e,t,n,r,i,a){WC(e,KC,t,n,r,i,a)}}})),YC,XC=s((()=>{R(),YC={extension:{type:I.ShapeBuilder,name:`rectangle`},build(e,t){let n=e,r=n.x,i=n.y,a=n.width,o=n.height;return a>0&&o>0&&(t[0]=r,t[1]=i,t[2]=r+a,t[3]=i,t[4]=r+a,t[5]=i+o,t[6]=r,t[7]=i+o,!0)},triangulate(e,t,n,r,i,a){let o=0;r*=n,t[r+o]=e[0],t[r+o+1]=e[1],o+=n,t[r+o]=e[2],t[r+o+1]=e[3],o+=n,t[r+o]=e[6],t[r+o+1]=e[7],o+=n,t[r+o]=e[4],t[r+o+1]=e[5],o+=n;let s=r/n;i[a++]=s,i[a++]=s+1,i[a++]=s+2,i[a++]=s+1,i[a++]=s+3,i[a++]=s+2}}})),ZC,QC=s((()=>{R(),ZC={extension:{type:I.ShapeBuilder,name:`triangle`},build(e,t){return t[0]=e.x,t[1]=e.y,t[2]=e.x2,t[3]=e.y2,t[4]=e.x3,t[5]=e.y3,!0},triangulate(e,t,n,r,i,a){let o=0;r*=n,t[r+o]=e[0],t[r+o+1]=e[1],o+=n,t[r+o]=e[2],t[r+o+1]=e[3],o+=n,t[r+o]=e[4],t[r+o+1]=e[5];let s=r/n;i[a++]=s,i[a++]=s+1,i[a++]=s+2}}}));function $C(e,t,n,r){let i=t.matrix?e.copyFrom(t.matrix).invert():e.identity();if(t.textureSpace===`local`){let e=n.getBounds(tw);t.width&&e.pad(t.width);let{x:r,y:a}=e,o=1/e.width,s=1/e.height,c=-r*o,l=-a*s,u=i.a,d=i.b,f=i.c,p=i.d;i.a*=o,i.b*=o,i.c*=s,i.d*=s,i.tx=c*u+l*f+i.tx,i.ty=c*d+l*p+i.ty}else if(t.texture.rotate){let{uvs:e,orig:n}=t.texture;i.scale(1/n.width,1/n.height),i.prepend(nw.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0))}else i.translate(t.texture.frame.x,t.texture.frame.y),i.scale(1/t.texture.source.width,1/t.texture.source.height);let a=t.texture.source.style;return!(t.fill instanceof wC)&&a.addressMode===`clamp-to-edge`&&(a.addressMode=`repeat`,a.update()),r&&i.append(ew.copyFrom(r).invert()),i}var ew,tw,nw,rw=s((()=>{B(),Pa(),TC(),ew=new z,tw=new G,nw=new z}));function iw(e,t){let{geometryData:n,batches:r}=t;r.length=0,n.indices.length=0,n.vertices.length=0,n.uvs.length=0;for(let t=0;t<e.instructions.length;t++){let i=e.instructions[t];if(i.action===`texture`)aw(i.data,r,n);else if(i.action===`fill`||i.action===`stroke`){let e=i.action===`stroke`,t=i.data.path.shapePath,a=i.data.style,o=i.data.hole;e&&o&&ow(o.shapePath,a,!0,r,n),o&&(t.shapePrimitives[t.shapePrimitives.length-1].holes=o.shapePath.shapePrimitives),ow(t,a,e,r,n)}}}function aw(e,t,n){let r=[],i=cw.rectangle,a=lw;a.x=e.dx,a.y=e.dy,a.width=e.dw,a.height=e.dh;let o=e.transform;if(!i.build(a,r))return;let{vertices:s,uvs:c,indices:l}=n,u=l.length,d=s.length/2;o&&NC(r,o),i.triangulate(r,s,2,d,l,u);let f=e.image,p=f.uvs;c.push(p.x0,p.y0,p.x1,p.y1,p.x3,p.y3,p.x2,p.y2);let m=ma.get(IC);m.indexOffset=u,m.indexSize=l.length-u,m.attributeOffset=d,m.attributeSize=s.length/2-d,m.baseColor=e.style,m.alpha=e.alpha,m.texture=f,m.geometryData=n,t.push(m)}function ow(e,t,n,r,i){let{vertices:a,uvs:o,indices:s}=i;e.shapePrimitives.forEach(({shape:e,transform:c,holes:l})=>{let u=[],d=cw[e.type];if(!d.build(e,u))return;let f=s.length,p=a.length/2,m=`triangle-list`;if(c&&NC(u,c),n){let n=e.closePath??!0,r=t;r.pixelLine?(HC(u,n,a,s),m=`line-list`):_C(u,r,!1,n,a,s)}else if(l){let e=[],t=u.slice();sw(l).forEach(n=>{e.push(t.length/2),t.push(...n)}),WC(t,e,a,2,p,s,f)}else d.triangulate(u,a,2,p,s,f);let h=o.length/2,g=t.texture;if(g!==q.WHITE){let n=$C(uw,t,e,c);AC(a,2,p,o,h,2,a.length/2-p,n)}else jC(o,h,2,a.length/2-p);let _=ma.get(IC);_.indexOffset=f,_.indexSize=s.length-f,_.attributeOffset=p,_.attributeSize=a.length/2-p,_.baseColor=t.color,_.alpha=t.alpha,_.texture=g,_.geometryData=i,_.topology=m,r.push(_)})}function sw(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n].shape,i=[];cw[r.type].build(r,i)&&t.push(i)}return t}var cw,lw,uw,dw=s((()=>{R(),B(),Pa(),MC(),PC(),$o(),ha(),LC(),VC(),vC(),UC(),JC(),XC(),QC(),rw(),GC(),cw={},L.handleByMap(I.ShapeBuilder,cw),L.add(YC,qC,ZC,RC,zC,BC),lw=new G,uw=new z}));function fw(e,t,n){e.beginPath();for(let r=0;r<n.length;r+=3){let i=n[r]*2,a=n[r+1]*2,o=n[r+2]*2;e.moveTo(t[i],t[i+1]),e.lineTo(t[a],t[a+1]),e.lineTo(t[o],t[o+1]),e.closePath()}e.fill()}function pw(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function mw(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function hw(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;mw(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function gw(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),hw(e,r.shape),a&&e.restore()}return!0}function _w(e,t,n,r){let i=e.fill;if(i instanceof wC){i.buildGradient();let a=i.texture;if(a){let o=X.getTintedPattern(a,t),s=n?Sw.copyFrom(n).scale(a.source.pixelWidth,a.source.pixelHeight):Sw.copyFrom(i.transform);return r&&!e.textureSpace&&s.append(r),X.applyPatternTransform(o,s),o}}if(i instanceof OC){let e=X.getTintedPattern(i.texture,t);return X.applyPatternTransform(e,i.transform,!1),e}let a=e.texture;if(a&&a!==q.WHITE){if(!a.source.resource)return vw;let r=X.getTintedPattern(a,t),i=e.matrix;if(n){let{resolution:e}=a.source;if(i=Sw.copyFrom(n),a.rotate){let{uvs:t,orig:n}=a;i.prepend(Cw.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0).invert()).scale(n.width*e,n.height*e)}else i.scale(a.source.pixelWidth,a.source.pixelHeight).translate(-a.frame.x*e,-a.frame.y*e)}return X.applyPatternTransform(r,i),r}return pw(t)}var vw,yw,bw,xw,Sw,Cw,ww,Tw=s((()=>{R(),Uo(),B(),su(),$o(),to(),Ya(),vC(),TC(),kC(),dw(),rw(),vw=`#808080`,yw=new z,bw=new z,xw=new z,Sw=new z,Cw=new z,ww=class{constructor(){this.shader=null}contextChange(e){}execute(e,t){let n=e.renderer,r=n.canvasContext,i=r.activeContext,a=t.groupTransform,o=n.globalUniforms.globalUniformData?.worldColor??4294967295,s=t.groupColorAlpha,c=(o>>>24&255)/255,l=(s>>>24&255)/255,u=n.filter?.alphaMultiplier??1,d=c*l*u;if(d<=0)return;let f=o&16777215,p=$a(Ja(s&16777215,f)),m=n._roundPixels|t._roundPixels;i.save(),r.setContextTransform(a,m===1),r.setBlendMode(t.groupBlendMode);let h=t.context.instructions;for(let e=0;e<h.length;e++){let t=h[e];if(t.action===`texture`){let e=t.data,n=e.image,o=n?X.getCanvasSource(n):null;if(!o)continue;let s=e.alpha*d;if(s<=0)continue;let c=Ja(e.style,p);i.globalAlpha=s;let l=o;c!==16777215&&(l=X.getTintedCanvas({texture:n},c));let u=n.frame,f=n.source._resolution??n.source.resolution??1,h=u.x*f,g=u.y*f,_=u.width*f,v=u.height*f;l!==o&&(h=0,g=0);let y=e.transform,b=y&&!y.isIdentity(),x=n.rotate;b||x?(yw.copyFrom(a),b&&yw.append(y),x&&K.matrixAppendRotationInv(yw,x,e.dx,e.dy,e.dw,e.dh),r.setContextTransform(yw,m===1)):r.setContextTransform(a,m===1),i.drawImage(l,h,g,l===o?_:l.width,l===o?v:l.height,x?0:e.dx,x?0:e.dy,e.dw,e.dh),(b||x)&&r.setContextTransform(a,m===1);continue}let n=t.data,o=n?.path?.shapePath;if(!o?.shapePrimitives?.length)continue;let s=n.style,c=Ja(s.color,p),l=s.alpha*d;if(l<=0)continue;let u=t.action===`stroke`;if(i.globalAlpha=l,u){let e=s;i.lineWidth=e.width,i.lineCap=e.cap,i.lineJoin=e.join,i.miterLimit=e.miterLimit}let f=o.shapePrimitives;if(!u&&n.hole?.shapePath?.shapePrimitives?.length){let e=f[f.length-1];e.holes=n.hole.shapePath.shapePrimitives}for(let e=0;e<f.length;e++){let t=f[e];if(!t?.shape)continue;let n=t.transform,r=n&&!n.isIdentity(),o=s.texture&&s.texture!==q.WHITE,l=s.textureSpace===`global`?n:null,d=_w(s,c,o?$C(bw,s,t.shape,l):null,r?xw.copyFrom(a).append(n):a);if(r&&(i.save(),i.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),u){let e=s;if(e.alignment!==.5&&!e.pixelLine){let n=[],r=[],a=[];cw[t.shape.type]?.build(t.shape,n)?(_C(n,e,!1,t.shape.closePath??!0,r,a),i.fillStyle=d,fw(i,r,a)):(i.strokeStyle=d,i.beginPath(),hw(i,t.shape),i.stroke())}else i.strokeStyle=d,i.beginPath(),hw(i,t.shape),i.stroke()}else i.fillStyle=d,i.beginPath(),hw(i,t.shape),gw(i,t.holes)?i.fill(`evenodd`):i.fill();r&&i.restore()}}i.restore()}destroy(){this.shader=null}},ww.extension={type:[I.CanvasPipesAdaptor],name:`graphics`}})),Ew,Dw,Ow=s((()=>{R(),Uo(),B(),to(),Ya(),su(),Ew=class e{static _getPatternRepeat(e,t){let n=e&&e!==`clamp-to-edge`,r=t&&t!==`clamp-to-edge`;return n&&r?`repeat`:n?`repeat-x`:r?`repeat-y`:`no-repeat`}start(e,t,n){}execute(t,n){let r=n.elements;if(!r||!r.length)return;let i=t.renderer,a=i.canvasContext,o=a.activeContext;for(let t=0;t<r.length;t++){let s=r[t];if(!s.packAsQuad)continue;let c=s,l=c.texture,u=l?X.getCanvasSource(l):null;if(!u)continue;let d=l.source.style,f=a.smoothProperty,p=d.scaleMode!==`nearest`;o[f]!==p&&(o[f]=p),a.setBlendMode(n.blendMode);let m=i.globalUniforms.globalUniformData?.worldColor??4294967295,h=c.color,g=(m>>>24&255)/255,_=(h>>>24&255)/255,v=i.filter?.alphaMultiplier??1,y=g*_*v;if(y<=0)continue;o.globalAlpha=y;let b=m&16777215,x=$a(Ja(h&16777215,b)),S=l.frame,C=d.addressModeU??d.addressMode,ee=d.addressModeV??d.addressMode,w=e._getPatternRepeat(C,ee),T=l.source._resolution??l.source.resolution??1,E=c.renderable?.renderGroup?.isCachedAsTexture,te=S.x*T,D=S.y*T,O=S.width*T,ne=S.height*T,k=c.bounds,A=i.renderTarget.renderTarget.isRoot,re=k.minX,ie=k.minY,ae=k.maxX-k.minX,oe=k.maxY-k.minY,se=l.rotate,j=l.uvs,ce=Math.min(j.x0,j.x1,j.x2,j.x3,j.y0,j.y1,j.y2,j.y3),le=Math.max(j.x0,j.x1,j.x2,j.x3,j.y0,j.y1,j.y2,j.y3),ue=w!==`no-repeat`&&(ce<0||le>1),de=se&&(!!ue||x===16777215&&!se);de?(e._tempPatternMatrix.copyFrom(c.transform),K.matrixAppendRotationInv(e._tempPatternMatrix,se,re,ie,ae,oe),a.setContextTransform(e._tempPatternMatrix,c.roundPixels===1,void 0,E&&A)):a.setContextTransform(c.transform,c.roundPixels===1,void 0,E&&A);let fe=ae,pe=oe,me=de?0:re,he=de?0:ie;if(!de&&c.roundPixels===1&&(me|=0,he|=0),ue){let t=u,n=x!==16777215&&!se,r=S.width<=l.source.width&&S.height<=l.source.height;n&&r&&(t=X.getTintedCanvas({texture:l},x));let i=o.createPattern(t,w);if(!i)continue;let a=fe,s=pe;if(a===0||s===0)continue;let c=1/a,d=1/s,f=(j.x1-j.x0)*c,p=(j.y1-j.y0)*c,m=(j.x3-j.x0)*d,h=(j.y3-j.y0)*d,g=j.x0-f*me-m*he,_=j.y0-p*me-h*he,v=l.source.pixelWidth,y=l.source.pixelHeight;e._tempPatternMatrix.set(f*v,p*y,m*v,h*y,g*v,_*y),X.applyPatternTransform(i,e._tempPatternMatrix),o.fillStyle=i,o.fillRect(me,he,fe,pe)}else{let e=x!==16777215||se?X.getTintedCanvas({texture:l},x):u,t=e!==u;o.drawImage(e,t?0:te,t?0:D,t?e.width:O,t?e.height:ne,me,he,fe,pe)}}}},Ew._tempPatternMatrix=new z,Ew.extension={type:[I.CanvasPipesAdaptor],name:`batch`},Dw=Ew})),kw,Aw=s((()=>{R(),kw=class{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;r[this._colorStackIndex]=r[this._colorStackIndex-1]&e.mask;let i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,n){this._renderer.renderPipes.batch.break(n);let r=this._colorStack;this._colorStackIndex--;let i=r[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,n.add({renderPipeId:`colorMask`,colorMask:i,canBundle:!1}))}execute(e){}destroy(){this._renderer=null,this._colorStack=null}},kw.extension={type:[I.CanvasPipes],name:`colorMask`}}));function jw(e){let t=[];return e.replace(Pw,(e,n,r)=>{let i=n.toLowerCase(),a=n,o=Mw(r);for(i===`m`&&o.length>2&&(t.push([a,...o.splice(0,2)]),i=`l`,a=a===`m`?`l`:`L`);;){if(o.length===Nw[i])return t.push([a,...o]),``;if(o.length<Nw[i])throw Error(`malformed path data`);t.push([a,...o.splice(0,Nw[i])])}}),t}function Mw(e){let t=e.match(Fw);return t?t.map(Number):[]}var Nw,Pw,Fw,Iw=s((()=>{Nw={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},Pw=/([astvzqmhlc])([^astvzqmhlc]*)/gi,Fw=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi}));function Lw(e,t){let n=jw(e),r=[],i=null,a=0,o=0;for(let e=0;e<n.length;e++){let s=n[e],c=s[0],l=s;switch(c){case`M`:a=l[1],o=l[2],t.moveTo(a,o);break;case`m`:a+=l[1],o+=l[2],t.moveTo(a,o);break;case`H`:a=l[1],t.lineTo(a,o);break;case`h`:a+=l[1],t.lineTo(a,o);break;case`V`:o=l[1],t.lineTo(a,o);break;case`v`:o+=l[1],t.lineTo(a,o);break;case`L`:a=l[1],o=l[2],t.lineTo(a,o);break;case`l`:a+=l[1],o+=l[2],t.lineTo(a,o);break;case`C`:a=l[5],o=l[6],t.bezierCurveTo(l[1],l[2],l[3],l[4],a,o);break;case`c`:t.bezierCurveTo(a+l[1],o+l[2],a+l[3],o+l[4],a+l[5],o+l[6]),a+=l[5],o+=l[6];break;case`S`:a=l[3],o=l[4],t.bezierCurveToShort(l[1],l[2],a,o);break;case`s`:t.bezierCurveToShort(a+l[1],o+l[2],a+l[3],o+l[4]),a+=l[3],o+=l[4];break;case`Q`:a=l[3],o=l[4],t.quadraticCurveTo(l[1],l[2],a,o);break;case`q`:t.quadraticCurveTo(a+l[1],o+l[2],a+l[3],o+l[4]),a+=l[3],o+=l[4];break;case`T`:a=l[1],o=l[2],t.quadraticCurveToShort(a,o);break;case`t`:a+=l[1],o+=l[2],t.quadraticCurveToShort(a,o);break;case`A`:a=l[6],o=l[7],t.arcToSvg(l[1],l[2],l[3],l[4],l[5],a,o);break;case`a`:a+=l[6],o+=l[7],t.arcToSvg(l[1],l[2],l[3],l[4],l[5],a,o);break;case`Z`:case`z`:t.closePath(),r.length>0&&(i=r.pop(),i?(a=i.startX,o=i.startY):(a=0,o=0)),i=null;break;default:U(`Unknown SVG path command: ${c}`)}c!==`Z`&&c!==`z`&&i===null&&(i={startX:a,startY:o},r.push(i))}return t}var Rw=s((()=>{Iw(),W()})),zw,Bw,Vw,Hw,Uw=s((()=>{R(),hm(),zg(),yo(),cv(),oa(),ha(),dw(),zw=class{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{ma.return(e)}),this.graphicsData&&ma.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}},Bw=class{constructor(){this.instructions=new vo}init(e){let t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Rg({maxTextures:t}),this.instructions.reset()}get geometry(){return H(na,`GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead.`),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}},Vw=class e{constructor(e){this._renderer=e,this._managedContexts=new sv({renderer:e,type:`resource`,name:`graphicsContext`})}init(t){e.defaultOptions.bezierSmoothness=t?.bezierSmoothness??e.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){let t=!!e._gpuData[this._renderer.uid],n=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&n.reset(),iw(e,n);let r=e.batchMode;n.isBatchable=e.customShader||r===`no-batch`?!1:r!==`auto`||n.geometryData.vertices.length<400,e.dirty=!1}return n}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){let t=ma.get(Bw,{maxTextures:this._renderer.limits.maxBatchableTextures}),n=e._gpuData[this._renderer.uid],{batches:r,geometryData:i}=n;n.graphicsData=t;let a=i.vertices.length,o=i.indices.length;for(let e=0;e<r.length;e++)r[e].applyTransform=!1;let s=t.batcher;s.ensureAttributeBuffer(a),s.ensureIndexBuffer(o),s.begin();for(let e=0;e<r.length;e++){let t=r[e];s.add(t)}s.finish(t.instructions);let c=s.geometry;c.indexBuffer.setDataWithSize(s.indexBuffer,s.indexSize,!0),c.buffers[0].setDataWithSize(s.attributeBuffer.float32View,s.attributeSize,!0);let l=s.batches;for(let e=0;e<s.batchIndex;e++){let t=l[e];t.bindGroup=fm(t.textures.textures,t.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){let t=new zw;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}},Vw.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:`graphicsContext`},Vw.defaultOptions={bezierSmoothness:.5},Hw=Vw}));function Ww(e,t,n,r,i,a,o,s,c,l){let u=Math.min(.99,Math.max(0,l??Hw.defaultOptions.bezierSmoothness)),d=(Yw-u)/1;return d*=d,Gw(t,n,r,i,a,o,s,c,e,d),e}function Gw(e,t,n,r,i,a,o,s,c,l){Kw(e,t,n,r,i,a,o,s,c,l,0),c.push(o,s)}function Kw(e,t,n,r,i,a,o,s,c,l,u){if(u>qw)return;let d=(e+n)/2,f=(t+r)/2,p=(n+i)/2,m=(r+a)/2,h=(i+o)/2,g=(a+s)/2,_=(d+p)/2,v=(f+m)/2,y=(p+h)/2,b=(m+g)/2,x=(_+y)/2,S=(v+b)/2;if(u>0){let u=o-e,d=s-t,f=Math.abs((n-o)*d-(r-s)*u),p=Math.abs((i-o)*d-(a-s)*u);if(f>Jw&&p>Jw){if((f+p)*(f+p)<=l*(u*u+d*d)){c.push(x,S);return}}else if(f>Jw){if(f*f<=l*(u*u+d*d)){c.push(x,S);return}}else if(p>Jw){if(p*p<=l*(u*u+d*d)){c.push(x,S);return}}else if(u=x-(e+o)/2,d=S-(t+s)/2,u*u+d*d<=l){c.push(x,S);return}}Kw(e,t,d,f,_,v,x,S,c,l,u+1),Kw(x,S,y,b,h,g,o,s,c,l,u+1)}var qw,Jw,Yw,Xw=s((()=>{Uw(),qw=8,Jw=1.1920929e-7,Yw=1}));function Zw(e,t,n,r,i,a,o,s){let c=Math.min(.99,Math.max(0,s??Hw.defaultOptions.bezierSmoothness)),l=(nT-c)/1;return l*=l,Qw(t,n,r,i,a,o,e,l),e}function Qw(e,t,n,r,i,a,o,s){$w(o,e,t,n,r,i,a,s,0),o.push(i,a)}function $w(e,t,n,r,i,a,o,s,c){if(c>eT)return;let l=(t+r)/2,u=(n+i)/2,d=(r+a)/2,f=(i+o)/2,p=(l+d)/2,m=(u+f)/2,h=a-t,g=o-n,_=Math.abs((r-a)*g-(i-o)*h);if(_>tT){if(_*_<=s*(h*h+g*g)){e.push(p,m);return}}else if(h=p-(t+a)/2,g=m-(n+o)/2,h*h+g*g<=s){e.push(p,m);return}$w(e,t,n,l,u,p,m,s,c+1),$w(e,p,m,d,f,a,o,s,c+1)}var eT,tT,nT,rT=s((()=>{Uw(),eT=8,tT=1.1920929e-7,nT=1}));function iT(e,t,n,r,i,a,o,s){let c=Math.abs(i-a);(!o&&i>a||o&&a>i)&&(c=2*Math.PI-c),s||=Math.max(6,Math.floor(6*r**(1/3)*(c/Math.PI))),s=Math.max(s,3);let l=c/s,u=i;l*=o?-1:1;for(let i=0;i<s+1;i++){let i=Math.cos(u),a=Math.sin(u),o=t+i*r,s=n+a*r;e.push(o,s),u+=l}}var aT=s((()=>{}));function oT(e,t,n,r,i,a){let o=e[e.length-2],s=e[e.length-1]-n,c=o-t,l=i-n,u=r-t,d=Math.abs(s*u-c*l);if(d<1e-8||a===0){(e[e.length-2]!==t||e[e.length-1]!==n)&&e.push(t,n);return}let f=s*s+c*c,p=l*l+u*u,m=s*l+c*u,h=a*Math.sqrt(f)/d,g=a*Math.sqrt(p)/d,_=h*m/f,v=g*m/p,y=h*u+g*c,b=h*l+g*s,x=c*(g+_),S=s*(g+_),C=u*(h+v),ee=l*(h+v),w=Math.atan2(S-b,x-y),T=Math.atan2(ee-b,C-y);iT(e,y+t,b+n,a,w,T,c*l>u*s)}var sT=s((()=>{aT()}));function cT(e,t){let n=t===-1.5707963267948966?-.551915024494:4/3*Math.tan(t/4),r=t===1.5707963267948966?.551915024494:n,i=Math.cos(e),a=Math.sin(e),o=Math.cos(e+t),s=Math.sin(e+t);return[{x:i-a*r,y:a+i*r},{x:o+s*r,y:s-o*r},{x:o,y:s}]}function lT(e,t,n,r,i,a,o,s=0,c=0,l=0){if(a===0||o===0)return;let u=Math.sin(s*uT/360),d=Math.cos(s*uT/360),f=d*(t-r)/2+u*(n-i)/2,p=-u*(t-r)/2+d*(n-i)/2;if(f===0&&p===0)return;a=Math.abs(a),o=Math.abs(o);let m=f**2/a**2+p**2/o**2;m>1&&(a*=Math.sqrt(m),o*=Math.sqrt(m)),mT(t,n,r,i,a,o,c,l,u,d,f,p,dT);let{ang1:h,ang2:g}=dT,{centerX:_,centerY:v}=dT,y=Math.abs(g)/(uT/4);Math.abs(1-y)<1e-7&&(y=1);let b=Math.max(Math.ceil(y),1);g/=b;let x=e[e.length-2],S=e[e.length-1],C={x:0,y:0};for(let t=0;t<b;t++){let t=cT(h,g),{x:n,y:r}=fT(t[0],a,o,d,u,_,v,C),{x:i,y:s}=fT(t[1],a,o,d,u,_,v,C),{x:c,y:l}=fT(t[2],a,o,d,u,_,v,C);Ww(e,x,S,n,r,i,s,c,l),x=c,S=l,h+=g}}var uT,dT,fT,pT,mT,hT=s((()=>{Xw(),uT=Math.PI*2,dT={centerX:0,centerY:0,ang1:0,ang2:0},fT=({x:e,y:t},n,r,i,a,o,s,c)=>{e*=n,t*=r;let l=i*e-a*t,u=a*e+i*t;return c.x=l+o,c.y=u+s,c},pT=(e,t,n,r)=>{let i=e*r-t*n<0?-1:1,a=e*n+t*r;return a>1&&(a=1),a<-1&&(a=-1),i*Math.acos(a)},mT=(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{let p=i**2,m=a**2,h=u**2,g=d**2,_=p*m-p*g-m*h;_<0&&(_=0),_/=p*g+m*h,_=Math.sqrt(_)*(o===s?-1:1);let v=_*i/a*d,y=_*-a/i*u,b=l*v-c*y+(e+n)/2,x=c*v+l*y+(t+r)/2,S=(u-v)/i,C=(d-y)/a,ee=(-u-v)/i,w=(-d-y)/a,T=pT(1,0,S,C),E=pT(S,C,ee,w);s===0&&E>0&&(E-=uT),s===1&&E<0&&(E+=uT),f.centerX=b,f.centerY=x,f.ang1=T,f.ang2=E}}));function gT(e,t,n){let r=(e,t)=>{let n=t.x-e.x,r=t.y-e.y,i=Math.sqrt(n*n+r*r);return{len:i,nx:n/i,ny:r/i}},i=(t,n)=>{t===0?e.moveTo(n.x,n.y):e.lineTo(n.x,n.y)},a=t[t.length-1];for(let o=0;o<t.length;o++){let s=t[o%t.length],c=s.radius??n;if(c<=0){i(o,s),a=s;continue}let l=t[(o+1)%t.length],u=r(s,a),d=r(s,l);if(u.len<1e-4||d.len<1e-4){i(o,s),a=s;continue}let f=Math.asin(u.nx*d.ny-u.ny*d.nx),p=1,m=!1;u.nx*d.nx-u.ny*-d.ny<0?f<0?f=Math.PI+f:(f=Math.PI-f,p=-1,m=!0):f>0&&(p=-1,m=!0);let h=f/2,g,_=Math.abs(Math.cos(h)*c/Math.sin(h));_>Math.min(u.len/2,d.len/2)?(_=Math.min(u.len/2,d.len/2),g=Math.abs(_*Math.sin(h)/Math.cos(h))):g=c;let v=s.x+d.nx*_+-d.ny*g*p,y=s.y+d.ny*_+d.nx*g*p,b=Math.atan2(u.ny,u.nx)+Math.PI/2*p,x=Math.atan2(d.ny,d.nx)-Math.PI/2*p;o===0&&e.moveTo(v+Math.cos(b)*g,y+Math.sin(b)*g),e.arc(v,y,g,b,x,m),a=s}}function _T(e,t,n,r){let i=(e,t)=>Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2),a=(e,t,n)=>({x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}),o=t.length;for(let s=0;s<o;s++){let c=t[(s+1)%o],l=c.radius??n;if(l<=0){s===0?e.moveTo(c.x,c.y):e.lineTo(c.x,c.y);continue}let u=t[s],d=t[(s+2)%o],f=i(u,c),p;p=f<1e-4?c:a(c,u,Math.min(f/2,l)/f);let m=i(d,c),h;h=m<1e-4?c:a(c,d,Math.min(m/2,l)/m),s===0?e.moveTo(p.x,p.y):e.lineTo(p.x,p.y),e.quadraticCurveTo(c.x,c.y,h.x,h.y,r)}}var vT=s((()=>{})),yT,bT,xT=s((()=>{bu(),Su(),Eu(),Pa(),ku(),La(),Xw(),rT(),aT(),sT(),hT(),vT(),yT=new G,bT=class{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ia,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();let n=this._currentPoly.points,r=n[n.length-2],i=n[n.length-1];return(r!==e||i!==t)&&n.push(e,t),this}arc(e,t,n,r,i,a){this._ensurePoly(!1);let o=this._currentPoly.points;return iT(o,e,t,n,r,i,a),this}arcTo(e,t,n,r,i){this._ensurePoly();let a=this._currentPoly.points;return oT(a,e,t,n,r,i),this}arcToSvg(e,t,n,r,i,a,o){let s=this._currentPoly.points;return lT(s,this._currentPoly.lastX,this._currentPoly.lastY,a,o,e,t,n,r,i),this}bezierCurveTo(e,t,n,r,i,a,o){this._ensurePoly();let s=this._currentPoly;return Ww(this._currentPoly.points,s.lastX,s.lastY,e,t,n,r,i,a,o),this}quadraticCurveTo(e,t,n,r,i){this._ensurePoly();let a=this._currentPoly;return Zw(this._currentPoly.points,a.lastX,a.lastY,e,t,n,r,i),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));let n=this.shapePrimitives,r=n.length;for(let t=0;t<e.instructions.length;t++){let n=e.instructions[t];this[n.action](...n.data)}if(e.checkForHoles&&n.length-r>1){let e=null;for(let t=r;t<n.length;t++){let r=n[t];if(r.shape.type===`polygon`){let i=r.shape,a=e?.shape;a&&a.containsPolygon(i)?(e.holes||(e.holes=[]),e.holes.push(r),n.copyWithin(t,t+1),n.length--,t--):e=r}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,n,r,i){return this.drawShape(new G(e,t,n,r),i),this}circle(e,t,n,r){return this.drawShape(new yu(e,t,n),r),this}poly(e,t,n){let r=new Tu(e);return r.closePath=t,this.drawShape(r,n),this}regularPoly(e,t,n,r,i=0,a){r=Math.max(r|0,3);let o=-1*Math.PI/2+i,s=Math.PI*2/r,c=[];for(let i=0;i<r;i++){let r=o-i*s;c.push(e+n*Math.cos(r),t+n*Math.sin(r))}return this.poly(c,!0,a),this}roundPoly(e,t,n,r,i,a=0,o){if(r=Math.max(r|0,3),i<=0)return this.regularPoly(e,t,n,r,a);let s=n*Math.sin(Math.PI/r)-.001;i=Math.min(i,s);let c=-1*Math.PI/2+a,l=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let a=0;a<r;a++){let r=a*l+c,s=e+n*Math.cos(r),d=t+n*Math.sin(r),f=r+Math.PI+u,p=r-Math.PI-u,m=s+i*Math.cos(f),h=d+i*Math.sin(f),g=s+i*Math.cos(p),_=d+i*Math.sin(p);a===0?this.moveTo(m,h):this.lineTo(m,h),this.quadraticCurveTo(s,d,g,_,o)}return this.closePath()}roundShape(e,t,n=!1,r){return e.length<3?this:(n?_T(this,e,t,r):gT(this,e,t),this.closePath())}filletRect(e,t,n,r,i){if(i===0)return this.rect(e,t,n,r);let a=Math.min(n,r)/2,o=Math.min(a,Math.max(-a,i)),s=e+n,c=t+r,l=o<0?-o:0,u=Math.abs(o);return this.moveTo(e,t+u).arcTo(e+l,t+l,e+u,t,u).lineTo(s-u,t).arcTo(s-l,t+l,s,t+u,u).lineTo(s,c-u).arcTo(s-l,c-l,e+n-u,c,u).lineTo(e+u,c).arcTo(e+l,c-l,e,c-u,u).closePath()}chamferRect(e,t,n,r,i,a){if(i<=0)return this.rect(e,t,n,r);let o=Math.min(i,Math.min(n,r)/2),s=e+n,c=t+r,l=[e+o,t,s-o,t,s,t+o,s,c-o,s-o,c,e+o,c,e,c-o,e,t+o];for(let e=l.length-1;e>=2;e-=2)l[e]===l[e-2]&&l[e-1]===l[e-3]&&l.splice(e-1,2);return this.poly(l,!0,a)}ellipse(e,t,n,r,i){return this.drawShape(new xu(e,t,n,r),i),this}roundRect(e,t,n,r,i,a){return this.drawShape(new Ou(e,t,n,r,i),a),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let n=this._currentPoly;return n&&this.endPoly(),n=new Tu,n.points.push(e,t),this._currentPoly=n,this}endPoly(e=!1){let t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new Tu,e)){let e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let t=e.shape.x,n=e.shape.y;if(e.transform&&!e.transform.isIdentity()){let r=e.transform,i=t;t=r.a*t+r.c*n+r.tx,n=r.b*i+r.d*n+r.ty}this._currentPoly.points.push(t,n)}else this._currentPoly.points.push(0,0)}}buildPath(){let e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){let n=e.instructions[t];this[n.action](...n.data)}this.finish()}get bounds(){let e=this._bounds;e.clear();let t=this.shapePrimitives;for(let n=0;n<t.length;n++){let r=t[n],i=r.shape.getBounds(yT);r.transform?e.addRect(i,r.transform):e.addRect(i)}return e}}}));function ST(e,t){return e?e.prepend(t):t.clone()}var CT,wT=s((()=>{qi(),ea(),W(),Rw(),xT(),CT=class e{constructor(e,t=!1){this.instructions=[],this.uid=Qi(`graphicsPath`),this._dirty=!0,this.checkForHoles=t,typeof e==`string`?Lw(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||=new bT(this),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:`addPath`,data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:`arc`,data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:`arcTo`,data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:`arcToSvg`,data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:`bezierCurveTo`,data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,n,r,i){let a=this.instructions[this.instructions.length-1],o=this.getLastPoint(Gi.shared),s=0,c=0;if(!a||a.action!==`bezierCurveTo`)s=o.x,c=o.y;else{s=a.data[2],c=a.data[3];let e=o.x,t=o.y;s=e+(e-s),c=t+(t-c)}return this.instructions.push({action:`bezierCurveTo`,data:[s,c,e,t,n,r,i]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:`closePath`,data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:`ellipse`,data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:`lineTo`,data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:`moveTo`,data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:`quadraticCurveTo`,data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,n){let r=this.instructions[this.instructions.length-1],i=this.getLastPoint(Gi.shared),a=0,o=0;if(!r||r.action!==`quadraticCurveTo`)a=i.x,o=i.y;else{a=r.data[0],o=r.data[1];let e=i.x,t=i.y;a=e+(e-a),o=t+(t-o)}return this.instructions.push({action:`quadraticCurveTo`,data:[a,o,e,t,n]}),this._dirty=!0,this}rect(e,t,n,r,i){return this.instructions.push({action:`rect`,data:[e,t,n,r,i]}),this._dirty=!0,this}circle(e,t,n,r){return this.instructions.push({action:`circle`,data:[e,t,n,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:`roundRect`,data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:`poly`,data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:`regularPoly`,data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:`roundPoly`,data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:`roundShape`,data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:`filletRect`,data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:`chamferRect`,data:e}),this._dirty=!0,this}star(e,t,n,r,i,a,o){i||=r/2;let s=-1*Math.PI/2+a,c=n*2,l=Math.PI*2/c,u=[];for(let n=0;n<c;n++){let a=n%2?i:r,o=n*l+s;u.push(e+a*Math.cos(o),t+a*Math.sin(o))}return this.poly(u,!0,o),this}clone(t=!1){let n=new e;if(n.checkForHoles=this.checkForHoles,!t)n.instructions=this.instructions.slice();else for(let e=0;e<this.instructions.length;e++){let t=this.instructions[e];n.instructions.push({action:t.action,data:t.data.slice()})}return n}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;let t=e.a,n=e.b,r=e.c,i=e.d,a=e.tx,o=e.ty,s=0,c=0,l=0,u=0,d=0,f=0,p=0,m=0;for(let h=0;h<this.instructions.length;h++){let g=this.instructions[h],_=g.data;switch(g.action){case`moveTo`:case`lineTo`:s=_[0],c=_[1],_[0]=t*s+r*c+a,_[1]=n*s+i*c+o;break;case`bezierCurveTo`:l=_[0],u=_[1],d=_[2],f=_[3],s=_[4],c=_[5],_[0]=t*l+r*u+a,_[1]=n*l+i*u+o,_[2]=t*d+r*f+a,_[3]=n*d+i*f+o,_[4]=t*s+r*c+a,_[5]=n*s+i*c+o;break;case`quadraticCurveTo`:l=_[0],u=_[1],s=_[2],c=_[3],_[0]=t*l+r*u+a,_[1]=n*l+i*u+o,_[2]=t*s+r*c+a,_[3]=n*s+i*c+o;break;case`arcToSvg`:s=_[5],c=_[6],p=_[0],m=_[1],_[0]=t*p+r*m,_[1]=n*p+i*m,_[5]=t*s+r*c+a,_[6]=n*s+i*c+o;break;case`circle`:_[4]=ST(_[3],e);break;case`rect`:_[4]=ST(_[4],e);break;case`ellipse`:_[8]=ST(_[8],e);break;case`roundRect`:_[5]=ST(_[5],e);break;case`addPath`:_[0].transform(e);break;case`poly`:_[2]=ST(_[2],e);break;case`regularPoly`:case`chamferRect`:_[5]=ST(_[5],e);break;case`closePath`:break;default:U(`unknown transform action`,g.action)}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,n=this.instructions[t];if(!n)return e.x=0,e.y=0,e;for(;n.action===`closePath`;){if(t--,t<0)return e.x=0,e.y=0,e;n=this.instructions[t]}switch(n.action){case`moveTo`:case`lineTo`:e.x=n.data[0],e.y=n.data[1];break;case`quadraticCurveTo`:e.x=n.data[2],e.y=n.data[3];break;case`bezierCurveTo`:e.x=n.data[4],e.y=n.data[5];break;case`arc`:case`arcToSvg`:e.x=n.data[5],e.y=n.data[6];break;case`addPath`:n.data[0].getLastPoint(e)}return e}}}));function TT(e,t,n){let r=e.getAttribute(t);return r?Number(r):n}var ET=s((()=>{}));function DT(e,t){let n=e.querySelectorAll(`defs`);for(let e=0;e<n.length;e++){let r=n[e];for(let e=0;e<r.children.length;e++){let n=r.children[e];switch(n.nodeName.toLowerCase()){case`lineargradient`:t.defs[n.id]=jT(n);break;case`radialgradient`:t.defs[n.id]=MT(n)}}}}function OT(e,t,n){let r=e.getAttribute(t);if(r?.trim().endsWith(`%`)){let e=Number(r.trim().slice(0,-1));return Number.isNaN(e)?n:e/100}return TT(e,t,n)}function kT(e){return(e.getAttribute(`gradientUnits`)||`objectBoundingBox`)===`objectBoundingBox`?`local`:`global`}function AT(e){let t=[];for(let n=0;n<e.children.length;n++){let r=e.children[n],i=OT(r,`offset`,0),a=Li.shared.setValue(r.getAttribute(`stop-color`)).toNumber();t.push({offset:i,color:a})}return t}function jT(e){let t=OT(e,`x1`,0),n=OT(e,`y1`,0),r=OT(e,`x2`,1),i=OT(e,`y2`,0);return new wC({type:`linear`,start:{x:t,y:n},end:{x:r,y:i},textureSpace:kT(e),colorStops:AT(e)})}function MT(e){let t=OT(e,`cx`,.5),n=OT(e,`cy`,.5),r=OT(e,`r`,.5),i=OT(e,`fx`,t),a=OT(e,`fy`,n),o=OT(e,`fr`,0);return new wC({type:`radial`,center:{x:i,y:a},innerRadius:o,outerCenter:{x:t,y:n},outerRadius:r,textureSpace:kT(e),colorStops:AT(e)})}var NT=s((()=>{Ri(),TC(),ET()}));function PT(e){let t=e.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:``}var FT=s((()=>{}));function IT(e,t){let n=e.getAttribute(`style`),r={},i={},a={strokeStyle:r,fillStyle:i,useFill:!1,useStroke:!1};for(let n in RT){let r=e.getAttribute(n);r&<(t,a,n,r.trim())}if(n){let e=n.split(`;`);for(let n=0;n<e.length;n++){let[r,i]=e[n].trim().split(`:`);RT[r]&<(t,a,r,i.trim())}}return{strokeStyle:a.useStroke?r:null,fillStyle:a.useFill?i:null,useFill:a.useFill,useStroke:a.useStroke}}function LT(e,t,n,r){switch(n){case`stroke`:if(r!==`none`){if(r.startsWith(`url(`)){let n=PT(r);t.strokeStyle.fill=e.defs[n]}else t.strokeStyle.color=Li.shared.setValue(r).toNumber();t.useStroke=!0}break;case`stroke-width`:t.strokeStyle.width=Number(r);break;case`fill`:if(r!==`none`){if(r.startsWith(`url(`)){let n=PT(r);t.fillStyle.fill=e.defs[n]}else t.fillStyle.color=Li.shared.setValue(r).toNumber();t.useFill=!0}break;case`fill-opacity`:t.fillStyle.alpha=Number(r);break;case`stroke-opacity`:t.strokeStyle.alpha=Number(r);break;case`opacity`:t.fillStyle.alpha=Number(r),t.strokeStyle.alpha=Number(r)}}var RT,zT=s((()=>{Ri(),FT(),RT={fill:{type:`paint`,default:0},"fill-opacity":{type:`number`,default:1},stroke:{type:`paint`,default:0},"stroke-width":{type:`number`,default:1},"stroke-opacity":{type:`number`,default:1},"stroke-linecap":{type:`string`,default:`butt`},"stroke-linejoin":{type:`string`,default:`miter`},"stroke-miterlimit":{type:`number`,default:10},"stroke-dasharray":{type:`string`,default:`none`},"stroke-dashoffset":{type:`number`,default:0},opacity:{type:`number`,default:1}}}));function BT(e){if(e.length<=2)return!0;let t=e.map(e=>e.area).sort((e,t)=>t-e),[n,r]=t,i=t[t.length-1],a=n/r,o=r/i;return!(a>3&&o<2)}var VT=s((()=>{}));function HT(e){return e.split(/(?=[Mm])/).filter(e=>e.trim().length>0)}function UT(e){let t=e.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;let n=t.map(Number),r=[],i=[];for(let e=0;e<n.length;e+=2)e+1<n.length&&(r.push(n[e]),i.push(n[e+1]));if(r.length===0||i.length===0)return 0;let a=Math.min(...r),o=Math.max(...r),s=Math.min(...i),c=Math.max(...i);return(o-a)*(c-s)}function WT(e,t){let n=new CT(e,!1);for(let e of n.instructions)t.instructions.push(e)}var GT=s((()=>{wT()}));function KT(e,t){if(typeof e==`string`){let t=document.createElement(`div`);t.innerHTML=e.trim(),e=t.querySelector(`svg`)}let n={context:t,defs:{},path:new CT};DT(e,n);let r=e.children,{fillStyle:i,strokeStyle:a}=IT(e,n);for(let e=0;e<r.length;e++){let t=r[e];t.nodeName.toLowerCase()!==`defs`&&qT(t,n,i,a)}return t}function qT(e,t,n,r){let i=e.children,{fillStyle:a,strokeStyle:o}=IT(e,t);a&&n?n={...n,...a}:a&&(n=a),o&&r?r={...r,...o}:o&&(r=o);let s=!n&&!r;s&&(n={color:0});let c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,ee;switch(e.nodeName.toLowerCase()){case`path`:{x=e.getAttribute(`d`);let i=e.getAttribute(`fill-rule`),a=HT(x),o=i===`evenodd`,s=a.length>1;if(o&&s){let e=a.map(e=>({path:e,area:UT(e)}));if(e.sort((e,t)=>t.area-e.area),a.length>3||!BT(e))for(let i=0;i<e.length;i++){let a=e[i],o=i===0;t.context.beginPath();let s=new CT(void 0,!0);WT(a.path,s),t.context.path(s),o?(n&&t.context.fill(n),r&&t.context.stroke(r)):t.context.cut()}else for(let i=0;i<e.length;i++){let a=e[i],o=i%2==1;t.context.beginPath();let s=new CT(void 0,!0);WT(a.path,s),t.context.path(s),o?t.context.cut():(n&&t.context.fill(n),r&&t.context.stroke(r))}}else S=new CT(x,!i||i===`evenodd`),t.context.path(S),n&&t.context.fill(n),r&&t.context.stroke(r);break}case`circle`:m=TT(e,`cx`,0),h=TT(e,`cy`,0),g=TT(e,`r`,0),t.context.ellipse(m,h,g,g),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`rect`:c=TT(e,`x`,0),l=TT(e,`y`,0),C=TT(e,`width`,0),ee=TT(e,`height`,0),_=TT(e,`rx`,0),v=TT(e,`ry`,0),_||v?t.context.roundRect(c,l,C,ee,_||v):t.context.rect(c,l,C,ee),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`ellipse`:m=TT(e,`cx`,0),h=TT(e,`cy`,0),_=TT(e,`rx`,0),v=TT(e,`ry`,0),t.context.beginPath(),t.context.ellipse(m,h,_,v),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`line`:u=TT(e,`x1`,0),d=TT(e,`y1`,0),f=TT(e,`x2`,0),p=TT(e,`y2`,0),t.context.beginPath(),t.context.moveTo(u,d),t.context.lineTo(f,p),r&&t.context.stroke(r);break;case`polygon`:b=e.getAttribute(`points`),y=b.match(/-?\d+/g).map(e=>parseInt(e,10)),t.context.poly(y,!0),n&&t.context.fill(n),r&&t.context.stroke(r);break;case`polyline`:b=e.getAttribute(`points`),y=b.match(/-?\d+/g).map(e=>parseInt(e,10)),t.context.poly(y,!1),r&&t.context.stroke(r);break;case`g`:case`svg`:break;default:U(`[SVG parser] <${e.nodeName}> elements unsupported`)}s&&(n=null);for(let e=0;e<i.length;e++)qT(i[e],t,n,r)}var JT=s((()=>{W(),wT(),NT(),ET(),zT(),VT(),GT()}));function YT(e){return Li.isColorLike(e)}function XT(e){return e instanceof OC}function ZT(e){return e instanceof wC}function QT(e){return e instanceof q}function $T(e,t,n){let r=Li.shared.setValue(t??0);return e.color=r.toNumber(),e.alpha=r.alpha===1?n.alpha:r.alpha,e.texture=q.WHITE,{...n,...e}}function eE(e,t,n){return e.texture=t,{...n,...e}}function tE(e,t,n){return e.fill=t,e.color=16777215,e.texture=t.texture,e.matrix=t.transform,e.textureSpace=t.textureSpace,{...n,...e}}function nE(e,t,n){return t.buildGradient(),e.fill=t,e.color=16777215,e.texture=t.texture,e.matrix=t.transform,e.textureSpace=t.textureSpace,{...n,...e}}function rE(e,t){let n={...t,...e},r=Li.shared.setValue(n.color);return n.alpha*=r.alpha,n.color=r.toNumber(),n}function iE(e,t){if(e==null)return null;let n={},r=e;return YT(e)?$T(n,e,t):QT(e)?eE(n,e,t):XT(e)?tE(n,e,t):ZT(e)?nE(n,e,t):r.fill&&XT(r.fill)?tE(r,r.fill,t):r.fill&&ZT(r.fill)?nE(r,r.fill,t):rE(r,t)}function aE(e,t){let{width:n,alignment:r,miterLimit:i,cap:a,join:o,pixelLine:s,...c}=t,l=iE(e,c);return l?{width:n,alignment:r,miterLimit:i,cap:a,join:o,pixelLine:s,...l}:null}var oE=s((()=>{Ri(),$o(),TC(),kC()}));function sE(e,t){let n=1,r=e.shapePath.shapePrimitives;for(let e=0;e<r.length;e++){let i=r[e].shape;if(i.type!==`polygon`)continue;let a=i.points,o=a.length;if(o<6)continue;let s=i.closePath;for(let e=0;e<o;e+=2){if(!s&&(e===0||e===o-2))continue;let r=(e-2+o)%o,i=(e+2)%o,c=a[r],l=a[r+1],u=a[e],d=a[e+1],f=a[i],p=a[i+1],m=c-u,h=l-d,g=f-u,_=p-d,v=m*m+h*h,y=g*g+_*_;if(v<1e-12||y<1e-12)continue;let b=(m*g+h*_)/Math.sqrt(v*y);b<-1?b=-1:b>1&&(b=1);let x=Math.sqrt((1-b)*.5);if(x<1e-6)continue;let S=Math.min(1/x,t);S>n&&(n=S)}}return n}var cE=s((()=>{})),lE,uE,dE,fE,pE=s((()=>{ri(),Ri(),B(),qi(),$o(),ea(),oa(),La(),wT(),JT(),oE(),cE(),lE=new Gi,uE=new z,dE=class e extends ni{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=Qi(`graphicsContext`),this.dirty=!0,this.batchMode=`auto`,this.instructions=[],this.destroyed=!1,this._activePath=new CT,this._transform=new z,this._fillStyle={...e.defaultFillStyle},this._strokeStyle={...e.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ia,this._boundsDirty=!0}clone(){let t=new e;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=iE(t,e.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=aE(t,e.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=iE(t,e.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=iE(t,e.defaultStrokeStyle),this}texture(e,t,n,r,i,a){return this.instructions.push({action:`texture`,data:{image:e,dx:n||0,dy:r||0,dw:i||e.frame.width,dh:a||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?Li.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new CT,this}fill(t,n){let r,i=this.instructions[this.instructions.length-1];return r=this._tick===0&&i?.action===`stroke`?i.data.path:this._activePath.clone(),r&&(t!=null&&(n!==void 0&&typeof t==`number`&&(H(V,`GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead`),t={color:t,alpha:n}),this._fillStyle=iE(t,e.defaultFillStyle)),this.instructions.push({action:`fill`,data:{style:this.fillStyle,path:r}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0),this}_initNextPathLocation(){let{x:e,y:t}=this._activePath.getLastPoint(Gi.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(t){let n,r=this.instructions[this.instructions.length-1];return n=this._tick===0&&r?.action===`fill`?r.data.path:this._activePath.clone(),n&&(t!=null&&(this._strokeStyle=aE(t,e.defaultStrokeStyle)),this.instructions.push({action:`stroke`,data:{style:this.strokeStyle,path:n}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0),this}cut(){for(let e=0;e<2;e++){let t=this.instructions[this.instructions.length-1-e],n=this._activePath.clone();if(t&&(t.action===`stroke`||t.action===`fill`)){if(t.data.hole)t.data.hole.addPath(n);else{t.data.hole=n;break}}}return this._initNextPathLocation(),this}arc(e,t,n,r,i,a){this._tick++;let o=this._transform;return this._activePath.arc(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,n,r,i,a),this}arcTo(e,t,n,r,i){this._tick++;let a=this._transform;return this._activePath.arcTo(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,a.a*n+a.c*r+a.tx,a.b*n+a.d*r+a.ty,i),this}arcToSvg(e,t,n,r,i,a,o){this._tick++;let s=this._transform;return this._activePath.arcToSvg(e,t,n,r,i,s.a*a+s.c*o+s.tx,s.b*a+s.d*o+s.ty),this}bezierCurveTo(e,t,n,r,i,a,o){this._tick++;let s=this._transform;return this._activePath.bezierCurveTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty,s.a*n+s.c*r+s.tx,s.b*n+s.d*r+s.ty,s.a*i+s.c*a+s.tx,s.b*i+s.d*a+s.ty,o),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,n,r){return this._tick++,this._activePath.ellipse(e,t,n,r,this._transform.clone()),this}circle(e,t,n){return this._tick++,this._activePath.circle(e,t,n,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;let n=this._transform;return this._activePath.lineTo(n.a*e+n.c*t+n.tx,n.b*e+n.d*t+n.ty),this}moveTo(e,t){this._tick++;let n=this._transform,r=this._activePath.instructions,i=n.a*e+n.c*t+n.tx,a=n.b*e+n.d*t+n.ty;return r.length===1&&r[0].action===`moveTo`?(r[0].data[0]=i,r[0].data[1]=a,this):(this._activePath.moveTo(i,a),this)}quadraticCurveTo(e,t,n,r,i){this._tick++;let a=this._transform;return this._activePath.quadraticCurveTo(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,a.a*n+a.c*r+a.tx,a.b*n+a.d*r+a.ty,i),this}rect(e,t,n,r){return this._tick++,this._activePath.rect(e,t,n,r,this._transform.clone()),this}roundRect(e,t,n,r,i){return this._tick++,this._activePath.roundRect(e,t,n,r,i,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,n,r,i=0,a){return this._tick++,this._activePath.regularPoly(e,t,n,r,i,a),this}roundPoly(e,t,n,r,i,a){return this._tick++,this._activePath.roundPoly(e,t,n,r,i,a),this}roundShape(e,t,n,r){return this._tick++,this._activePath.roundShape(e,t,n,r),this}filletRect(e,t,n,r,i){return this._tick++,this._activePath.filletRect(e,t,n,r,i),this}chamferRect(e,t,n,r,i,a){return this._tick++,this._activePath.chamferRect(e,t,n,r,i,a),this}star(e,t,n,r,i=0,a=0){return this._tick++,this._activePath.star(e,t,n,r,i,a,this._transform.clone()),this}svg(e){return this._tick++,KT(e,this),this}restore(){let e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,n,r,i,a){return e instanceof z?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,n,r,i,a),this)}transform(e,t,n,r,i,a){return e instanceof z?(this._transform.append(e),this):(uE.set(e,t,n,r,i,a),this._transform.append(uE),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,this.dirty=!0,this.emit(`update`,this,16)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;let e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){let n=this.instructions[t],r=n.action;if(r===`fill`){let t=n.data;e.addBounds(t.path.bounds)}else if(r===`texture`){let t=n.data;e.addFrame(t.dx,t.dy,t.dx+t.dw,t.dy+t.dh,t.transform)}if(r===`stroke`){let t=n.data,r=t.style.alignment,i=t.style.width*(1-r);t.style.join===`miter`&&(i*=sE(t.path,t.style.miterLimit));let a=t.path.bounds;e.addFrame(a.minX-i,a.minY-i,a.maxX+i,a.maxY+i)}}return e.isValid||e.set(0,0,0,0),e}containsPoint(e){if(!this.bounds.containsPoint(e.x,e.y))return!1;let t=this.instructions,n=!1;for(let r=0;r<t.length;r++){let i=t[r],a=i.data,o=a.path;if(!i.action||!o)continue;let s=a.style,c=o.shapePath.shapePrimitives;for(let t=0;t<c.length;t++){let r=c[t].shape;if(!s||!r)continue;let o=c[t].transform,l=o?o.applyInverse(e,lE):e;if(i.action===`fill`)n=r.contains(l.x,l.y);else{let e=s;n=r.strokeContains(l.x,l.y,e.width,e.alignment)}let u=a.hole;if(u){let e=u.shapePath?.shapePrimitives;if(e)for(let t=0;t<e.length;t++)e[t].shape.contains(l.x,l.y)&&(n=!1)}if(n)return!0}}return n}unload(){this.emit(`unload`,this);for(let e in this._gpuData)this._gpuData[e]?.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(!this.destroyed){if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit(`destroy`,this),this.removeAllListeners(),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&`uid`in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(t)),this._strokeStyle.texture&&(this._strokeStyle.fill&&`uid`in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(t))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}}},dE.defaultFillStyle={color:16777215,alpha:1,texture:q.WHITE,matrix:null,fill:null,textureSpace:`local`},dE.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:`butt`,join:`miter`,texture:q.WHITE,matrix:null,fill:null,textureSpace:`local`,pixelLine:!1},fE=dE})),mE,hE,gE,_E,vE=s((()=>{R(),yo(),cv(),mE=class{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&=(this.graphicsData.destroy(),null)}destroy(){this.reset()}},hE=class{constructor(){this.instructions=new vo}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}},gE=class e{constructor(e){this._renderer=e,this._managedContexts=new sv({renderer:e,type:`resource`,name:`graphicsContext`})}init(t){e.defaultOptions.bezierSmoothness=t?.bezierSmoothness??e.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){let t=e._gpuData,n=!!t[this._renderer.uid],r=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!n)&&(n&&r.reset(),r.isBatchable=!1,e.dirty=!1),r}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){let t=new hE,n=this.getGpuContext(e);return n.graphicsData=t,t.init(),t}_initContext(e){let t=new mE;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}},gE.extension={type:[I.CanvasSystem],name:`graphicsContext`},gE.defaultOptions={bezierSmoothness:.5},_E=gE})),yE,bE=s((()=>{R(),hf(),cv(),yE=class{constructor(e,t){this.state=mf.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new sv({renderer:e,type:`renderable`,priority:-1,name:`graphics`})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}},yE.extension={type:[I.CanvasPipes],name:`graphics`}})),xE,SE,CE=s((()=>{R(),hf(),cv(),ha(),k_(),LC(),xE=class{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{ma.return(e)}),this.batches.length=0}},SE=class{constructor(e,t){this.state=mf.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new sv({renderer:e,type:`renderable`,priority:-1,name:`graphics`})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){let t=e.context,n=!!e._gpuData,r=this.renderer.graphicsContext.updateGpuContext(t);return!!(r.isBatchable||n!==r.isBatchable)}addRenderable(e,t){let n=this.renderer.graphicsContext.updateGpuContext(e.context);(e.didViewUpdate||!e._gpuData[this.renderer.uid])&&this._rebuild(e),n.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){let t=this._getGpuDataForRenderable(e).batches;for(let e=0;e<t.length;e++){let n=t[e];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;let t=this.renderer,n=e.context;if(!t.graphicsContext.getGpuContext(n).batches.length)return;let r=n.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;let i=r.resources.localUniforms.uniforms;i.uTransformMatrix=e.groupTransform,i.uRound=t._roundPixels|e._roundPixels,O_(e.groupColorAlpha,i.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){let t=this._getGpuDataForRenderable(e),n=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),n.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){let n=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let e=0;e<r.length;e++){let i=r[e];n.addToBatch(i,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){let t=new xE;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){let n=e.context,r=this.renderer.graphicsContext.getGpuContext(n),i=this.renderer._roundPixels|e._roundPixels;t.batches=r.batches.map(t=>{let n=ma.get(IC);return t.copyTo(n),n.renderable=e,n.roundPixels=i,n})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}},SE.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`graphics`}})),wE=s((()=>{R(),vE(),bE(),Uw(),CE(),L.add(yE),L.add(SE),L.add(_E),L.add(Hw)})),Z,TE=s((()=>{oa(),yc(),pE(),wE(),Z=class e extends vc{constructor(e){e instanceof fE&&(e={context:e});let{context:t,roundPixels:n,...r}=e||{};super({label:`Graphics`,...r}),this.renderPipeId=`graphics`,t?this.context=t:(this.context=this._ownedContext=new fE,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=n??!1}set context(e){e!==this._context&&(this._context&&(this._context.off(`update`,this.onViewUpdate,this),this._context.off(`unload`,this.unload,this)),this._context=e,this._context.on(`update`,this.onViewUpdate,this),this._context.on(`unload`,this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||e?.context===!0)&&this._context.destroy(e),this._context?.off(`update`,this.onViewUpdate,this),this._context?.off(`unload`,this.unload,this),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod(`setFillStyle`,e)}setStrokeStyle(...e){return this._callContextMethod(`setStrokeStyle`,e)}fill(...e){return this._callContextMethod(`fill`,e)}stroke(...e){return this._callContextMethod(`stroke`,e)}texture(...e){return this._callContextMethod(`texture`,e)}beginPath(){return this._callContextMethod(`beginPath`,[])}cut(){return this._callContextMethod(`cut`,[])}arc(...e){return this._callContextMethod(`arc`,e)}arcTo(...e){return this._callContextMethod(`arcTo`,e)}arcToSvg(...e){return this._callContextMethod(`arcToSvg`,e)}bezierCurveTo(...e){return this._callContextMethod(`bezierCurveTo`,e)}closePath(){return this._callContextMethod(`closePath`,[])}ellipse(...e){return this._callContextMethod(`ellipse`,e)}circle(...e){return this._callContextMethod(`circle`,e)}path(...e){return this._callContextMethod(`path`,e)}lineTo(...e){return this._callContextMethod(`lineTo`,e)}moveTo(...e){return this._callContextMethod(`moveTo`,e)}quadraticCurveTo(...e){return this._callContextMethod(`quadraticCurveTo`,e)}rect(...e){return this._callContextMethod(`rect`,e)}roundRect(...e){return this._callContextMethod(`roundRect`,e)}poly(...e){return this._callContextMethod(`poly`,e)}regularPoly(...e){return this._callContextMethod(`regularPoly`,e)}roundPoly(...e){return this._callContextMethod(`roundPoly`,e)}roundShape(...e){return this._callContextMethod(`roundShape`,e)}filletRect(...e){return this._callContextMethod(`filletRect`,e)}chamferRect(...e){return this._callContextMethod(`chamferRect`,e)}star(...e){return this._callContextMethod(`star`,e)}svg(...e){return this._callContextMethod(`svg`,e)}restore(...e){return this._callContextMethod(`restore`,e)}save(){return this._callContextMethod(`save`,[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod(`resetTransform`,[])}rotateTransform(...e){return this._callContextMethod(`rotate`,e)}scaleTransform(...e){return this._callContextMethod(`scale`,e)}setTransform(...e){return this._callContextMethod(`setTransform`,e)}transform(...e){return this._callContextMethod(`transform`,e)}translateTransform(...e){return this._callContextMethod(`translate`,e)}clear(){return this._callContextMethod(`clear`,[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(t=!1){return t?new e(this._context.clone()):(this._ownedContext=null,new e(this._context))}lineStyle(e,t,n){H(V,`Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.`);let r={};return e&&(r.width=e),t&&(r.color=t),n&&(r.alpha=n),this.context.strokeStyle=r,this}beginFill(e,t){H(V,`Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.`);let n={};return e!==void 0&&(n.color=e),t!==void 0&&(n.alpha=t),this.context.fillStyle=n,this}endFill(){H(V,`Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.`),this.context.fill();let e=this.context.strokeStyle;return(e.width!==fE.defaultStrokeStyle.width||e.color!==fE.defaultStrokeStyle.color||e.alpha!==fE.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return H(V,`Graphics#drawCircle has been renamed to Graphics#circle`),this._callContextMethod(`circle`,e)}drawEllipse(...e){return H(V,`Graphics#drawEllipse has been renamed to Graphics#ellipse`),this._callContextMethod(`ellipse`,e)}drawPolygon(...e){return H(V,`Graphics#drawPolygon has been renamed to Graphics#poly`),this._callContextMethod(`poly`,e)}drawRect(...e){return H(V,`Graphics#drawRect has been renamed to Graphics#rect`),this._callContextMethod(`rect`,e)}drawRoundedRect(...e){return H(V,`Graphics#drawRoundedRect has been renamed to Graphics#roundRect`),this._callContextMethod(`roundRect`,e)}drawStar(...e){return H(V,`Graphics#drawStar has been renamed to Graphics#star`),this._callContextMethod(`star`,e)}}}));function EE(e,t,n,r,i,a){a=Math.max(0,Math.min(a,Math.min(r,i)/2)),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n)}function DE(e,t){switch(t.type){case`rectangle`:{let n=t;e.rect(n.x,n.y,n.width,n.height);break}case`roundedRectangle`:{let n=t;EE(e,n.x,n.y,n.width,n.height,n.radius);break}case`circle`:{let n=t;e.moveTo(n.x+n.radius,n.y),e.arc(n.x,n.y,n.radius,0,Math.PI*2);break}case`ellipse`:{let n=t;e.ellipse?(e.moveTo(n.x+n.halfWidth,n.y),e.ellipse(n.x,n.y,n.halfWidth,n.halfHeight,0,0,Math.PI*2)):(e.save(),e.translate(n.x,n.y),e.scale(n.halfWidth,n.halfHeight),e.moveTo(1,0),e.arc(0,0,1,0,Math.PI*2),e.restore());break}case`triangle`:{let n=t;e.moveTo(n.x,n.y),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3),e.closePath();break}default:{let n=t,r=n.points;if(!r?.length)break;e.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)e.lineTo(r[t],r[t+1]);n.closePath&&e.closePath();break}}}function OE(e,t,n){let r=[],i=[],a=[];if(!cw[t.type]?.build(t,r))return!1;_C(r,n,!1,t.closePath??!0,i,a);for(let t=0;t<a.length;t+=3){let n=a[t]*2,r=a[t+1]*2,o=a[t+2]*2;e.moveTo(i[n],i[n+1]),e.lineTo(i[r],i[r+1]),e.lineTo(i[o],i[o+1]),e.closePath()}return!0}function kE(e,t){if(!t?.length)return!1;for(let n=0;n<t.length;n++){let r=t[n];if(!r?.shape)continue;let i=r.transform,a=i&&!i.isIdentity();a&&(e.save(),e.transform(i.a,i.b,i.c,i.d,i.tx,i.ty)),DE(e,r.shape),a&&e.restore()}return!0}var AE,jE=s((()=>{R(),vC(),TE(),dw(),W(),AE=class{constructor(e){this._warnedMaskTypes=new Set,this._canvasMaskStack=[],this._renderer=e}push(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`pushMaskBegin`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,n){this._renderer.renderPipes.batch.break(n),n.add({renderPipeId:`stencilMask`,action:`popMaskEnd`,mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){if(e.action!==`pushMaskBegin`&&e.action!==`popMaskEnd`)return;let t=this._renderer,n=t.canvasContext,r=n?.activeContext;if(!r)return;if(e.action===`popMaskEnd`){this._canvasMaskStack.pop()&&r.restore();return}e.inverse&&this._warnOnce(`inverse`,`CanvasRenderer: inverse masks are not supported on Canvas2D; ignoring inverse flag.`);let i=e.mask.mask;if(!(i instanceof Z)){this._warnOnce(`nonGraphics`,`CanvasRenderer: only Graphics masks are supported in Canvas2D; skipping mask.`),this._canvasMaskStack.push(!1);return}let a=i,o=a.context?.instructions;if(!o?.length){this._canvasMaskStack.push(!1);return}r.save(),n.setContextTransform(a.groupTransform,(t._roundPixels|a._roundPixels)===1),r.beginPath();let s=!1,c=!1;for(let e=0;e<o.length;e++){let t=o[e],n=t.action;if(n!==`fill`&&n!==`stroke`)continue;let i=t.data,a=i?.path?.shapePath;if(!a?.shapePrimitives?.length)continue;let l=n===`stroke`,u=a.shapePrimitives;for(let e=0;e<u.length;e++){let t=u[e];if(!t?.shape)continue;let n=t.transform,a=n&&!n.isIdentity();a&&(r.save(),r.transform(n.a,n.b,n.c,n.d,n.tx,n.ty)),l&&i.style?s=OE(r,t.shape,i.style)||s:(DE(r,t.shape),c=kE(r,t.holes)||c,s=!0),a&&r.restore()}}s?(c?r.clip(`evenodd`):r.clip(),this._canvasMaskStack.push(!0)):(r.restore(),this._canvasMaskStack.push(!1))}destroy(){this._renderer=null,this._warnedMaskTypes=null,this._canvasMaskStack=null}_warnOnce(e,t){this._warnedMaskTypes.has(e)||(this._warnedMaskTypes.add(e),U(t))}},AE.extension={type:[I.CanvasPipes],name:`stencilMask`}}));function ME(){let e=iu(),t=Object.create(null);return t.inherit=NE,t.none=NE,t.normal=`source-over`,t.add=`lighter`,t.multiply=e?`multiply`:NE,t.screen=e?`screen`:NE,t.overlay=e?`overlay`:NE,t.darken=e?`darken`:NE,t.lighten=e?`lighten`:NE,t[`color-dodge`]=e?`color-dodge`:NE,t[`color-burn`]=e?`color-burn`:NE,t[`hard-light`]=e?`hard-light`:NE,t[`soft-light`]=e?`soft-light`:NE,t.difference=e?`difference`:NE,t.exclusion=e?`exclusion`:NE,t.saturation=e?`saturation`:NE,t.color=e?`color`:NE,t.luminosity=e?`luminosity`:NE,t[`linear-burn`]=e?`color-burn`:NE,t[`linear-dodge`]=e?`color-dodge`:NE,t[`linear-light`]=e?`hard-light`:NE,t[`pin-light`]=e?`hard-light`:NE,t[`vivid-light`]=e?`hard-light`:NE,t[`hard-mix`]=NE,t.negation=e?`difference`:NE,t[`normal-npm`]=t.normal,t[`add-npm`]=t.add,t[`screen-npm`]=t.screen,t.erase=`destination-out`,t.subtract=NE,t.divide=NE,t.min=NE,t.max=NE,t}var NE,PE=s((()=>{ou(),NE=`source-over`})),FE,IE,LE=s((()=>{Ri(),R(),B(),PE(),FE=new z,IE=class{constructor(e){this.activeResolution=1,this.smoothProperty=`imageSmoothingEnabled`,this.blendModes=ME(),this._activeBlendMode=`normal`,this._projTransform=null,this._outerBlend=!1,this._warnedBlendModes=new Set,this._renderer=e}resolutionChange(e){this.activeResolution=e}init(){let e=this._renderer.background.alpha<1;if(this.rootContext=this._renderer.canvas.getContext(`2d`,{alpha:e}),this.activeContext=this.rootContext,this.activeResolution=this._renderer.resolution,!this.rootContext.imageSmoothingEnabled){let e=this.rootContext;e.webkitImageSmoothingEnabled?this.smoothProperty=`webkitImageSmoothingEnabled`:e.mozImageSmoothingEnabled?this.smoothProperty=`mozImageSmoothingEnabled`:e.oImageSmoothingEnabled?this.smoothProperty=`oImageSmoothingEnabled`:e.msImageSmoothingEnabled&&(this.smoothProperty=`msImageSmoothingEnabled`)}}setContextTransform(e,t,n,r){let i=r?z.IDENTITY:this._renderer.globalUniforms.globalUniformData?.worldTransformMatrix||z.IDENTITY,a=FE;a.copyFrom(i),a.append(e);let o=this._projTransform,s=this.activeResolution;if(n||=s,o){let e=z.shared;e.copyFrom(a),e.prepend(o),a=e}t?this.activeContext.setTransform(a.a*n,a.b*n,a.c*n,a.d*n,a.tx*s|0,a.ty*s|0):this.activeContext.setTransform(a.a*n,a.b*n,a.c*n,a.d*n,a.tx*s,a.ty*s)}clear(e,t){let n=this.activeContext,r=this._renderer;if(n.clearRect(0,0,r.width,r.height),e){let i=Li.shared.setValue(e);n.globalAlpha=t??i.alpha,n.fillStyle=i.toHex(),n.fillRect(0,0,r.width,r.height),n.globalAlpha=1}}setBlendMode(e){if(this._activeBlendMode===e)return;this._activeBlendMode=e,this._outerBlend=!1;let t=this.blendModes[e];t?this.activeContext.globalCompositeOperation=t:(this._warnedBlendModes.has(e)||(console.warn(`CanvasRenderer: blend mode "${e}" is not supported in Canvas2D; falling back to "source-over".`),this._warnedBlendModes.add(e)),this.activeContext.globalCompositeOperation=`source-over`)}destroy(){this.rootContext=null,this.activeContext=null,this._warnedBlendModes.clear()}},IE.extension={type:[I.CanvasSystem],name:`canvasContext`}})),RE,zE=s((()=>{R(),RE=class{constructor(){this.maxTextures=16,this.maxBatchableTextures=16,this.maxUniformBindings=0}init(){}},RE.extension={type:[I.CanvasSystem],name:`limits`}})),BE,VE=s((()=>{Ri(),Jc(),W(),zl(),BE=class{init(e,t){this._renderer=e,this._renderTargetSystem=t}initGpuRenderTarget(e){let t=e.colorTexture,{canvas:n,context:r}=this._ensureCanvas(t);return{canvas:n,context:r,width:n.width,height:n.height}}resizeGpuRenderTarget(e){let t=e.colorTexture,{canvas:n}=this._ensureCanvas(t);n.width=e.pixelWidth,n.height=e.pixelHeight}startRenderPass(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e);this._renderer.canvasContext.activeContext=i.context,this._renderer.canvasContext.activeResolution=e.resolution,t&&this.clear(e,t,n,r)}clear(e,t,n,r){let i=this._renderTargetSystem.getGpuRenderTarget(e).context,a=r||{x:0,y:0,width:e.pixelWidth,height:e.pixelHeight};if(i.setTransform(1,0,0,1,0,0),i.clearRect(a.x,a.y,a.width,a.height),n){let e=Li.shared.setValue(n);e.alpha>0&&(i.globalAlpha=e.alpha,i.fillStyle=e.toHex(),i.fillRect(a.x,a.y,a.width,a.height),i.globalAlpha=1)}}finishRenderPass(){}copyToTexture(e,t,n,r,i){let a=this._renderTargetSystem.getGpuRenderTarget(e).canvas,o=t.source,{context:s}=this._ensureCanvas(o),c=i?.x??0,l=i?.y??0;return s.drawImage(a,n.x,n.y,r.width,r.height,c,l,r.width,r.height),o.update(),t}copyDepthTexture(e,t,n,r,i){U(`[CanvasRenderTargetAdaptor] copyDepthTexture is not supported in the canvas renderer`)}destroyGpuRenderTarget(e){}_ensureCanvas(e){let t=e.resource;(!t||!Rl.test(t))&&(t=Y.get().createCanvas(e.pixelWidth,e.pixelHeight),e.resource=t),(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(t.width=e.pixelWidth,t.height=e.pixelHeight);let n=t.getContext(`2d`);return{canvas:t,context:n}}}})),HE,UE=s((()=>{R(),by(),VE(),HE=class extends yy{constructor(e){super(e),this.adaptor=new BE,this.adaptor.init(e,this)}},HE.extension={type:[I.CanvasSystem],name:`renderTarget`}})),WE,GE=s((()=>{Jc(),R(),su(),WE=class{constructor(e){}init(){}initSource(e){}generateCanvas(e){let t=Y.get().createCanvas(),n=t.getContext(`2d`),r=X.getCanvasSource(e);if(!r)return t;let i=e.frame,a=e.source._resolution??e.source.resolution??1,o=i.x*a,s=i.y*a,c=i.width*a,l=i.height*a;return t.width=Math.ceil(c),t.height=Math.ceil(l),n.drawImage(r,o,s,c,l,0,0,c,l),t}getPixels(e){let t=this.generateCanvas(e);return{pixels:t.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,t.width,t.height).data,width:t.width,height:t.height}}destroy(){}},WE.extension={type:[I.CanvasSystem],name:`texture`}})),KE=l({CanvasRenderer:()=>eD}),qE,JE,YE,XE,ZE,QE,$E,eD,tD=s((()=>{R(),Eh(),Mh(),Tw(),Jh(),Ow(),Hg(),e_(),Aw(),jE(),u_(),sm(),rv(),Gd(),LE(),zE(),UE(),GE(),qE=[...tv,IE,RE,WE,HE],JE=[l_,Vg,qh,jh,$g,AE,kw,Th],YE=[Dw,ww],XE=[],ZE=[],QE=[],$E=[],L.handleByNamedList(I.CanvasSystem,XE),L.handleByNamedList(I.CanvasPipes,ZE),L.handleByNamedList(I.CanvasPipesAdaptor,QE),L.handleByNamedList(I.CanvasLoader,$E),L.add(...qE,...JE,...YE),eD=class extends om{constructor(){let e={name:`canvas`,type:Wd.CANVAS,systems:XE,renderPipes:ZE,renderPipeAdaptors:QE,loaders:$E};super(e)}}}));sm();var nD=[`webgl`,`webgpu`,`canvas`];async function rD(e){let t=[];e.preference?Array.isArray(e.preference)?t=e.preference.slice():(t.push(e.preference),nD.forEach(n=>{n!==e.preference&&t.push(n)})):t=nD.slice();let n,r={};for(let i=0;i<t.length;i++){let a=t[i];if(a===`webgpu`&&await dm()){let{WebGPURenderer:t}=await Promise.resolve().then(()=>(Sb(),pb));n=t,r={...e,...e.webgpu};break}if(a===`webgl`&&lm(e.failIfMajorPerformanceCaveat??om.defaultOptions.failIfMajorPerformanceCaveat)){let{WebGLRenderer:t}=await Promise.resolve().then(()=>(dC(),nC));n=t,r={...e,...e.webgl};break}if(a===`canvas`){let{CanvasRenderer:t}=await Promise.resolve().then(()=>(tD(),KE));n=t,r={...e,...e.canvasOptions};break}}if(delete r.webgpu,delete r.webgl,delete r.canvasOptions,!n)throw Error(`No available renderer for the current environment`);let i=new n;return await i.init(r),i}R();var iD=class{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener(`resize`,this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener(`resize`,this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&=(cancelAnimationFrame(this._resizeId),null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,t;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,t=globalThis.innerHeight;else{let{clientWidth:n,clientHeight:r}=this._resizeTo;e=n,t=r}this.renderer.resize(e,t),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener(`resize`,this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}};iD.extension=I.Application,R(),Cs(),Os();var aD=class{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,Ss.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?Ds.shared:new Ds,e.autoStart&&this.start()}static destroy(){if(this._ticker){let e=this._ticker;this.ticker=null,e.destroy()}}};aD.extension=I.Application,R(),L.add(iD),L.add(aD),R(),xs(),$h(),oa();var oD=class e{constructor(...e){this.stage=new J,e[0]!==void 0&&H(V,`Application constructor options are deprecated, please use Application.init() instead.`)}async init(t){t={...t},this.stage||=new J,this.renderer=await rD(t),e._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return H(V,`Application.view is deprecated, please use Application.canvas instead.`),this.renderer.canvas}get screen(){return this.renderer.screen}get domContainerRoot(){return this.renderer.renderPipes.dom?._domElement}destroy(t=!1,n=!1){let r=e._plugins.slice(0);r.reverse(),r.forEach(e=>{e.destroy.call(this)}),this.stage.destroy(n),this.stage=null,this.renderer.destroy(t),this.renderer=null}};oD._plugins=[];var sD=oD;L.handleByList(I.Application,sD._plugins),L.add(Zh);var cD={test(e){return typeof e==`string`&&e.startsWith(`info face=`)},parse(e){let t=e.match(/^[a-z]+\s+.+$/gm),n={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(let e in t){let r=t[e].match(/^[a-z]+/gm)[0],i=t[e].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),a={};for(let e in i){let t=i[e].split(`=`),n=t[0],r=t[1].replace(/"/gm,``),o=parseFloat(r);a[n]=isNaN(o)?r:o}n[r].push(a)}let r={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:``,distanceField:null,baseLineOffset:0},[i]=n.info,[a]=n.common,[o]=n.distanceField??[];o&&(r.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),r.fontSize=parseInt(i.size,10),r.fontFamily=i.face,r.lineHeight=parseInt(a.lineHeight,10);let s=n.page;for(let e=0;e<s.length;e++)r.pages.push({id:parseInt(s[e].id,10)||0,file:s[e].file});let c={};r.baseLineOffset=a.base===void 0?0:r.lineHeight-parseInt(a.base,10);let l=n.char;for(let e=0;e<l.length;e++){let t=l[e],n=parseInt(t.id,10),i=t.letter??t.char??String.fromCharCode(n);i===`space`&&(i=` `),c[n]=i,r.chars[i]={id:n,page:parseInt(t.page,10)||0,x:parseInt(t.x,10),y:parseInt(t.y,10),width:parseInt(t.width,10),height:parseInt(t.height,10),xOffset:parseInt(t.xoffset,10),yOffset:parseInt(t.yoffset,10),xAdvance:parseInt(t.xadvance,10),kerning:{}}}let u=n.kerning||[];for(let e=0;e<u.length;e++){let t=parseInt(u[e].first,10),n=parseInt(u[e].second,10),i=parseInt(u[e].amount,10);r.chars[c[n]]&&(r.chars[c[n]].kerning[c[t]]=i)}return r}},lD={test(e){let t=e;return typeof t!=`string`&&`getElementsByTagName`in t&&t.getElementsByTagName(`page`).length&&t.getElementsByTagName(`info`)[0].getAttribute(`face`)!==null},parse(e){let t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:``,distanceField:null,baseLineOffset:0},n=e.getElementsByTagName(`info`)[0],r=e.getElementsByTagName(`common`)[0],i=e.getElementsByTagName(`distanceField`)[0];i&&(t.distanceField={type:i.getAttribute(`fieldType`),range:parseInt(i.getAttribute(`distanceRange`),10)});let a=e.getElementsByTagName(`page`),o=e.getElementsByTagName(`char`),s=e.getElementsByTagName(`kerning`);t.fontSize=parseInt(n.getAttribute(`size`),10),t.fontFamily=n.getAttribute(`face`),t.lineHeight=parseInt(r.getAttribute(`lineHeight`),10);for(let e=0;e<a.length;e++)t.pages.push({id:parseInt(a[e].getAttribute(`id`),10)||0,file:a[e].getAttribute(`file`)});let c={},l=r.getAttribute(`base`);t.baseLineOffset=l===null?0:t.lineHeight-parseInt(l,10);for(let e=0;e<o.length;e++){let n=o[e],r=parseInt(n.getAttribute(`id`),10),i=n.getAttribute(`letter`)??n.getAttribute(`char`)??String.fromCharCode(r);i===`space`&&(i=` `),c[r]=i,t.chars[i]={id:r,page:parseInt(n.getAttribute(`page`),10)||0,x:parseInt(n.getAttribute(`x`),10),y:parseInt(n.getAttribute(`y`),10),width:parseInt(n.getAttribute(`width`),10),height:parseInt(n.getAttribute(`height`),10),xOffset:parseInt(n.getAttribute(`xoffset`),10),yOffset:parseInt(n.getAttribute(`yoffset`),10),xAdvance:parseInt(n.getAttribute(`xadvance`),10),kerning:{}}}for(let e=0;e<s.length;e++){let n=parseInt(s[e].getAttribute(`first`),10),r=parseInt(s[e].getAttribute(`second`),10),i=parseInt(s[e].getAttribute(`amount`),10);t.chars[c[r]]&&(t.chars[c[r]].kerning[c[n]]=i)}return t}};Jc();var uD={test(e){return typeof e==`string`&&e.match(/<font(\s|>)/)?lD.test(Y.get().parseXML(e)):!1},parse(e){return lD.parse(Y.get().parseXML(e))}},dD,fD=s((()=>{ri(),oa(),dD=class extends ni{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily=``,this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:`none`,range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return H(V,`BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead.`),this.fontFamily}get pageTextures(){return H(V,`BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead.`),this.pages}get size(){return H(V,`BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead.`),this.fontMetrics.fontSize}get distanceFieldRange(){return H(V,`BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead.`),this.distanceField.range}get distanceFieldType(){return H(V,`BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead.`),this.distanceField.type}destroy(e=!1){this.emit(`destroy`,this),this.removeAllListeners();for(let e in this.chars)this.chars[e].texture?.destroy();this.chars=null,e&&(this.pages.forEach(e=>e.texture.destroy(!0)),this.pages=null)}}}));function pD(e=1e3,t=0,n=!1){if(isNaN(e)||e<0)throw TypeError(`Invalid max value`);if(isNaN(t)||t<0)throw TypeError(`Invalid ttl value`);if(typeof n!=`boolean`)throw TypeError(`Invalid resetTtl value`);return new mD(e,t,n)}var mD,hD=s((()=>{mD=class{constructor(e=0,t=0,n=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=n,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){let t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){let t=Array(e.length);for(let n=0;n<e.length;n++){let r=e[n];t[n]=[r,this.get(r)]}return t}evict(e=!1){if(e||this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){let t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){let e=Array(this.size),t=this.first,n=0;for(;t!==null;)e[n++]=t.key,t=t.next;return e}setWithEvicted(e,t,n=this.resetTtl){let r=null;if(this.has(e))this.set(e,t,!0,n);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(e,t,n=!1,r=this.resetTtl){let i=this.items[e];return n||i!==void 0?(i.value=t,n===!1&&r&&(i.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(i)):(this.max>0&&this.size===this.max&&this.evict(!0),i=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=i:this.last.next=i,this.last=i),this}values(e=this.keys()){let t=Array(e.length);for(let n=0;n<e.length;n++)t[n]=this.get(e[n]);return t}}}));function gD(e){return!!e.tagStyles&&Object.keys(e.tagStyles).length>0}function _D(e){return e.includes(`<`)}function vD(e,t){return e.clone().assign(t)}function yD(e,t){let n=[],r=t.tagStyles;if(!gD(t)||!_D(e))return n.push({text:e,style:t}),n;let i=[t],a=[],o=``,s=0;for(;s<e.length;){let t=e[s];if(t===`<`){let c=e.indexOf(`>`,s);if(c===-1){o+=t,s++;continue}let l=e.indexOf(`<`,s+1);if(l!==-1&&l<c){o+=t,s++;continue}let u=e.slice(s+1,c);if(u.startsWith(`/`)){let t=u.slice(1).trim();if(a.length>0&&a[a.length-1]===t){o.length>0&&(n.push({text:o,style:i[i.length-1]}),o=``),i.pop(),a.pop(),s=c+1;continue}o+=e.slice(s,c+1),s=c+1;continue}{let t=u.trim();if(r[t]){o.length>0&&(n.push({text:o,style:i[i.length-1]}),o=``);let e=i[i.length-1],l=vD(e,r[t]);i.push(l),a.push(t),s=c+1;continue}o+=e.slice(s,c+1),s=c+1;continue}}o+=t,s++}return o.length>0&&n.push({text:o,style:i[i.length-1]}),n}var bD=s((()=>{}));function xD(e){return typeof e==`string`&&jD.has(e.charCodeAt(0))}function SD(e,t){return typeof e==`string`&&ND.has(e.charCodeAt(0))}function CD(e){return typeof e==`string`&&FD.has(e.charCodeAt(0))}function wD(e){return typeof e==`string`&&LD.has(e.charCodeAt(0))}function TD(e){return e===`normal`||e===`pre-line`}function ED(e){return e===`normal`}function DD(e){if(typeof e!=`string`)return``;let t=e.length-1;for(;t>=0&&SD(e[t]);)t--;return t<e.length-1?e.slice(0,t+1):e}function OD(e){let t=[],n=[];if(typeof e!=`string`)return t;for(let r=0;r<e.length;r++){let i=e[r],a=e[r+1];SD(i,a)||xD(i)?(n.length>0&&(t.push(n.join(``)),n.length=0),i===`\r`&&a===`
|
|
946
|
-
`?(t.push(`\r
|
|
947
|
-
`),r++):t.push(i)):(n.push(i),wD(i)&&a&&!SD(a)&&!xD(a)&&(t.push(n.join(``)),n.length=0))}return n.length>0&&t.push(n.join(``)),t}function kD(e,t,n,r){let i=n(e),a=[];for(let n=0;n<i.length;n++){let o=i[n],s=o,c=1;for(;i[n+c];){let a=i[n+c];if(!r(s,a,e,n,t))o+=a,s=a,c++;else break}n+=c-1,a.push(o)}return a}var AD,jD,MD,ND,PD,FD,ID,LD,RD,zD,BD=s((()=>{AD=[10,13],jD=new Set(AD),MD=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],ND=new Set(MD),PD=[9,32],FD=new Set(PD),ID=[45,8208,8211,8212,173],LD=new Set(ID),RD=/(\r\n|\r|\n)/,zD=/(?:\r\n|\r|\n)/}));function VD(e,t,n,r,i,a,o,s,c){let l=yD(e,t);if(ED(t.whiteSpace))for(let e=0;e<l.length;e++){let t=l[e];l[e]={text:t.text.replace(WD,` `),style:t.style}}let u=[],d=[];for(let e of l){let t=e.text.split(RD);for(let n=0;n<t.length;n++){let r=t[n];r===`\r
|
|
948
|
-
`||r===`\r`||r===`
|
|
949
|
-
`?(u.push(d),d=[]):r.length>0&&d.push({text:r,style:e.style})}}(d.length>0||u.length===0)&&u.push(d);let f=n?HD(u,t,r,a,s,c):u,p=[],m=[],h=[],g=[],_=[],v=0,y=t._fontString,b=o(y);b.fontSize===0&&(b.fontSize=t.fontSize,b.ascent=t.fontSize);let x=``,S=!!t.dropShadow,C=t._stroke?.width||0;for(let e of f){let n=0,a=b.ascent,s=b.descent,c=``;for(let t of e){let e=t.style._fontString,l=o(e);e!==x&&(r.font=e,x=e);let u=i(t.text,t.style.letterSpacing,r);n+=u,a=Math.max(a,l.ascent),s=Math.max(s,l.descent),c+=t.text;let d=t.style._stroke?.width||0;d>C&&(C=d),!S&&t.style.dropShadow&&(S=!0)}e.length===0&&(a=b.ascent,s=b.descent),p.push(n),m.push(a),h.push(s),_.push(c);let l=t.lineHeight||a+s;g.push(l+t.leading),v=Math.max(v,n)}let ee=C,w=v+ee+(t.dropShadow?t.dropShadow.distance:0),T=0;for(let e=0;e<g.length;e++)T+=g[e];return T=Math.max(T,g[0]+ee),{width:w,height:T+(t.dropShadow?t.dropShadow.distance:0),lines:_,lineWidths:p,lineHeight:(t.lineHeight||b.fontSize)+t.leading,maxLineWidth:v,fontProperties:b,runsByLine:f,lineAscents:m,lineDescents:h,lineHeights:g,hasDropShadow:S}}function HD(e,t,n,r,i,a){let{letterSpacing:o,whiteSpace:s,wordWrapWidth:c,breakWords:l}=t,u=TD(s),d=c+o,f={},p=``,m=(e,t)=>{let i=`${e}|${t.styleKey}`,a=f[i];if(a===void 0){let o=t._fontString;o!==p&&(n.font=o,p=o),a=r(e,t.letterSpacing,n)+t.letterSpacing,f[i]=a}return a},h=[];for(let t of e){let e=UD(t),n=h.length,r=t=>{let n=0,r=t;do{let{token:t,style:i}=e[r];n+=m(t,i),r++}while(r<e.length&&e[r].continuesFromPrevious);return n},o=t=>{let n=[],r=t;do n.push({token:e[r].token,style:e[r].style}),r++;while(r<e.length&&e[r].continuesFromPrevious);return n},s=[],c=0,f=!u,p=null,g=()=>{p&&p.text.length>0&&s.push(p),p=null},_=()=>{if(g(),s.length>0){let e=s[s.length-1];e.text=DD(e.text),e.text.length===0&&s.pop()}h.push(s),s=[],c=0,f=!1};for(let t=0;t<e.length;t++){let{token:n,style:v,continuesFromPrevious:y}=e[t],b=m(n,v);if(u){let e=SD(n),t=p?.text[p.text.length-1]??s[s.length-1]?.text.slice(-1)??``,r=t?SD(t):!1;if(e&&r)continue}let x=!y,S=x?r(t):b;if(S>d&&x){if(c>0&&_(),l){let e=o(t);for(let t=0;t<e.length;t++){let n=e[t].token,r=e[t].style,o=kD(n,l,a,i);for(let e of o){let t=m(e,r);t+c>d&&_(),!p||p.style!==r?(g(),p={text:e,style:r}):p.text+=e,c+=t}}t+=e.length-1}else{let e=o(t);g(),h.push(e.map(e=>({text:e.token,style:e.style}))),f=!1,t+=e.length-1}}else if(S+c>d&&x){if(SD(n)){f=!1;continue}_(),p={text:n,style:v},c=b}else if(y&&!l)!p||p.style!==v?(g(),p={text:n,style:v}):p.text+=n,c+=b;else{let e=SD(n);if(c===0&&e&&!f)continue;!p||p.style!==v?(g(),p={text:n,style:v}):p.text+=n,c+=b}}if(g(),s.length>0){let e=s[s.length-1];e.text=DD(e.text),e.text.length===0&&s.pop()}(s.length>0||h.length===n)&&h.push(s)}return h}function UD(e){let t=[],n=!1;for(let r of e){let e=OD(r.text),i=!0;for(let a of e){let e=SD(a)||xD(a),o=i&&n&&!e;t.push({token:a,style:r.style,continuesFromPrevious:o}),n=!e,i=!1}}return t}var WD,GD=s((()=>{bD(),BD(),WD=/\r\n|\r|\n/g}));function KD(e,t,n,r,i){let a=n[e];return typeof a!=`number`&&(a=i(e,t,r)+t,n[e]=a),a}function qD(e,t,n,r,i,a,o){let s=n.getContext(`2d`,JD);s.font=t._fontString;let c=0,l=``,u=[],d=Object.create(null),{letterSpacing:f,whiteSpace:p}=t,m=TD(p),h=ED(p),g=!m,_=t.wordWrapWidth+f,v=OD(e);for(let e=0;e<v.length;e++){let n=v[e];if(xD(n)){if(!h){u.push(DD(l)),g=!m,l=``,c=0;continue}n=` `}if(m){let e=SD(n),t=SD(l[l.length-1]);if(e&&t)continue}let p=KD(n,f,d,s,r);if(p>_){if(l!==``&&(u.push(DD(l)),l=``,c=0),i(n,t.breakWords)){let e=kD(n,t.breakWords,o,a);for(let t of e){let e=KD(t,f,d,s,r);e+c>_&&(u.push(DD(l)),g=!1,l=``,c=0),l+=t,c+=e}}else l.length>0&&(u.push(DD(l)),l=``,c=0),u.push(DD(n)),g=!1,l=``,c=0}else p+c>_&&(g=!1,u.push(DD(l)),l=``,c=0),(l.length>0||!SD(n)||g)&&(l+=n,c+=p)}let y=DD(l);return y.length>0&&u.push(y),u.join(`
|
|
950
|
-
`)}var JD,YD=s((()=>{BD(),JD={willReadFrequently:!0}})),XD,ZD,QD,$D=s((()=>{hD(),Jc(),GD(),bD(),BD(),YD(),XD={willReadFrequently:!0},ZD=class e{static get experimentalLetterSpacingSupported(){let t=e._experimentalLetterSpacingSupported;if(t===void 0){let n=Y.get().getCanvasRenderingContext2D().prototype;t=e._experimentalLetterSpacingSupported=`letterSpacing`in n||`textLetterSpacing`in n}return t}constructor(e,t,n,r,i,a,o,s,c,l){this.text=e,this.style=t,this.width=n,this.height=r,this.lines=i,this.lineWidths=a,this.lineHeight=o,this.maxLineWidth=s,this.fontProperties=c,l&&(this.runsByLine=l.runsByLine,this.lineAscents=l.lineAscents,this.lineDescents=l.lineDescents,this.lineHeights=l.lineHeights,this.hasDropShadow=l.hasDropShadow)}static measureText(t=` `,n,r=e._canvas,i=n.wordWrap){let a=`${t}-${n.styleKey}-wordWrap-${i}`;if(e._measurementCache.has(a))return e._measurementCache.get(a);if(gD(n)&&_D(t)){let r=VD(t,n,i,e._context,e._measureText,e._measureTextAdvance,e.measureFont,e.canBreakChars,e.wordWrapSplit),o=new e(t,n,r.width,r.height,r.lines,r.lineWidths,r.lineHeight,r.maxLineWidth,r.fontProperties,{runsByLine:r.runsByLine,lineAscents:r.lineAscents,lineDescents:r.lineDescents,lineHeights:r.lineHeights,hasDropShadow:r.hasDropShadow});return e._measurementCache.set(a,o),o}let o=n._fontString,s=e.measureFont(o);s.fontSize===0&&(s.fontSize=n.fontSize,s.ascent=n.fontSize,s.descent=0);let c=e._context;c.font=o;let l=(i?e._wordWrap(t,n,r):t).split(zD),u=Array(l.length),d=0;for(let t=0;t<l.length;t++){let r=e._measureText(l[t],n.letterSpacing,c);u[t]=r,d=Math.max(d,r)}let f=n._stroke?.width??0,p=n.lineHeight||s.fontSize,m=e._adjustWidthForStyle(d,n),h=Math.max(p,s.fontSize+f)+(l.length-1)*(p+n.leading),g=e._adjustHeightForStyle(h,n),_=new e(t,n,m,g,l,u,p+n.leading,d,s);return e._measurementCache.set(a,_),_}static _adjustWidthForStyle(e,t){let n=e+(t._stroke?.width||0);return t.dropShadow&&(n+=t.dropShadow.distance),n}static _adjustHeightForStyle(e,t){let n=e;return t.dropShadow&&(n+=t.dropShadow.distance),n}static _measureText(t,n,r){let{metricWidth:i,metrics:a,letterSpacingVal:o}=e._measureTextCore(t,n,r),s=-(a.actualBoundingBoxLeft??0),c=(a.actualBoundingBoxRight??0)-s;return a.width>0&&(c+=o),Math.max(i,c)}static _measureTextAdvance(t,n,r){return e._measureTextCore(t,n,r).metricWidth}static _measureTextCore(t,n,r){let i=!1;e.experimentalLetterSpacingSupported&&(e.experimentalLetterSpacing?(r.letterSpacing=`${n}px`,r.textLetterSpacing=`${n}px`,i=!0):(r.letterSpacing=`0px`,r.textLetterSpacing=`0px`));let a=r.measureText(t),o=a.width,s=0;return o>0&&(s=i?-n:(e.graphemeSegmenter(t).length-1)*n,o+=s),{metricWidth:o,metrics:a,letterSpacingVal:s}}static _wordWrap(t,n,r=e._canvas){return qD(t,n,r,e._measureTextAdvance,e.canBreakWords,e.canBreakChars,e.wordWrapSplit)}static isBreakingSpace(e,t){return SD(e,t)}static canBreakWords(e,t){return t}static canBreakChars(e,t,n,r,i){return!0}static wordWrapSplit(t){return e.graphemeSegmenter(t)}static measureFont(t){if(e._fonts[t])return e._fonts[t];let n=e._context;n.font=t;let r=n.measureText(e.METRICS_STRING+e.BASELINE_SYMBOL),i=r.actualBoundingBoxAscent??0,a=r.actualBoundingBoxDescent??0,o={ascent:i,descent:a,fontSize:i+a};return e._fonts[t]=o,o}static clearMetrics(t=``){t?delete e._fonts[t]:e._fonts={}}static get _canvas(){if(!e.__canvas){let t;try{let n=new OffscreenCanvas(0,0);if(n.getContext(`2d`,XD)?.measureText)return e.__canvas=n,n;t=Y.get().createCanvas()}catch{t=Y.get().createCanvas()}t.width=t.height=10,e.__canvas=t}return e.__canvas}static get _context(){return e.__context||=e._canvas.getContext(`2d`,XD),e.__context}},ZD.METRICS_STRING=`|ÉqÅ`,ZD.BASELINE_SYMBOL=`M`,ZD.BASELINE_MULTIPLIER=1.4,ZD.HEIGHT_MULTIPLIER=2,ZD.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter==`function`){let e=new Intl.Segmenter;return t=>{let n=e.segment(t),r=[],i=0;for(let e of n)r[i++]=e.segment;return r}}return e=>[...e]})(),ZD.experimentalLetterSpacing=!1,ZD._fonts={},ZD._measurementCache=pD(1e3),QD=ZD}));function eO(e){let t=typeof e.fontSize==`number`?`${e.fontSize}px`:e.fontSize,n=e.fontFamily;Array.isArray(e.fontFamily)||(n=e.fontFamily.split(`,`));for(let e=n.length-1;e>=0;e--){let t=n[e].trim();!/([\"\'])[^\'\"]+\1/.test(t)&&!tO.includes(t)&&(t=`"${t}"`),n[e]=t}return`${e.fontStyle} ${e.fontVariant} ${e.fontWeight} ${t} ${n.join(`,`)}`}var tO,nO=s((()=>{tO=[`serif`,`sans-serif`,`monospace`,`cursive`,`fantasy`,`system-ui`]}));function rO(e){let t=e;if(typeof t.dropShadow==`boolean`&&t.dropShadow){let n=aO.defaultDropShadow;e.dropShadow={alpha:t.dropShadowAlpha??n.alpha,angle:t.dropShadowAngle??n.angle,blur:t.dropShadowBlur??n.blur,color:t.dropShadowColor??n.color,distance:t.dropShadowDistance??n.distance}}if(t.strokeThickness!==void 0){H(V,`strokeThickness is now a part of stroke`);let n=t.stroke,r={};if(Li.isColorLike(n))r.color=n;else if(n instanceof wC||n instanceof OC)r.fill=n;else if(Object.hasOwnProperty.call(n,`color`)||Object.hasOwnProperty.call(n,`fill`))r=n;else throw Error(`Invalid stroke value.`);e.stroke={...r,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(H(V,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(t.fill)||t.fill.length===0)throw Error(`Invalid fill value. Expected an array of colors for gradient fill.`);t.fill.length!==t.fillGradientStops.length&&U(`The number of fill colors must match the number of fill gradient stops.`);let n=new wC({start:{x:0,y:0},end:{x:0,y:1},textureSpace:`local`}),r=t.fillGradientStops.slice(),i=t.fill.map(e=>Li.shared.setValue(e).toNumber());r.forEach((e,t)=>{n.addColorStop(e,i[t])}),e.fill={fill:n}}}var iO,aO,oO=s((()=>{ri(),Ri(),ea(),oa(),W(),TC(),kC(),pE(),oE(),nO(),iO=class e extends ni{constructor(t={}){super(),this.uid=Qi(`textStyle`),this._tick=0,this._cachedFontString=null,rO(t),t instanceof e&&(t=t._toObject());let n={...e.defaultTextStyle,...t};for(let e in n){let t=e;this[t]=n[e]}this._tagStyles=t.tagStyles??void 0,this.update(),this._tick=0}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this.update())}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords!==e&&(this._breakWords=e,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(this._dropShadow=typeof t==`object`&&t?this._createProxy({...e.defaultDropShadow,...t}):t?this._createProxy({...e.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.update())}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(this._fontSize=typeof e==`string`?parseInt(e,10):e,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant!==e&&(this._fontVariant=e,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.update())}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this.update())}get padding(){return this._padding}set padding(e){this._padding!==e&&(this._padding=e,this.update())}get filters(){return this._filters}set filters(e){this._filters!==e&&(this._filters=Object.freeze(e),this.update())}get trim(){return this._trim}set trim(e){this._trim!==e&&(this._trim=e,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline!==e&&(this._textBaseline=e,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace!==e&&(this._whiteSpace=e,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap!==e&&(this._wordWrap=e,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth!==e&&(this._wordWrapWidth=e,this.update())}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...fE.defaultFillStyle,...e},()=>{this._fill=iE({...this._originalFill},fE.defaultFillStyle)})),this._fill=iE(e===0?`black`:e,fE.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...fE.defaultStrokeStyle,...e},()=>{this._stroke=aE({...this._originalStroke},fE.defaultStrokeStyle)})),this._stroke=aE(e,fE.defaultStrokeStyle),this.update())}get tagStyles(){return this._tagStyles}set tagStyles(e){this._tagStyles!==e&&(this._tagStyles=e??void 0,this.update())}update(){this._tick++,this._cachedFontString=null,this.emit(`update`,this)}reset(){let t=e.defaultTextStyle;for(let e in t)this[e]=t[e]}assign(e){for(let t in e){let n=t;this[n]=e[t]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=eO(this)),this._cachedFontString}_toObject(){return{align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill?{...this._fill}:void 0,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke?{...this._stroke}:void 0,textBaseline:this.textBaseline,trim:this.trim,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0,tagStyles:this._tagStyles?{...this._tagStyles}:void 0}}clone(){return new e(this._toObject())}_getFinalPadding(){let e=0;if(this._filters)for(let t=0;t<this._filters.length;t++)e+=this._filters[t].padding;return Math.max(this._padding,e)}destroy(e=!1){if(this.removeAllListeners(),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(t),this._originalFill?.texture&&this._originalFill.texture.destroy(t),this._stroke?.texture&&this._stroke.texture.destroy(t),this._originalStroke?.texture&&this._originalStroke.texture.destroy(t)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(e,n,r)=>(e[n]===r||(e[n]=r,t?.(n,r),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(Li.isColorLike(e)||e instanceof wC||e instanceof OC)}},iO.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:`black`,distance:5},iO.defaultTextStyle={align:`left`,breakWords:!1,dropShadow:null,fill:`black`,fontFamily:`Arial`,fontSize:26,fontStyle:`normal`,fontVariant:`normal`,fontWeight:`normal`,leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:`alphabetic`,trim:!1,whiteSpace:`pre`,wordWrap:!1,wordWrapWidth:100},aO=iO}));function sO(e,t,n,r=0,i=0,a=0){if(e.texture===q.WHITE&&!e.fill)return Li.shared.setValue(e.color).setAlpha(e.alpha??1).toHexa();if(!e.fill){let n=t.createPattern(e.texture.source.resource,`repeat`),r=e.matrix.copyTo(z.shared);return r.scale(e.texture.source.pixelWidth,e.texture.source.pixelHeight),n.setTransform(r),n}if(e.fill instanceof OC){let n=e.fill,r=t.createPattern(n.texture.source.resource,`repeat`);return X.applyPatternTransform(r,n.transform,!1),r}if(e.fill instanceof wC){let o=e.fill,s=o.type===`linear`,c=o.textureSpace===`local`,l=1,u=1;c&&n&&(l=n.width+r,u=n.height+r);let d,f=!1;if(s){let{start:e,end:n}=o;d=t.createLinearGradient(e.x*l+i,e.y*u+a,n.x*l+i,n.y*u+a),f=Math.abs(n.x-e.x)<Math.abs((n.y-e.y)*.1)}else{let{center:e,innerRadius:n,outerCenter:r,outerRadius:s}=o;d=t.createRadialGradient(e.x*l+i,e.y*u+a,n*l,r.x*l+i,r.y*u+a,s*l)}if(f&&c&&n){let e=n.lineHeight/u;for(let t=0;t<n.lines.length;t++){let i=(t*n.lineHeight+r/2)/u;o.colorStops.forEach(t=>{let n=i+t.offset*e;n=Math.max(0,Math.min(1,n)),d.addColorStop(Math.floor(n*cO)/cO,Li.shared.setValue(t.color).toHex())})}}else o.colorStops.forEach(e=>{d.addColorStop(e.offset,Li.shared.setValue(e.color).toHex())});return d}return U(`FillStyle not recognised`,e),`red`}var cO,lO=s((()=>{Ri(),B(),su(),$o(),W(),TC(),kC(),cO=1e5})),uO,dO,fO=s((()=>{Ri(),Pa(),fu(),Vl(),$o(),ko(),oa(),$D(),nO(),lO(),oO(),fD(),uO=class e extends dD{constructor(t){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentMaxCharHeight=0,this._currentPageIndex=-1,this._skipKerning=!1;let n={...e.defaultOptions,...t};this._textureSize=n.textureSize,this._mipmap=n.mipmap;let r=n.style.clone();n.overrideFill&&(r._fill.color=16777215,r._fill.alpha=1,r._fill.texture=q.WHITE,r._fill.fill=null),this.applyFillAsTint=n.overrideFill;let i=r.fontSize;r.fontSize=this.baseMeasurementFontSize;let a=eO(r);n.overrideSize?(r._stroke&&(r._stroke.width*=this.baseRenderedFontSize/i),r.dropShadow&&(r.dropShadow.blur*=this.baseRenderedFontSize/i,r.dropShadow.distance*=this.baseRenderedFontSize/i)):r.fontSize=this.baseRenderedFontSize=i,this._style=r,this._skipKerning=n.skipKerning??!1,this.resolution=n.resolution??1,this._padding=n.padding??4,n.textureStyle&&(this._textureStyle=n.textureStyle instanceof Oo?n.textureStyle:new Oo(n.textureStyle)),this.fontMetrics=QD.measureFont(a),this.lineHeight=r.lineHeight||this.fontMetrics.fontSize||r.fontSize}ensureCharacters(e){let t=QD.graphemeSegmenter(e).filter(e=>!this._currentChars.includes(e)).filter((e,t,n)=>n.indexOf(e)===t);if(!t.length)return;this._currentChars=[...this._currentChars,...t];let n;n=this._currentPageIndex===-1?this._nextPage():this.pages[this._currentPageIndex];let{canvas:r,context:i}=n.canvasAndContext,a=n.texture.source,o=this._style,s=this._currentX,c=this._currentY,l=this._currentMaxCharHeight,u=this.baseRenderedFontSize/this.baseMeasurementFontSize,d=(o.dropShadow?.distance??0)+(o._stroke?.width??0),f=this._padding+d,p=!1,m=r.width/this.resolution,h=r.height/this.resolution;for(let e=0;e<t.length;e++){let n=t[e],d=QD.measureText(n,o,r,!1);d.lineHeight=d.height;let g=d.width*u,_=Math.ceil((o.fontStyle===`italic`?2:1)*g),v=d.height*u,y=_+f*2,b=v+f*2;if(p=!1,n!==`
|
|
951
|
-
`&&n!==`\r`&&n!==` `&&n!==` `&&(p=!0,l=Math.ceil(Math.max(b,l))),s+y>m&&(c+=l,l=b,s=0,c+l>h)){a.update();let e=this._nextPage();r=e.canvasAndContext.canvas,i=e.canvasAndContext.context,a=e.texture.source,s=0,c=0,l=0}let x=i.measureText(n).width/u;if(this.chars[n]={id:n.codePointAt(0),xOffset:-(f/u),yOffset:-(f/u),xAdvance:x,kerning:{}},p){this._drawGlyph(i,d,s+f,c+f,u,o);let e=a.width*u,t=a.height*u,r=new G(s/e*a.width,c/t*a.height,y/e*a.width,b/t*a.height);this.chars[n].texture=new q({source:a,frame:r}),s+=Math.ceil(y)}}a.update(),this._currentX=s,this._currentY=c,this._currentMaxCharHeight=l,this._skipKerning||this._applyKerning(t,i,u)}get pageTextures(){return H(V,`BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead.`),this.pages}_applyKerning(e,t,n){let r=this._measureCache;for(let i=0;i<e.length;i++){let a=e[i];for(let e=0;e<this._currentChars.length;e++){let i=this._currentChars[e],o=r[a];o||=r[a]=t.measureText(a).width;let s=r[i];s||=r[i]=t.measureText(i).width;let c=t.measureText(a+i).width,l=c-(o+s);l&&this.chars[a]&&(this.chars[a].kerning[i]=l/n),c=t.measureText(a+i).width,l=c-(o+s),l&&this.chars[i]&&(this.chars[i].kerning[a]=l/n)}}}_nextPage(){this._currentPageIndex++;let e=this.resolution,t=du.getOptimalCanvasAndContext(this._textureSize,this._textureSize,e);this._setupContext(t.context,this._style,e);let n=e*(this.baseRenderedFontSize/this.baseMeasurementFontSize),r=new q({source:new Bl({resource:t.canvas,resolution:n,alphaMode:`premultiply-alpha-on-upload`,autoGenerateMipmaps:this._mipmap})});this._textureStyle&&(r.source.style=this._textureStyle);let i={canvasAndContext:t,texture:r};return this.pages[this._currentPageIndex]=i,i}_setupContext(e,t,n){t.fontSize=this.baseRenderedFontSize,e.scale(n,n),e.font=eO(t),t.fontSize=this.baseMeasurementFontSize,e.textBaseline=t.textBaseline;let r=t._stroke,i=r?.width??0;if(r&&(e.lineWidth=i,e.lineJoin=r.join,e.miterLimit=r.miterLimit,e.strokeStyle=sO(r,e)),t._fill&&(e.fillStyle=sO(t._fill,e)),t.dropShadow){let r=t.dropShadow,i=Li.shared.setValue(r.color).toArray(),a=r.blur*n,o=r.distance*n;e.shadowColor=`rgba(${i[0]*255},${i[1]*255},${i[2]*255},${r.alpha})`,e.shadowBlur=a,e.shadowOffsetX=Math.cos(r.angle)*o,e.shadowOffsetY=Math.sin(r.angle)*o}else e.shadowColor=`black`,e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0}_drawGlyph(e,t,n,r,i,a){let o=t.text,s=t.fontProperties,c=(a._stroke?.width??0)*i,l=n+c/2,u=r-c/2,d=s.descent*i,f=t.lineHeight*i,p=!1;a.stroke&&c&&(p=!0,e.strokeText(o,l,u+f-d));let{shadowBlur:m,shadowOffsetX:h,shadowOffsetY:g}=e;a._fill&&(p&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.fillText(o,l,u+f-d)),p&&(e.shadowBlur=m,e.shadowOffsetX=h,e.shadowOffsetY=g)}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){let{canvasAndContext:t,texture:n}=this.pages[e];du.returnCanvasAndContext(t),n.destroy(!0)}this.pages=null}},uO.defaultOptions={textureSize:512,style:new aO,mipmap:!0},dO=uO}));function pO(e,t,n,r){let i={width:0,height:0,offsetY:0,scale:t.fontSize/n.baseMeasurementFontSize,lines:[{width:0,charPositions:[],spaceWidth:0,spacesIndex:[],chars:[]}]};i.offsetY=n.baseLineOffset;let a=i.lines[0],o=null,s=!0,c={spaceWord:!1,width:0,start:0,index:0,positions:[],chars:[]},l=n.baseMeasurementFontSize/t.fontSize,u=t.letterSpacing*l,d=t.wordWrapWidth*l,f=t.lineHeight?t.lineHeight*l:n.lineHeight,p=t.wordWrap&&t.breakWords,m=TD(t.whiteSpace),h=ED(t.whiteSpace);if(m||h){let t=[],n=m;for(let r=0;r<e.length;r++){let i=e[r];if(i===`\r`||i===`
|
|
952
|
-
`){if(h)i===`\r`&&e[r+1]===`
|
|
953
|
-
`&&r++,i=` `;else{m&&(n=!0),t.push(i);continue}}if(SD(i)){if(m&&CD(i)){if(n)continue;n=!0,t.push(` `)}else n=!1,t.push(i)}else n=!1,t.push(i)}e=t}let g=e=>{let t=a.width;for(let n=0;n<c.index;n++){let r=e.positions[n];a.chars.push(e.chars[n]),a.charPositions.push(r+t)}a.width+=e.width,(c.index>0||!m)&&(s=!1),c.width=0,c.index=0,c.chars.length=0},_=()=>{let e=a.chars.length-1;if(r){let t=a.chars[e];for(;CD(t);)a.width-=n.chars[t].xAdvance,a.spacesIndex.pop(),t=a.chars[--e]}i.width=Math.max(i.width,a.width),a={width:0,charPositions:[],chars:[],spaceWidth:0,spacesIndex:[]},s=!0,i.lines.push(a),i.height+=f},v=e=>e-u>d;for(let r=0;r<e.length+1;r++){let i,l=r===e.length;l||(i=e[r]);let d=n.chars[i];if(/(?:\s)/.test(i)||i===`\r`||i===`
|
|
954
|
-
`||l){if(!s&&t.wordWrap&&v(a.width+c.width)?(_(),g(c),!l&&d&&a.charPositions.push(0)):(c.start=a.width,g(c),!l&&d&&a.charPositions.push(0)),i===`\r`||i===`
|
|
955
|
-
`)_();else if(!l&&d){let e=d.xAdvance+(d.kerning?.[o]||0)+u;a.width+=e,a.spaceWidth=e,a.spacesIndex.push(a.charPositions.length),a.chars.push(i)}}else if(d){let e=d.kerning?.[o]||0,n=d.xAdvance+e+u;p&&v(c.width+n)&&(s||_(),g(c),_()),c.positions[c.index++]=c.width+e,c.chars.push(i),c.width+=n,wD(i)&&(!s&&t.wordWrap&&v(a.width+c.width)&&_(),g(c))}o=i}return _(),t.align===`center`?mO(i):t.align===`right`?hO(i):t.align===`justify`&&gO(i),i}function mO(e){for(let t=0;t<e.lines.length;t++){let n=e.lines[t],r=e.width/2-n.width/2;for(let e=0;e<n.charPositions.length;e++)n.charPositions[e]+=r}}function hO(e){for(let t=0;t<e.lines.length;t++){let n=e.lines[t],r=e.width-n.width;for(let e=0;e<n.charPositions.length;e++)n.charPositions[e]+=r}}function gO(e){let t=e.width;for(let n=0;n<e.lines.length-2;n++){let r=e.lines[n],i=0,a=r.spacesIndex[i++],o=0,s=r.spacesIndex.length,c=(t-r.width)/s;for(let e=0;e<r.charPositions.length;e++)e===a&&(a=r.spacesIndex[i++],o+=c),r.charPositions[e]+=o}}var _O=s((()=>{BD()}));function vO(e){if(e===``)return[];typeof e==`string`&&(e=[e]);let t=[];for(let n=0,r=e.length;n<r;n++){let r=e[n];if(Array.isArray(r)){if(r.length!==2)throw Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${r.length}.`);if(r[0].length===0||r[1].length===0)throw Error(`[BitmapFont]: Invalid character delimiter.`);let e=r[0].charCodeAt(0),n=r[1].charCodeAt(0);if(n<e)throw Error(`[BitmapFont]: Invalid character range.`);for(let r=e,i=n;r<=i;r++)t.push(String.fromCharCode(r))}else t.push(...Array.from(r))}if(t.length===0)throw Error(`[BitmapFont]: Empty set when resolving characters.`);return t}var yO=s((()=>{})),bO,xO,SO,CO=s((()=>{hD(),Xl(),oa(),W(),$D(),oO(),fO(),_O(),yO(),bO=0,xO=class{constructor(){this.ALPHA=[[`a`,`z`],[`A`,`Z`],` `],this.NUMERIC=[[`0`,`9`]],this.ALPHANUMERIC=[[`a`,`z`],[`A`,`Z`],[`0`,`9`],` `],this.ASCII=[[` `,`~`]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1,textureStyle:null},this.measureCache=pD(1e3)}getFont(e,t){let n=`${t.fontFamily}-bitmap`,r=!0;if(Yl.has(n)){let t=Yl.get(n);return t.ensureCharacters?.(e),t}if(t._fill.fill&&!t._stroke?(n+=t._fill.fill.styleKey,r=!1):(t._stroke||t.dropShadow)&&(n=`${t.styleKey}-bitmap`,r=!1),n+=`-${t.fontStyle}`,n+=`-${t.fontVariant}`,n+=`-${t.fontWeight}`,!Yl.has(n)){let e=Object.create(t);e._lineHeight=0;let i=new dO({style:e,overrideFill:r,overrideSize:!0,...this.defaultOptions});bO++,bO>50&&U(`BitmapText`,`You have dynamically created ${bO} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),i.once(`destroy`,()=>{bO--,Yl.remove(n)}),Yl.set(n,i)}let i=Yl.get(n);return i.ensureCharacters?.(e),i}getLayout(e,t,n=!0){let r=this.getFont(e,t),i=`${e}-${t.styleKey}-${n}`;if(this.measureCache.has(i))return this.measureCache.get(i);let a=pO(QD.graphemeSegmenter(e),t,r,n);return this.measureCache.set(i,a),a}measureText(e,t,n=!0){return this.getLayout(e,t,n)}install(...e){let t=e[0];typeof t==`string`&&(t={name:t,style:e[1],chars:e[2]?.chars,resolution:e[2]?.resolution,padding:e[2]?.padding,skipKerning:e[2]?.skipKerning},H(V,`BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})`));let n=t?.name;if(!n)throw Error("[BitmapFontManager] Property `name` is required.");t={...this.defaultOptions,...t};let r=t.style,i=r instanceof aO?r:new aO(r),a=t.dynamicFill??this._canUseTintForStyle(i),o=new dO({style:i,overrideFill:a,skipKerning:t.skipKerning,padding:t.padding,resolution:t.resolution,overrideSize:!1,textureStyle:t.textureStyle}),s=vO(t.chars);return o.ensureCharacters(s.join(``)),Yl.set(`${n}-bitmap`,o),o.once(`destroy`,()=>Yl.remove(`${n}-bitmap`)),o}uninstall(e){let t=`${e}-bitmap`,n=Yl.get(t);n&&n.destroy()}_canUseTintForStyle(e){return!e._stroke&&(!e.dropShadow||e.dropShadow.color===0)&&!e._fill.fill&&e._fill.color===16777215}},SO=new xO})),wO=l({BitmapFont:()=>TO}),TO,EO=s((()=>{Uo(),Pa(),$o(),fD(),CO(),TO=class extends dD{constructor(e,t){super();let{textures:n,data:r}=e;Object.keys(r.pages).forEach(e=>{let t=r.pages[parseInt(e,10)],i=n[t.id];this.pages.push({texture:i})}),Object.keys(r.chars).forEach(e=>{let t=r.chars[e],{frame:i,source:a,rotate:o}=n[t.page],s=K.transformRectCoords(t,i,o,new G),c=new q({frame:s,orig:new G(0,0,t.width,t.height),source:a,rotate:o});this.chars[e]={id:e.codePointAt(0),xOffset:t.xOffset,yOffset:t.yOffset,xAdvance:t.xAdvance,kerning:t.kerning??{},texture:c}}),this.baseRenderedFontSize=r.fontSize,this.baseMeasurementFontSize=r.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:r.fontSize},this.baseLineOffset=r.baseLineOffset,this.lineHeight=r.lineHeight,this.fontFamily=r.fontFamily,this.distanceField=r.distanceField??{type:`none`,range:0},this.url=t}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){let{texture:t}=this.pages[e];t.destroy(!0)}this.pages=null}static install(e){SO.install(e)}static uninstall(e){SO.uninstall(e)}}}));Wc(),pl(),Jc(),R(),tl();var DO=[`.xml`,`.fnt`],OO={extension:{type:I.CacheParser,name:`cacheBitmapFont`},test:e=>!!e?.pages&&!!e?.chars&&typeof e?.fontFamily==`string`&&e.fontFamily!==``,getCacheableAssets(e,t){let n={};return e.forEach(e=>{n[e]=t,n[`${e}-bitmap`]=t}),n[`${t.fontFamily}-bitmap`]=t,n}},kO={extension:{type:I.LoadParser,priority:Uc.Normal},name:`loadBitmapFont`,id:`bitmap-font`,test(e){return DO.includes(el.extname(e).toLowerCase())},async testParse(e){return cD.test(e)||uD.test(e)},async parse(e,t,n){let r=cD.test(e)?cD.parse(e):uD.parse(e),{src:i}=t,{pages:a}=r,o=[],s=r.distanceField?{scaleMode:`linear`,alphaMode:`premultiply-alpha-on-upload`,autoGenerateMipmaps:!1,resolution:1}:{};for(let e=0;e<a.length;++e){let t=a[e].file,n=el.join(el.dirname(i),t);n=fl(n,i),o.push({src:n,data:s})}let[c,{BitmapFont:l}]=await Promise.all([n.load(o),Promise.resolve().then(()=>(EO(),wO))]);return new l({data:r,textures:o.map(e=>c[e.src])},i)},async load(e,t){return await(await Y.get().fetch(e)).text()},async unload(e,t,n){await Promise.all(e.pages.map(e=>n.unload(e.texture.source._sourceOrigin))),e.destroy()}},AO=class{constructor(e,t=!1){this._loader=e,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=t}add(e){e.forEach(e=>{this._assetList.push(e)}),this.verbose&&console.log(`[BackgroundLoader] assets: `,this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;let e=[],t=Math.min(this._assetList.length,this._maxConcurrent);for(let n=0;n<t;n++)e.push(this._assetList.pop());await this._loader.load(e),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(e){this._isActive!==e&&(this._isActive=e,e&&!this._isLoading&&this._next())}};R(),$o();var jO={extension:{type:I.CacheParser,name:`cacheTextureArray`},test:e=>Array.isArray(e)&&e.every(e=>e instanceof q),getCacheableAssets:(e,t)=>{let n={};return e.forEach(e=>{t.forEach((t,r)=>{n[e+(r===0?``:r+1)]=t})}),n}};async function MO(e){if(`Image`in globalThis)return new Promise(t=>{let n=new Image;n.onload=()=>{t(!0)},n.onerror=()=>{t(!1)},n.src=e});if(`createImageBitmap`in globalThis&&`fetch`in globalThis){try{let t=await(await fetch(e)).blob();await createImageBitmap(t)}catch{return!1}return!0}return!1}R();var NO={extension:{type:I.DetectionParser,priority:1},test:async()=>MO(`data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=`),add:async e=>[...e,`avif`],remove:async e=>e.filter(e=>e!==`avif`)};R();var PO=[`png`,`jpg`,`jpeg`],FO={extension:{type:I.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async e=>[...e,...PO],remove:async e=>e.filter(e=>!PO.includes(e))},IO=`WorkerGlobalScope`in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function LO(e){return!IO&&document.createElement(`video`).canPlayType(e)!==``}R();var RO={extension:{type:I.DetectionParser,priority:0},test:async()=>LO(`video/mp4`),add:async e=>[...e,`mp4`,`m4v`],remove:async e=>e.filter(e=>e!==`mp4`&&e!==`m4v`)};R();var zO={extension:{type:I.DetectionParser,priority:0},test:async()=>LO(`video/ogg`),add:async e=>[...e,`ogv`],remove:async e=>e.filter(e=>e!==`ogv`)};R();var BO={extension:{type:I.DetectionParser,priority:0},test:async()=>LO(`video/webm`),add:async e=>[...e,`webm`],remove:async e=>e.filter(e=>e!==`webm`)};R();var VO={extension:{type:I.DetectionParser,priority:0},test:async()=>MO(`data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=`),add:async e=>[...e,`webp`],remove:async e=>e.filter(e=>e!==`webp`)};W(),tl(),rl(),cl();var HO=class e{constructor(){this.loadOptions={...e.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(e,t,n)=>(this._parsersValidated=!1,e[t]=n,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(e,t){let n={promise:null,parser:null};return n.promise=(async()=>{let r=null,i=null;if((t.parser||t.loadParser)&&(i=this._parserHash[t.parser||t.loadParser],t.loadParser&&U(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),i||U(`[Assets] specified load parser "${t.parser||t.loadParser}" not found while loading ${e}`)),!i){for(let n=0;n<this.parsers.length;n++){let r=this.parsers[n];if(r.load&&r.test?.(e,t,this)){i=r;break}}if(!i)return U(`[Assets] ${e} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}r=await i.load(e,t,this),n.parser=i;for(let e=0;e<this.parsers.length;e++){let i=this.parsers[e];i.parse&&i.parse&&await i.testParse?.(r,t,this)&&(r=await i.parse(r,t,this)||r,n.parser=i)}return r})(),n}async load(t,n){this._parsersValidated||this._validateParsers();let{onProgress:r,onError:i,strategy:a,retryCount:o,retryDelay:s}=typeof n==`function`?{...e.defaultOptions,...this.loadOptions,onProgress:n}:{...e.defaultOptions,...this.loadOptions,...n||{}},c=0,l={},u=sl(t),d=nl(t,e=>({alias:[e],src:e,data:{}})),f=d.reduce((e,t)=>e+(t.progressSize||1),0),p=d.map(async e=>{let t=el.toAbsolute(e.src);l[e.src]||(await this._loadAssetWithRetry(t,e,{onProgress:r,onError:i,strategy:a,retryCount:o,retryDelay:s},l),c+=e.progressSize||1,r&&r(c/f))});return await Promise.all(p),u?l[d[0].src]:l}async unload(e){let t=nl(e,e=>({alias:[e],src:e})).map(async e=>{let t=el.toAbsolute(e.src),n=this.promiseCache[t];if(n){let r=await n.promise;delete this.promiseCache[t],await n.parser?.unload?.(r,e,this)}});await Promise.all(t)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(e=>e.name||e.id).reduce((e,t)=>(!t.name&&!t.id?U(`[Assets] parser should have an id`):(e[t.name]||e[t.id])&&U(`[Assets] parser id conflict "${t.id}"`),e[t.name]=t,t.id&&(e[t.id]=t),e),{})}async _loadAssetWithRetry(e,t,n,r){let i=0,{onError:a,strategy:o,retryCount:s,retryDelay:c}=n,l=e=>new Promise(t=>setTimeout(t,e));for(;;)try{this.promiseCache[e]||(this.promiseCache[e]=this._getLoadPromiseAndParser(e,t)),r[t.src]=await this.promiseCache[e].promise;return}catch(n){if(delete this.promiseCache[e],delete r[t.src],i++,o===`retry`&&!(o!==`retry`||i>s)){a&&a(n,t),await l(c);continue}if(o===`skip`){a&&a(n,t);return}a&&a(n,t);let u=Error(`[Loader.load] Failed to load ${e}.
|
|
956
|
-
${n}`);throw n instanceof Error&&n.stack&&(u.stack=n.stack),u}}};HO.defaultOptions={onProgress:void 0,onError:void 0,strategy:`throw`,retryCount:3,retryDelay:250};var UO=HO;function WO(e,t){if(Array.isArray(t)){for(let n of t)if(e.startsWith(`data:${n}`))return!0;return!1}return e.startsWith(`data:${t}`)}tl();function GO(e,t){let n=e.split(`?`)[0],r=el.extname(n).toLowerCase();return Array.isArray(t)?t.includes(r):r===t}Jc(),R(),Wc();var KO=`.json`,qO=`application/json`,JO={extension:{type:I.LoadParser,priority:Uc.Low},name:`loadJson`,id:`json`,test(e){return WO(e,qO)||GO(e,KO)},async load(e){return await(await Y.get().fetch(e)).json()}};Jc(),R(),Wc();var YO=`.txt`,XO=`text/plain`,ZO={name:`loadTxt`,id:`text`,extension:{type:I.LoadParser,priority:Uc.Low,name:`loadTxt`},test(e){return WO(e,XO)||GO(e,YO)},async load(e){return await(await Y.get().fetch(e)).text()}};Jc(),R(),W(),tl(),Xl(),Wc();var QO=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],$O=[`.ttf`,`.otf`,`.woff`,`.woff2`],ek=[`font/ttf`,`font/otf`,`font/woff`,`font/woff2`],tk=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function nk(e){let t=el.extname(e),n=el.basename(e,t).replace(/(-|_)/g,` `).toLowerCase().split(` `).map(e=>e.charAt(0).toUpperCase()+e.slice(1)),r=n.length>0;for(let e of n)if(!e.match(tk)){r=!1;break}let i=n.join(` `);return r||(i=`"${i.replace(/[\\"]/g,`\\$&`)}"`),i}var rk=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function ik(e){return rk.test(e)?e:encodeURI(e)}var ak={extension:{type:I.LoadParser,priority:Uc.Low},name:`loadWebFont`,id:`web-font`,test(e){return WO(e,ek)||GO(e,$O)},async load(e,t){let n=Y.get().getFontFaceSet();if(n){let r=[],i=t.data?.family??nk(e),a=t.data?.weights?.filter(e=>QO.includes(e))??[`normal`],o=t.data??{};for(let t=0;t<a.length;t++){let s=a[t],c=new FontFace(i,`url('${ik(e)}')`,{...o,weight:s});await c.load(),n.add(c),r.push(c)}return Yl.has(`${i}-and-url`)?Yl.get(`${i}-and-url`).entries.push({url:e,faces:r}):Yl.set(`${i}-and-url`,{entries:[{url:e,faces:r}]}),r.length===1?r[0]:r}return U(`[loadWebFont] FontFace API is not supported. Skipping loading font`),null},unload(e){let t=Array.isArray(e)?e:[e],n=t[0].family,r=Yl.get(`${n}-and-url`),i=r.entries.find(e=>e.faces.some(e=>t.indexOf(e)!==-1));i.faces=i.faces.filter(e=>t.indexOf(e)===-1),i.faces.length===0&&(r.entries=r.entries.filter(e=>e!==i)),t.forEach(e=>{Y.get().getFontFaceSet().delete(e)}),r.entries.length===0&&Yl.remove(`${n}-and-url`)}};dl();function ok(e,t=1){let n=ul.RETINA_PREFIX?.exec(e);return n?parseFloat(n[1]):t}$o(),W(),Xl();function sk(e,t,n){e.label=n,e._sourceOrigin=n;let r=new q({source:e,label:n}),i=()=>{delete t.promiseCache[n],Yl.has(n)&&Yl.remove(n)};return r.source.once(`destroy`,()=>{t.promiseCache[n]&&(U(`[Assets] A TextureSource managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the TextureSource.`),i())}),r.once(`destroy`,()=>{e.destroyed||(U(`[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture.`),i())}),r}Jc(),R(),Vl(),pE(),Wc();var ck=`.svg`,lk=`image/svg+xml`,uk={extension:{type:I.LoadParser,priority:Uc.Low,name:`loadSVG`},name:`loadSVG`,id:`svg`,config:{crossOrigin:`anonymous`,parseAsGraphicsContext:!1},test(e){return WO(e,lk)||GO(e,ck)},async load(e,t,n){return t.data?.parseAsGraphicsContext??this.config.parseAsGraphicsContext?fk(e):dk(e,t,n,this.config.crossOrigin)},unload(e){e.destroy(!0)}};async function dk(e,t,n,r){let i=await Y.get().fetch(e),a=Y.get().createImage();a.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(await i.text())}`,a.crossOrigin=r,await a.decode();let o=t.data?.width??a.width,s=t.data?.height??a.height,c=t.data?.resolution||ok(e),l=Math.ceil(o*c),u=Math.ceil(s*c),d=Y.get().createCanvas(l,u),f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(a,0,0,o*c,s*c);let{parseAsGraphicsContext:p,...m}=t.data??{};return sk(new Bl({resource:d,alphaMode:`premultiply-alpha-on-upload`,resolution:c,...m}),n,e)}async function fk(e){let t=await(await Y.get().fetch(e)).text(),n=new fE;return n.svg(t),n}var pk=`(function () {
|
|
957
|
-
'use strict';
|
|
958
|
-
|
|
959
|
-
const WHITE_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";
|
|
960
|
-
async function checkImageBitmap() {
|
|
961
|
-
try {
|
|
962
|
-
if (typeof createImageBitmap !== "function") return false;
|
|
963
|
-
const response = await fetch(WHITE_PNG);
|
|
964
|
-
const imageBlob = await response.blob();
|
|
965
|
-
const imageBitmap = await createImageBitmap(imageBlob);
|
|
966
|
-
return imageBitmap.width === 1 && imageBitmap.height === 1;
|
|
967
|
-
} catch (_e) {
|
|
968
|
-
return false;
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
void checkImageBitmap().then((result) => {
|
|
972
|
-
self.postMessage(result);
|
|
973
|
-
});
|
|
974
|
-
|
|
975
|
-
})();
|
|
976
|
-
`,mk=null,hk=class{constructor(){mk||=URL.createObjectURL(new Blob([pk],{type:`application/javascript`})),this.worker=new Worker(mk)}};hk.revokeObjectURL=function(){mk&&=(URL.revokeObjectURL(mk),null)};var gk=`(function () {
|
|
977
|
-
'use strict';
|
|
978
|
-
|
|
979
|
-
async function loadImageBitmap(url, alphaMode) {
|
|
980
|
-
const response = await fetch(url);
|
|
981
|
-
if (!response.ok) {
|
|
982
|
-
throw new Error(\`[WorkerManager.loadImageBitmap] Failed to fetch \${url}: \${response.status} \${response.statusText}\`);
|
|
983
|
-
}
|
|
984
|
-
const imageBlob = await response.blob();
|
|
985
|
-
return alphaMode === "premultiplied-alpha" ? createImageBitmap(imageBlob, { premultiplyAlpha: "none" }) : createImageBitmap(imageBlob);
|
|
986
|
-
}
|
|
987
|
-
self.onmessage = async (event) => {
|
|
988
|
-
try {
|
|
989
|
-
const imageBitmap = await loadImageBitmap(event.data.data[0], event.data.data[1]);
|
|
990
|
-
self.postMessage({
|
|
991
|
-
data: imageBitmap,
|
|
992
|
-
uuid: event.data.uuid,
|
|
993
|
-
id: event.data.id
|
|
994
|
-
}, [imageBitmap]);
|
|
995
|
-
} catch (e) {
|
|
996
|
-
self.postMessage({
|
|
997
|
-
error: e,
|
|
998
|
-
uuid: event.data.uuid,
|
|
999
|
-
id: event.data.id
|
|
1000
|
-
});
|
|
1001
|
-
}
|
|
1002
|
-
};
|
|
1003
|
-
|
|
1004
|
-
})();
|
|
1005
|
-
`,_k=null,vk=class{constructor(){_k||=URL.createObjectURL(new Blob([gk],{type:`application/javascript`})),this.worker=new Worker(_k)}};vk.revokeObjectURL=function(){_k&&=(URL.revokeObjectURL(_k),null)};var yk=0,bk,xk=new class{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported===void 0&&(this._isImageBitmapSupported=new Promise(e=>{let{worker:t}=new hk;t.addEventListener(`message`,n=>{t.terminate(),hk.revokeObjectURL(),e(n.data)})})),this._isImageBitmapSupported}loadImageBitmap(e,t){return this._run(`loadImageBitmap`,[e,t?.data?.alphaMode])}async _initWorkers(){this._initialized||=!0}_getWorker(){bk===void 0&&(bk=navigator.hardwareConcurrency||4);let e=this._workerPool.pop();return!e&&this._createdWorkers<bk&&(this._createdWorkers++,e=new vk().worker,e.addEventListener(`message`,e=>{this._complete(e.data),this._returnWorker(e.target),this._next()})),e}_returnWorker(e){this._workerPool.push(e)}_complete(e){this._resolveHash[e.uuid]&&(e.error===void 0?this._resolveHash[e.uuid].resolve(e.data):this._resolveHash[e.uuid].reject(e.error),delete this._resolveHash[e.uuid])}async _run(e,t){await this._initWorkers();let n=new Promise((n,r)=>{this._queue.push({id:e,arguments:t,resolve:n,reject:r})});return this._next(),n}_next(){if(!this._queue.length)return;let e=this._getWorker();if(!e)return;let t=this._queue.pop(),n=t.id;this._resolveHash[yk]={resolve:t.resolve,reject:t.reject},e.postMessage({data:t.arguments,uuid:yk++,id:n})}reset(){this._workerPool.forEach(e=>e.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:e})=>{e?.(Error(`WorkerManager has been reset before completion`))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}};Jc(),R(),Vl(),Wc();var Sk=[`.jpeg`,`.jpg`,`.png`,`.webp`,`.avif`],Ck=[`image/jpeg`,`image/png`,`image/webp`,`image/avif`];async function wk(e,t){let n=await Y.get().fetch(e);if(!n.ok)throw Error(`[loadImageBitmap] Failed to fetch ${e}: ${n.status} ${n.statusText}`);let r=await n.blob();return t?.data?.alphaMode===`premultiplied-alpha`?createImageBitmap(r,{premultiplyAlpha:`none`}):createImageBitmap(r)}var Tk={name:`loadTextures`,id:`texture`,extension:{type:I.LoadParser,priority:Uc.High,name:`loadTextures`},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:`anonymous`},test(e){return WO(e,Ck)||GO(e,Sk)},async load(e,t,n){let r=null;return r=globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await xk.isImageBitmapSupported()?await xk.loadImageBitmap(e,t):await wk(e,t):await new Promise((t,n)=>{r=Y.get().createImage(),r.crossOrigin=this.config.crossOrigin,r.src=e,r.complete?t(r):(r.onload=()=>{t(r)},r.onerror=n)}),sk(new Bl({resource:r,alphaMode:`premultiply-alpha-on-upload`,resolution:t.data?.resolution||ok(e),...t.data}),n,e)},unload(e){e.destroy(!0)}};R(),ql(),Wl();var Ek=[`.mp4`,`.m4v`,`.webm`,`.ogg`,`.ogv`,`.h264`,`.avi`,`.mov`],Dk,Ok;function kk(e,t,n){n===void 0&&!t.startsWith(`data:`)?e.crossOrigin=jk(t):n!==!1&&(e.crossOrigin=typeof n==`string`?n:`anonymous`)}function Ak(e){return new Promise((t,n)=>{e.addEventListener(`canplaythrough`,r),e.addEventListener(`error`,i),e.load();function r(){a(),t()}function i(e){a(),n(e)}function a(){e.removeEventListener(`canplaythrough`,r),e.removeEventListener(`error`,i)}})}function jk(e,t=globalThis.location){if(e.startsWith(`data:`))return``;t||=globalThis.location;let n=new URL(e,document.baseURI);return n.hostname!==t.hostname||n.port!==t.port||n.protocol!==t.protocol?`anonymous`:``}function Mk(){let e=[],t=[];for(let n of Ek){let r=Kl.MIME_TYPES[n.substring(1)]||`video/${n.substring(1)}`;LO(r)&&(e.push(n),t.includes(r)||t.push(r))}return{validVideoExtensions:e,validVideoMime:t}}var Nk={name:`loadVideo`,id:`video`,extension:{type:I.LoadParser,name:`loadVideo`},test(e){if(!Dk||!Ok){let{validVideoExtensions:e,validVideoMime:t}=Mk();Dk=e,Ok=t}let t=WO(e,Ok),n=GO(e,Dk);return t||n},async load(e,t,n){let r={...Kl.defaultOptions,resolution:t.data?.resolution||ok(e),alphaMode:t.data?.alphaMode||await Hl(),...t.data},i=document.createElement(`video`),a={preload:r.autoLoad===!1?void 0:`auto`,"webkit-playsinline":r.playsinline===!1?void 0:``,playsinline:r.playsinline===!1?void 0:``,muted:r.muted===!0?``:void 0,loop:r.loop===!0?``:void 0,autoplay:r.autoPlay===!1?void 0:``};Object.keys(a).forEach(e=>{let t=a[e];t!==void 0&&i.setAttribute(e,t)}),r.muted===!0&&(i.muted=!0),kk(i,e,r.crossorigin);let o=document.createElement(`source`),s;if(r.mime)s=r.mime;else if(e.startsWith(`data:`))s=e.slice(5,e.indexOf(`;`));else if(!e.startsWith(`blob:`)){let t=e.split(`?`)[0].slice(e.lastIndexOf(`.`)+1).toLowerCase();s=Kl.MIME_TYPES[t]||`video/${t}`}return o.src=e,s&&(o.type=s),new Promise((a,s)=>{r.preload&&!r.autoPlay&&i.load(),i.addEventListener(`canplay`,c),i.addEventListener(`error`,l),o.addEventListener(`error`,l),i.appendChild(o);async function c(){let o=new Kl({...r,resource:i});u(),t.data.preload&&await Ak(i),a(sk(o,n,e))}function l(e){u(),s(e)}function u(){i.removeEventListener(`canplay`,c),i.removeEventListener(`error`,l),o.removeEventListener(`error`,l)}})},unload(e){e.destroy(!0)}};R(),dl();var Pk={extension:{type:I.ResolveParser,name:`resolveTexture`},test:Tk.test,parse:e=>({resolution:parseFloat(ul.RETINA_PREFIX.exec(e)?.[1]??`1`),format:e.split(`.`).pop(),src:e})};R(),dl();var Fk={extension:{type:I.ResolveParser,priority:-2,name:`resolveJson`},test:e=>ul.RETINA_PREFIX.test(e)&&e.endsWith(`.json`),parse:Pk.parse};R(),W(),Xl(),dl(),rl(),cl();var Ik=new class{constructor(){this._detections=[],this._initialized=!1,this.resolver=new ul,this.loader=new UO,this.cache=Yl,this._backgroundLoader=new AO(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(e={}){if(this._initialized){U(`[Assets]AssetManager already initialized, did you load before calling this Assets.init()?`);return}if(this._initialized=!0,e.defaultSearchParams&&this.resolver.setDefaultSearchParams(e.defaultSearchParams),e.basePath&&(this.resolver.basePath=e.basePath),e.bundleIdentifier&&this.resolver.setBundleIdentifier(e.bundleIdentifier),e.manifest){let t=e.manifest;typeof t==`string`&&(t=await this.load(t)),this.resolver.addManifest(t)}let t=e.texturePreference?.resolution??1,n=typeof t==`number`?[t]:t,r=await this._detectFormats({preferredFormats:e.texturePreference?.format,skipDetections:e.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:r,resolution:n}}),e.preferences&&this.setPreferences(e.preferences),e.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...e.loadOptions})}add(e){this.resolver.add(e)}async load(e,t){this._initialized||await this.init();let n=sl(e),r=nl(e).map(e=>{if(typeof e!=`string`){let t=this.resolver.getAlias(e);return t.some(e=>!this.resolver.hasKey(e))&&this.add(e),Array.isArray(t)?t[0]:t}return this.resolver.hasKey(e)||this.add({alias:e,src:e}),e}),i=this.resolver.resolve(r),a=await this._mapLoadToResolve(i,t);return n?a[r[0]]:a}addBundle(e,t){this.resolver.addBundle(e,t)}async loadBundle(e,t){this._initialized||await this.init();let n=!1;typeof e==`string`&&(n=!0,e=[e]);let r=this.resolver.resolveBundle(e),i={},a=Object.keys(r),o=0,s=[],c=()=>{t?.(s.reduce((e,t)=>e+t,0)/o)},l=a.map((e,t)=>{let n=r[e],a=Object.values(n),l=[...new Set(a.flat())].reduce((e,t)=>e+(t.progressSize||1),0);return s.push(0),o+=l,this._mapLoadToResolve(n,e=>{s[t]=e*l,c()}).then(t=>{i[e]=t})});return await Promise.all(l),n?i[e[0]]:i}async backgroundLoad(e){this._initialized||await this.init(),typeof e==`string`&&(e=[e]);let t=this.resolver.resolve(e);this._backgroundLoader.add(Object.values(t))}async backgroundLoadBundle(e){this._initialized||await this.init(),typeof e==`string`&&(e=[e]);let t=this.resolver.resolveBundle(e);Object.values(t).forEach(e=>{this._backgroundLoader.add(Object.values(e))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(e){if(typeof e==`string`)return Yl.get(e);let t={};for(let n=0;n<e.length;n++)t[n]=Yl.get(e[n]);return t}async _mapLoadToResolve(e,t){let n=[...new Set(Object.values(e))];this._backgroundLoader.active=!1;let r=await this.loader.load(n,t);this._backgroundLoader.active=!0;let i={};return n.forEach(e=>{let t=r[e.src],n=[e.src];e.alias&&n.push(...e.alias),n.forEach(e=>{i[e]=t}),Yl.set(n,t)}),i}async unload(e){this._initialized||await this.init();let t=nl(e).map(e=>typeof e==`string`?e:e.src),n=this.resolver.resolve(t);await this._unloadFromResolved(n)}async unloadBundle(e){this._initialized||await this.init(),e=nl(e);let t=this.resolver.resolveBundle(e),n=Object.keys(t).map(e=>this._unloadFromResolved(t[e]));await Promise.all(n)}async _unloadFromResolved(e){let t=Object.values(e);t.forEach(e=>{Yl.remove(e.src)}),await this.loader.unload(t)}async _detectFormats(e){let t=[];e.preferredFormats&&(t=Array.isArray(e.preferredFormats)?e.preferredFormats:[e.preferredFormats]);for(let n of e.detections)e.skipDetections||await n.test()?t=await n.add(t):e.skipDetections||(t=await n.remove(t));return t=t.filter((e,n)=>t.indexOf(e)===n),t}get detections(){return this._detections}setPreferences(e){this.loader.parsers.forEach(t=>{t.config&&Object.keys(t.config).filter(t=>t in e).forEach(n=>{t.config[n]=e[n]})})}};L.handleByList(I.LoadParser,Ik.loader.parsers).handleByList(I.ResolveParser,Ik.resolver.parsers).handleByList(I.CacheParser,Ik.cache.parsers).handleByList(I.DetectionParser,Ik.detections),L.add(jO,FO,NO,VO,RO,zO,BO,JO,ZO,ak,uk,Tk,Nk,kO,OO,Pk,Fk);var Lk={loader:I.LoadParser,resolver:I.ResolveParser,cache:I.CacheParser,detection:I.DetectionParser};L.handle(I.Asset,e=>{let t=e.ref;Object.entries(Lk).filter(([e])=>!!t[e]).forEach(([e,n])=>L.add(Object.assign(t[e],{extension:t[e].extension??n})))},e=>{let t=e.ref;Object.keys(Lk).filter(e=>!!t[e]).forEach(e=>L.remove(t[e]))});var Rk=`
|
|
1006
|
-
in vec2 vTextureCoord;
|
|
1007
|
-
in vec4 vColor;
|
|
1008
|
-
|
|
1009
|
-
out vec4 finalColor;
|
|
1010
|
-
|
|
1011
|
-
uniform float uColorMatrix[20];
|
|
1012
|
-
uniform float uAlpha;
|
|
1013
|
-
|
|
1014
|
-
uniform sampler2D uTexture;
|
|
1015
|
-
|
|
1016
|
-
float rand(vec2 co)
|
|
1017
|
-
{
|
|
1018
|
-
return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
void main()
|
|
1022
|
-
{
|
|
1023
|
-
vec4 color = texture(uTexture, vTextureCoord);
|
|
1024
|
-
float randomValue = rand(gl_FragCoord.xy * 0.2);
|
|
1025
|
-
float diff = (randomValue - 0.5) * 0.5;
|
|
1026
|
-
|
|
1027
|
-
if (uAlpha == 0.0) {
|
|
1028
|
-
finalColor = color;
|
|
1029
|
-
return;
|
|
1030
|
-
}
|
|
1031
|
-
|
|
1032
|
-
if (color.a > 0.0) {
|
|
1033
|
-
color.rgb /= color.a;
|
|
1034
|
-
}
|
|
1035
|
-
|
|
1036
|
-
vec4 result;
|
|
1037
|
-
|
|
1038
|
-
result.r = (uColorMatrix[0] * color.r);
|
|
1039
|
-
result.r += (uColorMatrix[1] * color.g);
|
|
1040
|
-
result.r += (uColorMatrix[2] * color.b);
|
|
1041
|
-
result.r += (uColorMatrix[3] * color.a);
|
|
1042
|
-
result.r += uColorMatrix[4];
|
|
1043
|
-
|
|
1044
|
-
result.g = (uColorMatrix[5] * color.r);
|
|
1045
|
-
result.g += (uColorMatrix[6] * color.g);
|
|
1046
|
-
result.g += (uColorMatrix[7] * color.b);
|
|
1047
|
-
result.g += (uColorMatrix[8] * color.a);
|
|
1048
|
-
result.g += uColorMatrix[9];
|
|
1049
|
-
|
|
1050
|
-
result.b = (uColorMatrix[10] * color.r);
|
|
1051
|
-
result.b += (uColorMatrix[11] * color.g);
|
|
1052
|
-
result.b += (uColorMatrix[12] * color.b);
|
|
1053
|
-
result.b += (uColorMatrix[13] * color.a);
|
|
1054
|
-
result.b += uColorMatrix[14];
|
|
1055
|
-
|
|
1056
|
-
result.a = (uColorMatrix[15] * color.r);
|
|
1057
|
-
result.a += (uColorMatrix[16] * color.g);
|
|
1058
|
-
result.a += (uColorMatrix[17] * color.b);
|
|
1059
|
-
result.a += (uColorMatrix[18] * color.a);
|
|
1060
|
-
result.a += uColorMatrix[19];
|
|
1061
|
-
|
|
1062
|
-
vec3 rgb = mix(color.rgb, result.rgb, uAlpha);
|
|
1063
|
-
|
|
1064
|
-
// Premultiply alpha again.
|
|
1065
|
-
rgb *= result.a;
|
|
1066
|
-
|
|
1067
|
-
finalColor = vec4(rgb, result.a);
|
|
1068
|
-
}
|
|
1069
|
-
`,zk=`struct GlobalFilterUniforms {
|
|
1070
|
-
uInputSize:vec4<f32>,
|
|
1071
|
-
uInputPixel:vec4<f32>,
|
|
1072
|
-
uInputClamp:vec4<f32>,
|
|
1073
|
-
uOutputFrame:vec4<f32>,
|
|
1074
|
-
uGlobalFrame:vec4<f32>,
|
|
1075
|
-
uOutputTexture:vec4<f32>,
|
|
1076
|
-
};
|
|
1077
|
-
|
|
1078
|
-
struct ColorMatrixUniforms {
|
|
1079
|
-
uColorMatrix:array<vec4<f32>, 5>,
|
|
1080
|
-
uAlpha:f32,
|
|
1081
|
-
};
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
|
|
1085
|
-
@group(0) @binding(1) var uTexture: texture_2d<f32>;
|
|
1086
|
-
@group(0) @binding(2) var uSampler : sampler;
|
|
1087
|
-
@group(1) @binding(0) var<uniform> colorMatrixUniforms : ColorMatrixUniforms;
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
struct VSOutput {
|
|
1091
|
-
@builtin(position) position: vec4<f32>,
|
|
1092
|
-
@location(0) uv : vec2<f32>,
|
|
1093
|
-
};
|
|
1094
|
-
|
|
1095
|
-
fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
|
|
1096
|
-
{
|
|
1097
|
-
var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
|
|
1098
|
-
|
|
1099
|
-
position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
|
|
1100
|
-
position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
|
|
1101
|
-
|
|
1102
|
-
return vec4(position, 0.0, 1.0);
|
|
1103
|
-
}
|
|
1104
|
-
|
|
1105
|
-
fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
|
|
1106
|
-
{
|
|
1107
|
-
return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
@vertex
|
|
1111
|
-
fn mainVertex(
|
|
1112
|
-
@location(0) aPosition : vec2<f32>,
|
|
1113
|
-
) -> VSOutput {
|
|
1114
|
-
return VSOutput(
|
|
1115
|
-
filterVertexPosition(aPosition),
|
|
1116
|
-
filterTextureCoord(aPosition),
|
|
1117
|
-
);
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
@fragment
|
|
1122
|
-
fn mainFragment(
|
|
1123
|
-
@location(0) uv: vec2<f32>,
|
|
1124
|
-
) -> @location(0) vec4<f32> {
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
var c = textureSample(uTexture, uSampler, uv);
|
|
1128
|
-
|
|
1129
|
-
if (colorMatrixUniforms.uAlpha == 0.0) {
|
|
1130
|
-
return c;
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
// Un-premultiply alpha before applying the color matrix. See issue #3539.
|
|
1135
|
-
if (c.a > 0.0) {
|
|
1136
|
-
c.r /= c.a;
|
|
1137
|
-
c.g /= c.a;
|
|
1138
|
-
c.b /= c.a;
|
|
1139
|
-
}
|
|
1140
|
-
|
|
1141
|
-
var cm = colorMatrixUniforms.uColorMatrix;
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
var result = vec4<f32>(0.);
|
|
1145
|
-
|
|
1146
|
-
result.r = (cm[0][0] * c.r);
|
|
1147
|
-
result.r += (cm[0][1] * c.g);
|
|
1148
|
-
result.r += (cm[0][2] * c.b);
|
|
1149
|
-
result.r += (cm[0][3] * c.a);
|
|
1150
|
-
result.r += cm[1][0];
|
|
1151
|
-
|
|
1152
|
-
result.g = (cm[1][1] * c.r);
|
|
1153
|
-
result.g += (cm[1][2] * c.g);
|
|
1154
|
-
result.g += (cm[1][3] * c.b);
|
|
1155
|
-
result.g += (cm[2][0] * c.a);
|
|
1156
|
-
result.g += cm[2][1];
|
|
1157
|
-
|
|
1158
|
-
result.b = (cm[2][2] * c.r);
|
|
1159
|
-
result.b += (cm[2][3] * c.g);
|
|
1160
|
-
result.b += (cm[3][0] * c.b);
|
|
1161
|
-
result.b += (cm[3][1] * c.a);
|
|
1162
|
-
result.b += cm[3][2];
|
|
1163
|
-
|
|
1164
|
-
result.a = (cm[3][3] * c.r);
|
|
1165
|
-
result.a += (cm[4][0] * c.g);
|
|
1166
|
-
result.a += (cm[4][1] * c.b);
|
|
1167
|
-
result.a += (cm[4][2] * c.a);
|
|
1168
|
-
result.a += cm[4][3];
|
|
1169
|
-
|
|
1170
|
-
var rgb = mix(c.rgb, result.rgb, colorMatrixUniforms.uAlpha);
|
|
1171
|
-
|
|
1172
|
-
rgb.r *= result.a;
|
|
1173
|
-
rgb.g *= result.a;
|
|
1174
|
-
rgb.b *= result.a;
|
|
1175
|
-
|
|
1176
|
-
return vec4(rgb, result.a);
|
|
1177
|
-
}`;Ri(),vd(),Vd(),tf(),vf(),bf();var Bk=class extends _f{constructor(e={}){let t=new ef({uColorMatrix:{value:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],type:`f32`,size:20},uAlpha:{value:1,type:`f32`}}),n=Bd.from({vertex:{source:zk,entryPoint:`mainVertex`},fragment:{source:zk,entryPoint:`mainFragment`}}),r=_d.from({vertex:yf,fragment:Rk,name:`color-matrix-filter`});super({...e,gpuProgram:n,glProgram:r,resources:{colorMatrixUniforms:t}}),this.alpha=1}_loadMatrix(e,t=!1){if(t){let t=[...e];this._multiply(t,this.matrix,e),this.resources.colorMatrixUniforms.uniforms.uColorMatrix=t}else this.resources.colorMatrixUniforms.uniforms.uColorMatrix=e;this.resources.colorMatrixUniforms.update()}_multiply(e,t,n){return e[0]=t[0]*n[0]+t[1]*n[5]+t[2]*n[10]+t[3]*n[15],e[1]=t[0]*n[1]+t[1]*n[6]+t[2]*n[11]+t[3]*n[16],e[2]=t[0]*n[2]+t[1]*n[7]+t[2]*n[12]+t[3]*n[17],e[3]=t[0]*n[3]+t[1]*n[8]+t[2]*n[13]+t[3]*n[18],e[4]=t[0]*n[4]+t[1]*n[9]+t[2]*n[14]+t[3]*n[19]+t[4],e[5]=t[5]*n[0]+t[6]*n[5]+t[7]*n[10]+t[8]*n[15],e[6]=t[5]*n[1]+t[6]*n[6]+t[7]*n[11]+t[8]*n[16],e[7]=t[5]*n[2]+t[6]*n[7]+t[7]*n[12]+t[8]*n[17],e[8]=t[5]*n[3]+t[6]*n[8]+t[7]*n[13]+t[8]*n[18],e[9]=t[5]*n[4]+t[6]*n[9]+t[7]*n[14]+t[8]*n[19]+t[9],e[10]=t[10]*n[0]+t[11]*n[5]+t[12]*n[10]+t[13]*n[15],e[11]=t[10]*n[1]+t[11]*n[6]+t[12]*n[11]+t[13]*n[16],e[12]=t[10]*n[2]+t[11]*n[7]+t[12]*n[12]+t[13]*n[17],e[13]=t[10]*n[3]+t[11]*n[8]+t[12]*n[13]+t[13]*n[18],e[14]=t[10]*n[4]+t[11]*n[9]+t[12]*n[14]+t[13]*n[19]+t[14],e[15]=t[15]*n[0]+t[16]*n[5]+t[17]*n[10]+t[18]*n[15],e[16]=t[15]*n[1]+t[16]*n[6]+t[17]*n[11]+t[18]*n[16],e[17]=t[15]*n[2]+t[16]*n[7]+t[17]*n[12]+t[18]*n[17],e[18]=t[15]*n[3]+t[16]*n[8]+t[17]*n[13]+t[18]*n[18],e[19]=t[15]*n[4]+t[16]*n[9]+t[17]*n[14]+t[18]*n[19]+t[19],e}brightness(e,t){let n=[e,0,0,0,0,0,e,0,0,0,0,0,e,0,0,0,0,0,1,0];this._loadMatrix(n,t)}tint(e,t){let[n,r,i]=Li.shared.setValue(e).toArray(),a=[n,0,0,0,0,0,r,0,0,0,0,0,i,0,0,0,0,0,1,0];this._loadMatrix(a,t)}greyscale(e,t){let n=[e,e,e,0,0,e,e,e,0,0,e,e,e,0,0,0,0,0,1,0];this._loadMatrix(n,t)}grayscale(e,t){this.greyscale(e,t)}blackAndWhite(e){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],e)}hue(e,t){e=(e||0)/180*Math.PI;let n=Math.cos(e),r=Math.sin(e),i=Math.sqrt,a=1/3,o=i(a),s=[n+(1-n)*a,a*(1-n)-o*r,a*(1-n)+o*r,0,0,a*(1-n)+o*r,n+a*(1-n),a*(1-n)-o*r,0,0,a*(1-n)-o*r,a*(1-n)+o*r,n+a*(1-n),0,0,0,0,0,1,0];this._loadMatrix(s,t)}contrast(e,t){let n=(e||0)+1,r=-.5*(n-1),i=[n,0,0,0,r,0,n,0,0,r,0,0,n,0,r,0,0,0,1,0];this._loadMatrix(i,t)}saturate(e=0,t){let n=e*2/3+1,r=(n-1)*-.5,i=[n,r,r,0,0,r,n,r,0,0,r,r,n,0,0,0,0,0,1,0];this._loadMatrix(i,t)}desaturate(){this.saturate(-1)}negative(e){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],e)}sepia(e){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],e)}technicolor(e){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,.046249425232852304,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-.2758903984886823,-.231103377548616,-.7501899197440212,1.847597816108189,0,.12137623870388682,0,0,0,1,0],e)}polaroid(e){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],e)}toBGR(e){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],e)}kodachrome(e){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,.24991995145868634,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,.09698983488904393,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,.13972481597886063,0,0,0,1,0],e)}browni(e){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,.1860075629647401,-.037703249837783157,.8609577587992641,.15059552388459913,0,-.14497417640467167,.24113635128153335,-.07441037908422492,.44972182064877153,0,-.029655197167024642,0,0,0,1,0],e)}vintage(e){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,.037848179746251466,.02578397704808868,.6441188644374771,.03259127616149294,0,.029265996770472907,.0466055556782719,-.0851232987247891,.5241648018700465,0,.020232119953863904,0,0,0,1,0],e)}colorTone(e,t,n,r,i){e||=.2,t||=.15,n||=16770432,r||=3375104;let a=Li.shared,[o,s,c]=a.setValue(n).toArray(),[l,u,d]=a.setValue(r).toArray(),f=[.3,.59,.11,0,0,o,s,c,e,0,l,u,d,t,0,o-l,s-u,c-d,0,0];this._loadMatrix(f,i)}night(e,t){e||=.1;let n=[e*-2,-e,0,0,0,-e,0,e,0,0,0,e,e*2,0,0,0,0,0,1,0];this._loadMatrix(n,t)}predator(e,t){let n=[11.224130630493164*e,-4.794486999511719*e,-2.8746118545532227*e,0*e,.40342438220977783*e,-3.6330697536468506*e,9.193157196044922*e,-2.951810836791992*e,0*e,-1.316135048866272*e,-3.2184197902679443*e,-4.2375030517578125*e,7.476448059082031*e,0*e,.8044459223747253*e,0,0,0,1,0];this._loadMatrix(n,t)}lsd(e){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],e)}reset(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)}get matrix(){return this.resources.colorMatrixUniforms.uniforms.uColorMatrix}set matrix(e){this.resources.colorMatrixUniforms.uniforms.uColorMatrix=e}get alpha(){return this.resources.colorMatrixUniforms.uniforms.uAlpha}set alpha(e){this.resources.colorMatrixUniforms.uniforms.uAlpha=e}};vu(),Af(),Of(),Lf(),oa();var Vk=class e extends If{constructor(...t){let n=t[0]??{};n instanceof Float32Array&&(H(V,`use new MeshGeometry({ positions, uvs, indices }) instead`),n={positions:n,uvs:t[1],indices:t[2]}),n={...e.defaultOptions,...n};let r=n.positions||new Float32Array([0,0,1,0,1,1,0,1]),i=n.uvs;i||=n.positions?new Float32Array(r.length):new Float32Array([0,0,1,0,1,1,0,1]);let a=n.indices||new Uint32Array([0,1,2,0,2,3]),o=n.shrinkBuffersToFit,s=new kf({data:r,label:`attribute-mesh-positions`,shrinkToFit:o,usage:Df.VERTEX|Df.COPY_DST}),c=new kf({data:i,label:`attribute-mesh-uvs`,shrinkToFit:o,usage:Df.VERTEX|Df.COPY_DST}),l=new kf({data:a,label:`index-mesh-buffer`,shrinkToFit:o,usage:Df.INDEX|Df.COPY_DST});super({attributes:{aPosition:{buffer:s,format:`float32x2`,stride:8,offset:0},aUV:{buffer:c,format:`float32x2`,stride:8,offset:0}},indexBuffer:l,topology:n.topology}),this.batchMode=`auto`}get positions(){return this.attributes.aPosition.buffer.data}set positions(e){this.attributes.aPosition.buffer.data=e}get uvs(){return this.attributes.aUV.buffer.data}set uvs(e){this.attributes.aUV.buffer.data=e}get indices(){return this.indexBuffer.data}set indices(e){this.indexBuffer.data=e}};Vk.defaultOptions={topology:`triangle-list`,shrinkBuffersToFit:!1};var Hk=Vk,Uk=class{constructor(){this.batcherName=`default`,this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(e){this._topology=e}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(e){this.texture!==e&&(this.texture=e,this._textureMatrixUpdateId=-1)}get uvs(){let e=this.geometry.getBuffer(`aUV`),t=e.data,n=t,r=this.texture.textureMatrix;return r.isSimple||(n=this._transformedUvs,(this._textureMatrixUpdateId!==r._updateID||this._uvUpdateId!==e._updateID)&&((!n||n.length<t.length)&&(n=this._transformedUvs=new Float32Array(t.length)),this._textureMatrixUpdateId=r._updateID,this._uvUpdateId=e._updateID,r.multiplyUvs(t,n))),n}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}};R(),B(),Ud(),tf(),cg(),k_();var Wk=class{destroy(){}},Gk=class{constructor(e,t){this.localUniforms=new ef({uTransformMatrix:{value:new z,type:`mat3x3<f32>`},uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uRound:{value:0,type:`f32`}}),this.localUniformsBindGroup=new Hd({0:this.localUniforms}),this.renderer=e,this._adaptor=t,this._adaptor.init()}validateRenderable(e){let t=this._getMeshData(e),n=t.batched,r=e.batched;if(t.batched=r,n!==r)return!0;if(r){let n=e._geometry;if(n.indices.length!==t.indexSize||n.positions.length!==t.vertexSize)return t.indexSize=n.indices.length,t.vertexSize=n.positions.length,!0;let r=this._getBatchableMesh(e);return r.texture.uid!==e._texture.uid&&(r._textureMatrixUpdateId=-1),!r._batcher.checkAndUpdateTexture(r,e._texture)}return!1}addRenderable(e,t){let n=this.renderer.renderPipes.batch,r=this._getMeshData(e);if(e.didViewUpdate&&(r.indexSize=e._geometry.indices?.length,r.vertexSize=e._geometry.positions?.length),r.batched){let r=this._getBatchableMesh(e);r.setTexture(e._texture),r.geometry=e._geometry,n.addToBatch(r,t)}else n.break(t),t.add(e)}updateRenderable(e){if(e.batched){let t=this._getBatchableMesh(e);t.setTexture(e._texture),t.geometry=e._geometry,t._batcher.updateElement(t)}}execute(e){if(!e.isRenderable)return;e.state.blend&&(e.state.blendMode=sg(e.groupBlendMode,e.texture._source));let t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),O_(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){var t,n;return(t=e._gpuData)[n=this.renderer.uid]||(t[n]=new Wk),e._gpuData[this.renderer.uid].meshData||this._initMeshData(e)}_initMeshData(e){return e._gpuData[this.renderer.uid].meshData={batched:e.batched,indexSize:0,vertexSize:0},e._gpuData[this.renderer.uid].meshData}_getBatchableMesh(e){var t,n;return(t=e._gpuData)[n=this.renderer.uid]||(t[n]=new Wk),e._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(e)}_initBatchableMesh(e){let t=new Uk;return t.renderable=e,t.setTexture(e._texture),t.transform=e.groupTransform,t.roundPixels=this.renderer._roundPixels|e._roundPixels,e._gpuData[this.renderer.uid].batchableMesh=t,t}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}};Gk.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`mesh`},R(),L.add(Gk),Lf(),hf(),$o(),oa(),yc();var Kk=class extends vc{constructor(...e){let t=e[0];t instanceof If&&(H(V,`Mesh: use new Mesh({ geometry, shader }) instead`),t={geometry:t,shader:e[1]},e[3]&&(H(V,`Mesh: drawMode argument has been removed, use geometry.topology instead`),t.geometry.topology=e[3]));let{geometry:n,shader:r,texture:i,roundPixels:a,state:o,...s}=t;super({label:`Mesh`,...s}),this.renderPipeId=`mesh`,this._shader=null,this.allowChildren=!1,this.shader=r??null,this.texture=i??r?.texture??q.WHITE,this.state=o??mf.for2d(),this._geometry=n,this._geometry.on(`update`,this.onViewUpdate,this),this.roundPixels=a??!1}get material(){return H(V,`mesh.material property has been removed, use mesh.shader instead`),this._shader}set shader(e){this._shader!==e&&(this._shader=e,this.onViewUpdate())}get shader(){return this._shader}set geometry(e){this._geometry!==e&&(this._geometry?.off(`update`,this.onViewUpdate,this),e.on(`update`,this.onViewUpdate,this),this._geometry=e,this.onViewUpdate())}get geometry(){return this._geometry}set texture(e){e||=q.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this.shader&&(this.shader.texture=e),this._texture=e,this.onViewUpdate())}get texture(){return this._texture}get batched(){return this._shader||this.state.data&12?!1:this._geometry instanceof Hk?this._geometry.batchMode===`auto`?this._geometry.positions.length/2<=100:this._geometry.batchMode===`batch`:!1}get bounds(){return this._geometry.bounds}updateBounds(){this._bounds=this._geometry.bounds}containsPoint(e){let{x:t,y:n}=e;if(!this.bounds.containsPoint(t,n))return!1;let r=this.geometry.getBuffer(`aPosition`).data,i=this.geometry.topology===`triangle-strip`?3:1;if(this.geometry.getIndex()){let e=this.geometry.getIndex().data,a=e.length;for(let o=0;o+2<a;o+=i){let i=e[o]*2,a=e[o+1]*2,s=e[o+2]*2;if(_u(t,n,r[i],r[i+1],r[a],r[a+1],r[s],r[s+1]))return!0}}else{let e=r.length/2;for(let a=0;a+2<e;a+=i){let e=a*2,i=(a+1)*2,o=(a+2)*2;if(_u(t,n,r[e],r[e+1],r[i],r[i+1],r[o],r[o+1]))return!0}}return!1}destroy(e){if(super.destroy(e),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._geometry?.off(`update`,this.onViewUpdate,this),this._texture=null,this._geometry=null,this._shader=null}};B(),Zi();var qk=class{constructor({matrix:e,observer:t}={}){this.dirty=!0,this._matrix=e??new z,this.observer=t,this.position=new Xi(this,0,0),this.scale=new Xi(this,1,1),this.pivot=new Xi(this,0,0),this.skew=new Xi(this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1}get matrix(){let e=this._matrix;return this.dirty&&=(e.a=this._cx*this.scale.x,e.b=this._sx*this.scale.x,e.c=this._cy*this.scale.y,e.d=this._sy*this.scale.y,e.tx=this.position.x-(this.pivot.x*e.a+this.pivot.y*e.c),e.ty=this.position.y-(this.pivot.x*e.b+this.pivot.y*e.d),!1),e}_onUpdate(e){this.dirty=!0,e===this.skew&&this.updateSkew(),this.observer?._onUpdate(this)}updateSkew(){this._cx=Math.cos(this._rotation+this.skew.y),this._sx=Math.sin(this._rotation+this.skew.y),this._cy=-Math.sin(this._rotation-this.skew.x),this._sy=Math.cos(this._rotation-this.skew.x),this.dirty=!0}toString(){return`[pixi.js/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`}setFromMatrix(e){e.decompose(this),this.dirty=!0}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this.skew))}};R(),B(),qi(),su(),to(),Ya();var Jk=new z,Yk=new z,Xk=[new Gi,new Gi,new Gi,new Gi],Zk=class{constructor(e){this._renderer=e}validateRenderable(e){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){let t=this._renderer,n=t.canvasContext,r=n.activeContext;r.save(),n.setBlendMode(e.groupBlendMode);let i=t.globalUniforms.globalUniformData?.worldColor??4294967295,a=e.groupColorAlpha,o=(i>>>24&255)/255,s=(a>>>24&255)/255,c=t.filter?.alphaMultiplier??1,l=o*s*c;if(l<=0){r.restore();return}r.globalAlpha=l;let u=i&16777215,d=$a(Ja(a&16777215,u)),f=e.texture,p=X.getTintedPattern(f,d),m=e.width,h=e.height,g=e.groupTransform,_=f.source._resolution??f.source.resolution??1;Yk.copyFrom(e._tileTransform.matrix),e.applyAnchorToTexture||Yk.translate(-e.anchor.x*m,-e.anchor.y*h);let v=Yk.tx,y=Yk.ty;Yk.scale(1/_,1/_),Yk.tx=v,Yk.ty=y,Jk.identity(),Jk.prepend(Yk),Jk.prepend(g);let b=t._roundPixels|e._roundPixels;n.setContextTransform(Jk,b===1),r.fillStyle=p;let x=e.anchor.x*-m,S=e.anchor.y*-h;Xk[0].set(x,S),Xk[1].set(x+m,S),Xk[2].set(x+m,S+h),Xk[3].set(x,S+h);for(let e=0;e<4;e++)Yk.applyInverse(Xk[e],Xk[e]);r.beginPath(),r.moveTo(Xk[0].x,Xk[0].y);for(let e=1;e<4;e++)r.lineTo(Xk[e].x,Xk[e].y);r.closePath(),r.fill(),r.restore()}destroy(){this._renderer=null}};Zk.extension={type:[I.CanvasPipes],name:`tilingSprite`};var Qk={name:`tiling-bit`,vertex:{header:`
|
|
1178
|
-
struct TilingUniforms {
|
|
1179
|
-
uMapCoord:mat3x3<f32>,
|
|
1180
|
-
uClampFrame:vec4<f32>,
|
|
1181
|
-
uClampOffset:vec2<f32>,
|
|
1182
|
-
uTextureTransform:mat3x3<f32>,
|
|
1183
|
-
uSizeAnchor:vec4<f32>
|
|
1184
|
-
};
|
|
1185
|
-
|
|
1186
|
-
@group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
|
|
1187
|
-
@group(2) @binding(1) var uTexture: texture_2d<f32>;
|
|
1188
|
-
@group(2) @binding(2) var uSampler: sampler;
|
|
1189
|
-
`,main:`
|
|
1190
|
-
uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy;
|
|
1191
|
-
|
|
1192
|
-
position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy;
|
|
1193
|
-
`},fragment:{header:`
|
|
1194
|
-
struct TilingUniforms {
|
|
1195
|
-
uMapCoord:mat3x3<f32>,
|
|
1196
|
-
uClampFrame:vec4<f32>,
|
|
1197
|
-
uClampOffset:vec2<f32>,
|
|
1198
|
-
uTextureTransform:mat3x3<f32>,
|
|
1199
|
-
uSizeAnchor:vec4<f32>
|
|
1200
|
-
};
|
|
1201
|
-
|
|
1202
|
-
@group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
|
|
1203
|
-
@group(2) @binding(1) var uTexture: texture_2d<f32>;
|
|
1204
|
-
@group(2) @binding(2) var uSampler: sampler;
|
|
1205
|
-
`,main:`
|
|
1206
|
-
|
|
1207
|
-
var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV);
|
|
1208
|
-
coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy;
|
|
1209
|
-
var unclamped = coord;
|
|
1210
|
-
coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw);
|
|
1211
|
-
|
|
1212
|
-
var bias = 0.;
|
|
1213
|
-
|
|
1214
|
-
if(unclamped.x == coord.x && unclamped.y == coord.y)
|
|
1215
|
-
{
|
|
1216
|
-
bias = -32.;
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
outColor = textureSampleBias(uTexture, uSampler, coord, bias);
|
|
1220
|
-
`}},$k={name:`tiling-bit`,vertex:{header:`
|
|
1221
|
-
uniform mat3 uTextureTransform;
|
|
1222
|
-
uniform vec4 uSizeAnchor;
|
|
1223
|
-
|
|
1224
|
-
`,main:`
|
|
1225
|
-
uv = (uTextureTransform * vec3(aUV, 1.0)).xy;
|
|
1226
|
-
|
|
1227
|
-
position = (position - uSizeAnchor.zw) * uSizeAnchor.xy;
|
|
1228
|
-
`},fragment:{header:`
|
|
1229
|
-
uniform sampler2D uTexture;
|
|
1230
|
-
uniform mat3 uMapCoord;
|
|
1231
|
-
uniform vec4 uClampFrame;
|
|
1232
|
-
uniform vec2 uClampOffset;
|
|
1233
|
-
`,main:`
|
|
1234
|
-
|
|
1235
|
-
vec2 coord = vUV + ceil(uClampOffset - vUV);
|
|
1236
|
-
coord = (uMapCoord * vec3(coord, 1.0)).xy;
|
|
1237
|
-
vec2 unclamped = coord;
|
|
1238
|
-
coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);
|
|
1239
|
-
|
|
1240
|
-
outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
|
|
1241
|
-
|
|
1242
|
-
`}};B(),Xm(),dh(),mh(),rf(),tf(),$o();var eA,tA,nA=class extends nf{constructor(){eA??=Jm({name:`tiling-sprite-shader`,bits:[ch,Qk,fh]}),tA??=Ym({name:`tiling-sprite-shader`,bits:[uh,$k,ph]});let e=new ef({uMapCoord:{value:new z,type:`mat3x3<f32>`},uClampFrame:{value:new Float32Array([0,0,1,1]),type:`vec4<f32>`},uClampOffset:{value:new Float32Array([0,0]),type:`vec2<f32>`},uTextureTransform:{value:new z,type:`mat3x3<f32>`},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:`vec4<f32>`}});super({glProgram:tA,gpuProgram:eA,resources:{localUniforms:new ef({uTransformMatrix:{value:new z,type:`mat3x3<f32>`},uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uRound:{value:0,type:`f32`}}),tilingUniforms:e,uTexture:q.EMPTY.source,uSampler:q.EMPTY.source.style}})}updateUniforms(e,t,n,r,i,a){let o=this.resources.tilingUniforms,s=a.width,c=a.height,l=a.textureMatrix,u=o.uniforms.uTextureTransform;u.set(n.a*s/e,n.b*s/t,n.c*c/e,n.d*c/t,n.tx/e,n.ty/t),u.invert(),o.uniforms.uMapCoord=l.mapCoord,o.uniforms.uClampFrame=l.uClampFrame,o.uniforms.uClampOffset=l.uClampOffset,o.uniforms.uTextureTransform=u,o.uniforms.uSizeAnchor[0]=e,o.uniforms.uSizeAnchor[1]=t,o.uniforms.uSizeAnchor[2]=r,o.uniforms.uSizeAnchor[3]=i,a&&(this.resources.uTexture=a.source,this.resources.uSampler=a.source.style)}},rA=class extends Hk{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}};function iA(e,t){let n=e.anchor.x,r=e.anchor.y;t[0]=-n*e.width,t[1]=-r*e.height,t[2]=(1-n)*e.width,t[3]=-r*e.height,t[4]=(1-n)*e.width,t[5]=(1-r)*e.height,t[6]=-n*e.width,t[7]=(1-r)*e.height}function aA(e,t,n,r){let i=0,a=e.length/(t||2),o=r.a,s=r.b,c=r.c,l=r.d,u=r.tx,d=r.ty;for(n*=t;i<a;){let r=e[n],a=e[n+1];e[n]=o*r+c*a+u,e[n+1]=s*r+l*a+d,n+=t,i++}}B();function oA(e,t){let n=e.texture,r=n.frame.width,i=n.frame.height,a=0,o=0;e.applyAnchorToTexture&&(a=e.anchor.x,o=e.anchor.y),t[0]=t[6]=-a,t[2]=t[4]=1-a,t[1]=t[3]=-o,t[5]=t[7]=1-o;let s=e._tileTransform.matrix,c=z.shared;c.set(s.a*r/e.width,s.b*r/e.height,s.c*i/e.width,s.d*i/e.height,s.tx/e.width,s.ty/e.height),c.invert(),aA(t,2,0,c)}R(),cg(),hf(),Gd(),cv(),k_();var sA=new rA,cA=class{constructor(){this.canBatch=!0,this.geometry=new Hk({indices:sA.indices.slice(),positions:sA.positions.slice(),uvs:sA.uvs.slice()})}destroy(){this.geometry.destroy(),this.shader?.destroy()}},lA=class{constructor(e){this._state=mf.default2d,this._renderer=e,this._managedTilingSprites=new sv({renderer:e,type:`renderable`,name:`tilingSprite`})}validateRenderable(e){let t=this._getTilingSpriteData(e),n=t.canBatch;this._updateCanBatch(e);let r=t.canBatch;if(r&&r===n){let{batchableMesh:n}=t;return!n._batcher.checkAndUpdateTexture(n,e.texture)}return n!==r}addRenderable(e,t){let n=this._renderer.renderPipes.batch;this._updateCanBatch(e);let r=this._getTilingSpriteData(e),{geometry:i,canBatch:a}=r;if(a){r.batchableMesh||=new Uk;let a=r.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),a.geometry=i,a.renderable=e,a.transform=e.groupTransform,a.setTexture(e._texture)),a.roundPixels=this._renderer._roundPixels|e._roundPixels,n.addToBatch(a,t)}else n.break(t),r.shader||=new nA,this.updateRenderable(e),t.add(e)}execute(e){let t=this._renderer,{shader:n}=this._getTilingSpriteData(e);n.groups[0]=t.globalUniforms.bindGroup;let r=n.resources.localUniforms.uniforms;r.uTransformMatrix=e.groupTransform,r.uRound=t._roundPixels|e._roundPixels,O_(e.groupColorAlpha,r.uColor,0),this._state.blendMode=sg(e.groupBlendMode,e.texture._source),t.encoder.draw({geometry:sA,shader:n,state:this._state})}updateRenderable(e){let t=this._getTilingSpriteData(e),{canBatch:n}=t;if(n){let{batchableMesh:n}=t;e.didViewUpdate&&this._updateBatchableMesh(e),n._batcher.updateElement(n)}else if(e.didViewUpdate){let{shader:n}=t;n.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}_getTilingSpriteData(e){return e._gpuData[this._renderer.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){let t=new cA;return t.renderable=e,e._gpuData[this._renderer.uid]=t,this._managedTilingSprites.add(e),t}_updateBatchableMesh(e){let{geometry:t}=this._getTilingSpriteData(e),n=e.texture.source.style;n.addressMode!==`repeat`&&(n.addressMode=`repeat`,n.update()),oA(e,t.uvs),iA(e,t.positions)}destroy(){this._managedTilingSprites.destroy(),this._renderer=null}_updateCanBatch(e){let t=this._getTilingSpriteData(e),n=e.texture,r=!0;return this._renderer.type===Wd.WEBGL&&(r=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=n.textureMatrix.isSimple&&(r||n.source.isPowerOfTwo),t.canBatch}};lA.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`tilingSprite`},R(),L.add(Zk),L.add(lA),Xl(),Zi(),$o(),oa(),yc();var uA=class e extends vc{constructor(...t){let n=t[0]||{};n instanceof q&&(n={texture:n}),t.length>1&&(H(V,`use new TilingSprite({ texture, width:100, height:100 }) instead`),n.width=t[1],n.height=t[2]),n={...e.defaultOptions,...n};let{texture:r,anchor:i,tilePosition:a,tileScale:o,tileRotation:s,width:c,height:l,applyAnchorToTexture:u,roundPixels:d,...f}=n??{};super({label:`TilingSprite`,...f}),this.renderPipeId=`tilingSprite`,this.batched=!0,this.allowChildren=!1,this._anchor=new Xi({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=u,this.texture=r,this._width=c??r.width,this._height=l??r.height,this._tileTransform=new qk({observer:{_onUpdate:()=>this.onViewUpdate()}}),i&&(this.anchor=i),this.tilePosition=a,this.tileScale=o,this.tileRotation=s,this.roundPixels=d??!1}static from(t,n={}){return typeof t==`string`?new e({texture:Yl.get(t),...n}):new e({texture:t,...n})}get uvRespectAnchor(){return H(V,`uvRespectAnchor is deprecated, please use applyAnchorToTexture instead`),this.applyAnchorToTexture}set uvRespectAnchor(e){H(V,`uvRespectAnchor is deprecated, please use applyAnchorToTexture instead`),this.applyAnchorToTexture=e}get clampMargin(){return this._texture.textureMatrix.clampMargin}set clampMargin(e){this._texture.textureMatrix.clampMargin=e}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get tilePosition(){return this._tileTransform.position}set tilePosition(e){this._tileTransform.position.copyFrom(e)}get tileScale(){return this._tileTransform.scale}set tileScale(e){typeof e==`number`?this._tileTransform.scale.set(e):this._tileTransform.scale.copyFrom(e)}set tileRotation(e){this._tileTransform.rotation=e}get tileRotation(){return this._tileTransform.rotation}get tileTransform(){return this._tileTransform}set texture(e){e||=q.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get texture(){return this._texture}set width(e){this._width=e,this.onViewUpdate()}get width(){return this._width}set height(e){this._height=e,this.onViewUpdate()}get height(){return this._height}setSize(e,t){typeof e==`object`&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||={},e.width=this._width,e.height=this._height,e}updateBounds(){let e=this._bounds,t=this._anchor,n=this._width,r=this._height;e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}containsPoint(e){let t=this._width,n=this._height,r=-t*this._anchor._x,i=0;return e.x>=r&&e.x<=r+t&&(i=-n*this._anchor._y,e.y>=i&&e.y<=i+n)}destroy(e=!1){if(super.destroy(e),this._anchor=null,this._tileTransform=null,this._bounds=null,typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null}};uA.defaultOptions={texture:q.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1};var dA=uA;Zi(),oa(),yc();var fA=class extends vc{constructor(e,t){let{text:n,resolution:r,style:i,anchor:a,width:o,height:s,roundPixels:c,...l}=e;super({...l}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=n??``,this.style=i,this.resolution=r??null,this.allowChildren=!1,this._anchor=new Xi({_onUpdate:()=>{this.onViewUpdate()}}),a&&(this.anchor=a),this.roundPixels=c??!1,o!==void 0&&(this.width=o),s!==void 0&&(this.height=s)}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||={},this._style?.off(`update`,this.onViewUpdate,this),this._style=e instanceof this._styleClass?e:new this._styleClass(e),this._style.on(`update`,this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||={},e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e==`object`?(t=e.height??e.width,e=e.width):t??=e,e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){let t=this.bounds.width,n=this.bounds.height,r=-t*this.anchor.x,i=0;return e.x>=r&&e.x<=r+t&&(i=-n*this.anchor.y,e.y>=i&&e.y<=i+n)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){this._style?.off(`update`,this.onViewUpdate,this),super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e==`boolean`?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}};function pA(e,t){let n=e[0]??{};return(typeof n==`string`||e[1])&&(H(V,`use new ${t}({ text: "hi!", style }) instead`),n={text:n,style:e[1]}),n}Jc(),So(),Pa();var mA=null,hA=null;function gA(e,t){mA||(mA=Y.get().createCanvas(256,128),hA=mA.getContext(`2d`,{willReadFrequently:!0}),hA.globalCompositeOperation=`copy`,hA.globalAlpha=1),(mA.width<e||mA.height<t)&&(mA.width=bo(e),mA.height=bo(t))}function _A(e,t,n){for(let r=0,i=4*n*t;r<t;++r,i+=4)if(e[i+3]!==0)return!1;return!0}function vA(e,t,n,r,i){let a=4*t;for(let t=r,o=r*a+4*n;t<=i;++t,o+=a)if(e[o+3]!==0)return!1;return!0}function yA(...e){let t=e[0];t.canvas||(t={canvas:e[0],resolution:e[1]});let{canvas:n}=t,r=Math.min(t.resolution??1,1),i=t.width??n.width,a=t.height??n.height,o=t.output;if(gA(i,a),!hA)throw TypeError(`Failed to get canvas 2D context`);hA.drawImage(n,0,0,i,a,0,0,i*r,a*r);let s=hA.getImageData(0,0,i,a).data,c=0,l=0,u=i-1,d=a-1;for(;l<a&&_A(s,i,l);)++l;if(l===a)return G.EMPTY;for(;_A(s,i,d);)--d;for(;vA(s,i,c,l,d);)++c;for(;vA(s,i,u,l,d);)--u;return++u,++d,hA.globalCompositeOperation=`source-over`,hA.strokeRect(c,l,u-c,d-l),hA.globalCompositeOperation=`copy`,o??=new G,o.set(c/r,l/r,(u-c)/r,(d-l)/r),o}Ri(),Pa(),fu(),$D(),nO(),lO();var bA=new G;function xA(e){let t=0;for(let n=0;n<e.length;n++)e.charCodeAt(n)===32&&t++;return t}var SA=new class{getCanvasAndContext(e){let{text:t,style:n,resolution:r=1}=e,i=n._getFinalPadding(),a=QD.measureText(t||` `,n),o=Math.ceil(Math.ceil(Math.max(1,a.width)+i*2)*r),s=Math.ceil(Math.ceil(Math.max(1,a.height)+i*2)*r),c=du.getOptimalCanvasAndContext(o,s);return this._renderTextToCanvas(n,i,r,c,a),{canvasAndContext:c,frame:n.trim?yA({canvas:c.canvas,width:o,height:s,resolution:1,output:bA}):bA.set(0,0,o,s)}}returnCanvasAndContext(e){du.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,n,r,i){if(i.runsByLine&&i.runsByLine.length>0){this._renderTaggedTextToCanvas(i,e,t,n,r);return}let{canvas:a,context:o}=r,s=eO(e),c=i.lines,l=i.lineHeight,u=i.lineWidths,d=i.maxLineWidth,f=i.fontProperties,p=a.height;if(o.resetTransform(),o.scale(n,n),o.textBaseline=e.textBaseline,e._stroke?.width){let t=e._stroke;o.lineWidth=t.width,o.miterLimit=t.miterLimit,o.lineJoin=t.join,o.lineCap=t.cap}o.font=s;let m,h,g=e.dropShadow?2:1,_=(e._stroke?.width??0)/2,v=(l-f.fontSize)/2;l-f.fontSize<0&&(v=0);for(let a=0;a<g;++a){let s=e.dropShadow&&a===0,g=s?Math.ceil(Math.max(1,p)+t*2):0,y=g*n;if(s)this._setupDropShadow(o,e,n,y);else{let n=e._gradientBounds,r=e._gradientOffset;if(n){let a={width:n.width,height:n.height,lineHeight:n.height,lines:i.lines};this._setFillAndStrokeStyles(o,e,a,t,_,r?.x??0,r?.y??0)}else r?this._setFillAndStrokeStyles(o,e,i,t,_,r.x,r.y):this._setFillAndStrokeStyles(o,e,i,t,_);o.shadowColor=`rgba(0,0,0,0)`}for(let n=0;n<c.length;n++){m=_,h=_+n*l+f.ascent+v,m+=this._getAlignmentOffset(u[n],d,e.align);let i=0;if(e.align===`justify`&&e.wordWrap&&n<c.length-1){let e=xA(c[n]);e>0&&(i=(d-u[n])/e)}e._stroke?.width&&this._drawLetterSpacing(c[n],e,r,m+t,h+t-g,!0,i),e._fill!==void 0&&this._drawLetterSpacing(c[n],e,r,m+t,h+t-g,!1,i)}}}_renderTaggedTextToCanvas(e,t,n,r,i){let{canvas:a,context:o}=i,{runsByLine:s,lineWidths:c,maxLineWidth:l,lineAscents:u,lineHeights:d,hasDropShadow:f}=e,p=a.height;o.resetTransform(),o.scale(r,r),o.textBaseline=t.textBaseline;let m=f?2:1,h=t._stroke?.width??0;for(let e of s)for(let t of e){let e=t.style._stroke?.width??0;e>h&&(h=e)}let g=h/2,_=[];for(let e=0;e<s.length;e++){let t=s[e],n=[];for(let e of t){let t=eO(e.style);o.font=t,n.push({width:QD._measureText(e.text,e.style.letterSpacing,o),font:t})}_.push(n)}for(let e=0;e<m;++e){let a=f&&e===0,m=a?Math.ceil(Math.max(1,p)+n*2):0,h=m*r;a||(o.shadowColor=`rgba(0,0,0,0)`);let v=g;for(let e=0;e<s.length;e++){let f=s[e],p=c[e],y=u[e],b=d[e],x=_[e],S=g;S+=this._getAlignmentOffset(p,l,t.align);let C=0;if(t.align===`justify`&&t.wordWrap&&e<s.length-1){let e=0;for(let t of f)e+=xA(t.text);e>0&&(C=(l-p)/e)}let ee=v+y,w=S+n;for(let e=0;e<f.length;e++){let t=f[e],{width:s,font:c}=x[e];if(o.font=c,o.textBaseline=t.style.textBaseline,t.style._stroke?.width){let e=t.style._stroke;if(o.lineWidth=e.width,o.miterLimit=e.miterLimit,o.lineJoin=e.join,o.lineCap=e.cap,a){if(t.style.dropShadow)this._setupDropShadow(o,t.style,r,h);else{let e=xA(t.text);w+=s+e*C;continue}}else{let r=QD.measureFont(c),i=t.style.lineHeight||r.fontSize;o.strokeStyle=sO(e,o,{width:s,height:i,lineHeight:i,lines:[t.text]},n*2,w-n,v)}this._drawLetterSpacing(t.text,t.style,i,w,ee+n-m,!0,C)}let l=xA(t.text);w+=s+l*C}w=S+n;for(let e=0;e<f.length;e++){let t=f[e],{width:s,font:c}=x[e];if(o.font=c,o.textBaseline=t.style.textBaseline,t.style._fill!==void 0){if(a){if(t.style.dropShadow)this._setupDropShadow(o,t.style,r,h);else{let e=xA(t.text);w+=s+e*C;continue}}else{let e=QD.measureFont(c),r=t.style.lineHeight||e.fontSize,i={width:s,height:r,lineHeight:r,lines:[t.text]};o.fillStyle=sO(t.style._fill,o,i,n*2,w-n,v)}this._drawLetterSpacing(t.text,t.style,i,w,ee+n-m,!1,C)}let l=xA(t.text);w+=s+l*C}v+=b}}}_setFillAndStrokeStyles(e,t,n,r,i,a=0,o=0){if(e.fillStyle=t._fill?sO(t._fill,e,n,r*2,a,o):null,t._stroke?.width){let s=i+r*2;e.strokeStyle=sO(t._stroke,e,n,s,a,o)}}_setupDropShadow(e,t,n,r){e.fillStyle=`black`,e.strokeStyle=`black`;let i=t.dropShadow,a=i.color,o=i.alpha;e.shadowColor=Li.shared.setValue(a).setAlpha(o).toRgbaString();let s=i.blur*n,c=i.distance*n;e.shadowBlur=s,e.shadowOffsetX=Math.cos(i.angle)*c,e.shadowOffsetY=Math.sin(i.angle)*c+r}_getAlignmentOffset(e,t,n){return n===`right`?t-e:n===`center`?(t-e)/2:0}_drawLetterSpacing(e,t,n,r,i,a=!1,o=0){let{context:s}=n,c=t.letterSpacing,l=!1;if(QD.experimentalLetterSpacingSupported&&(QD.experimentalLetterSpacing?(s.letterSpacing=`${c}px`,s.textLetterSpacing=`${c}px`,l=!0):(s.letterSpacing=`0px`,s.textLetterSpacing=`0px`)),(c===0||l)&&o===0){a?s.strokeText(e,r,i):s.fillText(e,r,i);return}if(o!==0&&(c===0||l)){let t=e.split(` `),n=r,c=s.measureText(` `).width;for(let e=0;e<t.length;e++)a?s.strokeText(t[e],n,i):s.fillText(t[e],n,i),n+=s.measureText(t[e]).width+c+o;return}let u=r,d=QD.graphemeSegmenter(e),f=s.measureText(e).width,p=0;for(let e=0;e<d.length;++e){let t=d[e];a?s.strokeText(t,u,i):s.fillText(t,u,i);let n=``;for(let t=e+1;t<d.length;++t)n+=d[t];p=s.measureText(n).width,u+=f-p+c,t===` `&&(u+=o),f=p}}};ko(),W();var CA=!1;function wA(e){if(CA)return;let t=new Oo({scaleMode:e.scaleMode});e._resourceId!==t._resourceId&&(CA=!0,U(`Text textureStyle: only scaleMode is applied to a text texture, the other fields are ignored`))}Cl();function TA(e,t){let{texture:n,bounds:r}=e,i=t._style._getFinalPadding();Sl(r,t._anchor,n);let a=t._anchor._x*i*2,o=t._anchor._y*i*2;r.minX-=i-a,r.minY-=i-o,r.maxX-=i-a,r.maxY-=i-o}Oh();var EA=class extends Dh{};R(),cv();var DA=class{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),e.runners.contextChange.add(this),this._managedTexts=new sv({renderer:e,type:`renderable`,onUnload:this.onTextUnload.bind(this),name:`canvasText`})}resolutionChange(){for(let e in this._managedTexts.items){let t=this._managedTexts.items[e];t?._autoResolution&&t.onViewUpdate()}}contextChange(){for(let e in this._managedTexts.items)this._managedTexts.items[e]?.unload()}validateRenderable(e){let t=this._getGpuText(e),n=e.styleKey;return t.currentKey!==n||e._didTextUpdate}addRenderable(e,t){let n=this._getGpuText(e);if(e._didTextUpdate||n.currentKey!==e.styleKey){let t=e._autoResolution?this._renderer.resolution:e.resolution;(n.currentKey!==e.styleKey||e._resolution!==t)&&this._updateGpuText(e),e._didTextUpdate=!1,TA(n,e)}this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){let t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new EA;return t.currentKey=`--`,t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,this._managedTexts.add(e),t}onTextUnload(e){let t=e._gpuData[this._renderer.uid];if(!t)return;let{canvasText:n}=this._renderer;n.getReferenceCount(t.currentKey)>0?n.decreaseReferenceCount(t.currentKey):t.texture&&n.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}};DA.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`text`},fs(),oa(),oO(),Fu();var OA=class{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,n,r){typeof e==`string`&&(H(`8.0.0`,`CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments`),e={text:e,style:n,resolution:t}),e.style instanceof aO||(e.style=new aO(e.style)),typeof e.text!=`string`&&(e.text=e.text.toString());let{text:i,style:a,textureStyle:o,autoGenerateMipmaps:s}=e,c=e.resolution??this._renderer.resolution,{frame:l,canvasAndContext:u}=SA.getCanvasAndContext({text:i,style:a,resolution:c}),d=Nu(u.canvas,l.width,l.height,c,s,o?.scaleMode);if(a.trim&&(l.pad(a.padding),d.frame.copyFrom(l),d.frame.scale(1/c),d.updateUvs()),a.filters){let e=this._applyFilters(d,a.filters);return this.returnTexture(d),SA.returnCanvasAndContext(u),e}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||SA.returnCanvasAndContext(u),d}returnTexture(e){let t=e.source,n=t.resource;if(this._retainCanvasContext&&n?.getContext){let e=n.getContext(`2d`);e&&SA.returnCanvasAndContext({canvas:n,context:e})}t.resource=null,t.uploadMethodId=`unknown`,t.alphaMode=`no-premultiply-alpha`,ds.returnTexture(e)}renderTextToCanvas(){H(`8.10.0`,`CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead`)}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;let t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;let n=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle,autoGenerateMipmaps:e.autoGenerateMipmaps});return this._activeTextures[t]={texture:n,usageCount:1},n}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){let n=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind({target:n,clear:!1}),r}destroy(){this._renderer=null;for(let e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}};R();var kA=class extends OA{constructor(e){super(e,!0)}};kA.extension={type:[I.CanvasSystem],name:`canvasText`},R();var AA=class extends OA{constructor(e){super(e,!1)}};AA.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:`canvasText`},R(),L.add(kA),L.add(AA),L.add(DA),Po(),ko(),$D(),oO();var jA=class extends fA{constructor(...e){let t=pA(e,`Text`);super(t,aO),this.renderPipeId=`text`,t.textureStyle&&(this.textureStyle=t.textureStyle instanceof Oo?t.textureStyle:new Oo(t.textureStyle),wA(this.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??No.defaultOptions.autoGenerateMipmaps}updateBounds(){let e=this._bounds,t=this._anchor,n=0,r=0;if(this._style.trim){let{frame:e,canvasAndContext:t}=SA.getCanvasAndContext({text:this.text,style:this._style,resolution:1});SA.returnCanvasAndContext(t),n=e.width,r=e.height}else{let e=QD.measureText(this._text,this._style);n=e.width,r=e.height}e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}};Xl(),cv(),TE(),$D(),CO(),_O();var MA=class extends Z{destroy(){this.context.customShader&&this.context.customShader.destroy(),super.destroy()}},NA=class{constructor(e){this._renderer=e,this._managedBitmapTexts=new sv({renderer:e,type:`renderable`,priority:-2,name:`bitmapText`})}validateRenderable(e){let t=this._getGpuBitmapText(e);return this._renderer.renderPipes.graphics.validateRenderable(t)}addRenderable(e,t){let n=this._getGpuBitmapText(e);PA(e,n),e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,n)),this._renderer.renderPipes.graphics.addRenderable(n,t),n.context.customShader&&this._updateDistanceField(e)}updateRenderable(e){let t=this._getGpuBitmapText(e);PA(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){let{context:n}=t,r=SO.getFont(e.text,e._style);if(n.clear(),r.distanceField.type!==`none`){let e=this.getSdfShader();e&&(n.customShader||=e)}let i=QD.graphemeSegmenter(e.text),a=e._style,o=r.baseLineOffset,s=pO(i,a,r,!0),c=a.padding,l=s.scale,u=s.width,d=s.height+s.offsetY;a._stroke&&(u+=a._stroke.width/l,d+=a._stroke.width/l),n.translate(-e._anchor._x*u-c,-e._anchor._y*d-c).scale(l,l);let f=r.applyFillAsTint?a._fill.color:16777215,p=r.fontMetrics.fontSize,m=r.lineHeight;a.lineHeight&&(p=a.fontSize/l,m=a.lineHeight/l);let h=(m-p)/2;h-r.baseLineOffset<0&&(h=0);for(let e=0;e<s.lines.length;e++){let t=s.lines[e];for(let e=0;e<t.charPositions.length;e++){let i=t.chars[e],a=r.chars[i];if(a?.texture){let r=a.texture;n.texture(r,f,Math.round(t.charPositions[e]+a.xOffset),Math.round(o+a.yOffset+h),r.orig.width,r.orig.height)}}o+=m}}_getGpuBitmapText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new MA;return e._gpuData[this._renderer.uid]=t,this._updateContext(e,t),this._managedBitmapTexts.add(e),t}_updateDistanceField(e){let t=this._getGpuBitmapText(e).context,n=e._style.fontFamily,r=Yl.get(`${n}-bitmap`),{a:i,b:a,c:o,d:s}=e.groupTransform,c=Math.sqrt(i*i+a*a),l=Math.sqrt(o*o+s*s),u=(Math.abs(c)+Math.abs(l))/2,d=r.baseRenderedFontSize/e._style.fontSize,f=u*r.distanceField.range*(1/d);t.customShader.resources.localUniforms.uniforms.uDistance=f}destroy(){this._managedBitmapTexts.destroy(),this._renderer=null,this._managedBitmapTexts=null}};function PA(e,t){t.groupTransform=e.groupTransform,t.groupColorAlpha=e.groupColorAlpha,t.groupColor=e.groupColor,t.groupBlendMode=e.groupBlendMode,t.globalDisplayStatus=e.globalDisplayStatus,t.groupTransform=e.groupTransform,t.localDisplayStatus=e.localDisplayStatus,t.groupAlpha=e.groupAlpha,t._roundPixels=e._roundPixels}R();var FA=class extends NA{getSdfShader(){return null}};FA.extension={type:[I.CanvasPipes],name:`bitmapText`};var IA={name:`local-uniform-msdf-bit`,vertex:{header:`
|
|
1243
|
-
struct LocalUniforms {
|
|
1244
|
-
uColor:vec4<f32>,
|
|
1245
|
-
uTransformMatrix:mat3x3<f32>,
|
|
1246
|
-
uDistance: f32,
|
|
1247
|
-
uRound:f32,
|
|
1248
|
-
}
|
|
1249
|
-
|
|
1250
|
-
@group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
1251
|
-
`,main:`
|
|
1252
|
-
vColor *= localUniforms.uColor;
|
|
1253
|
-
modelMatrix *= localUniforms.uTransformMatrix;
|
|
1254
|
-
`,end:`
|
|
1255
|
-
if(localUniforms.uRound == 1)
|
|
1256
|
-
{
|
|
1257
|
-
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
1258
|
-
}
|
|
1259
|
-
`},fragment:{header:`
|
|
1260
|
-
struct LocalUniforms {
|
|
1261
|
-
uColor:vec4<f32>,
|
|
1262
|
-
uTransformMatrix:mat3x3<f32>,
|
|
1263
|
-
uDistance: f32
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
@group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
1267
|
-
`,main:`
|
|
1268
|
-
outColor = vec4<f32>(calculateMSDFAlpha(outColor, vColor, localUniforms.uDistance));
|
|
1269
|
-
`}},LA={name:`local-uniform-msdf-bit`,vertex:{header:`
|
|
1270
|
-
uniform mat3 uTransformMatrix;
|
|
1271
|
-
uniform vec4 uColor;
|
|
1272
|
-
uniform float uRound;
|
|
1273
|
-
`,main:`
|
|
1274
|
-
vColor *= uColor;
|
|
1275
|
-
modelMatrix *= uTransformMatrix;
|
|
1276
|
-
`,end:`
|
|
1277
|
-
if(uRound == 1.)
|
|
1278
|
-
{
|
|
1279
|
-
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
1280
|
-
}
|
|
1281
|
-
`},fragment:{header:`
|
|
1282
|
-
uniform float uDistance;
|
|
1283
|
-
`,main:`
|
|
1284
|
-
outColor = vec4(calculateMSDFAlpha(outColor, vColor, uDistance));
|
|
1285
|
-
`}},RA={name:`msdf-bit`,fragment:{header:`
|
|
1286
|
-
fn calculateMSDFAlpha(msdfColor:vec4<f32>, shapeColor:vec4<f32>, distance:f32) -> f32 {
|
|
1287
|
-
|
|
1288
|
-
// MSDF
|
|
1289
|
-
var median = msdfColor.r + msdfColor.g + msdfColor.b -
|
|
1290
|
-
min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
|
|
1291
|
-
max(msdfColor.r, max(msdfColor.g, msdfColor.b));
|
|
1292
|
-
|
|
1293
|
-
// SDF
|
|
1294
|
-
median = min(median, msdfColor.a);
|
|
1295
|
-
|
|
1296
|
-
var screenPxDistance = distance * (median - 0.5);
|
|
1297
|
-
var alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
|
|
1298
|
-
if (median < 0.01) {
|
|
1299
|
-
alpha = 0.0;
|
|
1300
|
-
} else if (median > 0.99) {
|
|
1301
|
-
alpha = 1.0;
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
// Gamma correction for coverage-like alpha
|
|
1305
|
-
var luma: f32 = dot(shapeColor.rgb, vec3<f32>(0.299, 0.587, 0.114));
|
|
1306
|
-
var gamma: f32 = mix(1.0, 1.0 / 2.2, luma);
|
|
1307
|
-
var coverage: f32 = pow(shapeColor.a * alpha, gamma);
|
|
1308
|
-
|
|
1309
|
-
return coverage;
|
|
1310
|
-
|
|
1311
|
-
}
|
|
1312
|
-
`}},zA={name:`msdf-bit`,fragment:{header:`
|
|
1313
|
-
float calculateMSDFAlpha(vec4 msdfColor, vec4 shapeColor, float distance) {
|
|
1314
|
-
|
|
1315
|
-
// MSDF
|
|
1316
|
-
float median = msdfColor.r + msdfColor.g + msdfColor.b -
|
|
1317
|
-
min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
|
|
1318
|
-
max(msdfColor.r, max(msdfColor.g, msdfColor.b));
|
|
1319
|
-
|
|
1320
|
-
// SDF
|
|
1321
|
-
median = min(median, msdfColor.a);
|
|
1322
|
-
|
|
1323
|
-
float screenPxDistance = distance * (median - 0.5);
|
|
1324
|
-
float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
|
|
1325
|
-
|
|
1326
|
-
if (median < 0.01) {
|
|
1327
|
-
alpha = 0.0;
|
|
1328
|
-
} else if (median > 0.99) {
|
|
1329
|
-
alpha = 1.0;
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
// Gamma correction for coverage-like alpha
|
|
1333
|
-
float luma = dot(shapeColor.rgb, vec3(0.299, 0.587, 0.114));
|
|
1334
|
-
float gamma = mix(1.0, 1.0 / 2.2, luma);
|
|
1335
|
-
float coverage = pow(shapeColor.a * alpha, gamma);
|
|
1336
|
-
|
|
1337
|
-
return coverage;
|
|
1338
|
-
}
|
|
1339
|
-
`}};B(),Xm(),$m(),sh(),mh(),Ng(),rf(),tf();var BA,VA,HA=class extends nf{constructor(e){let t=new ef({uColor:{value:new Float32Array([1,1,1,1]),type:`vec4<f32>`},uTransformMatrix:{value:new z,type:`mat3x3<f32>`},uDistance:{value:4,type:`f32`},uRound:{value:0,type:`f32`}});BA??=Jm({name:`sdf-shader`,bits:[Zm,nh(e),IA,RA,fh]}),VA??=Ym({name:`sdf-shader`,bits:[Qm,ih(e),LA,zA,ph]}),super({glProgram:VA,gpuProgram:BA,resources:{localUniforms:t,batchSamplers:jg(e)}})}};R();var UA=class extends NA{getSdfShader(){return new HA(this._renderer.limits.maxBatchableTextures)}};UA.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`bitmapText`},R(),L.add(FA),L.add(UA),W(),oO(),CO();var WA=class extends fA{constructor(...e){var t;let n=pA(e,`BitmapText`);n.style??=n.style||{},(t=n.style).fill??(t.fill=16777215),super(n,aO),this.renderPipeId=`bitmapText`}_onTouch(e){this._gcLastUsed=e;for(let t in this._gpuData)this._gpuData[t]?._onTouch(e)}updateBounds(){let e=this._bounds,t=this._anchor,n=SO.measureText(this.text,this._style),r=n.scale,i=n.offsetY*r,a=n.width*r,o=n.height*r,s=this._style._stroke;s&&(a+=s.width,o+=s.width),e.minX=-t._x*a,e.maxX=e.minX+a,e.minY=-t._y*(o+i),e.maxY=e.minY+o}set resolution(e){e!==null&&U(`[BitmapText] dynamically updating the resolution is not supported. Resolution should be managed by the BitmapFont.`)}get resolution(){return this._resolution}};Ri(),oO();function GA(e){let t=e._stroke,n=e._fill,r=[`div { ${[`color: ${Li.shared.setValue(n.color).setAlpha(n.alpha??1).toHexa()}`,`font-size: ${e.fontSize}px`,`font-family: ${e.fontFamily}`,`font-weight: ${e.fontWeight}`,`font-style: ${e.fontStyle}`,`font-variant: ${e.fontVariant}`,`letter-spacing: ${e.letterSpacing}px`,`text-align: ${e.align}`,`padding: ${e.padding}px`,`white-space: ${e.whiteSpace===`pre`&&e.wordWrap?`pre-wrap`:e.whiteSpace}`,...e.lineHeight?[`line-height: ${e.lineHeight}px`]:[],...e.wordWrap?[`word-break: ${e.breakWords?`break-word`:`normal`}`,`max-width: ${e.wordWrapWidth}px`]:[],...t?[qA(t)]:[],...e.dropShadow?[KA(e.dropShadow)]:[],...e.cssOverrides].join(`;`)} }`];return XA(e.tagStyles,r),r.join(` `)}function KA(e){let t={...e},n=Li.shared.setValue(t.color).setAlpha(t.alpha??1).toHexa(),r=`${Math.round(Math.cos(t.angle)*t.distance)}px ${Math.round(Math.sin(t.angle)*t.distance)}px`;return t.blur>0?`text-shadow: ${r} ${t.blur}px ${n}`:`text-shadow: ${r} ${n}`}function qA(e){let t=Li.shared.setValue(e.color).setAlpha(e.alpha??1).toHexa();return[`-webkit-text-stroke-width: ${e.width}px`,`-webkit-text-stroke-color: ${t}`,`text-stroke-width: ${e.width}px`,`text-stroke-color: ${t}`,`paint-order: stroke`].join(`;`)}var JA={fontSize:`font-size: {{VALUE}}px`,fontFamily:`font-family: {{VALUE}}`,fontWeight:`font-weight: {{VALUE}}`,fontStyle:`font-style: {{VALUE}}`,fontVariant:`font-variant: {{VALUE}}`,letterSpacing:`letter-spacing: {{VALUE}}px`,align:`text-align: {{VALUE}}`,padding:`padding: {{VALUE}}px`,whiteSpace:`white-space: {{VALUE}}`,lineHeight:`line-height: {{VALUE}}px`,wordWrapWidth:`max-width: {{VALUE}}px`},YA={fill:e=>`color: ${Li.shared.setValue(e).toHexa()}`,breakWords:e=>`word-break: ${e?`break-all`:`normal`}`,stroke:qA,dropShadow:e=>e===!0?KA(aO.defaultDropShadow):e&&typeof e==`object`?KA({...aO.defaultDropShadow,...e}):``};function XA(e,t){for(let n in e){let r=e[n],i=[];for(let e in r)YA[e]?i.push(YA[e](r[e])):JA[e]&&i.push(JA[e].replace(`{{VALUE}}`,r[e]));t.push(`${n} { ${i.join(`;`)} }`)}}W(),oO();var ZA=class e extends aO{constructor(e={}){super(e),this._cssOverrides=[],this.cssOverrides=e.cssOverrides??[],this.tagStyles=e.tagStyles??{}}get tagStyles(){return this._tagStyles}set tagStyles(e){this._tagStyles!==e&&(this._tagStyles=e??{},this.update())}set cssOverrides(e){this._cssOverrides=e instanceof Array?e:[e],this.update()}get cssOverrides(){return this._cssOverrides}update(){this._cssStyle=null,super.update()}clone(){return new e({align:this.align,breakWords:this.breakWords,dropShadow:this.dropShadow?{...this.dropShadow}:null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,cssOverrides:this.cssOverrides,tagStyles:{...this.tagStyles}})}get cssStyle(){return this._cssStyle||=GA(this),this._cssStyle}addOverride(...e){let t=e.filter(e=>!this.cssOverrides.includes(e));t.length>0&&(this.cssOverrides.push(...t),this.update())}removeOverride(...e){let t=e.filter(e=>this.cssOverrides.includes(e));t.length>0&&(this.cssOverrides=this.cssOverrides.filter(e=>!t.includes(e)),this.update())}set fill(e){typeof e!=`string`&&typeof e!=`number`&&U(`[HTMLTextStyle] only color fill is not supported by HTMLText`),super.fill=e}set stroke(e){e&&typeof e!=`string`&&typeof e!=`number`&&U(`[HTMLTextStyle] only color stroke is not supported by HTMLText`),super.stroke=e}};Jc();var QA=`http://www.w3.org/2000/svg`,$A=`http://www.w3.org/1999/xhtml`,ej=class{constructor(){this.svgRoot=document.createElementNS(QA,`svg`),this.foreignObject=document.createElementNS(QA,`foreignObject`),this.domElement=document.createElementNS($A,`div`),this.styleElement=document.createElementNS($A,`style`);let{foreignObject:e,svgRoot:t,styleElement:n,domElement:r}=this;e.setAttribute(`width`,`10000`),e.setAttribute(`height`,`10000`),e.style.overflow=`hidden`,t.appendChild(e),e.appendChild(n),e.appendChild(r),this.image=Y.get().createImage()}destroy(){this.svgRoot.remove(),this.foreignObject.remove(),this.styleElement.remove(),this.domElement.remove(),this.image.src=``,this.image.remove(),this.svgRoot=null,this.foreignObject=null,this.styleElement=null,this.domElement=null,this.image=null,this.canvasAndContext=null}},tj;function nj(e,t,n,r){r||=tj||=new ej;let{domElement:i,styleElement:a,svgRoot:o}=r;i.innerHTML=`<style>${t.cssStyle};</style><div style='padding:0'>${e}</div>`,i.setAttribute(`style`,`transform-origin: top left; display: inline-block`),n&&(a.textContent=n),document.body.appendChild(o);let s=i.scrollWidth,c=i.scrollHeight;if(o.remove(),t.dropShadow){let{distance:e,angle:n,blur:r}=t.dropShadow,i=Math.abs(Math.round(Math.cos(n)*e)),a=Math.abs(Math.round(Math.sin(n)*e));s+=i+r,c+=a+r}let l=t.padding*2;return{width:s-l,height:c-l}}Oh();var rj=class extends Dh{constructor(){super(...arguments),this.generatingTexture=!1,this.currentKey=`--`}destroy(){this.texturePromise=null,this.generatingTexture=!1,this.currentKey=`--`,super.destroy()}};R(),$o(),cv();var ij=class{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),e.runners.contextChange.add(this),this._managedTexts=new sv({renderer:e,type:`renderable`,onUnload:this.onTextUnload.bind(this),name:`htmlText`})}resolutionChange(){for(let e in this._managedTexts.items){let t=this._managedTexts.items[e];t?._autoResolution&&t.onViewUpdate()}}contextChange(){for(let e in this._managedTexts.items)this._managedTexts.items[e]?.unload()}validateRenderable(e){let t=this._getGpuText(e),n=e.styleKey;return t.currentKey!==n}addRenderable(e,t){let n=this._getGpuText(e);if(e._didTextUpdate||n.currentKey!==e.styleKey){let t=e._autoResolution?this._renderer.resolution:e.resolution;(n.currentKey!==e.styleKey||e.resolution!==t)&&this._updateGpuText(e).catch(e=>{console.error(e)}),e._didTextUpdate=!1,TA(n,e)}this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuText(e);t._batcher.updateElement(t)}async _updateGpuText(e){e._didTextUpdate=!1;let t=this._getGpuText(e);if(t.generatingTexture)return;let n=t.texturePromise;t.texturePromise=null,t.generatingTexture=!0,e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;let r=this._renderer.htmlText.getTexturePromise(e);n&&(r=r.finally(()=>{this._renderer.htmlText.decreaseReferenceCount(t.currentKey),this._renderer.htmlText.returnTexturePromise(n)})),t.texturePromise=r,t.currentKey=e.styleKey;let i=await r;if(!t.renderable)return;t.texture=i;let a=e.renderGroup||e.parentRenderGroup;a&&(a.structureDidChange=!0),t.generatingTexture=!1,TA(t,e)}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){let t=new rj;return t.renderable=e,t.transform=e.groupTransform,t.texture=q.EMPTY,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,e._gpuData[this._renderer.uid]=t,this._managedTexts.add(e),t}onTextUnload(e){let t=e._gpuData[this._renderer.uid];if(!t?.texturePromise)return;let{htmlText:n}=this._renderer;n.getReferenceCount(t.currentKey)===null?n.returnTexturePromise(t.texturePromise):n.decreaseReferenceCount(t.currentKey)}destroy(){this._managedTexts.destroy(),this._renderer=null}};ij.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:`htmlText`};function aj(e,t){let n=t.fontFamily,r=[],i={},a=e.match(/font-family:([^;"\s]+)/g);function o(e){i[e]||(r.push(e),i[e]=!0)}if(Array.isArray(n))for(let e=0;e<n.length;e++)o(n[e]);else o(n);a&&a.forEach(e=>{o(e.split(`:`)[1].trim())});for(let e in t.tagStyles){let n=t.tagStyles[e].fontFamily;o(n)}return r}Jc();async function oj(e){let t=await(await Y.get().fetch(e)).blob(),n=new FileReader;return await new Promise((e,r)=>{n.onloadend=()=>e(n.result),n.onerror=r,n.readAsDataURL(t)})}async function sj(e,t){let n=await oj(t);return`@font-face {
|
|
1340
|
-
font-family: "${e.fontFamily}";
|
|
1341
|
-
font-weight: ${e.fontWeight};
|
|
1342
|
-
font-style: ${e.fontStyle};
|
|
1343
|
-
src: url('${n}');
|
|
1344
|
-
}`}Xl();var cj=new Map;async function lj(e){let t=e.filter(e=>Yl.has(`${e}-and-url`)).map(e=>{if(!cj.has(e)){let{entries:t}=Yl.get(`${e}-and-url`),n=[];t.forEach(t=>{let r=t.url,i=t.faces.map(e=>({weight:e.weight,style:e.style}));n.push(...i.map(t=>sj({fontWeight:t.weight,fontStyle:t.style,fontFamily:e},r)))}),cj.set(e,Promise.all(n).then(e=>e.join(`
|
|
1345
|
-
`)))}return cj.get(e)});return(await Promise.all(t)).join(`
|
|
1346
|
-
`)}function uj(e,t,n,r,i){let{domElement:a,styleElement:o,svgRoot:s}=i;a.innerHTML=`<style>${t.cssStyle}</style><div style='padding:0;'>${e}</div>`,a.setAttribute(`style`,`transform: scale(${n});transform-origin: top left; display: inline-block`),o.textContent=r;let{width:c,height:l}=i.image;return s.setAttribute(`width`,c.toString()),s.setAttribute(`height`,l.toString()),new XMLSerializer().serializeToString(s)}fu();function dj(e,t){let n=du.getOptimalCanvasAndContext(e.width,e.height,t),{context:r}=n;return r.clearRect(0,0,e.width,e.height),r.drawImage(e,0,0),n}function fj(e,t,n){return new Promise(async r=>{n&&await new Promise(e=>setTimeout(e,100)),e.onload=()=>{r()},e.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(t)}`,e.crossOrigin=`anonymous`})}R(),fu(),fs(),Gd(),NS(),W(),ha(),Fu();var pj=class{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===Wd.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){let t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;let n=this._buildTexturePromise(e).then(e=>(this._activeTextures[t].texture=e,e));return this._activeTextures[t]={texture:null,promise:n,usageCount:1},n}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){let t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(e=>{t.texture=e,this._cleanUp(t.texture)}).catch(()=>{U(`HTMLTextSystem: Failed to clean texture`)}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){let{text:t,style:n,resolution:r,textureStyle:i,autoGenerateMipmaps:a}=e,o=ma.get(ej),s=aj(t,n),c=await lj(s),l=nj(t,n,c,o),u=Math.ceil(Math.ceil(Math.max(1,l.width)+n.padding*2)*r),d=Math.ceil(Math.ceil(Math.max(1,l.height)+n.padding*2)*r),f=o.image;f.width=(u|0)+2,f.height=(d|0)+2,await fj(f,uj(t,n,r,c,o),MS()&&s.length>0);let p=f,m;this._createCanvas&&(m=dj(f,r));let h=Nu(m?m.canvas:p,f.width-2,f.height-2,r,a,i?.scaleMode);return this._renderer?.texture.initSource(h.source),this._createCanvas&&du.returnCanvasAndContext(m),ma.return(o),h}returnTexturePromise(e){e.then(e=>{this._cleanUp(e)}).catch(()=>{U(`HTMLTextSystem: Failed to clean texture`)})}_cleanUp(e){let t=e.source;ds.returnTexture(e),t.resource=null,t.uploadMethodId=`unknown`}destroy(){this._renderer=null;for(let e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}};pj.extension={type:[I.WebGLSystem,I.WebGPUSystem,I.CanvasSystem],name:`htmlText`},R(),L.add(pj),L.add(ij),Po(),ko();var mj=class extends fA{constructor(...e){let t=pA(e,`HtmlText`);super(t,ZA),this.renderPipeId=`htmlText`,t.textureStyle&&(this.textureStyle=t.textureStyle instanceof Oo?t.textureStyle:new Oo(t.textureStyle),wA(this.textureStyle)),this.autoGenerateMipmaps=t.autoGenerateMipmaps??No.defaultOptions.autoGenerateMipmaps}updateBounds(){let e=this._bounds,t=this._anchor,{width:n,height:r}=nj(this.text,this._style);e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}get text(){return this._text}set text(e){let t=this._sanitiseText(e.toString());super.text=t}_sanitiseText(e){return this._removeInvalidHtmlTags(e.replace(/<br>/gi,`<br/>`).replace(/<hr>/gi,`<hr/>`).replace(/ /gi,` `))}_removeInvalidHtmlTags(e){return e.replace(/<[^>]*?(?=<|$)/g,``)}};oa();var hj=class e extends Hk{constructor(...e){super({});let t=e[0]??{};typeof t==`number`&&(H(V,`PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead`),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(t){t={...e.defaultOptions,...t},this.verticesX=this.verticesX??t.verticesX,this.verticesY=this.verticesY??t.verticesY,this.width=this.width??t.width,this.height=this.height??t.height;let n=this.verticesX*this.verticesY,r=[],i=[],a=[],o=this.verticesX-1,s=this.verticesY-1,c=this.width/o,l=this.height/s;for(let e=0;e<n;e++){let t=e%this.verticesX,n=e/this.verticesX|0;r.push(t*c,n*l),i.push(t/o,n/s)}let u=o*s;for(let e=0;e<u;e++){let t=e%o,n=e/o|0,r=n*this.verticesX+t,i=n*this.verticesX+t+1,s=(n+1)*this.verticesX+t,c=(n+1)*this.verticesX+t+1;a.push(r,i,s,i,c,s)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(i),this.indexBuffer.data=new Uint32Array(a),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};hj.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};var gj=hj;wo();var _j=class extends Kk{constructor(e){let{texture:t,verticesX:n,verticesY:r,...i}=e,a=new gj(Co({width:t.width,height:t.height,verticesX:n,verticesY:r}));super(Co({...i,geometry:a,texture:t})),this.texture=t,this.autoResize=!0}textureUpdated(){let e=this.geometry,{width:t,height:n}=this.texture;this.autoResize&&(e.width!==t||e.height!==n)&&(e.width=t,e.height=n,e.build({}))}set texture(e){this._texture?.off(`update`,this.textureUpdated,this),super.texture=e,e.on(`update`,this.textureUpdated,this),this.textureUpdated()}get texture(){return this._texture}destroy(e){this.texture.off(`update`,this.textureUpdated,this),super.destroy(e)}};R(),su(),to(),Ya();var vj=[[0,0],[0,0],[0,0]],yj=[[0,0],[0,0],[0,0]],bj=[[0,0],[0,0],[0,0]],xj=[[0,0],[0,0],[0,0]];function Sj(e,t,n,r,i,a,o){e[0][0]=t,e[0][1]=n,e[1][0]=r,e[1][1]=i,e[2][0]=a,e[2][1]=o}var Cj=class{constructor(e){this._renderer=e}validateRenderable(e){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){let t=this._renderer,n=t.canvasContext,r=n.activeContext;r.save();let i=e.groupTransform,a=t._roundPixels|e._roundPixels;n.setContextTransform(i,a===1),n.setBlendMode(e.groupBlendMode);let o=t.globalUniforms.globalUniformData?.worldColor??4294967295,s=e.groupColorAlpha,c=(o>>>24&255)/255,l=(s>>>24&255)/255,u=t.filter?.alphaMultiplier??1,d=c*l*u;if(d<=0){r.restore();return}r.globalAlpha=d;let f=o&16777215,p=$a(Ja(s&16777215,f)),m=e.texture,h=X.getCanvasSource(m);if(!h){r.restore();return}let g=n.smoothProperty,_=m.source.style.scaleMode!==`nearest`;r[g]!==_&&(r[g]=_);let v=p!==16777215||m.rotate!==0,y=v?X.getTintedCanvas({texture:m},p):h,{leftWidth:b,topHeight:x,rightWidth:S,bottomHeight:C,width:ee,height:w}=e,T=b+S,E=x+C,te=Math.min(T>ee?ee/T:1,E>w?w/E:1,1),D=b*te,O=S*te,ne=x*te,k=C*te,A=Math.max(0,ee-D-O),re=Math.max(0,w-ne-k),ie=e.anchor,ae=m.source._resolution??m.source.resolution??1,oe=m.frame.x*ae,se=m.frame.y*ae,j=-ie.x*ee,ce=-ie.y*w,le=b*ae,ue=x*ae,de=S*ae,fe=C*ae,pe=m.frame.width*ae,me=m.frame.height*ae;v&&(oe=0,se=0,pe=y.width,me=y.height);let he=pe-le-de,ge=me-ue-fe,_e=he>0?oe+le:Math.max(oe,Math.min(oe+le,oe+pe-1)),ve=he>0?he:1,M=ge>0?se+ue:Math.max(se,Math.min(se+ue,se+me-1)),N=ge>0?ge:1;Sj(vj,oe,le,_e,ve,oe+pe-de,de),Sj(yj,se,ue,M,N,se+me-fe,fe),Sj(bj,j,D,j+D,A,j+ee-O,O),Sj(xj,ce,ne,ce+ne,re,ce+w-k,k);for(let e=0;e<3;e++){let t=bj[e][1];if(t<=0)continue;let n=vj[e][0],i=vj[e][1],a=bj[e][0];for(let e=0;e<3;e++){let o=xj[e][1];o<=0||r.drawImage(y,n,yj[e][0],i,yj[e][1],a,xj[e][0],t,o)}}r.restore()}destroy(){this._renderer=null}};Cj.extension={type:[I.CanvasPipes],name:`nineSliceSprite`};var wj=class e extends gj{constructor(t={}){t={...e.defaultOptions,...t},super({width:t.width,height:t.height,verticesX:4,verticesY:4}),this._trimX=0,this._trimY=0,this._trimWidth=t.originalWidth??e.defaultOptions.originalWidth,this._trimHeight=t.originalHeight??e.defaultOptions.originalHeight,this.update(t)}update(e){this.width=e.width??this.width,this.height=e.height??this.height,this._originalWidth=e.originalWidth??this._originalWidth,this._originalHeight=e.originalHeight??this._originalHeight,this._leftWidth=e.leftWidth??this._leftWidth,this._rightWidth=e.rightWidth??this._rightWidth,this._topHeight=e.topHeight??this._topHeight,this._bottomHeight=e.bottomHeight??this._bottomHeight,this._anchorX=e.anchor?.x,this._anchorY=e.anchor?.y,e.trim===void 0?(this._trimWidth=this._originalWidth,this._trimHeight=this._originalHeight):(this._trimX=e.trim?.x??0,this._trimY=e.trim?.y??0,this._trimWidth=e.trim?.width??this._originalWidth,this._trimHeight=e.trim?.height??this._originalHeight),this.updateUvs(),this.updatePositions()}updatePositions(){let e=this.positions,{width:t,height:n,_leftWidth:r,_rightWidth:i,_topHeight:a,_bottomHeight:o,_anchorX:s,_anchorY:c}=this,l=r+i,u=t>l?1:t/l,d=a+o,f=n>d?1:n/d,p=Math.min(u,f),m=s*t,h=c*n;e[0]=e[8]=e[16]=e[24]=-m,e[2]=e[10]=e[18]=e[26]=r*p-m,e[4]=e[12]=e[20]=e[28]=t-i*p-m,e[6]=e[14]=e[22]=e[30]=t-m,e[1]=e[3]=e[5]=e[7]=-h,e[9]=e[11]=e[13]=e[15]=a*p-h,e[17]=e[19]=e[21]=e[23]=n-o*p-h,e[25]=e[27]=e[29]=e[31]=n-h,this.getBuffer(`aPosition`).update()}updateUvs(){let e=this.uvs,t=this._originalWidth,n=this._originalHeight,r=this._trimX/t,i=this._trimY/n,a=(this._trimX+this._trimWidth)/t,o=(this._trimY+this._trimHeight)/n;e[0]=e[8]=e[16]=e[24]=r,e[1]=e[3]=e[5]=e[7]=i,e[6]=e[14]=e[22]=e[30]=a,e[25]=e[27]=e[29]=e[31]=o;let s=1/t,c=1/n;e[2]=e[10]=e[18]=e[26]=r+s*this._leftWidth,e[9]=e[11]=e[13]=e[15]=i+c*this._topHeight,e[4]=e[12]=e[20]=e[28]=a-s*this._rightWidth,e[17]=e[19]=e[21]=e[23]=o-c*this._bottomHeight,this.getBuffer(`aUV`).update()}};wj.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};var Tj=wj;R(),cv();var Ej=class extends Uk{constructor(){super(),this.geometry=new Tj}destroy(){this.geometry.destroy()}},Dj=class{constructor(e){this._renderer=e,this._managedSprites=new sv({renderer:e,type:`renderable`,name:`nineSliceSprite`})}addRenderable(e,t){let n=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,n),this._renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.geometry.update(e),t.setTexture(e._texture)}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){let t=e._gpuData[this._renderer.uid]=new Ej,n=t;return n.renderable=e,n.transform=e.groupTransform,n.texture=e._texture,n.roundPixels=this._renderer._roundPixels|e._roundPixels,this._managedSprites.add(e),e.didViewUpdate||this._updateBatchableSprite(e,n),t}destroy(){this._managedSprites.destroy(),this._renderer=null}};Dj.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:`nineSliceSprite`},R(),L.add(Cj),L.add(Dj),Zi(),$o(),yc();var Oj=class e extends vc{constructor(t){t instanceof q&&(t={texture:t});let{width:n,height:r,anchor:i,leftWidth:a,rightWidth:o,topHeight:s,bottomHeight:c,texture:l,roundPixels:u,...d}=t;super({label:`NineSliceSprite`,...d}),this.renderPipeId=`nineSliceSprite`,this.batched=!0,this._leftWidth=a??l?.defaultBorders?.left??Tj.defaultOptions.leftWidth,this._topHeight=s??l?.defaultBorders?.top??Tj.defaultOptions.topHeight,this._rightWidth=o??l?.defaultBorders?.right??Tj.defaultOptions.rightWidth,this._bottomHeight=c??l?.defaultBorders?.bottom??Tj.defaultOptions.bottomHeight,this._width=n??l.width??Tj.defaultOptions.width,this._height=r??l.height??Tj.defaultOptions.height,this.allowChildren=!1,this.texture=l??e.defaultOptions.texture,this.roundPixels=u??!1,this._anchor=new Xi({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:this.texture.defaultAnchor&&(this.anchor=this.texture.defaultAnchor)}get anchor(){return this._anchor}set anchor(e){typeof e==`number`?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return this._width}set width(e){this._width=e,this.onViewUpdate()}get height(){return this._height}set height(e){this._height=e,this.onViewUpdate()}setSize(e,t){typeof e==`object`&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||={},e.width=this._width,e.height=this._height,e}get leftWidth(){return this._leftWidth}set leftWidth(e){this._leftWidth=e,this.onViewUpdate()}get topHeight(){return this._topHeight}set topHeight(e){this._topHeight=e,this.onViewUpdate()}get rightWidth(){return this._rightWidth}set rightWidth(e){this._rightWidth=e,this.onViewUpdate()}get bottomHeight(){return this._bottomHeight}set bottomHeight(e){this._bottomHeight=e,this.onViewUpdate()}get texture(){return this._texture}set texture(e){e||=q.EMPTY;let t=this._texture;t!==e&&(t&&t.dynamic&&t.off(`update`,this.onViewUpdate,this),e.dynamic&&e.on(`update`,this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get originalWidth(){return this._texture.width}get originalHeight(){return this._texture.height}get trim(){return this._texture.trim??null}destroy(e){if(super.destroy(e),typeof e==`boolean`?e:e?.texture){let t=typeof e==`boolean`?e:e?.textureSource;this._texture.destroy(t)}this._texture=null}updateBounds(){let e=this._bounds,t=this._anchor,n=this._width,r=this._height;e.minX=-t._x*n,e.maxX=e.minX+n,e.minY=-t._y*r,e.maxY=e.minY+r}};Oj.defaultOptions={texture:q.EMPTY};var kj=Oj;R(),nu(),xl(),B(),qi(),Pa(),Eg(),Xm(),$m(),sh(),mh(),Ng(),Af(),Of(),Lf(),rf(),g_(),Po(),$o(),tu(),xs(),TC(),TE(),Tl(),$D(),oO(),ri(),L.add(Gf,Jf);function Aj(e,t,n,r){let i=Math.max(e,t);return!Number.isFinite(r)||r<=0||!Number.isFinite(i)||i<=0||i*n<=r?n:Math.max(1,Math.floor(r/i))}var jj=class{constructor(e){this.over=0,this.under=0,this.ceiling=Mj(e.ceiling);let t=e.minRatio??1;this.floor=Math.min(Number.isFinite(t)&&t>0?t:1,this.ceiling);let n=e.targetFps??60;this.budget=Number.isFinite(n)&&n>0?1/n:1/60,this.downAfter=Nj(e.overBudgetFrames,60),this.upAfter=Nj(e.underBudgetFrames,600),this.step=Number.isFinite(e.step)&&e.step>0?e.step:.25,this.ratio_=this.ceiling}get ratio(){return this.ratio_}setCeiling(e){return this.ceiling=Mj(e),this.ratio_>this.ceiling&&(this.ratio_=this.ceiling,this.over=0,this.under=0),this.ratio_}observe(e){return!Number.isFinite(e)||e<=0||(e>this.budget?(this.over++,this.under=0,this.over>=this.downAfter&&this.ratio_>this.floor&&(this.ratio_=Math.max(this.floor,this.ratio_-this.step),this.over=0)):(this.under++,this.over=0,this.under>=this.upAfter&&this.ratio_<this.ceiling&&(this.ratio_=Math.min(this.ceiling,this.ratio_+this.step),this.under=0))),this.ratio_}reset(){this.ratio_=this.ceiling,this.over=0,this.under=0}};function Mj(e){return Number.isFinite(e)&&e>0?e:1}function Nj(e,t){return Number.isFinite(e)?Math.max(1,Math.floor(e)):t}var Pj=e=>Math.min(1,Math.max(0,e));function Fj(e,t,n=`diagonal`,r=1){let i=e*t,a=[],o=r>>>0||1;for(let r=0;r<t;r++)for(let i=0;i<e;i++)n===`diagonal`?a.push(i+r):n===`rows`?a.push(r*e+i):n===`spiral`?a.push(Math.min(i,r,e-1-i,t-1-r)):(o=Math.imul(o,1664525)+1013904223>>>0,a.push(o/2**32));let s=Math.min(...a),c=Math.max(...a);return a.map(e=>i===1||c===s?0:(e-s)/(c-s))}function Ij(e,t,n){let r=Pj(n);return Pj((t-e*r)/(1-r||1))}function Lj(e,t=1.08){let n=Pj(e);return n<.7?Er.easeOutCubic(n/.7)*t:t+(1-t)*Er.easeInOutQuad((n-.7)/.3)}function Rj(e){return typeof e==`function`?e:Er[e??`easeInOutQuad`]}function zj(e,t){return e??{x:t.width/2,y:t.height/2}}function Bj(e){if(!e.snapshot)return null;let t=new wl(e.snapshot);return t.width=e.width,t.height=e.height,t}function Vj(e,t,n){return{update:t,destroy(){n?.(),e.destroy({children:!0})}}}function Hj(e={}){let t=Math.max(1,Math.floor(e.columns??8)),n=Math.max(1,Math.floor(e.rows??5)),r=e.stagger??.5,i=e.rotation??0;return{name:`tileShrink`,start(a){let o=new J;a.over.addChild(o);let s=Fj(t,n,e.order??`diagonal`,e.seed),c=[],l=a.snapshot,u=a.width/t,d=a.height/n;if(l){let e=l.frame;for(let r=0;r<n;r++)for(let i=0;i<t;i++){let a=new G(e.x+i*e.width/t,e.y+r*e.height/n,e.width/t,e.height/n),s=new wl(new q({source:l.source,frame:a}));s.anchor.set(.5),s.width=u,s.height=d,s.position.set((i+.5)*u,(r+.5)*d),c.push({sprite:s,width:s.scale.x,height:s.scale.y}),o.addChild(s)}}return Vj(o,e=>{c.forEach(({sprite:t,width:n,height:a},o)=>{let c=1-Ij(s[o],e,r);t.scale.set(n*c,a*c),t.rotation=(1-c)*i,t.visible=c>0})})}}}function Uj(e={}){return{name:`shrink`,start(t){let n=new J;t.over.addChild(n);let r=Bj(t);r&&n.addChild(r);let i=zj(e.to,t);return Vj(n,e=>{let t=1-e;n.scale.set(t),n.position.set(i.x*(1-t),i.y*(1-t)),n.alpha=1-e*e})}}}function Wj(e,t,n){return{name:e,start(e){let r=new J;e.under.addChild(r);let i=Bj(e);i&&r.addChild(i);let a=zj(t,e),o=e.incoming;return Vj(r,e=>{let t=n(e);o.scale.set(t),o.position.set(a.x*(1-t),a.y*(1-t)),o.alpha=Pj(e*3)},()=>{o.scale.set(1),o.position.set(0,0),o.alpha=1})}}}function Gj(e={}){return Wj(`pop`,e.from,t=>Lj(t,e.overshoot))}function Kj(e={}){return Wj(`grow`,e.from,e=>e)}function qj(e={}){let t=e.direction??`left`,n=t===`left`?-1:+(t===`right`),r=t===`up`?-1:+(t===`down`);return{name:`slide`,start(e){let t=new J;e.over.addChild(t);let i=Bj(e);i&&t.addChild(i);let a=e.incoming;return Vj(t,i=>{t.position.set(n*e.width*i,r*e.height*i),a.position.set(-n*e.width*(1-i),-r*e.height*(1-i))},()=>a.position.set(0,0))}}}function Jj(e={}){return{name:`iris`,start(t){let n=new J;t.under.addChild(n);let r=Bj(t);r&&n.addChild(r);let i=zj(e.from,t),a=Math.hypot(Math.max(i.x,t.width-i.x),Math.max(i.y,t.height-i.y)),o=new Z;return t.incoming.addChild(o),t.incoming.mask=o,Vj(n,e=>{o.clear().circle(i.x,i.y,a*e).fill({color:16777215})},()=>{t.incoming.mask=null,o.destroy()})}}}function Yj(){return{name:`dissolve`,start(e){let t=new J;e.over.addChild(t);let n=Bj(e);return n&&t.addChild(n),Vj(t,e=>{t.alpha=1-e})}}}function Xj(e,t,n=!1){let r=Pj(t),i=Er.easeOutCubic(r);return e===`pop`?{scale:n?i:Lj(r),alpha:Pj(r*3),offset:0}:e===`grow`?{scale:i,alpha:Pj(r*3),offset:0}:e===`slide`?{scale:1,alpha:i,offset:(1-i)*48}:{scale:1,alpha:i,offset:0}}var Zj=class{constructor(e,t,n,r){this.under=new J,this.over=new J,this.elapsed=0,this.finished=!1,this.snapshot=n,this.duration=Math.max(1e-4,e.duration??.5),this.ease=Rj(e.easing),this.pause=e.pause??!1,this.onDone=e.onDone,this.runtime=e.transition.start({width:t.width,height:t.height,snapshot:n,incoming:r,under:this.under,over:this.over}),this.runtime.update(0)}get progress(){return this.finished?1:Math.min(1,this.elapsed/this.duration)}get done(){return this.finished}update(e){return this.finished?!0:(this.elapsed+=e,this.elapsed>=this.duration?(this.finish(),!0):(this.runtime.update(this.ease(this.progress)),!1))}finish(){this.finished||(this.finished=!0,this.runtime.update(1),this.runtime.destroy(),this.snapshot?.destroy(!0),this.under.destroy({children:!0}),this.over.destroy({children:!0}),this.onDone?.())}},Qj=`mwg-pixel-art`,$j=new b(`renderer`);function eM(){if(document.getElementById(Qj))return;let e=document.createElement(`style`);e.id=Qj,e.textContent=`.${Qj} { image-rendering: pixelated; }`,document.head.appendChild(e)}function tM(e){let t=null,n=()=>{t=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),t.addEventListener(`change`,r,{once:!0})},r=()=>{e(),n()};return n(),()=>t?.removeEventListener(`change`,r)}var nM=class e{static{this.instance=null}constructor(t={}){this.app=new sD,this.elapsed=0,this.timeTotal=0,this.timeScale=1,this.onFrame=new p,this.hitStopRemaining=0,this.hitStopScale=0,this.stack=new h,this.pending=[],this.running=null,this.started=!1,this.stopWatchingDpr=null,this.stopWatchingVisibility=null,this.suspended_=!1,this.timeScaleBeforeSuspend=1,this.scaler=null,this.options={canvas:t.canvas??document.createElement(`canvas`),background:t.background??0,maxDelta:t.maxDelta??.25,pixelArt:t.pixelArt??!0,resizeTo:t.resizeTo??window,extensions:t.extensions??[],autoPause:t.autoPause??!0,audio:t.audio??null,qualityScaling:t.qualityScaling??null},this.options.pixelArt&&(No.defaultOptions.scaleMode=`nearest`),e.instance=this}get width(){return this.app.renderer.screen.width}get height(){return this.app.renderer.screen.height}static get active(){return e.instance}static get current(){if(!e.instance)throw Error(`no Game has been created yet`);return e.instance}async start(e){if(this.started)throw Error(`this Game has already been started`);this.started=!0;for(let e of this.options.extensions)e();if(gt(),await this.app.init({canvas:this.options.canvas,background:this.options.background,resizeTo:this.options.resizeTo,antialias:!1,preserveDrawingBuffer:!1,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.options.canvas.isConnected||document.body.appendChild(this.options.canvas),this.options.pixelArt&&(eM(),this.options.canvas.classList.add(Qj)),this.app.renderer.on(`resize`,()=>{this.stack.resize(this.width,this.height),this.fitResolutionToDevice()}),this.fitResolutionToDevice(),this.stopWatchingDpr=tM(()=>{this.fitResolutionToDevice()}),this.options.autoPause&&typeof document<`u`){let e=()=>{document.hidden?this.suspend():this.resume()};document.addEventListener(`visibilitychange`,e),this.stopWatchingVisibility=()=>document.removeEventListener(`visibilitychange`,e)}this.expose(),this.switchNow(e),this.app.ticker.add(e=>this.frame(e.deltaMS/1e3))}switchScene(e,t){this.pending.push({kind:`switch`,next:e,transition:t})}transition(e,t){this.pending.push({kind:`swap`,swap:e,transition:t})}get transitioning(){return this.running!==null}pushScene(e){this.pending.push({kind:`push`,next:e})}popScene(e){this.pending.push({kind:`pop`,result:e})}get currentScene(){return this.stack.current}hitStop(e,t=0){this.hitStopRemaining=e,this.hitStopScale=t}step(e){this.frame(e),this.app.renderer.render(this.app.stage)}get suspended(){return this.suspended_}suspend(){this.suspended_||(this.suspended_=!0,this.timeScaleBeforeSuspend=this.timeScale,this.timeScale=0,this.stack.current?.onSuspend(),this.options.audio?.suspend())}resume(){this.suspended_&&(this.suspended_=!1,this.timeScale=this.timeScaleBeforeSuspend,this.stack.current?.onResume(void 0),this.options.audio?.resume())}expose(){let e=globalThis;e.__PIXI_APP__=this.app,e.__MWG__=this}fitResolutionToDevice(){let e=this.app.renderer.gl,t=e?e.getParameter(e.MAX_TEXTURE_SIZE):1/0,n=window.devicePixelRatio||1,r=Aj(this.width,this.height,n,t);!this.scaler&&this.options.qualityScaling&&(this.scaler=new jj({...this.options.qualityScaling,ceiling:r}));let i=this.scaler?this.scaler.setCeiling(r):r;i!==this.app.renderer.resolution&&($j.warn(`this device cannot render a ${this.width}x${this.height} canvas at ${n}x (its limit is ${t}); using ${r}x instead, which is softer than the display`),this.app.renderer.resize(this.width,this.height,i))}frame(e){this.pending.length>0&&this.endTransition();for(let e of this.pending)e.kind===`switch`?this.applySwitch(e.next,e.transition):e.kind===`swap`?this.applySwap(e.swap,e.transition):e.kind===`push`?this.applyPush(e.next):this.applyPop(e.result);this.pending.length=0,this.hitStopRemaining>0&&!this.suspended_&&(this.hitStopRemaining-=e,this.timeScale=this.hitStopRemaining>0?this.hitStopScale:1),this.running&&this.running.runner.update(e)&&this.endTransition();let t=this.running?.runner.pause===!0;this.elapsed=t?0:Math.min(e,this.options.maxDelta)*this.timeScale;let n=this.suspended_||this.elapsed<=0?null:this.scaler;if(n){let e=n.observe(this.elapsed);e!==this.app.renderer.resolution&&this.app.renderer.resize(this.width,this.height,e)}this.timeTotal+=this.elapsed,ot(),this.stack.update(this.elapsed),this.onFrame.dispatch(this.elapsed),Ke()}switchNow(e){this.applySwitch(e)}snapshot(e){return!e||br()?null:this.app.renderer.generateTexture(this.app.stage)}beginTransition(e,t){let n=new J;n.addChild(...this.app.stage.removeChildren());let r=new Zj(e,{width:this.width,height:this.height},t,n);this.app.stage.addChild(r.under,n,r.over),this.running={runner:r,wrapper:n}}endTransition(){let e=this.running;if(!e)return;this.running=null,e.runner.finish();let t=e.wrapper.removeChildren();this.app.stage.removeChildren(),this.app.stage.addChild(...t),e.wrapper.destroy()}applySwap(e,t){let n=this.snapshot(t);e(),n?this.beginTransition(t,n):t.onDone?.()}applySwitch(e,t){let n=this.snapshot(t),r=new e;this.stack.replace(r),this.app.stage.removeChildren(),this.app.stage.addChild(r.stage),this.elapsed=0,this.timeTotal=0,this.timeScale=1,r.resize(this.width,this.height),n&&t?this.beginTransition(t,n):t?.onDone?.()}applyPush(e){let t=new e;this.stack.push(t),this.app.stage.addChild(t.stage),this.elapsed=0,this.timeTotal=0,this.timeScale=1,t.resize(this.width,this.height)}applyPop(e){let t=this.stack.current;this.stack.pop(e),t&&this.app.stage.removeChild(t.stage)}destroy(){_t(),this.stopWatchingDpr?.(),this.stopWatchingVisibility?.(),this.stack.destroy(),this.onFrame.removeAll(),this.app.destroy(!0,{children:!0}),e.instance===this&&(e.instance=null)}},rM=class extends m{constructor(...e){super(...e),this.stage=new J}transitionTo(e,t){let n=nM.active;n?n.transition(e,t):e()}teardown(){this.stage.destroy({children:!0})}},iM={name:`color-add-bit`,vertex:{header:`
|
|
1347
|
-
in vec4 aColorAdd;
|
|
1348
|
-
out vec4 vColorAdd;
|
|
1349
|
-
`,main:`
|
|
1350
|
-
vColorAdd = aColorAdd;
|
|
1351
|
-
`},fragment:{header:`
|
|
1352
|
-
in vec4 vColorAdd;
|
|
1353
|
-
`,end:`
|
|
1354
|
-
// Pixi works in premultiplied alpha, so the added colour is scaled by the
|
|
1355
|
-
// final alpha. That keeps a transparent texel transparent instead of leaving
|
|
1356
|
-
// a coloured halo where the sprite is empty.
|
|
1357
|
-
float addedAlpha = finalColor.a + vColorAdd.a;
|
|
1358
|
-
finalColor = vec4(finalColor.rgb + vColorAdd.rgb * addedAlpha, addedAlpha);
|
|
1359
|
-
`}},aM={name:`color-add-bit`,vertex:{header:`
|
|
1360
|
-
@in aColorAdd: vec4<f32>;
|
|
1361
|
-
@out vColorAdd: vec4<f32>;
|
|
1362
|
-
`,main:`
|
|
1363
|
-
vColorAdd = aColorAdd;
|
|
1364
|
-
`},fragment:{header:`
|
|
1365
|
-
@in vColorAdd: vec4<f32>;
|
|
1366
|
-
`,end:`
|
|
1367
|
-
let addedAlpha = finalColor.a + vColorAdd.a;
|
|
1368
|
-
finalColor = vec4<f32>(finalColor.rgb + vColorAdd.rgb * addedAlpha, addedAlpha);
|
|
1369
|
-
`}},oM=class extends nf{constructor(e){super({glProgram:Ym({name:`color-transform-batch`,bits:[Qm,iM,ih(e),ph]}),gpuProgram:Jm({name:`color-transform-batch`,bits:[Zm,aM,nh(e),fh]}),resources:{batchSamplers:jg(e)}}),this.maxTextures=e}},sM=7,cM=class extends If{constructor(){let e=new kf({data:new Float32Array(1),label:`mwg-color-transform-attribute-buffer`,usage:Df.VERTEX|Df.COPY_DST,shrinkToFit:!1}),t=new kf({data:new Uint32Array(1),label:`mwg-color-transform-index-buffer`,usage:Df.INDEX|Df.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:e,format:`float32x2`,stride:28,offset:0},aUV:{buffer:e,format:`float32x2`,stride:28,offset:8},aColor:{buffer:e,format:`unorm8x4`,stride:28,offset:16},aTextureIdAndRound:{buffer:e,format:`uint16x2`,stride:28,offset:20},aColorAdd:{buffer:e,format:`unorm8x4`,stride:28,offset:24}},indexBuffer:t})}},lM=0,uM=e=>e.colorAdd??lM;function dM(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){e[n]=r*l+a*u+s,e[n+1]=o*u+i*l+c,e[n+2]=d,e[n+3]=f,t[n+4]=p,t[n+5]=m,t[n+6]=h}var fM=class e extends Tg{static{this.extension={type:[I.Batcher],name:`mwg-color-transform`}}constructor(t){super(t),this.geometry=new cM,this.name=e.extension.name,this.vertexSize=sM,this.shader=new oM(t.maxTextures)}packAttributes(e,t,n,r,i){let a=i<<16|e.roundPixels&65535,{a:o,b:s,c,d:l,tx:u,ty:d}=e.transform,{positions:f,uvs:p}=e,m=e.color,h=uM(e),g=e.attributeOffset,_=g+e.attributeSize;for(let e=g;e<_;e++){let i=e*2,g=f[i],_=f[i+1];t[r++]=o*g+c*_+u,t[r++]=l*_+s*g+d,t[r++]=p[i],t[r++]=p[i+1],n[r++]=m,n[r++]=a,n[r++]=h}}packQuadAttributes(e,t,n,r,i){let{a,b:o,c:s,d:c,tx:l,ty:u}=e.transform,{bounds:d}=e,f=e.texture.uvs,p=d.maxX,m=d.minX,h=d.maxY,g=d.minY,_=e.color,v=uM(e),y=i<<16|e.roundPixels&65535;dM(t,n,r,a,o,s,c,l,u,m,g,f.x0,f.y0,_,y,v),r+=sM,dM(t,n,r,a,o,s,c,l,u,p,g,f.x1,f.y1,_,y,v),r+=sM,dM(t,n,r,a,o,s,c,l,u,p,h,f.x2,f.y2,_,y,v),r+=sM,dM(t,n,r,a,o,s,c,l,u,m,h,f.x3,f.y3,_,y,v)}_updateMaxTextures(e){this.shader.maxTextures!==e&&(this.shader.destroy(),this.shader=new oM(e))}destroy(){this.shader.destroy(),super.destroy()}},pM=`mwg-tinted-sprite`;function mM(e){e.renderPipeId=pM}var hM=class{static{this.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:pM}}constructor(e){this.renderer=e}addRenderable(e,t){let n=this.element(e);e.didViewUpdate&&this.sync(e,n),this.renderer.renderPipes.batch.addToBatch(n,t)}updateRenderable(e){let t=this.element(e);e.didViewUpdate&&this.sync(e,t),t._batcher.updateElement(t)}validateRenderable(e){let t=this.element(e);return!t._batcher.checkAndUpdateTexture(t,e.texture)}sync(e,t){t.bounds=e.visualBounds,t.texture=e.texture,t.colorAdd=e.colorAdd}element(e){let t=e._gpuData;return t[this.renderer.uid]??this.create(e,t)}create(e,t){let n=new gM;return n.renderable=e,n.transform=e.groupTransform,n.texture=e.texture,n.bounds=e.visualBounds,n.roundPixels=this.renderer._roundPixels|e._roundPixels,n.colorAdd=e.colorAdd,t[this.renderer.uid]=n,n}destroy(){this.renderer=null}},gM=class{constructor(){this.batcherName=fM.extension.name,this.topology=`triangle-list`,this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this.colorAdd=0,this._attributeStart=0,this._textureId=0,this._indexStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null,this.colorAdd=0}destroy(){this.reset()}},_M=!1;function vM(){_M||(_M=!0,L.add(fM),L.add(hM))}function yM(e,t,n,r=0){return(xM(r)<<24|xM(n)<<16|xM(t)<<8|xM(e))>>>0}function bM(e,t){return yM((e>>16&255)/255*t,(e>>8&255)/255*t,(e&255)/255*t)}function xM(e){return Math.max(0,Math.min(255,Math.round(e*255)))}var SM=lM;vM();var CM=class extends wl{constructor(e){super(e),this._colorAdd=0,mM(this)}get colorAdd(){return this._colorAdd}set colorAdd(e){this._colorAdd!==e&&(this._colorAdd=e,this.onViewUpdate())}setColorAdd(e,t,n,r=0){this.colorAdd=yM(e,t,n,r)}lerpTint(e,t){let n=Math.round((1-t)*255);this.tint=n<<16|n<<8|n,this.colorAdd=bM(e,t)}silhouette(e){this.tint=0,this.colorAdd=bM(e,1)}resetColor(){this.tint=16777215,this.colorAdd=0}};function wM(e){return[e>>16&255,e>>8&255,e&255]}function TM(e){let[t,n,r]=wM(e);return Math.floor((t+n+r)/3)}function EM(e,t,n){return Math.trunc(n*e+(1-n)*t)}function DM(e,t,n){let[r,i,a]=wM(e),[o,s,c]=wM(t);return EM(r,o,n)<<16|EM(i,s,n)<<8|EM(a,c,n)}function OM(e,t){let n=e.length>0?TM(e[0]):255;return{from:e,to:e.map(e=>{let r=TM(e);return n!==0&&r<=n?DM(t.mid,t.min,r/n):DM(t.mid,t.max,(255-r)/(255-n))})}}function kM(e,t,n=`exact`){let r=t.from.map(wM),i=new Uint8ClampedArray(e.length);for(let a=0;a<e.length;a+=4){let o=e[a+3],s=e[a],c=e[a+1],l=e[a+2];if(i[a]=s,i[a+1]=c,i[a+2]=l,i[a+3]=o,o===0||r.length===0)continue;if(n===`exact`){let e=r.findIndex(([e,t,n])=>e===s&&t===c&&n===l);if(e<0)continue;let[n,o,u]=wM(t.to[e]??t.from[e]);i[a]=n,i[a+1]=o,i[a+2]=u;continue}let u=0,d=1/0;for(let e=0;e<r.length;e+=1){let[t,n,i]=r[e],a=s-t,o=c-n,f=l-i,p=a*a+o*o+f*f;p<d&&(d=p,u=e)}let[f,p,m]=wM(t.to[u]??t.from[u]);i[a]=f,i[a+1]=p,i[a+2]=m}return i}function AM(e,t,n){let r=e.width,i=e.height;if(r<=0||i<=0||!e.source)return e;let a=!t.createCanvas,o=t.createCanvas?.(r,i)??(typeof document>`u`?null:document.createElement(`canvas`));if(!o)return e;o.width=r,o.height=i;let s=o.getContext(`2d`);if(!s)return e;let c=a?{drawImage:s.drawImage.bind(s),getImageData:s.getImageData.bind(s),putImageData:(e,t,n)=>s.putImageData(new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),t,n)}:s;return s.drawImage(e.source.resource,0,0),n(c,r,i),q.from(o)}function jM(e,t,n={},r=`exact`){return AM(e,n,(e,n,i)=>{let a=kM(e.getImageData(0,0,n,i).data,t,r);e.putImageData({data:a,width:n,height:i},0,0)})}function MM(e){e=e.replace(/^"|"$/g,``);let t=[],n=0,r=0;for(let i=0;i<e.length;i+=1)e[i]===`(`?r+=1:e[i]===`)`?r=Math.max(0,r-1):e[i]===`~`&&r===0&&(t.push(e.slice(n,i)),n=i+1);t.push(e.slice(n));let i=(t.shift()??``).trim(),a=[];for(let e of t){let t=/^([A-Za-z][A-Za-z0-9_-]*)(?:\((.*)\))?$/.exec(e.trim());t&&a.push({name:t[1].toUpperCase(),args:t[2]===void 0?[]:t[2].split(`,`).map(e=>e.trim())})}return{path:i,modifiers:a}}function NM(e,t){return e.modifiers.find(e=>e.name===t.toUpperCase())}function PM(e){return e!==void 0&&/^(linear|smooth)$/i.test(e)?`linear`:`nearest`}function FM(e,t,n){return[1,0,0,0,e/255,0,1,0,0,t/255,0,0,1,0,n/255,0,0,0,1,0]}function IM(e){return[(e.red??100)/100,0,0,0,0,0,(e.green??100)/100,0,0,0,0,0,(e.blue??100)/100,0,0,0,0,0,1,0]}function LM(e,t){let n=1-t,r=(e>>16&255)/255,i=(e>>8&255)/255,a=(e&255)/255;return[n,0,0,0,r*t,0,n,0,0,i*t,0,0,n,0,a*t,0,0,0,1,0]}function RM(e){let t=[`R`,`G`,`B`,`A`].map((t,n)=>e[n]??t),n=e=>{switch(e){case`R`:return[1,0,0,0,0];case`G`:return[0,1,0,0,0];case`B`:return[0,0,1,0,0];case`A`:return[0,0,0,1,0];case`0`:return[0,0,0,0,0];case`1`:return[0,0,0,0,1]}};return t.flatMap(e=>n(e))}function zM(e,t){let n=new Bk;n.matrix=t,e.filters=[n]}function BM(e){if(e===void 0)return;let t=e.trim(),n=t.endsWith(`%`),r=Number(n?t.slice(0,-1):t);if(Number.isFinite(r))return n||r>1?r/100:r}function VM(e){if(e===void 0)return;let t=Number.parseInt(e.replace(/^#/,``),16);return Number.isFinite(t)?t:void 0}function HM(e,t,n=1){let r=NM(t,`FL`);r&&(r.args.length===0||r.args.some(e=>/horiz|horizontal|x/i.test(e)))&&(e.scale.x*=-1),r?.args.some(e=>/vert|vertical|y/i.test(e))&&(e.scale.y*=-1);let i=NM(t,`SCALE`);if(i){let t=Number(i.args[0]),r=Number(i.args[1]??i.args[0]);Number.isFinite(t)&&t>0&&(e.width=t*n),Number.isFinite(r)&&r>0&&(e.height=r*n)}if(NM(t,`GS`)){let t=new Bk;t.greyscale(1,!1),e.filters=[...e.filters??[],t]}let a=NM(t,`CS`);if(a){let t=a.args.slice(0,3).map(Number);if(t.length===3&&t.every(e=>Number.isFinite(e))){let n=new Bk;n.matrix=FM(t[0],t[1],t[2]),e.filters=[...e.filters??[],n]}}let o=NM(t,`R`),s=NM(t,`G`),c=NM(t,`B`);if(o||s||c){let t=o?Number(o.args[0]):void 0,n=s?Number(s.args[0]):void 0,r=c?Number(c.args[0]):void 0,i=new Bk;i.matrix=IM({red:Number.isFinite(t)?t:void 0,green:Number.isFinite(n)?n:void 0,blue:Number.isFinite(r)?r:void 0}),e.filters=[...e.filters??[],i]}let l=NM(t,`CHAN`);if(l&&l.args.length>0){let t=l.args.map(e=>e.trim().toUpperCase()),n=new Bk;n.matrix=RM(t),e.filters=[...e.filters??[],n]}let u=NM(t,`O`);if(u){let t=BM(u.args[0]);t!==void 0&&(e.alpha*=Math.min(1,Math.max(0,t)))}}function UM(e,t,n={},r=1){e.texture=JM(e.texture,t,n),HM(e,t,r)}function WM(e,t){let n=NM(t,`CROP`);if(!n||n.args.length<4||!e.source)return e;let r=n.args.slice(0,4).map(Number);if(r.some(e=>!Number.isFinite(e))||r[2]<=0||r[3]<=0)return e;let i=Math.max(0,r[0]),a=Math.max(0,r[1]),o=Math.min(r[2],Math.max(0,e.width-i)),s=Math.min(r[3],Math.max(0,e.height-a));return o>0&&s>0?new q({source:e.source,frame:new G(i,a,o,s)}):e}function GM(e,t){let n=e.trim();return VM(n)??t?.(n)}function KM(e,t){let n=[],r=[];for(let i of e){let[e,a]=i.split(`>`);if(e===void 0||a===void 0)continue;let o=GM(e,t),s=GM(a,t);o!==void 0&&s!==void 0&&(n.push(o),r.push(s))}return{from:n,to:r}}function qM(e,t){let n=e.join(`,`),r=n.indexOf(`>`);if(r<0)return{from:[],to:[]};let i=e=>e.split(`,`).map(e=>GM(e,t)).filter(e=>e!==void 0);return{from:i(n.slice(0,r)),to:i(n.slice(r+1))}}function JM(e,t,n={}){let r=e,i=NM(t,`RC`);if(i&&i.args.length>0){let e=KM(i.args,n.resolveColor);e.from.length>0&&(r=jM(r,e,n,`exact`))}let a=NM(t,`PAL`);if(a){let e=qM(a.args,n.resolveColor);e.from.length>0&&e.from.length===e.to.length&&(r=jM(r,e,n,`exact`))}let o=NM(t,`BLIT`);if(o&&o.args.length>0&&n.resolveTexture){let e=n.resolveTexture(o.args[0]);if(e){let t=Number(o.args[1]??0)||0,i=Number(o.args[2]??0)||0;r=AM(r,n,n=>{n.drawImage(e.source.resource,t,i)})}}let s=NM(t,`MASK`);if(s&&s.args.length>0&&n.resolveTexture){let e=n.resolveTexture(s.args[0]);if(e){let t=Number(s.args[1]??0)||0,i=Number(s.args[2]??0)||0;r=AM(r,n,(r,a,o)=>{let s=r.getImageData(0,0,a,o),c=YM(e.width,e.height,n);if(!c)return;let l=c.getContext(`2d`);if(!l)return;l.drawImage(e.source.resource,0,0);let u=l.getImageData(0,0,e.width,e.height),d=XM(s.data,a,o,u.data,e.width,e.height,t,i);r.putImageData({data:d,width:a,height:o},0,0)})}}let c=NM(t,`BLEND`);if(c){let e=GM(c.args[0]??``,n.resolveColor),t=BM(c.args[1]);e!==void 0&&t!==void 0&&(r=AM(r,n,(n,r,i)=>{let a=ZM(n.getImageData(0,0,r,i).data,e,t);n.putImageData({data:a,width:r,height:i},0,0)}))}let l=NM(t,`ROTATE`);if(l){let e=Number(l.args[0]);if(Number.isFinite(e)&&e%360!=0){let t=r.width,i=r.height;if(t>0&&i>0&&r.source){let a=YM(t,i,n),o=a?.getContext(`2d`);if(a&&o){o.drawImage(r.source.resource,0,0);let a=QM(o.getImageData(0,0,t,i).data,t,i,e,PM(l.args[1])),s=YM(a.width,a.height,n),c=s?.getContext(`2d`);s&&c&&(c.putImageData({data:a.data,width:a.width,height:a.height},0,0),r=q.from(s))}}}}return r}function YM(e,t,n){let r=n.createCanvas?.(e,t)??(typeof document>`u`?null:document.createElement(`canvas`));return r?(r.width=e,r.height=t,r):null}function XM(e,t,n,r,i,a,o,s){let c=new Uint8ClampedArray(e.length);for(let l=0;l<n;l+=1)for(let n=0;n<t;n+=1){let u=(l*t+n)*4,d=n-o,f=l-s,p=d>=0&&d<i&&f>=0&&f<a?r[(f*i+d)*4+3]:0;c[u]=e[u],c[u+1]=e[u+1],c[u+2]=e[u+2],c[u+3]=Math.round(e[u+3]*p/255)}return c}function ZM(e,t,n){let r=Math.min(1,Math.max(0,n)),i=t>>16&255,a=t>>8&255,o=t&255,s=new Uint8ClampedArray(e.length);for(let t=0;t<e.length;t+=4){let n=e[t+3];s[t+3]=n,n===0?(s[t]=e[t],s[t+1]=e[t+1],s[t+2]=e[t+2]):(s[t]=e[t]*(1-r)+i*r,s[t+1]=e[t+1]*(1-r)+a*r,s[t+2]=e[t+2]*(1-r)+o*r)}return s}function QM(e,t,n,r,i=`nearest`){let a=r*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=t/2,l=n/2,u=0,d=0;for(let[e,t]of[[-c,-l],[c,-l],[c,l],[-c,l]])u=Math.max(u,Math.abs(e*o-t*s)),d=Math.max(d,Math.abs(e*s+t*o));let f=Math.max(1,Math.round(u*2)),p=Math.max(1,Math.round(d*2)),m=new Uint8ClampedArray(f*p*4),h=t/2-.5,g=n/2-.5,_=f/2-.5,v=p/2-.5,y=i===`linear`&&r%90!=0;for(let r=0;r<p;r+=1)for(let i=0;i<f;i+=1){let a=i-_,c=r-v,l=a*o+c*s+h,u=-a*s+c*o+g,d=(r*f+i)*4;if(y)$M(e,t,n,l,u,m,d);else{let r=Math.round(l),i=Math.round(u);if(r<0||r>=t||i<0||i>=n)continue;let a=(i*t+r)*4;m[d]=e[a],m[d+1]=e[a+1],m[d+2]=e[a+2],m[d+3]=e[a+3]}}return{data:m,width:f,height:p}}function $M(e,t,n,r,i,a,o){if(r<-.5||i<-.5||r>t-.5||i>n-.5)return;let s=Math.floor(r),c=Math.floor(i),l=r-s,u=i-c,d=0,f=0,p=0,m=0;for(let r=0;r<=1;r+=1)for(let i=0;i<=1;i+=1){let a=(i===0?1-l:l)*(r===0?1-u:u);if(a===0)continue;let o=kn(s+i,0,t-1),h=(kn(c+r,0,n-1)*t+o)*4,g=e[h+3];d+=g*a,f+=e[h]*g*a,p+=e[h+1]*g*a,m+=e[h+2]*g*a}d<=0||(a[o]=f/d,a[o+1]=p/d,a[o+2]=m/d,a[o+3]=d)}var eN=class{constructor(e,{fps:t=10,loop:n=!0,startTime:r=0}={}){if(e.length===0)throw Error(`an animation needs at least one frame`);if(!(t>0))throw Error(`an animation needs a positive fps, got ${t}`);this.frameDuration=1/t,this.frames=e.map(e=>tN(e)?e:{texture:e}),this.times=this.frames.map(e=>e.duration??this.frameDuration),this.loop=n,this.startTime=r;let i=0,a=0;for(let e of this.frames)e.duration===void 0?i++:a+=e.duration;this.duration=i*this.frameDuration+a}frameAt(e){return this.frames[this.frameIndexAt(e)]}frameIndexAt(e){let t=e-this.startTime;if(t<=0)return 0;let n=this.duration;if(n<=0)return this.frames.length-1;let r=this.loop?t%n:Math.min(t,n);for(let e=0;e<this.times.length;e++){if(r<this.times[e])return e;r-=this.times[e]}return this.frames.length-1}};function tN(e){return e.texture!==void 0}var nN=class extends CM{constructor(...e){super(...e),this.animations=new Map,this.current=null,this.currentName=null,this.elapsed=0,this.finished=!1,this.offset={x:0,y:0},this.onFinish=null,this.paused=!1}add(e,t,n){return this.animations.set(e,new eN(t,n)),this}has(e){return this.animations.has(e)}get playing(){return this.currentName}get isFinished(){return this.finished}get frameOffset(){return this.offset}get elapsedTime(){return this.elapsed}play(e,t=!1){if(!t&&this.currentName===e&&!this.finished)return this;let n=this.animations.get(e);if(!n)throw Error(`no animation named "${e}" on this sprite`);return this.current=n,this.currentName=e,this.elapsed=0,this.finished=!1,this.show(n.frameAt(0)),this}stop(){this.current=null,this.currentName=null}update(e){let t=this.current;!t||this.paused||this.finished||(this.elapsed+=e,this.show(t.frameAt(this.elapsed)),!t.loop&&this.elapsed>=t.startTime+t.duration&&(this.finished=!0,this.onFinish?.(this.currentName)))}show(e){this.texture=e.texture,this.offset.x=e.offsetX??0,this.offset.y=e.offsetY??0}};function rN(e,t,n,r){return t>=e.x-r&&t<=e.x+e.width+r&&n>=e.y-r&&n<=e.y+e.height+r}function iN(e,t,n,r=0){return rN(e.view,t,n,r)}var aN=class{constructor(){this.members=[]}get size(){return this.members.length}add(e){return this.members.includes(e)||this.members.push(e),this}remove(e){let t=this.members.indexOf(e);return t<0?!1:(this.members.splice(t,1),!0)}clear(){this.members.length=0}update(e,t,n=0){let r=e.view;for(let e of[...this.members])rN(r,e.x,e.y,n)&&e.update(t)}};function oN(e){for(let t of[`columns`,`rows`])if(!Number.isInteger(e[t])||e[t]<2)throw RangeError(`a pinned deform grid needs integer ${t} of at least 2, saw ${e[t]}`);for(let t of[`width`,`height`])if(!Number.isFinite(e[t])||e[t]<=0)throw RangeError(`a pinned deform grid needs ${t} above 0, saw ${e[t]}`)}function sN(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw Error(`a deform control point needs finite coordinates, saw (${e}, ${t})`)}var cN=class{constructor(e){oN(e),this.columns=e.columns,this.rows=e.rows,this.width=e.width,this.height=e.height,this.rest=new Float32Array(this.count*2),this.offsets=new Float32Array(this.count*2);for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++){let n=(e*this.columns+t)*2;this.rest[n]=t/(this.columns-1)*this.width,this.rest[n+1]=e/(this.rows-1)*this.height}}get count(){return this.columns*this.rows}indexOf(e,t){if(!Number.isInteger(e)||!Number.isInteger(t)||e<0||t<0||e>=this.columns||t>=this.rows)throw RangeError(`control point (${e}, ${t}) is outside a ${this.columns}x${this.rows} grid`);return t*this.columns+e}checkIndex(e){if(!Number.isInteger(e)||e<0||e>=this.count)throw RangeError(`control point ${e} is outside a grid of ${this.count} points`)}restAt(e){return this.checkIndex(e),{x:this.rest[e*2],y:this.rest[e*2+1]}}at(e){return this.checkIndex(e),{x:this.rest[e*2]+this.offsets[e*2],y:this.rest[e*2+1]+this.offsets[e*2+1]}}isMoved(e){return this.checkIndex(e),this.offsets[e*2]!==0||this.offsets[e*2+1]!==0}movedCount(){let e=0;for(let t=0;t<this.count;t++)(this.offsets[t*2]!==0||this.offsets[t*2+1]!==0)&&e++;return e}drag(e,t,n){this.checkIndex(e),sN(t,n),this.offsets[e*2]=t-this.rest[e*2],this.offsets[e*2+1]=n-this.rest[e*2+1]}dragMany(e){for(let t of e)this.checkIndex(t.index),sN(t.x,t.y);for(let t of e)this.drag(t.index,t.x,t.y)}nudge(e,t,n){this.checkIndex(e),sN(t,n),this.offsets[e*2]+=t,this.offsets[e*2+1]+=n}reset(e){e===void 0?this.offsets.fill(0):(this.checkIndex(e),this.offsets[e*2]=0,this.offsets[e*2+1]=0)}rebase(e){if(!(e instanceof Float32Array)||e.length!==this.rest.length)throw Error(`rebase needs a Float32Array of ${this.rest.length} floats, saw length ${e?.length}`);for(let t of e)if(!Number.isFinite(t))throw Error(`rebase needs finite rest positions`);this.rest.set(e),this.offsets.fill(0)}positions(){let e=new Float32Array(this.rest.length);return this.writePositions(e),e}writePositions(e){if(!(e instanceof Float32Array)||e.length!==this.rest.length)throw Error(`a deform target needs a Float32Array of ${this.rest.length} floats, saw length ${e?.length}`);for(let t=0;t<this.rest.length;t++)e[t]=this.rest[t]+this.offsets[t]}},lN=class extends _j{constructor(e,t){let n=t?.columns??4,r=t?.rows??4,i=new cN({columns:n,rows:r,width:e.width,height:e.height});super({texture:e,verticesX:n,verticesY:r}),this.deform=i,this.autoResize=!1,this.deform.rebase(Float32Array.from(this.positionArray())),this.sync()}positionArray(){return this.geometry.getAttribute(`aPosition`).buffer.data}sync(){let e=this.geometry.getAttribute(`aPosition`);this.deform.writePositions(e.buffer.data),e.buffer.update()}get columns(){return this.deform.columns}get rows(){return this.deform.rows}get count(){return this.deform.count}indexOf(e,t){return this.deform.indexOf(e,t)}restAt(e){return this.deform.restAt(e)}vertexAt(e){return this.deform.at(e)}isMoved(e){return this.deform.isMoved(e)}movedCount(){return this.deform.movedCount()}dragVertex(e,t,n){this.deform.drag(e,t,n),this.sync()}dragVertices(e){this.deform.dragMany(e),this.sync()}nudgeVertex(e,t,n){this.deform.nudge(e,t,n),this.sync()}resetVertices(e){this.deform.reset(e),this.sync()}},uN=l({advance:()=>bN,advancePlayback:()=>gN,advancePose:()=>xN,boneOrder:()=>dN,create:()=>fN,createMixer:()=>_N,crossfadeTo:()=>vN,mixPoses:()=>yN,resolve:()=>pN,samplePose:()=>mN,sampleTransformPose:()=>hN,solveTwoBoneIK:()=>wN,validatePose:()=>CN});function dN(e){let t=new Map(e.bones.map(e=>[e.name,e])),n=[],r=new Set,i=new Set,a=e=>{if(!r.has(e.name)){if(i.has(e.name))throw Error(`skeleton cycle involving ${e.name}`);if(e.parent&&!t.has(e.parent))throw Error(`skeleton bone ${e.name} names no parent ${e.parent}`);if(e.parent){i.add(e.name);let n=t.get(e.parent);n&&a(n),i.delete(e.name)}r.has(e.name)||(r.add(e.name),n.push(e.name))}};for(let t of e.bones)a(t);return n}function fN(e){let t=new Set;for(let n of e){if(t.has(n.name))throw Error(`duplicate skeleton bone ${n.name}`);if(t.add(n.name),n.limits&&!(n.limits.min<=n.limits.max))throw Error(`invalid joint limits for bone ${n.name}`)}let n=dN({bones:e});for(let t of e)if(t.parent&&n.indexOf(t.parent)>=n.indexOf(t.name))throw Error(`skeleton bone ${t.name} cannot precede its parent ${t.parent}`);return{bones:e}}function pN(e,t={}){let n=typeof t.rotations==`object`?t.rotations:t,r=t.translations??{},i=t.scales??{},a=new Map(e.bones.map(e=>[e.name,e])),o=new Map;for(let t of dN(e)){let e=a.get(t);if(!e)throw Error(`skeleton bone ${t} went missing`);let s=e.parent?o.get(e.parent):void 0,c=(e.rotation??0)+(n[t]??0),l=(s?s.angle:0)+c,u=i[t]??{x:1,y:1},d=(s?s.scaleX:1)*u.x,f=(s?s.scaleY:1)*u.y,p=l*Math.PI/180,m={a:Math.cos(p)*d,b:Math.sin(p)*d,c:-Math.sin(p)*f,d:Math.cos(p)*f},h=s?{a:s.matrix.a,b:s.matrix.b,c:s.matrix.c,d:s.matrix.d}:{a:1,b:0,c:0,d:1},g=e.origin?.x??0,_=e.origin?.y??0,v=g+(r[t]?.x??0),y=_+(r[t]?.y??0),b=(s?s.tipX:0)+h.a*v+h.c*y,x=(s?s.tipY:0)+h.b*v+h.d*y;for(let e of[m.a,m.b,m.c,m.d])if(!Number.isFinite(e))throw Error(`invalid transform for bone ${t}`);o.set(t,{name:t,x:b,y:x,angle:l,scaleX:d,scaleY:f,matrix:m,tipX:b+m.a*(e.length??0),tipY:x+m.b*(e.length??0)})}return[...o.values()]}function mN(e,t,n){return{...hN(e,t,n).rotations}}function hN(e,t,n){let r=e.frames;if(!r.length)return n&&CN(n,{}),{rotations:{}};let i=e.loop&&e.duration>0?(t%e.duration+e.duration)%e.duration:t,a=r[0];if(!e.loop&&i>=e.duration)a=r[r.length-1];else if(i>=r[0].time){a=r[r.length-1];for(let e=1;e<r.length;e++)if(i<r[e].time){let t=r[e].time-r[e-1].time;a=SN(r[e-1],r[e],t>0?(i-r[e-1].time)/t:0,!0);break}}let o=SN(a,a,0,!0);return n&&CN(n,o.rotations),o}function gN(e,t){let n=e.clip,r=e.time+t*e.rate;return n.loop&&n.duration>0?(r%=n.duration,r<0&&(r+=n.duration)):r=Math.max(0,Math.min(n.duration,r)),{clip:n,time:r,rate:e.rate}}function _N(e,t,n=1){return{skeleton:e,base:{clip:t,time:0,rate:n},layers:[]}}function vN(e,t,n=.25,r=e.base.rate){n<=0?(e.base={clip:t,time:0,rate:r},e.crossfade=void 0):(e.crossfade={from:e.base,remaining:n,duration:n},e.base={clip:t,time:0,rate:r})}function yN(e,t){let n={rotations:e};for(let e of[...t].sort((e,t)=>e.priority-t.priority)){let t=Math.max(0,Math.min(1,e.weight));t&&(n=SN(n,{rotations:e.pose},t,!1))}return{...n.rotations}}function bN(e,t){return{...xN(e,t).rotations}}function xN(e,t){e.base=gN(e.base,t);for(let n of e.layers)n.playback=gN(n.playback,t);let n=hN(e.base.clip,e.base.time,e.skeleton);if(e.crossfade){let r=e.crossfade;r.from=gN(r.from,t),r.remaining=Math.max(0,r.remaining-t);let i=hN(r.from.clip,r.from.time,e.skeleton),a=r.duration>0?1-r.remaining/r.duration:1;n=SN(i,n,a,!0),r.remaining===0&&(e.crossfade=void 0)}for(let t of[...e.layers].sort((e,t)=>e.priority-t.priority))n=SN(n,hN(t.playback.clip,t.playback.time,e.skeleton),Math.max(0,Math.min(1,t.weight)),!1);return n}function SN(e,t,n,r){let i={...e.rotations};for(let a of new Set([...Object.keys(t.rotations),...r?Object.keys(e.rotations):[]]))i[a]=(e.rotations[a]??0)*(1-n)+(t.rotations[a]??0)*n;let a={rotations:i};for(let i of[`translations`,`scales`]){let o=e[i]??{},s=t[i]??{},c=+(i===`scales`),l={...o};for(let e of new Set([...Object.keys(s),...r?Object.keys(o):[]]))l[e]={x:(o[e]?.x??c)*(1-n)+(s[e]?.x??c)*n,y:(o[e]?.y??c)*(1-n)+(s[e]?.y??c)*n};Object.keys(l).length&&(a[i]=l)}return a}function CN(e,t){for(let n of e.bones){let e=(n.rotation??0)+(t[n.name]??0);if(!Number.isFinite(e))throw Error(`invalid rotation for bone ${n.name}`);if(n.limits&&(e<n.limits.min||e>n.limits.max))throw Error(`joint limit for bone ${n.name}: ${e} outside [${n.limits.min}, ${n.limits.max}]`)}}function wN(e,t,n,r,i=1,a={}){let o=e.bones.find(e=>e.name===t),s=e.bones.find(e=>e.name===n);if(!o||!s||s.parent!==t)throw Error(`IK chain ${t}/${n} must be connected`);if((s.origin?.x??0)!==0||(s.origin?.y??0)!==0)throw Error(`IK bone ${n} needs a zero origin`);let c=o.length??0,l=s.length??0;if(!(c>0&&l>0)||!Number.isFinite(c+l))throw Error(`IK chain ${t}/${n} needs positive finite lengths`);if(!Number.isFinite(r.x)||!Number.isFinite(r.y)||i!==1&&i!==-1)throw Error(`invalid IK target or bend for ${t}/${n}`);let u=pN(e,a),d=u.find(e=>e.name===t);if(!d)throw Error(`IK chain ${t}/${n} resolves no base`);let f=r.x-d.x,p=r.y-d.y,m=Math.hypot(f,p);if(m>c+l+1e-9||m<Math.abs(c-l)-1e-9)throw Error(`unreachable IK target for ${t}/${n}`);let h=i*Math.acos(Math.max(-1,Math.min(1,(m*m-c*c-l*l)/(2*c*l)))),g=Math.atan2(p,f)-Math.atan2(l*Math.sin(h),c+l*Math.cos(h)),_=o.parent?u.find(e=>e.name===o.parent):void 0,v=_?_.angle:0,y={...a,[t]:g*180/Math.PI-v-(o.rotation??0),[n]:h*180/Math.PI-(s.rotation??0)};return CN(e,y),y}var TN=class extends J{constructor(e,t){super(),this.parts=new Map,this.skeleton=e,this.mixer=t}bind(e,t){let n=new CM(t);return this.parts.set(e,n),this.addChild(n),n}part(e){return this.parts.get(e)}apply(e){let t=new Map(pN(this.skeleton,e).map(e=>[e.name,e]));for(let[e,n]of this.parts){let r=t.get(e);if(!r)throw Error(`skeletal sprite binds no bone named ${e}`);let{a:i,b:a,c:o,d:s}=r.matrix;n.setFromMatrix(new z(i,a,o,s,r.x,r.y))}if(this.diagnostics){this.setChildIndex(this.diagnostics,this.children.length-1);let e=this.diagnostics.clear();for(let n of t.values())e.moveTo(n.x,n.y).lineTo(n.tipX,n.tipY).stroke({color:65535,width:2}),e.circle(n.x,n.y,4).fill(16768256),e.circle(n.tipX,n.tipY,2).fill(16729224),e.moveTo(n.x-7,n.y).lineTo(n.x+7,n.y).moveTo(n.x,n.y-7).lineTo(n.x,n.y+7).stroke({color:16768256,width:1})}}setDiagnostics(e){e&&!this.diagnostics&&(this.diagnostics=this.addChild(new Z)),!e&&this.diagnostics&&(this.diagnostics.destroy(),this.diagnostics=void 0)}update(e){if(!this.mixer)throw Error(`a skeletal sprite without a mixer needs apply(pose)`);this.apply(bN(this.mixer,e))}},EN=class{constructor(e){if(this.points=[],this.previous=[],e.segments<2)throw Error(`an articulated chain needs at least two segments`);if(e.length<=0)throw Error(`an articulated chain needs a positive length`);this.length=e.length,this.stiffness=Math.max(0,Math.min(1,e.stiffness??1)),this.bendLimit=(e.bendLimit??90)*(Math.PI/180);for(let t=0;t<e.segments;t++)this.points.push({x:-t*e.length,y:0}),this.previous.push({x:-t*e.length,y:0})}pull(e,t){this.points[0].x=e,this.points[0].y=t}update(e){for(let e=0;e<this.points.length;e++)this.previous[e]={x:this.points[e].x,y:this.points[e].y};for(let e=1;e<this.points.length;e++){let t=this.previous[e-1],n=this.points[e],r=t.x-n.x,i=t.y-n.y,a=Math.hypot(r,i);if(a>this.length){let e=a>0?(a-this.length)/a:0;n.x+=r*e*this.stiffness,n.y+=i*e*this.stiffness}}for(let e=2;e<this.points.length;e++){let t=this.points[e-2],n=this.points[e-1],r=this.points[e],i=Math.atan2(n.y-t.y,n.x-t.x),a=Math.atan2(r.y-n.y,r.x-n.x)-i;for(;a>Math.PI;)a-=2*Math.PI;for(;a<-Math.PI;)a+=2*Math.PI;if(Math.abs(a)<=this.bendLimit)continue;let o=i+Math.sign(a)*this.bendLimit;r.x=n.x+Math.cos(o)*this.length,r.y=n.y+Math.sin(o)*this.length}}},DN=class extends J{constructor(e,t){if(super(),t.length!==e.points.length)throw Error(`a chain rig needs one texture per segment`);this.chain=e,this.segments=t.map(e=>{let t=new CM(e);return t.anchor.set(0,.5),this.addChild(t),t})}update(e){this.chain.update(e);for(let e=0;e<this.segments.length;e++){let t=this.chain.points[e],n=this.chain.points[e+1]??t;this.segments[e].position.set(t.x,t.y),this.segments[e].rotation=Math.atan2(n.y-t.y,n.x-t.x)}}},ON=``;function kN(e){ON=e.endsWith(`/`)||e===``?e:e+`/`}var AN;function jN(e){AN=e}function MN(){return AN||(typeof window>`u`?void 0:window.__MWG_ASSETS__)}function NN(){return MN()!==void 0}function PN(){return Object.keys(MN()??{})}function FN(e){let t=MN();return!t||e in t}function IN(e){if(/^(data|blob):/.test(e))return e;let t=MN();if(!t)return ON+e;let n=t[e];if(n===void 0)throw Error(`asset "${e}" is not in this build - check it is under the folder passed to compile-resources`);return n}var LN={"image/png":`png`,"image/jpeg":`jpg`,"image/webp":`webp`,"image/gif":`gif`,"image/svg+xml":`svg`};async function RN(e,t={}){let{onProgress:n,resolution:r,optional:i,onMissing:a}=typeof t==`function`?{onProgress:t,resolution:void 0,optional:void 0,onMissing:void 0}:t,o=new Set(i??[]),s=e.filter(e=>!Ik.cache.has(e)),c=s.filter(e=>!o.has(e)),l=s.filter(e=>o.has(e)),u=e=>{let t=IN(e),n={alias:e,src:t};if(r!==void 0&&(n.data={resolution:r}),t.startsWith(`data:`)){let r=/^data:([^;,]+)/.exec(t)?.[1],i=(r&&LN[r])??/\.([a-z0-9]+)$/i.exec(e)?.[1];i&&(n.format=i)}Ik.add(n)};if(l.length===0&&c.length===0){n?.(1);return}for(let e of c)u(e);let d=c.length>0?Ik.load(c,n):Promise.resolve(),f=l.map(async e=>{u(e);try{await Ik.load(e)}catch(t){a?.(e,t)}});await Promise.all([d,...f]),l.length>0&&c.length===0&&n?.(1)}function zN(e,t){if(!Ik.cache.has(e)){if(t!==void 0)return t;throw Error(`texture "${e}" has not been loaded - pass it to load() first`)}return Ik.get(e)}function BN(e,t){if(!Ik.cache.has(e)){if(t!==void 0)return t;throw Error(`asset "${e}" has not been loaded - pass it to load() first`)}return Ik.get(e)}function VN(e){return Ik.cache.has(e)}async function HN(e){let t=e.filter(e=>Ik.cache.has(e));t.length!==0&&await Ik.unload(t)}var UN=new Map;async function WN(e,t,n={}){let r=n.fetch??globalThis.fetch;if(!r)throw Error(`fetch is unavailable; provide LoadBinaryOptions.fetch`);let i=e.filter(e=>!UN.has(e));if(i.length===0){t?.(1);return}let a=0;await Promise.all(i.map(async e=>{let n=await r(IN(e));if(!n.ok)throw Error(`failed to load binary asset "${e}": ${n.status}`);UN.set(e,await n.arrayBuffer()),a++,t?.(a/i.length)}))}function GN(e){let t=UN.get(e);if(!t)throw Error(`binary asset "${e}" has not been loaded - pass it to loadBinary() first`);return t}function KN(e){return UN.has(e)}function qN(e){for(let t of e)UN.delete(t)}var JN=[{name:`<script>`,pattern:/<script[\s/>]/i},{name:`<foreignObject>`,pattern:/<foreignobject[\s/>]/i},{name:`<iframe>`,pattern:/<iframe[\s/>]/i},{name:`<embed>`,pattern:/<embed[\s/>]/i},{name:`<object>`,pattern:/<object[\s/>]/i},{name:`an event-handler attribute`,pattern:/\son[a-z]+\s*=/i},{name:`a javascript: URL`,pattern:/javascript\s*:/i},{name:`a data: URL of an active type`,pattern:/data:(?:text\/html|application\/xml|image\/svg\+xml)/i}];function YN(e){for(let{name:t,pattern:n}of JN)if(n.test(e))throw Error(`SVG refused: contains ${t}`);return e}function XN(e){return`data:image/svg\+xml,${encodeURIComponent(e)}`}function ZN(e,t){let n=YN(e);if(t.length===0)throw Error(`SVG scale variants need at least one named scale`);let r=new Set;for(let e of t){if(!e.name)throw Error(`an SVG scale variant needs a name`);if(!Number.isFinite(e.resolution)||e.resolution<=0)throw Error(`SVG scale variant ${e.name} needs a positive resolution`);if(r.has(e.name))throw Error(`duplicate SVG scale variant ${e.name}`);r.add(e.name)}let i=XN(n);return t.map(e=>({name:e.name,src:i,resolution:e.resolution}))}function QN(e){let t=YN(e),n=/^([\s\S]*?)<svg([^>]*)>/i.exec(t),r=t.lastIndexOf(`</svg>`);if(!n||r<0)throw Error(`SVG group split needs an <svg> root`);let i=t.slice(n[0].length,r),a=[...i.matchAll(/<(defs|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi)].map(e=>e[0]).join(``),o=i.replace(/<(defs|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,``),s=Object.create(null),c=0;for(;c<o.length;){let e=/<g\b([^>]*?)(\/?)>/i.exec(o.slice(c));if(!e)break;let t=e[1],r=/\bid\s*=\s*["']([^"']+)["']/i.exec(t)?.[1],i=c+e.index+e[0].length;if(e[2]===`/`){if(!r)throw Error(`SVG group split refuses a group with no id`);if(r in s)throw Error(`SVG group split refuses a duplicate id ${r}`);s[r]=`${n[0]}${a}${e[0]}</svg>`,c=i;continue}let l=1,u=i,d=``;for(;l>0&&u<o.length;){let e=o.slice(u).match(/<g\b[^>]*>|<\/g\s*>/i);if(!e)throw Error(`SVG group ${r??`<unnamed>`} never closes`);e[0].startsWith(`</`)?(l--,l===0&&(d=e[0])):/\/\s*>$/.test(e[0])||l++,u+=e.index+e[0].length}if(l!==0)throw Error(`SVG group ${r??`<unnamed>`} never closes`);let f=o.slice(i,u-d.length);if(c=u,!r)throw Error(`SVG group split refuses a group with no id`);if(r in s)throw Error(`SVG group split refuses a duplicate id ${r}`);s[r]=`${n[0]}${a}${e[0]}${f}</g></svg>`}if(Object.keys(s).length===0)throw Error(`SVG group split found no named groups`);return s}var $N=class{constructor(e={}){if(this.entries=new Map,this.clock=0,this.budgetBytes=e.budgetBytes??1/0,!(this.budgetBytes>=0))throw Error(`asset stream budget must not be negative`);this.loadAssets=e.load??RN,this.releaseAssets=e.release??HN}async preload(e,t){if(!e.id)throw Error(`asset bundle needs an id`);if(e.estimatedBytes!==void 0&&e.estimatedBytes<0)throw Error(`asset bundle size must not be negative`);let n=this.entries.get(e.id);if(n?.ready){n.lastUsed=++this.clock,t?.(1);return}let r=e.paths.filter(e=>!this.isRetained(e));r.length>0?await this.loadAssets([...r],t):t?.(1),this.entries.set(e.id,{...e,lastUsed:++this.clock,ready:!0}),await this.enforceBudget(e.id)}async preloadLikely(e,t){let n=[...e].sort((e,t)=>(t.priority??0)-(e.priority??0));for(let[e,r]of n.entries())await this.preload(r,t&&(r=>t((e+r)/n.length)));t?.(1)}use(e){let t=this.entries.get(e);return t?.ready?(t.lastUsed=++this.clock,!0):!1}isReady(e){return this.entries.get(e)?.ready??!1}async unload(e){let t=this.entries.get(e);if(!t)return;this.entries.delete(e);let n=t.paths.filter(e=>!this.isRetained(e));n.length>0&&await this.releaseAssets(n)}get estimatedBytes(){return[...this.entries.values()].reduce((e,t)=>e+(t.estimatedBytes??0),0)}async enforceBudget(e){for(;this.estimatedBytes>this.budgetBytes;){let t=[...this.entries.values()].filter(t=>t.id!==e).sort((e,t)=>e.lastUsed-t.lastUsed)[0];if(!t)return;await this.unload(t.id)}}isRetained(e){return[...this.entries.values()].some(t=>t.ready&&t.paths.includes(e))}};async function eP(e,t,n=fetch){let r=await n(e);if(!r.ok)throw Error(`fetchWithByteProgress: ${e} responded ${r.status}`);let i=r.headers.get(`content-length`),a=i!==null&&i!==``?Number(i):null;if(!r.body){let e=await r.blob();return t?.({loaded:e.size,total:a??e.size}),e}let o=r.body.getReader(),s=[],c=0;for(;;){let{done:e,value:n}=await o.read();if(e)break;s.push(n),c+=n.byteLength,t?.({loaded:c,total:a})}return new Blob(s)}async function tP(e){if(e.trimStart().startsWith(`<`))return YN(e);let t=IN(e);if(t.startsWith(`data:`)){let n=t.indexOf(`,`);if(n<0)throw Error(`invalid SVG data URI for ${e}`);return YN(/;base64/i.test(t.slice(0,n))?new TextDecoder().decode(Uint8Array.from(atob(t.slice(n+1)),e=>e.charCodeAt(0))):decodeURIComponent(t.slice(n+1)))}let n=await fetch(t);if(!n.ok)throw Error(`SVG failed to load ${e}: ${n.status}`);return YN(await n.text())}var nP=new WeakMap;async function rP(e,t={}){let n=t.resolution??1;if(!Number.isFinite(n)||n<=0)throw Error(`SVG parts need a positive finite resolution`);let r=QN(await tP(e)),i=t.groups??Object.keys(r);for(let e of i)if(!Object.hasOwn(r,e))throw Error(`SVG parts unknown group ${e}`);let a=Object.create(null);for(let e of i){let t=XN(r[e].replace(`</svg>`,`<!-- mwg-resolution:${n} --></svg>`)),i=`mwg-svg-part:${n}:${t}`;a[e]=await Ik.load({alias:i,src:t,format:`svg`,data:{resolution:n}}),nP.set(a[e],i)}return Object.freeze(a)}async function iP(e){for(let t of new Set(Object.values(e))){let e=nP.get(t);e&&(await Ik.unload(e),nP.delete(t))}}var aP=l({AssetStream:()=>$N,fetchWithByteProgress:()=>eP,get:()=>BN,getBinary:()=>GN,has:()=>FN,isBinaryLoaded:()=>KN,isCompiled:()=>NN,isLoaded:()=>VN,load:()=>RN,loadBinary:()=>WN,loadSvgParts:()=>rP,paths:()=>PN,release:()=>HN,releaseBinary:()=>qN,releaseSvgParts:()=>iP,resolve:()=>IN,sanitizeSvg:()=>YN,setAssetMap:()=>jN,setBase:()=>kN,splitSvgGroups:()=>QN,svgDataUri:()=>XN,svgScaleVariants:()=>ZN,texture:()=>zN});function oP(e){return{x:e.x,y:e.y,width:e.width,height:e.height}}var sP=class e{constructor(e,t,n){this.frames=new Map,this.names=new Map,this.texture=e,this.frameWidth=t,this.frameHeight=n,this.columns=t>0?Math.floor(e.width/t):0,this.rows=n>0?Math.floor(e.height/n):0,t>0&&(e.width%t!==0||e.height%n!==0)&&console.warn(`sprite sheet ${e.width}x${e.height} is not a whole number of ${t}x${n} frames; the frames will be cut from the wrong places`)}static grid(t,n=0,r=n){return new e(zN(t),n,r)}static strip(t,n){if(!(n>0))throw Error(`a sprite strip needs at least one frame`);let r=zN(t);return new e(r,r.width/n,r.height)}static fromTexture(t,n=0,r=n){return new e(t,n,r)}get count(){return this.columns*this.rows}name(e,t){return this.names.set(e,t),this}nameAll(e){for(let[t,n]of Object.entries(e))this.names.set(t,n);return this}indexOf(e){let t=this.names.get(e);if(t===void 0)throw Error(`this sheet has no frame named "${e}"`);return t}get(e){let t=typeof e==`string`?this.indexOf(e):e,n=this.frames.get(t);if(n)return n;if(t<0||t>=this.count)throw Error(`frame ${t} is outside this sheet, which holds ${this.count}`);let r=new q({source:this.texture.source,frame:new G(t%this.columns*this.frameWidth,Math.floor(t/this.columns)*this.frameHeight,this.frameWidth,this.frameHeight)});return this.frames.set(t,r),r}rect(e,t,n,r,i){if(r<=0||i<=0)throw Error(`a sprite sheet rect needs a positive width and height`);return this.frames.set(e,new q({source:this.texture.source,frame:new G(t,n,r,i)})),this}region(e){let t=this.get(e);return{texture:t,frame:oP(t.frame)}}range(e,t){let n=[];for(let r=e;r<=t;r++)n.push(this.get(r));return n}pick(...e){return e.map(e=>this.get(e))}},cP=class{constructor(e={}){if(this.world=new J,this.x=0,this.y=0,this.requestedZoom=1,this.viewWidth=0,this.viewHeight=0,this.screenX=0,this.screenY=0,this.followTarget=null,this.followIntensity=0,this.shakeMagnitude=0,this.shakeRemaining=0,this.shakeDuration=1,this.shakeX=0,this.shakeY=0,this.bounds=null,this.step=0,this._angle=0,this.targetAngle=null,this.angleIntensity=0,e.grid!==void 0&&e.grid!==`square`&&e.grid!==`hex`)throw Error(`camera grid must be "square" or "hex", not "${e.grid}"`);this.stepsPerTurn=e.grid===`hex`?6:4,this.deadzone=e.deadzone??0,this.pixelPerfectTileSize=e.pixelPerfectTileSize,this.resolution=e.resolution??(()=>1),this.zoom=e.zoom??1}get rotationSteps(){return this.step}get rotation(){return this._angle}get uprightRotation(){return-this.rotation}setRotationStep(e){if(!Number.isInteger(e))throw Error(`camera rotation step must be an integer`);this.step=(e%this.stepsPerTurn+this.stepsPerTurn)%this.stepsPerTurn,this._angle=this.step/this.stepsPerTurn*Math.PI*2,this.targetAngle=null,this.apply()}rotate(e=1){this.setRotationStep(this.step+e)}rotateTo(e){this._angle=e,this.targetAngle=null,this.angleIntensity=0,this.apply()}animateRotationTo(e,t=4){this.targetAngle=e,this.angleIntensity=t}get spin(){let e=this.rotation;return{cos:Math.cos(e),sin:Math.sin(e)}}get zoom(){return this.pixelPerfectTileSize?uP(this.requestedZoom,this.pixelPerfectTileSize,this.resolution()):this.requestedZoom}set zoom(e){this.requestedZoom=Math.max(.01,e)}setViewport(e,t,n=0,r=0){this.viewWidth=e,this.viewHeight=t,this.screenX=n,this.screenY=r}fit(e,t){this.zoom=Math.min(this.viewWidth/e,this.viewHeight/t),this.snapTo(e/2,t/2)}get view(){let e=this.viewWidth/this.zoom,t=this.viewHeight/this.zoom,{x:n,y:r}=this.clampedCentre(this.x,this.y);if(this._angle===0)return{x:n-e/2,y:r-t/2,width:e,height:t};let i=[this.toWorld(this.screenX,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY),this.toWorld(this.screenX+this.viewWidth,this.screenY+this.viewHeight),this.toWorld(this.screenX,this.screenY+this.viewHeight)],a=i.map(e=>e.x),o=i.map(e=>e.y),s=Math.min(...a),c=Math.min(...o);return{x:s,y:c,width:Math.max(...a)-s,height:Math.max(...o)-c}}setBounds(e){this.bounds=e}snapTo(e,t){this.x=e,this.y=t,this.followTarget=null,this.followIntensity=0,this.apply()}panTo(e,t,n=4){this.followTarget={x:e,y:t},this.followIntensity=n}follow(e,t=8){this.followTarget=e,this.followIntensity=t}stopFollowing(){this.followTarget=null,this.followIntensity=0}shake(e,t=.4){br()||(this.shakeMagnitude=e,this.shakeRemaining=this.shakeDuration=t)}shakeScreen(e,t=.4){this.shake(e/this.zoom,t)}update(e){if(this.followTarget&&this.followIntensity>0){let t=this.viewWidth/this.zoom*this.deadzone/2,n=this.viewHeight/this.zoom*this.deadzone/2,r=this.followTarget.x-this.x,i=this.followTarget.y-this.y;r=r>t?r-t:r<-t?r+t:0,i=i>n?i-n:i<-n?i+n:0;let a=br()?1:1-Math.exp(-this.followIntensity*e);this.x+=r*a,this.y+=i*a}if(this.targetAngle!==null&&this.angleIntensity>0){let t=lP(this._angle,this.targetAngle),n=br()?1:1-Math.exp(-this.angleIntensity*e);this._angle+=t*n}if(this.shakeRemaining>0){this.shakeRemaining-=e;let t=Math.max(0,this.shakeRemaining/this.shakeDuration);this.shakeX=D(-this.shakeMagnitude,this.shakeMagnitude)*t,this.shakeY=D(-this.shakeMagnitude,this.shakeMagnitude)*t}else this.shakeX=this.shakeY=0;this.apply()}toScreen(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=e-n,s=t-r;return{x:(o*i-s*a)*this.zoom+this.screenX+this.viewWidth/2,y:(o*a+s*i)*this.zoom+this.screenY+this.viewHeight/2}}toWorld(e,t){let{x:n,y:r}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY),{cos:i,sin:a}=this.spin,o=(e-this.screenX-this.viewWidth/2)/this.zoom,s=(t-this.screenY-this.viewHeight/2)/this.zoom;return{x:n+o*i+s*a,y:r-o*a+s*i}}clampedCentre(e,t){if(!this.bounds)return{x:e,y:t};let n=this.viewWidth/this.zoom/2,r=this.viewHeight/this.zoom/2,{minX:i,minY:a,maxX:o,maxY:s}=this.bounds;return{x:o-i<n*2?(i+o)/2:kn(e,i+n,o-n),y:s-a<r*2?(a+s)/2:kn(t,a+r,s-r)}}apply(){let{x:e,y:t}=this.clampedCentre(this.x+this.shakeX,this.y+this.shakeY);this.world.scale.set(this.zoom),this._angle===0?(this.world.rotation=0,this.world.pivot.set(0,0),this.world.x=this.snapToDevice(this.screenX+this.viewWidth/2-e*this.zoom),this.world.y=this.snapToDevice(this.screenY+this.viewHeight/2-t*this.zoom)):(this.world.rotation=this.rotation,this.world.pivot.set(e,t),this.world.x=this.snapToDevice(this.screenX+this.viewWidth/2),this.world.y=this.snapToDevice(this.screenY+this.viewHeight/2))}snapToDevice(e){let t=this.resolution();return Math.round(e*t)/t}};function lP(e,t){let n=Math.PI*2,r=(t-e)%n;return r>Math.PI&&(r-=n),r<-Math.PI&&(r+=n),r}function uP(e,t,n=1){return Math.max(1,Math.round(e*t*n))/(t*n)}function dP(e={}){let t=nM.current,n=new cP({resolution:()=>t.app.renderer.resolution,...e});return n.setViewport(t.width,t.height),n}var fP=class{constructor(e){this.container=new J,this.clip=new Z,this.camera=new cP(e),this.container.addChild(this.camera.world),this.container.addChild(this.clip),this.container.mask=this.clip,this.resize(e.x,e.y,e.width,e.height)}resize(e,t,n,r){this.camera.setViewport(n,r,e,t),this.clip.clear().rect(e,t,n,r).fill(16777215)}update(e){this.camera.update(e)}};function pP(e,t){if(e>=t){let n=Math.floor(e/2);return[{x:0,y:0,width:n,height:t},{x:n,y:0,width:e-n,height:t}]}let n=Math.floor(t/2);return[{x:0,y:0,width:e,height:n},{x:0,y:n,width:e,height:t-n}]}var mP={protanopia:[.567,.433,0,0,0,.558,.442,0,0,0,0,.242,.758,0,0,0,0,0,1,0],deuteranopia:[.625,.375,0,0,0,.7,.3,0,0,0,0,.3,.7,0,0,0,0,0,1,0],tritanopia:[.95,.05,0,0,0,0,.433,.567,0,0,0,.475,.525,0,0,0,0,0,1,0]};function hP(e){let t=new Bk;return t.matrix=mP[e],t}function gP(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}function _P(e,t,n,r=`square`){return r===`hex`?$n(e,t,n,n):{x:(e+.5)*n,y:(t+.5)*n}}var vP=class extends J{constructor(e){super(),this.drawn=new Set,this.marker=new Z,this.widthInCells=e.widthInCells,this.cellSize=e.cellSize??2,this.shape=e.shape??`square`,this.renderTexture=h_.create({width:this.shape===`hex`?Math.ceil((e.widthInCells-1)*this.cellSize*.75+this.cellSize):e.widthInCells*this.cellSize,height:this.shape===`hex`?e.heightInCells*this.cellSize+this.cellSize/2:e.heightInCells*this.cellSize}),this.sprite=new wl(this.renderTexture),this.addChild(this.sprite),this.addChild(this.marker)}get exploredCount(){return this.drawn.size}sync(e,t){let n=gP(e,this.drawn);if(n.length===0)return;let r=new Z;for(let e of n){this.drawn.add(e);let n=e%this.widthInCells,i=Math.floor(e/this.widthInCells),a=_P(n,i,this.cellSize,this.shape);if(this.shape===`hex`){let e=this.cellSize/2,o=[];for(let t=0;t<6;t++){let n=Math.PI/3*t;o.push(a.x+Math.cos(n)*e,a.y+Math.sin(n)*e)}r.poly(o).fill({color:t(n,i)})}else r.rect(a.x-this.cellSize/2,a.y-this.cellSize/2,this.cellSize,this.cellSize).fill({color:t(n,i)})}nM.current.app.renderer.render({container:r,target:this.renderTexture,clear:!1}),r.destroy()}setMarker(e,t,n,r=16777215){this.setMarkers([{x:e,y:t,facing:n,color:r}])}setMarkers(e){this.marker.clear();for(let t of e){let e=t.color??16777215,n=_P(t.x,t.y,this.cellSize,this.shape);if(this.marker.circle(n.x,n.y,Math.max(1,this.cellSize)).fill({color:e}),t.facing!==void 0){let r=this.cellSize*2;this.marker.moveTo(n.x,n.y).lineTo(n.x+Math.cos(t.facing)*r,n.y+Math.sin(t.facing)*r).stroke({color:e,width:1})}}}reset(){this.drawn.clear(),nM.current.app.renderer.render({container:new J,target:this.renderTexture,clear:!0})}destroy(e){this.renderTexture.destroy(!0),super.destroy(e)}},yP=24,bP=48,xP=[0,16,48,80];function SP(e,t){if(!Number.isInteger(t))throw Error(`${e} must be an integer, got ${t}`)}function CP(e){if(e!==0&&e!==1&&e!==2&&e!==3)throw Error(`RPG Maker autotile slot must be 0, 1, 2, or 3, got ${e}`)}function wP(e){if(e.length===0)throw Error(`RPG Maker autotile shape table cannot be empty`);for(let t=0;t<e.length;t++){if(e[t].length!==4)throw Error(`RPG Maker autotile shape ${t} needs exactly 4 quadrants`);for(let n of e[t])if(n.length!==2||!n.every(Number.isInteger)||n.some(e=>e<0))throw Error(`RPG Maker autotile shape ${t} has an invalid quadrant offset`)}}function TP(e,t){let n=xP[t]+Math.floor(e/48),r=n%8,i=Math.floor(n/8);return t===0?[Math.floor(r/4)*8,i*6+Math.floor(r/2)%2*3]:t===1?[r*2,(i-2)*3]:t===2?[r*2,(i-6)*2]:[r*2,Math.floor((i-10)*2.5+(i%2==1?.5:0))]}function EP(e,t,n,r){if(SP(`RPG Maker autotile tileId`,e),e<0)throw Error(`RPG Maker autotile tileId must be non-negative, got ${e}`);if(CP(t),SP(`RPG Maker autotile shape`,n),wP(r),n<0||n>=r.length)throw Error(`RPG Maker autotile shape ${n} is outside the table, which holds ${r.length}`);let[i,a]=TP(e,t);return{tileId:e,slot:t,shape:n,destinationX:e%16*bP,destinationY:Math.floor(e/16)*bP,quadrants:r[n].map(([e,t],n)=>({sourceX:(i*2+e)*yP,sourceY:(a*2+t)*yP,destinationX:n%2*yP,destinationY:Math.floor(n/2)*yP}))}}var DP=class{constructor(e){this.cache=new Map,this.table=e,wP(e)}get(e,t,n){let r=`${e}:${t}:${n}`,i=this.cache.get(r);if(i)return i;let a=EP(e,t,n,this.table);return this.cache.set(r,a),a}clear(){this.cache.clear()}},OP=[2048,2816,4352,5888],kP=[768,1536,1536,2304];function AP(e){if(!Number.isInteger(e))return null;for(let t=0;t<4;t++)if(e>=OP[t]&&e<OP[t]+kP[t])return t;return null}var jP=[[[2,4],[1,4],[2,3],[1,3]],[[2,0],[1,4],[2,3],[1,3]],[[2,4],[3,0],[2,3],[1,3]],[[2,0],[3,0],[2,3],[1,3]],[[2,4],[1,4],[2,3],[3,1]],[[2,0],[1,4],[2,3],[3,1]],[[2,4],[3,0],[2,3],[3,1]],[[2,0],[3,0],[2,3],[3,1]],[[2,4],[1,4],[2,1],[1,3]],[[2,0],[1,4],[2,1],[1,3]],[[2,4],[3,0],[2,1],[1,3]],[[2,0],[3,0],[2,1],[1,3]],[[2,4],[1,4],[2,1],[3,1]],[[2,0],[1,4],[2,1],[3,1]],[[2,4],[3,0],[2,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],[[0,4],[1,4],[0,3],[1,3]],[[0,4],[3,0],[0,3],[1,3]],[[0,4],[1,4],[0,3],[3,1]],[[0,4],[3,0],[0,3],[3,1]],[[2,2],[1,2],[2,3],[1,3]],[[2,2],[1,2],[2,3],[3,1]],[[2,2],[1,2],[2,1],[1,3]],[[2,2],[1,2],[2,1],[3,1]],[[2,4],[3,4],[2,3],[3,3]],[[2,4],[3,4],[2,1],[3,3]],[[2,0],[3,4],[2,3],[3,3]],[[2,0],[3,4],[2,1],[3,3]],[[2,4],[1,4],[2,5],[1,5]],[[2,0],[1,4],[2,5],[1,5]],[[2,4],[3,0],[2,5],[1,5]],[[2,0],[3,0],[2,5],[1,5]],[[0,4],[3,4],[0,3],[3,3]],[[2,2],[1,2],[2,5],[1,5]],[[0,2],[1,2],[0,3],[1,3]],[[0,2],[1,2],[0,3],[3,1]],[[2,2],[3,2],[2,3],[3,3]],[[2,2],[3,2],[2,1],[3,3]],[[2,4],[3,4],[2,5],[3,5]],[[2,0],[3,4],[2,5],[3,5]],[[0,4],[1,4],[0,5],[1,5]],[[0,4],[3,0],[0,5],[1,5]],[[0,2],[3,2],[0,3],[3,3]],[[0,2],[1,2],[0,5],[1,5]],[[0,4],[3,4],[0,5],[3,5]],[[2,2],[3,2],[2,5],[3,5]],[[0,2],[3,2],[0,5],[3,5]],[[0,0],[1,0],[0,1],[1,1]]],MP=[[[2,2],[1,2],[2,1],[1,1]],[[0,2],[1,2],[0,1],[1,1]],[[2,0],[1,0],[2,1],[1,1]],[[0,0],[1,0],[0,1],[1,1]],[[2,2],[3,2],[2,1],[3,1]],[[0,2],[3,2],[0,1],[3,1]],[[2,0],[3,0],[2,1],[3,1]],[[0,0],[3,0],[0,1],[3,1]],[[2,2],[1,2],[2,3],[1,3]],[[0,2],[1,2],[0,3],[1,3]],[[2,0],[1,0],[2,3],[1,3]],[[0,0],[1,0],[0,3],[1,3]],[[2,2],[3,2],[2,3],[3,3]],[[0,2],[3,2],[0,3],[3,3]],[[2,0],[3,0],[2,3],[3,3]],[[0,0],[3,0],[0,3],[3,3]]],NP=[[26,27,32,33],[4,27,32,33],[26,5,32,33],[4,5,32,33],[26,27,32,11],[4,27,32,11],[26,5,32,11],[4,5,32,11],[26,27,10,33],[4,27,10,33],[26,5,10,33],[4,5,10,33],[26,27,10,11],[4,27,10,11],[26,5,10,11],[4,5,10,11],[24,25,30,31],[24,5,30,31],[24,25,30,11],[24,5,30,11],[14,15,20,21],[14,15,20,11],[14,15,10,21],[14,15,10,11],[28,29,34,35],[28,29,10,35],[4,29,34,35],[4,29,10,35],[38,39,44,45],[4,39,44,45],[38,5,44,45],[4,5,44,45],[24,29,30,35],[14,15,44,45],[12,13,18,19],[12,13,18,11],[16,17,22,23],[16,17,10,23],[40,41,46,47],[4,41,46,47],[36,37,42,43],[36,5,42,43],[12,17,18,23],[12,13,42,43],[36,41,42,47],[16,17,46,47],[12,17,42,47],[0,1,6,7]],PP=[46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,45,39,45,39,33,31,33,29,45,39,45,39,33,31,33,29,37,27,37,27,23,15,23,13,37,27,37,27,22,11,22,9,45,39,45,39,33,31,33,29,45,39,45,39,33,31,33,29,36,26,36,26,21,7,21,5,36,26,36,26,20,3,20,1,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,46,44,46,44,43,41,43,40,46,44,46,44,43,41,43,40,42,32,42,32,35,19,35,18,42,32,42,32,34,17,34,16,45,38,45,38,33,30,33,28,45,38,45,38,33,30,33,28,37,25,37,25,23,14,23,12,37,25,37,25,22,10,22,8,45,38,45,38,33,30,33,28,45,38,45,38,33,30,33,28,36,24,36,24,21,6,21,4,36,24,36,24,20,2,20,0];function FP(e){return!Number.isInteger(e)||e<=0||e>=384?null:{index:Math.floor(e/48),pattern:e%48}}function IP(e){let t=0;return e(0,-1)&&(t|=1),e(1,-1)&&(t|=2),e(1,0)&&(t|=4),e(1,1)&&(t|=8),e(0,1)&&(t|=16),e(-1,1)&&(t|=32),e(-1,0)&&(t|=64),e(-1,-1)&&(t|=128),PP[t]}var LP=[16,32,32,48];function RP(e){if(e.format===`rpgm-mv`){if(CP(e.slot),wP(e.table),e.tableEdge&&e.slot!==1)throw Error(`a table-edge layout needs slot 1 (A2), got slot ${e.slot}`);let t=LP[e.slot],n=xP[e.slot];for(let r of e.cycles){if(r.length===0)throw Error(`an autotile animation cycle needs at least one kind`);for(let i of r)if(!Number.isInteger(i)||i<n||i>=n+t)throw Error(`animation cycle kind ${i} is outside slot ${e.slot}'s kinds ${n}-${n+t-1}`)}}else{if(!Number.isInteger(e.index)||e.index<0||e.index>7)throw Error(`an XP autotile index must be 0-7, got ${e.index}`);if(!Number.isInteger(e.frames)||e.frames<1)throw Error(`an XP autotile frame count must be at least 1, got ${e.frames}`)}}var zP=24,BP=16,VP=6,HP=96,UP=32;function WP(e,t,n){if(t<=0)return null;if(!Number.isInteger(n)||n<0)throw Error(`an autotile animation frame must be an integer at or above zero, got ${n}`);return e.format===`rpgm-mv`?KP(e,t,n):qP(e,t,n)}function GP(e,t){let n=xP[e.slot]+Math.floor(t/48),r=t%48%e.table.length,i=n%8*2,a=(Math.floor(n/8)-2)*3,o=zP/2;return[2,3].map((t,n)=>{let[s,c]=e.table[r][t];return{sourceX:(i*2+s)*zP,sourceY:(a*2+c)*zP+o,sourceWidth:zP,sourceHeight:o,destX:n/2,destY:0,destWidth:1/2,destHeight:1/4}})}function KP(e,t,n){let r=OP[e.slot],i=kP[e.slot];if(!Number.isInteger(t)||t<r||t>=r+i)throw Error(`tile ${t} is outside slot ${e.slot}'s ids ${r}-${r+i-1}`);let a=t-r;if(e.tableEdge)return GP(e,a);let o=xP[e.slot]+Math.floor(a/48),s=e.tableFor?e.tableFor(o):e.table,c=a%48%s.length;for(let t of e.cycles){let e=t.indexOf(o);if(e>=0){o=t[(e+n)%t.length];break}}return EP((o-xP[e.slot])*48+a%48,e.slot,c,s).quadrants.map((e,t)=>({sourceX:e.sourceX,sourceY:e.sourceY,sourceWidth:zP,sourceHeight:zP,destX:t%2/2,destY:Math.floor(t/2)/2,destWidth:1/2,destHeight:1/2}))}function qP(e,t,n){if(!Number.isInteger(t)||t<e.index*48||t>=e.index*48+48||t<=0)throw Error(`tile ${t} is outside XP autotile ${e.index}'s ids ${e.index*48}-${e.index*48+47}`);if(e.single)return[{sourceX:n%e.frames*UP,sourceY:0,sourceWidth:UP,sourceHeight:UP,destX:0,destY:0,destWidth:1,destHeight:1}];let r=NP[t%48],i=n%e.frames*HP;return r.map((e,t)=>({sourceX:e%VP*BP+i,sourceY:Math.floor(e/VP)*BP,sourceWidth:BP,sourceHeight:BP,destX:t%2/2,destY:Math.floor(t/2)/2,destWidth:1/2,destHeight:1/2}))}var JP=128;function YP(e){let t=new Int32Array(e.width*e.height),n=t=>AP(t)===1&&((e.flags[t]??0)&JP)!==0;for(let r=1;r<e.height;r++)for(let i=0;i<e.width;i++){let a=r*e.width+i,o=e.objects[a-e.width]??0;if(!n(o)||n(e.objects[a]??0))continue;let s=AP(e.ground[a]??0);s!==2&&s!==3&&(t[a]=o)}return t}var XP=-1,ZP=7237230,QP=10132122;function $P(e,t){if(!Number.isInteger(e)||e<0||e>=4096)throw Error(`tileFrame needs a sheet index from 0 to 4095, got ${e}`);if(!Number.isInteger(t)||t<0||t>=1<<20)throw Error(`tileFrame needs a frame index from 0 to ${(1<<20)-1}, got ${t}`);return e<<20|t}function eF(e){return e>>>20}function tF(e){return e&(1<<20)-1}var nF=class extends J{constructor(e){if(super(),this.layers=[],this.layersByName=new Map,this.chunks=[],this.widthInTiles=e.width,this.heightInTiles=e.height,this.sheets=Array.isArray(e.sheet)?[...e.sheet]:[e.sheet],this.sheets.length===0)throw Error(`a TileMap needs at least one sheet`);if(this.tileWidth=e.tileWidth??this.sheets[0].frameWidth,this.tileHeight=e.tileHeight??this.sheets[0].frameHeight,this.shape=e.shape??`square`,this.heightStep=e.heightStep??this.tileHeight/2,!(this.heightStep>0))throw Error(`a TileMap's heightStep must be a positive number, got ${e.heightStep}`);this.chunkSize=e.chunkSize??16,this.chunkColumns=Math.ceil(this.widthInTiles/this.chunkSize),this.chunkRows=Math.ceil(this.heightInTiles/this.chunkSize);let t=this.widthInTiles*this.heightInTiles;this.cellTint=new Uint32Array(t).fill(16777215),this.cellAdd=new Uint32Array(t),this.cellHeight=new Int32Array(t),this.faces=Array(t).fill(null)}get layerCount(){return this.layers.length}get worldWidth(){switch(this.shape){case`square`:return this.widthInTiles*this.tileWidth;case`hex`:return this.widthInTiles<=0?0:(this.widthInTiles-1)*this.tileWidth*.75+this.tileWidth;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileWidth/2);case`staggered`:return this.widthInTiles*this.tileWidth+this.tileWidth/2}}get worldHeight(){switch(this.shape){case`square`:return this.heightInTiles*this.tileHeight;case`hex`:return this.heightInTiles*this.tileHeight+this.tileHeight/2;case`isometric`:return(this.widthInTiles+this.heightInTiles)*(this.tileHeight/2);case`staggered`:return this.heightInTiles*(this.tileHeight/2)+this.tileHeight/2}}inside(e,t){return e>=0&&t>=0&&e<this.widthInTiles&&t<this.heightInTiles}index(e,t){return t*this.widthInTiles+e}addLayer(e,t){let{cells:n,container:r,chunks:i}=this.beginLayer(e,t?.length),a={kind:`tiles`,name:e,data:t?Int32Array.from(t):new Int32Array(n).fill(-1),sprites:Array(n).fill(null),container:r};this.layers.push(a),this.layersByName.set(e,a),this.chunks.push(i),this.addChild(r);let o=this.layers.length===1;for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++){let n=a.data[this.index(t,e)];n!==-1&&this.buildSprite(a,t,e,n),o&&this.syncFaces(t,e)}return this}beginLayer(e,t){if(this.layersByName.has(e))throw Error(`this map already has a layer named "${e}"`);let n=this.widthInTiles*this.heightInTiles;if(t!==void 0&&t!==n)throw Error(`layer "${e}" has ${t} cells, but the map has ${n}`);let r=new J,i=[];for(let e=0;e<this.chunkColumns*this.chunkRows;e++){let e=new J;i.push(e),r.addChild(e)}return{cells:n,container:r,chunks:i}}addAutotileLayer(e,t,n){let r=Array.isArray(n)?n:[n];if(r.length===0)throw Error(`autotile layer "${e}" needs at least one set`);let{cells:i,container:a,chunks:o}=this.beginLayer(e,t.length),s=r.map((t,n)=>this.resolveAutotileSet(e,t,n)),c=new Set;for(let t of s){let n=t.layout.format===`rpgm-mv`?`slot ${t.layout.slot}`:`autotile ${t.layout.index}`;if(c.has(n))throw Error(`autotile layer "${e}" has two sets for ${n}`);c.add(n)}let l=0;r.forEach((t,n)=>{let r=t.animationFrame??0;if(!Number.isInteger(r)||r<0)throw Error(`autotile layer "${e}" set ${n} starts at an invalid animation frame, got ${t.animationFrame}`);if(n===0)l=r;else if(r!==l)throw Error(`autotile layer "${e}" sets disagree on their initial animation frame (${l} vs ${r})`)});let u=Int32Array.from(t);for(let t=0;t<i;t++)u[t]>0&&this.claimAutotileSets(s,e,u[t]);let d={kind:`autotile`,name:e,data:u,sprites:Array(i).fill(null),container:a,sets:s,frame:l};this.layers.push(d),this.layersByName.set(e,d),this.chunks.push(o),this.addChild(a);let f=this.layers.length===1;for(let t=0;t<this.heightInTiles;t++)for(let n=0;n<this.widthInTiles;n++){let r=this.index(n,t),i=u[r];i<=0||(d.sprites[r]=this.makeAutotileSprites(d,this.claimAutotileSets(s,e,i),n,t,i),f&&this.syncFaces(n,t))}return this}setAutotileFrame(e,t){let n=this.layerAt(e);if(n.kind!==`autotile`)throw Error(`layer "${n.name}" is not an autotile layer`);if(!Number.isInteger(t)||t<0)throw Error(`an autotile animation frame must be an integer at or above zero, got ${t}`);if(n.frame!==t){n.frame=t;for(let e=0;e<this.heightInTiles;e++)for(let r=0;r<this.widthInTiles;r++){let i=this.index(r,e),a=n.data[i];if(a<=0)continue;let o=this.claimAutotileSets(n.sets,n.name,a),s=this.autotilePieces(o,a,t),c=n.sprites[i];if(c)for(let e=0;e<c.length;e++)c[e].texture=s.textures[e]}}}addShadowLayer(e,t,n={}){let{cells:r,container:i,chunks:a}=this.beginLayer(e,t.length),o=n.color??0,s=n.alpha??.5;if(!Number.isFinite(s)||s<0||s>1)throw Error(`shadow layer "${e}" alpha must be between 0 and 1, got ${n.alpha}`);let c=Int32Array.from(t,e=>e>0?e&15:0),l={kind:`shadow`,name:e,data:c,sprites:Array(r).fill(null),container:i,color:o,alpha:s};this.layers.push(l),this.layersByName.set(e,l),this.chunks.push(a),this.addChild(i);for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)c[this.index(t,e)]>0&&this.buildShadowSprites(l,t,e);return this}buildShadowSprites(e,t,n){let r=this.index(t,n),i=this.cellOrigin(t,n),a=this.cellHeight[r]*this.heightStep,o=this.tileWidth/2,s=this.tileHeight/2,c=this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)],l=[];for(let t=0;t<4;t++){if(!(e.data[r]&1<<t))continue;let n=new CM(q.WHITE);n.x=i.x+t%2*o,n.y=i.y-a+Math.floor(t/2)*s,n.width=o,n.height=s,n.tint=e.color,n.alpha=e.alpha,c.addChild(n),l.push(n)}e.sprites[r]=l}setShadowCell(e,t,n,r){let i=this.index(t,n);e.data[i]=r>0?r&15:0;for(let t of e.sprites[i]??[])t.destroy();e.sprites[i]=null,e.data[i]>0&&this.buildShadowSprites(e,t,n)}getAutotileFrame(e){let t=this.layerAt(e);if(t.kind!==`autotile`)throw Error(`layer "${t.name}" is not an autotile layer`);return t.frame}resolveAutotileSet(e,t,n){let r=`autotile layer "${e}" set ${n}`;if(!t||!t.sheet)throw Error(`${r} needs a source sheet`);let i=t.format??`rpgm-mv`;if(i!==`rpgm-mv`&&i!==`rpgm-xp`)throw Error(`${r} has an unknown format "${t.format}"`);return i===`rpgm-mv`?this.resolveRpgmSet(r,t):this.resolveXpSet(r,t)}resolveRpgmSet(e,t){if(t.slot===void 0)throw Error(`${e} needs a slot (0-3) for its MV sheet`);if(t.mode!==void 0&&t.mode!==`floor`&&t.mode!==`wall`&&t.mode!==`mixed`)throw Error(`${e} has an unknown mode "${t.mode}"`);if(t.animation!==void 0&&!Array.isArray(t.animation))throw Error(`${e} animation must list kind runs, got ${typeof t.animation}`);let n=t.mode??(t.slot<2?`floor`:`wall`),r=n===`mixed`&&t.slot===3&&t.table===void 0,i={format:`rpgm-mv`,slot:t.slot,table:t.table??(n===`floor`||t.tableEdge||n===`mixed`&&t.slot<2?jP:MP),...r?{tableFor:e=>Math.floor(e/8)%2==0?jP:MP}:{},...t.tableEdge?{tableEdge:!0}:{},cycles:t.animation??[]};return RP(i),{sheet:t.sheet,layout:i,cache:new Map,claims:e=>AP(e)===t.slot}}resolveXpSet(e,t){let n=t.index??0,r=t.sheet.texture,i=r.height===32;if(r.height!==32&&r.height!==128)throw Error(`${e} is ${r.height}px tall - XP autotile images are 128px templates or 32px single-tile strips`);let a=i?32:96,o=t.frames??Math.max(1,Math.floor(r.width/a)),s={format:`rpgm-xp`,index:n,frames:o,single:i};if(RP(s),o>Math.floor(r.width/a))throw Error(`${e} asks for ${o} frames but its sheet fits ${Math.floor(r.width/a)}`);return{sheet:t.sheet,layout:s,cache:new Map,claims:e=>{let t=FP(e);return t!==null&&t.index===n}}}claimAutotileSets(e,t,n){for(let t of e)if(t.claims(n))return t;throw Error(`tile ${n} in autotile layer "${t}" matches none of its sets`)}autotilePieces(e,t,n){let r=`${t}:${n}`,i=e.cache.get(r);if(i)return i;let a=WP(e.layout,t,n),o={parts:a,textures:a.map(t=>new q({source:e.sheet.texture.source,frame:new G(t.sourceX,t.sourceY,t.sourceWidth,t.sourceHeight)}))};return e.cache.set(r,o),o}makeAutotileSprites(e,t,n,r,i){let a=this.index(n,r),o=this.autotilePieces(t,i,e.frame),s=this.cellOrigin(n,r),c=this.cellHeight[a]*this.heightStep,l=o.textures.map((e,t)=>{let n=o.parts[t],r=new CM(e);return r.x=s.x+n.destX*this.tileWidth,r.y=s.y-c+n.destY*this.tileHeight,r.scale.set(n.destWidth*this.tileWidth/n.sourceWidth,n.destHeight*this.tileHeight/n.sourceHeight),r.tint=this.cellTint[a],r.colorAdd=this.cellAdd[a],r}),u=this.chunks[this.layers.indexOf(e)][this.chunkIndex(n,r)];for(let e of l)u.addChild(e);return l}setAutotileCell(e,t,n,r){let i=this.index(t,n);e.data[i]=r;let a=e.sprites[i];if(r<=0){if(a)for(let e of a)e.destroy();e.sprites[i]=null;return}let o=this.claimAutotileSets(e.sets,e.name,r),s=this.autotilePieces(o,r,e.frame);if(a&&a.length===s.textures.length)for(let e=0;e<a.length;e++)a[e].texture=s.textures[e];else{if(a)for(let e of a)e.destroy();e.sprites[i]=this.makeAutotileSprites(e,o,t,n,r)}}eachCellSprite(e,t,n){let r=e.sprites[t];if(r){if(Array.isArray(r))for(let e of r)n(e);else n(r)}}firstCellSprite(e,t){let n=e.sprites[t];return n?Array.isArray(n)?n[0]:n:null}layerAt(e){let t=typeof e==`number`?this.layers[e]:this.layersByName.get(e);if(!t)throw Error(`no such layer: ${e}`);return t}chunkIndex(e,t){return Math.floor(t/this.chunkSize)*this.chunkColumns+Math.floor(e/this.chunkSize)}projectedCenter(e,t){switch(this.shape){case`square`:return{x:(e+.5)*this.tileWidth,y:(t+.5)*this.tileHeight};case`hex`:return $n(e,t,this.tileWidth,this.tileHeight);case`isometric`:return{x:(e-t+(this.heightInTiles-1))*(this.tileWidth/2)+this.tileWidth/2,y:(e+t)*(this.tileHeight/2)+this.tileHeight/2};case`staggered`:return{x:e*this.tileWidth+(t&1)*(this.tileWidth/2)+this.tileWidth/2,y:t*(this.tileHeight/2)+this.tileHeight/2}}}projectedTile(e,t){switch(this.shape){case`square`:return{x:Math.floor(e/this.tileWidth),y:Math.floor(t/this.tileHeight)};case`hex`:return er(e,t,this.tileWidth,this.tileHeight);case`isometric`:{let n=(e-this.tileWidth/2)/(this.tileWidth/2)-(this.heightInTiles-1),r=(t-this.tileHeight/2)/(this.tileHeight/2);return{x:Math.round((n+r)/2),y:Math.round((r-n)/2)}}case`staggered`:{let n=Math.round((t-this.tileHeight/2)/(this.tileHeight/2));return{x:Math.round((e-this.tileWidth/2-(n&1)*(this.tileWidth/2))/this.tileWidth),y:n}}}}cellOrigin(e,t){let n=this.projectedCenter(e,t);return{x:n.x-this.tileWidth/2,y:n.y-this.tileHeight/2}}textureFor(e){let t=eF(e);if(t>=this.sheets.length)throw Error(`frame ${e} names sheet ${t}, but this map has ${this.sheets.length}`);return this.sheets[t].get(tF(e))}buildSprite(e,t,n,r){let i=new CM(this.textureFor(r)),a=this.cellOrigin(t,n);i.x=a.x,i.y=a.y-this.cellHeight[this.index(t,n)]*this.heightStep;let o=this.index(t,n);return i.tint=this.cellTint[o],i.colorAdd=this.cellAdd[o],e.sprites[o]=i,this.chunks[this.layers.indexOf(e)][this.chunkIndex(t,n)].addChild(i),i}getTile(e,t,n){return this.inside(t,n)?this.layerAt(e).data[this.index(t,n)]:-1}setTile(e,t,n,r){if(!this.inside(t,n))return;let i=this.layerAt(e),a=this.index(t,n);if(i.data[a]!==r){if(i.kind===`autotile`)this.setAutotileCell(i,t,n,r);else if(i.kind===`shadow`)this.setShadowCell(i,t,n,r);else{i.data[a]=r;let e=i.sprites[a];r===-1?(e?.destroy(),i.sprites[a]=null):e?e.texture=this.textureFor(r):this.buildSprite(i,t,n,r)}this.layers[0]===i&&this.syncFaces(t,n)}}setLayerData(e,t){this.layerAt(e);for(let n=0;n<this.heightInTiles;n++)for(let r=0;r<this.widthInTiles;r++)this.setTile(e,r,n,t[this.index(r,n)]??-1)}stampRect(e,t,n,r,i,a){if(this.layerAt(e),a.length!==r*i)throw Error(`a ${r}x${i} stamp needs ${r*i} frames, got ${a.length}`);if(t<0||n<0||t+r>this.widthInTiles||n+i>this.heightInTiles)throw Error(`a ${r}x${i} stamp at (${t},${n}) does not fit the ${this.widthInTiles}x${this.heightInTiles} map`);for(let o=0;o<i;o++)for(let i=0;i<r;i++)this.setTile(e,t+i,n+o,a[o*r+i])}setCellColor(e,t,n,r=0){if(!this.inside(e,t))return;let i=this.index(e,t);if(this.cellTint[i]===n&&this.cellAdd[i]===r)return;this.cellTint[i]=n,this.cellAdd[i]=r;for(let e of this.layers)e.kind!==`shadow`&&this.eachCellSprite(e,i,e=>{e.tint=n,e.colorAdd=r});let a=this.faces[i];a&&(a.tint=n)}getCellTint(e,t){return this.inside(e,t)?this.cellTint[this.index(e,t)]:0}clearColors(){for(let e=0;e<this.heightInTiles;e++)for(let t=0;t<this.widthInTiles;t++)this.setCellColor(t,e,16777215,0)}setCellHeight(e,t,n){if(!this.inside(e,t))return;if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);let r=this.index(e,t);if(this.cellHeight[r]===n)return;let i=(n-this.cellHeight[r])*this.heightStep;this.cellHeight[r]=n;for(let e of this.layers)this.eachCellSprite(e,r,e=>{e.y-=i});this.syncFaces(e,t)}getCellHeight(e,t){return this.inside(e,t)?this.cellHeight[this.index(e,t)]:0}get faceCount(){return this.faces.filter(e=>e!==null).length}syncFaces(e,t){if(this.layers.length===0)return;let n=this.index(e,t),r=(this.shape===`isometric`||this.shape===`staggered`)&&this.cellHeight[n]>0&&this.layers[0].data[n]!==-1,i=this.faces[n];if(!r){i&&(i.destroy(),this.faces[n]=null);return}let a=i??new Z;if(this.drawFaces(a,e,t),a.tint=this.cellTint[n],!i){this.faces[n]=a;let r=this.chunks[0][this.chunkIndex(e,t)],i=this.firstCellSprite(this.layers[0],n);i?r.addChildAt(a,r.getChildIndex(i)):r.addChild(a)}}drawFaces(e,t,n){let r=this.cellOrigin(t,n),i=r.x,a=r.y,o=this.tileWidth/2,s=this.tileHeight/2,c=this.heightStep,l=this.cellHeight[this.index(t,n)];e.clear();for(let t=1;t<=l;t++){let n=t*c,r=(t-1)*c;e.poly([i,a+s-n,i+o,a+s*2-n,i+o,a+s*2-r,i,a+s-r]).fill(ZP),e.poly([i+o,a+s*2-n,i+o*2,a+s-n,i+o*2,a+s-r,i+o,a+s*2-r]).fill(QP)}}toTile(e,t){return this.projectedTile(e,t)}tileCenter(e,t){let n=this.projectedCenter(e,t);return n.y-=this.getCellHeight(e,t)*this.heightStep,n}cull(e){let t=e.view,n=this.projectedTile(t.x,t.y),r=this.projectedTile(t.x+t.width,t.y),i=this.projectedTile(t.x,t.y+t.height),a=this.projectedTile(t.x+t.width,t.y+t.height),o=Math.min(n.x,r.x,i.x,a.x),s=Math.max(n.x,r.x,i.x,a.x),c=Math.min(n.y,r.y,i.y,a.y),l=Math.max(n.y,r.y,i.y,a.y),u=Math.floor(o/this.chunkSize)-1,d=Math.floor(s/this.chunkSize)+1,f=Math.floor(c/this.chunkSize)-1,p=Math.floor(l/this.chunkSize)+1;for(let e=0;e<this.chunkRows;e++){let t=e>=f&&e<=p;for(let n=0;n<this.chunkColumns;n++){let r=t&&n>=u&&n<=d,i=e*this.chunkColumns+n;for(let e of this.chunks)e[i].renderable=r}}}get visibleChunks(){return this.chunks.length===0?0:this.chunks[0].filter(e=>e.renderable).length}},rF=class extends J{constructor(...e){super(...e),this.layers=new Map}addLayer(e,t,n=0){this.removeLayer(e);let r=new CM(t);return this.layers.set(e,{sprite:r,order:n}),this.addChild(r),this.resort(),r}removeLayer(e){let t=this.layers.get(e);t&&(this.layers.delete(e),t.sprite.destroy())}layer(e){return this.layers.get(e)?.sprite}hasLayer(e){return this.layers.has(e)}setTexture(e,t){let n=this.layers.get(e);n&&(n.sprite.texture=t)}resort(){[...this.layers.values()].sort((e,t)=>e.order-t.order).forEach((e,t)=>this.setChildIndex(e.sprite,t))}},iF=class{constructor(e,t,n,r={}){this.elapsed=0,this.arrived=!1,this.sprite=e,this.fromX=t.x,this.fromY=t.y,this.toX=n.x,this.toY=n.y,this.animation=r.animation;let i=Math.hypot(n.x-t.x,n.y-t.y);this.duration=r.duration??i/(r.speed??400),this.duration<=0&&(this.duration=1e-6),e.x=t.x,e.y=t.y}get done(){return this.arrived}get progress(){return Math.min(1,this.elapsed/this.duration)}get frame(){return this.animation?.frameAt(this.elapsed)}get frameOffset(){let e=this.frame;return{x:e?.offsetX??0,y:e?.offsetY??0}}update(e){if(this.arrived)return!1;this.elapsed+=e;let t=this.progress;return this.sprite.x=this.fromX+(this.toX-this.fromX)*t,this.sprite.y=this.fromY+(this.toY-this.fromY)*t,t>=1&&(this.arrived=!0,!0)}};function aF(e){return e===!0||e===`progress`?`progress`:typeof e==`number`&&e>0?`seconds`:`none`}var oF=class extends J{constructor(...e){super(...e),this.live=[]}add(e,t,n,r={}){let i,a;e instanceof q?(a=new wl(e),this.addChild(a),i=a):i=e,r.tint!==void 0&&typeof i.tint==`number`&&(i.tint=r.tint);let o=aF(r.fadeIn),s=typeof r.fadeIn==`number`?r.fadeIn:0,c=typeof i.alpha==`number`?i.alpha:1;o!==`none`&&(i.alpha=0);let l={projectile:new iF(i,t,n,r),sprite:i,built:a,onArrive:r.onArrive,spin:r.spin??(r.spinDegrees===void 0?void 0:r.spinDegrees*Math.PI/180),fadeMode:o,fadeIn:s,baseAlpha:c,elapsed:0};return this.live.push(l),{projectile:l.projectile,get done(){return l.projectile.done},cancel:()=>{let e=this.live.indexOf(l);e!==-1&&(this.live.splice(e,1),this.release(l))}}}update(e){for(let t=this.live.length-1;t>=0;t--){let n=this.live[t];n.elapsed+=e,n.spin!==void 0&&(n.sprite.rotation=(n.sprite.rotation??0)+n.spin*e),n.fadeMode===`seconds`&&(n.sprite.alpha=n.baseAlpha*Math.min(1,n.elapsed/n.fadeIn));let r=n.projectile.update(e);n.fadeMode===`progress`&&(n.sprite.alpha=n.baseAlpha*n.projectile.progress),r&&(this.live.splice(t,1),this.release(n),n.onArrive?.())}}get count(){return this.live.length}clear(){for(let e of this.live.splice(0))this.release(e)}destroy(){this.clear(),super.destroy()}release(e){e.built&&(this.removeChild(e.built),e.built.destroy())}},sF=class extends J{constructor(e,t,n={}){super(),this.elapsed=0,this.expired=!1,this.lifeFraction=1,this.from={...e},this.to={...t},this.colour=n.colour??16777215,this.thin=n.thin??!1;let r=n.texture;if(r===void 0?(this.texture=void 0,this.stretch=!1,this.textureAnchor=0):r instanceof q?(this.texture=r,this.stretch=!1,this.textureAnchor=0):(this.texture=r.source,this.stretch=r.stretch??!1,this.textureAnchor=r.anchor??.5),this.thickness=n.width??2,this.duration=Math.max(1e-6,n.duration??.2),this.texture&&this.stretch)this.body=new wl(this.texture),this.body.anchor.set(0,this.textureAnchor);else if(this.texture){let e=new dA({texture:this.texture,width:1,height:this.thickness});e.anchor.set(0,this.textureAnchor),this.body=e}else this.body=new Z;(n.additive??!0)&&(this.body.blendMode=`add`),this.addChild(this.body),this.redraw()}get progress(){return Math.min(1,this.elapsed/this.duration)}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.redraw()}update(e){return!this.expired&&(this.elapsed+=e,this.alpha=1-this.progress,this.lifeFraction=this.thin?1-this.progress:1,this.thin&&this.redraw(),this.elapsed>=this.duration&&(this.expired=!0,!0))}destroy(){this.removeChild(this.body),this.body.destroy(),super.destroy()}redraw(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t);if(this.position.set(this.from.x,this.from.y),this.rotation=n>0?Math.atan2(t,e):0,this.body instanceof dA)this.body.width=n,this.body.height=this.thickness*this.lifeFraction;else if(this.body instanceof wl){let e=this.texture?.width||1,t=this.texture?.height||1;this.body.scale.x=n/e,this.body.scale.y=this.thickness/t*this.lifeFraction}else{let e=this.body;e.clear(),e.moveTo(0,0),e.lineTo(n,0),e.stroke({width:this.thickness*this.lifeFraction,color:this.colour})}}},cF=class extends J{constructor(...e){super(...e),this.live=[]}add(e,t,n){let r=new sF(e,t,n);return this.addChild(r),this.live.push(r),r}update(e){for(let t=this.live.length-1;t>=0;t--)if(this.live[t].update(e)){let[e]=this.live.splice(t,1);this.removeChild(e),e.destroy()}}get count(){return this.live.length}clear(){for(let e of this.live.splice(0))this.removeChild(e),e.destroy()}destroy(){this.clear(),super.destroy()}},lF=class{constructor(e,t,n={}){this.elapsed=0,this.sinceFlicker=0,this.expired=!1,this.current=[],this.from={...e},this.to={...t},this.segments=Math.max(0,Math.floor(n.segments??6)),this.jitter=n.jitter??12,this.flickerInterval=n.flickerInterval,this.random=n.random??Math.random,this.duration=n.duration,this.reroll()}get points(){return this.current}get done(){return this.expired}retarget(e,t){e&&(this.from={...e}),t&&(this.to={...t}),this.flickerInterval===void 0&&this.reroll()}update(e){return!this.expired&&(this.elapsed+=e,this.flickerInterval!==void 0&&(this.sinceFlicker+=e,this.sinceFlicker>=this.flickerInterval&&(this.sinceFlicker=0,this.reroll())),this.duration!==void 0&&this.elapsed>=this.duration&&(this.expired=!0,!0))}reroll(){let e=this.to.x-this.from.x,t=this.to.y-this.from.y,n=Math.hypot(e,t),r=n>0?-t/n:0,i=n>0?e/n:0,a=[{...this.from}],o=this.segments+1;for(let n=1;n<o;n+=1){let s=n/o,c=Math.sin(Math.PI*s),l=(this.random()*2-1)*this.jitter*c;a.push({x:this.from.x+e*s+r*l,y:this.from.y+t*s+i*l})}a.push({...this.to}),this.current=a}},uF=class{constructor(e,t={}){this.elapsed=0,this.expired=!1,this.child=e,this.offsetX=t.offsetX??0,this.offsetY=t.offsetY??0,this.duration=t.duration}get done(){return this.expired}follow(e,t){return this.child.x=e+this.offsetX,this.child.y=t+this.offsetY,this}update(e){return this.expired||this.duration===void 0?!1:(this.elapsed+=e,this.elapsed>=this.duration&&(this.expired=!0,!0))}},dF=class extends J{constructor(e){super(),this.cells=new Map,this.ripples=[],this.offset=0,this.eventMode=`none`,this.columns=e.width,this.tileSize=e.tileSize??16,this.speed=e.speed??5,this.rippleTexture=e.rippleTexture,this.rippleDuration=e.rippleDuration??.5;for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){if(!e.isLiquid(n,t))continue;let r=new dA({texture:e.texture,width:this.tileSize,height:this.tileSize});r.eventMode=`none`,r.position.set(n*this.tileSize,t*this.tileSize),r.tilePosition.set(-r.x,-r.y),r.visible=!1,this.cells.set(n+t*this.columns,r),this.addChild(r)}}setCellColor(e,t,n){let r=this.cells.get(e+t*this.columns);r&&(r.tint=n,r.visible=n!==0)}ripple(e,t){if(!this.rippleTexture||!this.cells.get(e+t*this.columns)?.visible)return;let n=new wl(this.rippleTexture);n.eventMode=`none`,n.anchor.set(.5),n.position.set((e+.5)*this.tileSize,(t+.5)*this.tileSize),n.scale.set(0),this.addChild(n),this.ripples.push({sprite:n,age:0})}get rippleCount(){return this.ripples.length}update(e){this.offset+=this.speed*e;for(let e of this.cells.values())e.visible&&(e.tilePosition.y=-e.y+this.offset);for(let t=this.ripples.length-1;t>=0;t--){let n=this.ripples[t];if(n.age+=e,n.age>=this.rippleDuration)n.sprite.destroy(),this.ripples.splice(t,1);else{let e=n.age/this.rippleDuration;n.sprite.scale.set(e),n.sprite.alpha=1-e}}}};function fF(e,t,n,r,i,a){let o=t*r;for(let s=0;s<n;s++)for(let n=0;n<t;n++){let t=i(n,s);for(let i=0;i<r;i++)for(let c=0;c<r;c++){let l=a[typeof t==`number`?t:t[i*r+c]??0]??[0,0,0,0];e.set(l,((s*r+i)*o+n*r+c)*4)}}}var pF=class extends wl{constructor(e){let t=e.resolution??2,n=document.createElement(`canvas`);n.width=e.width*t,n.height=e.height*t;let r=n.getContext(`2d`);if(!r)throw Error(`FogLayer needs a 2D canvas context`);super(q.from(n)),this.context=r,this.image=r.createImageData(n.width,n.height),this.columns=e.width,this.rows=e.height,this.cellResolution=t,this.palette=e.palette,this.texture.source.scaleMode=`linear`,this.scale.set((e.tileSize??16)/t),this.eventMode=`none`}setPalette(e){this.palette=e}refresh(e){fF(this.image.data,this.columns,this.rows,this.cellResolution,e,this.palette),this.context.putImageData(this.image,0,0),this.texture.source.update()}destroy(){super.destroy({texture:!0,textureSource:!0})}},mF=`halo`,hF=class extends nN{constructor(e){super(),this.offsetX=e.offsetX??0,this.offsetY=e.offsetY??0,this.blendMode=e.blendMode??`add`,this.add(mF,e.frames,e.animation),this.play(mF)}follow(e,t){return this.position.set(e+this.offsetX,t+this.offsetY),this}};_e();function gF(e){return typeof e==`number`?e:D(e[0],e[1])}function _F(e){if(typeof e==`number`)return e;let t=D(),n=n=>{let r=e[0]>>n&255,i=e[1]>>n&255;return Math.round(r+(i-r)*t)<<n};return n(16)|n(8)|n(0)}function vF(e){return typeof e==`function`?e:t=>e[0]+(e[1]-e[0])*t}var yF=class extends J{constructor(e={}){super(),this.pool=[],this.sprites=[],this.tintOverridden=!1,this.emitting=!1,this.followTarget=null,this.followOffsetX=0,this.followOffsetY=0,this.followEnabled=null,this.followVisible=null,this.poolCursor=0,this.debt=0;let t=Math.max(1,Math.floor(e.max??200));this.rate=e.rate??0,this.life=e.life??[.4,.9],this.speed=e.speed??[20,60],this.angleRange=e.angle??[0,Math.PI*2],this.gravityX=e.gravity?.x??0,this.gravityY=e.gravity?.y??0,this.scaleOf=vF(e.scale??[1,1]),this.alphaOf=vF(e.alpha??[1,0]),this.flicker=Math.min(1,Math.max(0,e.flicker??0)),this.spin=e.spin??0,this.tintRange=e.tint??16777215,this.frames=e.frames,this.spawnArea=e.spawn??null;for(let n=0;n<t;n++){this.pool.push({x:0,y:0,vx:0,vy:0,age:0,life:0,rotation:0,spin:0,scale:1,alpha:1,tint:16777215,frame:0,active:!1});let t=this.frames?.[0]??e.texture;if(t){let n=new wl(t);n.anchor.set(.5),n.visible=!1,typeof e.tint==`number`&&(n.tint=e.tint),this.sprites.push(n),this.addChild(n)}}}start(){this.emitting=!0}stop(){this.emitting=!1,this.debt=0}attach(e,t={}){this.followTarget=e,this.followOffsetX=t.offsetX??0,this.followOffsetY=t.offsetY??0,this.followEnabled=t.enabled??null,this.followVisible=t.visible??null,this.syncFollow()}detach(){this.followTarget=null,this.followEnabled=null,this.followVisible!==null&&(this.visible=!0),this.followVisible=null,this.followOffsetX=0,this.followOffsetY=0}get attachedTo(){return this.followTarget}syncFollow(){let e=this.followTarget;if(!e)return;if(typeof e!=`function`&&e.destroyed){this.detach();return}let t=typeof e==`function`?e():e;this.x=t.x+this.followOffsetX,this.y=t.y+this.followOffsetY,this.followVisible!==null&&(this.visible=this.followVisible())}followEmissionAllowed(){return this.followEnabled?.()??!0}get isEmitting(){return this.emitting}get activeCount(){let e=0;for(let t of this.pool)t.active&&e++;return e}get particles(){return this.pool}burst(e,t={}){this.syncFollow(),t.tint!==void 0&&(this.tintOverridden=!0);let n=0;for(let r=0;r<e&&this.spawn(t);r++)n++;return n}spawn(e={}){let t=null;for(let e=0;e<this.pool.length;e++){let e=this.pool[this.poolCursor];if(this.poolCursor=(this.poolCursor+1)%this.pool.length,!e.active){t=e;break}}if(!t)return!1;let n=gF(this.angleRange),r=gF(this.speed),i=+!br(),a=this.spawnOffset();return t.x=(e.x??this.x)+a.x,t.y=(e.y??this.y)+a.y,t.vx=Math.cos(n)*r*i,t.vy=Math.sin(n)*r*i,t.age=0,t.life=Math.max(1e-6,gF(this.life)),t.rotation=0,t.spin=gF(this.spin)*i,t.scale=this.scaleOf(0),t.alpha=this.alphaOf(0),t.tint=e.tint??_F(this.tintRange),t.frame=0,t.active=!0,!0}spawnOffset(){let e=this.spawnArea;if(!e)return{x:0,y:0};let t=e.height??e.width;if(e.shape===`rect`)return{x:(D()-.5)*e.width,y:(D()-.5)*t};let n=Math.sqrt(D()),r=D()*Math.PI*2;return{x:Math.cos(r)*n*(e.width/2),y:Math.sin(r)*n*(t/2)}}update(e){if(this.syncFollow(),this.emitting&&this.rate>0&&this.followEmissionAllowed()){for(this.debt+=this.rate*e;this.debt>=1;)if(--this.debt,!this.spawn()){this.debt=0;break}}let t=br();for(let n of this.pool){if(!n.active)continue;if(n.age+=e,n.age>=n.life){n.active=!1;continue}t?(n.vx=0,n.vy=0,n.spin=0):(n.vx+=this.gravityX*e,n.vy+=this.gravityY*e),n.x+=n.vx*e,n.y+=n.vy*e,n.rotation+=n.spin*e;let r=n.age/n.life;n.scale=this.scaleOf(r),n.alpha=this.alphaOf(r),this.flicker>0&&!t&&(n.scale*=1-this.flicker*D()),this.frames&&(n.frame=Math.min(this.frames.length-1,Math.floor(r*this.frames.length)))}this.draw()}draw(){if(this.sprites.length===0)return;let e=typeof this.tintRange!=`number`||this.tintOverridden;for(let t=0;t<this.pool.length;t++){let n=this.pool[t],r=this.sprites[t];r.visible=n.active,n.active&&(r.x=n.x-this.x,r.y=n.y-this.y,r.rotation=n.rotation,r.alpha=n.alpha,r.scale.set(n.scale),e&&(r.tint=n.tint),this.frames&&(r.texture=this.frames[n.frame]??r.texture))}}clear(){for(let e of this.pool)e.active=!1;this.debt=0,this.draw()}},bF=class extends J{constructor(e={}){super(),this.overlay=new Z,this.phase=`idle`,this.elapsed=0,this.duration=0,this.fromAlpha=0,this.toAlpha=0,this.queue=[],this.defaultColor=e.color??0,this.viewWidth=e.width??0,this.viewHeight=e.height??0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor,this.addChild(this.overlay),this.redraw()}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.redraw()}redraw(){this.overlay.clear(),this.viewWidth>0&&this.viewHeight>0&&this.overlay.rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get isBusy(){return this.phase!==`idle`}get washAlpha(){return this.overlay.alpha}fadeOut(e,t){this.begin(`fadeOut`,e,this.overlay.alpha,1,t)}fadeIn(e,t){this.begin(`fadeIn`,e,this.overlay.alpha,0,t)}flash(e,t,n=1){this.begin(`flash`,e,0,n,t)}sequence(e){this.queue=e.slice(1),e.length===0?this.phase=`idle`:this.beginStep(e[0])}setTint(e,t){this.queue=[],this.phase=`idle`,this.elapsed=0,this.overlay.tint=e,this.overlay.alpha=Math.max(0,Math.min(1,t))}clear(){this.queue=[],this.phase=`idle`,this.elapsed=0,this.overlay.alpha=0,this.overlay.tint=this.defaultColor}beginStep(e){switch(e.kind){case`fadeOut`:return this.begin(`fadeOut`,e.duration,this.overlay.alpha,1,e.color);case`fadeIn`:return this.begin(`fadeIn`,e.duration,this.overlay.alpha,0,e.color);case`flash`:return this.begin(`flash`,e.duration,0,e.peak??1,e.color);case`hold`:return this.begin(`hold`,e.duration,this.overlay.alpha,this.overlay.alpha,e.color??this.overlay.tint)}}advance(){let e=this.queue.shift();return e?this.beginStep(e):(this.phase=`idle`,!0)}begin(e,t,n,r,i){return br()&&(t=0),this.overlay.tint=i??this.defaultColor,this.fromAlpha=n,this.toAlpha=r,this.elapsed=0,this.duration=t,t>0?(this.phase=e,this.overlay.alpha=e===`flash`?0:n,!1):(this.overlay.alpha=e===`flash`?0:r,this.advance())}update(e){if(this.phase===`idle`)return!1;if(br())return this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.advance();this.elapsed+=e;let t=Math.min(1,this.elapsed/this.duration);if(this.phase===`flash`){let e=t<.5?Er.easeOutQuad(t*2):1-Er.easeInQuad((t-.5)*2);this.overlay.alpha=this.toAlpha*e}else{let e=Er.easeInOutQuad(t);this.overlay.alpha=this.fromAlpha+(this.toAlpha-this.fromAlpha)*e}return t>=1&&(this.overlay.alpha=this.phase===`flash`?0:this.toAlpha,this.advance())}},xF=class{constructor(e,t){this.idleOrMove=`idle`,this.inAction=!1,this.sprite=e,this.animationName=t.animationName,this.variant=t.variant??``,this.sprite.onFinish=()=>this.onSpriteFinish(),this.apply(this.idleOrMove)}get state(){return this.inAction?`action`:this.idleOrMove}get variantName(){return this.variant}setMoving(e,t){t!==void 0&&(this.variant=t),this.idleOrMove=e?`move`:`idle`,this.inAction||this.apply(this.idleOrMove)}playAction(e,t=!1){(!this.inAction||t)&&(e!==void 0&&(this.variant=e),this.inAction=!0,this.apply(`action`))}onSpriteFinish(){this.inAction&&(this.inAction=!1,this.apply(this.idleOrMove))}apply(e){let t=this.animationName(e,this.variant);this.sprite.has(t)&&this.sprite.play(t,e===`action`)}},SF=class{constructor(e,t){this.active=new Set,this.elapsed=0,this.flashColor=0,this.flashStrength=0,this.flashDuration=0,this.flashRemaining=0,this.target=e,this.styles=t.styles}set(e,t){t?this.active.add(e):this.active.delete(e)}has(e){return this.active.has(e)}flash(e,t,n){this.flashColor=e,this.flashStrength=t,this.flashDuration=Math.max(n,1e-6),this.flashRemaining=this.flashDuration}update(e){this.elapsed+=e,this.flashRemaining>0&&(this.flashRemaining=Math.max(0,this.flashRemaining-e));let t=0,n=0,r=0;for(let e of this.active){let i=this.styles[e];if(!i)continue;let a=i.strength??.5,o=i.pulseRate?a*(.5+.5*Math.sin(this.elapsed*i.pulseRate*Math.PI*2)):a;t+=(i.color>>16&255)/255*o,n+=(i.color>>8&255)/255*o,r+=(i.color&255)/255*o}if(this.flashRemaining>0){let e=this.flashRemaining/this.flashDuration,i=this.flashStrength*e;t+=(this.flashColor>>16&255)/255*i,n+=(this.flashColor>>8&255)/255*i,r+=(this.flashColor&255)/255*i}this.target.colorAdd=yM(Math.min(1,t),Math.min(1,n),Math.min(1,r))}},CF={scaleX:1,scaleY:1,dy:0,rotation:0,skewX:0},wF={done:Promise.resolve(),cancel(){}},TF=class{constructor(e,t={}){this.contributions=new Map,this.loops=new Set,this.nextId=0,this.flipX=!1,this.flipY=!1,this.destroyed=!1,this.target=e,this.tweener=t.tweener??new Dr,this.ownsTweener=t.tweener===void 0,this.intent=t.intent??`decorative`,this.rest={y:e.y,rotation:e.rotation,scaleX:e.scale.x,scaleY:e.scale.y,skewX:e.skew.x}}squash(e){let{amount:t,duration:n}=e;return this.run(n,e=>{let n=Math.sin(Math.PI*e)*t;return{scaleX:1+n,scaleY:1-n}})}hop(e){let{height:t,duration:n}=e;return this.run(n,e=>({dy:-Math.sin(Math.PI*e)*t}))}bob(e){let{amplitude:t,period:n,cycles:r}=e;return r===void 0?this.loop(e=>({dy:Math.sin(2*Math.PI*e/n)*t})):this.run(n*r,e=>({dy:Math.sin(2*Math.PI*r*e)*t}))}wobble(e){let{angle:t,duration:n}=e;return this.run(n,e=>({rotation:Math.sin(4*Math.PI*e)*(1-e)*t}))}spin(e){let{turns:t,duration:n}=e;return this.run(n,e=>({rotation:Math.PI*2*t*e}),Er.easeInOutQuad)}shear(e){let{amount:t,duration:n}=e;return this.run(n,e=>({skewX:Math.sin(Math.PI*e)*t}))}flip(e,t){return e===`x`?this.flipX=t??!this.flipX:this.flipY=t??!this.flipY,this.write(),e===`x`?this.flipX:this.flipY}update(e){this.ownsTweener&&this.tweener.update(e);for(let t of[...this.loops])t(e)}get isBusy(){return this.contributions.size>0}destroy(){this.destroyed=!0,this.contributions.clear(),this.loops.clear(),this.flipX=this.flipY=!1,this.write()}run(e,t,n=Er.linear){if(this.destroyed)return wF;let r=this.nextId++,i=()=>{this.contributions.delete(r),this.write()};return this.contributions.set(r,CF),{done:this.tweener.tween(e,e=>{this.contributions.has(r)&&(this.contributions.set(r,{...CF,...t(e)}),this.write())},{ease:n,intent:this.intent}).then(i),cancel:i}}loop(e){if(this.destroyed)return wF;let t=this.nextId++,n=0,r,i=new Promise(e=>r=e),a=r=>{n+=r;let i=br()&&this.intent===`decorative`;this.contributions.set(t,i?CF:{...CF,...e(n)}),this.write()};return this.contributions.set(t,CF),this.loops.add(a),{done:i,cancel:()=>{this.loops.delete(a),this.contributions.delete(t),this.write(),r()}}}write(){let e=1,t=1,n=0,r=0,i=0;for(let a of this.contributions.values())e*=a.scaleX,t*=a.scaleY,n+=a.dy,r+=a.rotation,i+=a.skewX;let{rest:a,target:o}=this;o.y=a.y+n,o.rotation=a.rotation+r,o.scale.x=a.scaleX*e*(this.flipX?-1:1),o.scale.y=a.scaleY*t*(this.flipY?-1:1),o.skew.x=a.skewX+i}};function EF(e,t){let n=e??{x:0,y:0};if(!Number.isFinite(n.x)||!Number.isFinite(n.y))throw RangeError(`a cloth ${t} needs finite coordinates, saw (${n.x}, ${n.y})`);return{x:n.x,y:n.y}}var DF=class{constructor(e){if(!Number.isFinite(e.width)||e.width<=0)throw RangeError(`a cloth needs width above 0, saw ${e.width}`);if(!Number.isFinite(e.height)||e.height<=0)throw RangeError(`a cloth needs height above 0, saw ${e.height}`);for(let t of[`segmentsX`,`segmentsY`])if(!Number.isInteger(e[t])||e[t]<1)throw RangeError(`a cloth needs integer ${t} of at least 1, saw ${e[t]}`);let t=e.stiffness??.9;if(!Number.isFinite(t)||t<0||t>1)throw RangeError(`a cloth needs stiffness between 0 and 1, saw ${t}`);let n=e.damping??.02;if(!Number.isFinite(n)||n<0||n>1)throw RangeError(`a cloth needs damping between 0 and 1, saw ${n}`);this.segmentsX=e.segmentsX,this.segmentsY=e.segmentsY,this.stiffness=t,this.damping=n,this.gravity=EF(e.gravity,`gravity`),this.wind=EF(e.wind,`wind`);let r=this.pointCount;this.rest=new Float32Array(r*2),this.positions=new Float32Array(r*2),this.previous=new Float32Array(r*2),this.pinned=new Uint8Array(r),this.links=[];let i=e.width/e.segmentsX,a=e.height/e.segmentsY;for(let t=0;t<=e.segmentsY;t++)for(let n=0;n<=e.segmentsX;n++){let e=this.indexOf(n,t);this.rest[e*2]=n*i,this.rest[e*2+1]=t*a,t===0&&(this.pinned[e]=1)}this.reset();let o=(e,t)=>this.indexOf(e,t);for(let t=0;t<=e.segmentsY;t++)for(let n=0;n<e.segmentsX;n++)this.links.push([o(n,t),o(n+1,t),i]);for(let t=0;t<e.segmentsY;t++)for(let n=0;n<=e.segmentsX;n++)this.links.push([o(n,t),o(n,t+1),a])}get pointCount(){return(this.segmentsX+1)*(this.segmentsY+1)}indexOf(e,t){if(!Number.isInteger(e)||!Number.isInteger(t)||e<0||t<0||e>this.segmentsX||t>this.segmentsY)throw RangeError(`cloth point (${e}, ${t}) is outside a ${this.segmentsX+1}x${this.segmentsY+1} grid`);return t*(this.segmentsX+1)+e}checkIndex(e){if(!Number.isInteger(e)||e<0||e>=this.pointCount)throw RangeError(`cloth point ${e} does not exist`)}pointPosition(e){return this.checkIndex(e),{x:this.positions[e*2],y:this.positions[e*2+1]}}isPinned(e){return this.checkIndex(e),this.pinned[e]===1}pointLinks(){return this.links.map(([e,t])=>[e,t])}pinPoint(e){this.checkIndex(e),this.pinned[e]=1,this.previous[e*2]=this.positions[e*2],this.previous[e*2+1]=this.positions[e*2+1]}unpinPoint(e){this.checkIndex(e),this.pinned[e]=0}setWind(e,t){let n=EF({x:e,y:t},`wind`);this.wind=n}setGravity(e,t){let n=EF({x:e,y:t},`gravity`);this.gravity=n}reset(){this.positions.set(this.rest),this.previous.set(this.rest)}movedCount(){let e=0;for(let t=0;t<this.pointCount;t++)this.positions[t*2]===this.rest[t*2]?this.positions[t*2+1]!==this.rest[t*2+1]&&e++:e++;return e}writePositions(e){if(!(e instanceof Float32Array)||e.length!==this.positions.length)throw RangeError(`a cloth target needs a Float32Array of ${this.positions.length} floats, saw length ${e?.length}`);e.set(this.positions)}update(e){if(!Number.isFinite(e)||e<0)throw RangeError(`a cloth update needs dt of at least 0, saw ${e}`);if(e===0)return;let t=1-this.damping,n=(this.gravity.x+this.wind.x)*e*e,r=(this.gravity.y+this.wind.y)*e*e,{positions:i,previous:a,pinned:o}=this;for(let e=0;e<this.pointCount;e++){if(o[e]===1)continue;let s=i[e*2],c=i[e*2+1];i[e*2]=s+(s-a[e*2])*t+n,i[e*2+1]=c+(c-a[e*2+1])*t+r,a[e*2]=s,a[e*2+1]=c}for(let e=0;e<2;e++)this.relax()}relax(){let{positions:e,pinned:t,stiffness:n}=this;if(n!==0)for(let[r,i,a]of this.links){let o=e[i*2]-e[r*2],s=e[i*2+1]-e[r*2+1],c=Math.hypot(o,s);if(c===0)continue;let l=(c-a)/c*n,u=t[r]===1,d=t[i]===1;if(u&&d)continue;let f=u?0:d?1:.5,p=d?0:u?1:.5;e[r*2]+=o*l*f,e[r*2+1]+=s*l*f,e[i*2]-=o*l*p,e[i*2+1]-=s*l*p}}},OF=class extends _j{constructor(e,t={}){let n=t.segmentsX??8,r=t.segmentsY??8,i=new DF({width:e.width,height:e.height,segmentsX:n,segmentsY:r,stiffness:t.stiffness,damping:t.damping,gravity:t.gravity,wind:t.wind});super({texture:e,verticesX:n+1,verticesY:r+1}),this.cloth=i,this.intent=t.intent??`decorative`,this.autoResize=!1,this.sync()}get segmentsX(){return this.cloth.segmentsX}get segmentsY(){return this.cloth.segmentsY}get pointCount(){return this.cloth.pointCount}indexOf(e,t){return this.cloth.indexOf(e,t)}pointPosition(e){return this.cloth.pointPosition(e)}isPinned(e){return this.cloth.isPinned(e)}movedCount(){return this.cloth.movedCount()}pinPoint(e){this.cloth.pinPoint(e)}unpinPoint(e){this.cloth.unpinPoint(e)}setWind(e,t){this.cloth.setWind(e,t)}setGravity(e,t){this.cloth.setGravity(e,t)}update(e){br()&&this.intent===`decorative`||(this.cloth.update(e),this.sync())}sync(){let e=this.geometry.getAttribute(`aPosition`);this.cloth.writePositions(e.buffer.data),e.buffer.update()}},kF=class extends Z{constructor(e){super(),this.spring=e.spring,this.color=e.color??16777215,this.opacity=e.alpha??1,this.lineWidth=e.lineWidth??2,this.sync()}sync(){let e=this.spring.anchorPosition,t=this.spring.position;this.clear(),this.moveTo(e.x,e.y).lineTo(t.x,t.y).stroke({color:this.color,width:this.lineWidth,alpha:this.opacity})}},AF=.35,jF=.12;function MF(e,t,n){let r=Math.sin(e*127.1+t*311.7+n*74.7)*43758.5453;return r-Math.floor(r)}function NF(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=e-r,o=t-i,s=a*a*(3-2*a),c=o*o*(3-2*o),l=MF(r,i,n)+(MF(r+1,i,n)-MF(r,i,n))*s,u=MF(r,i+1,n)+(MF(r+1,i+1,n)-MF(r,i+1,n))*s;return Math.min(1,Math.max(0,l+(u-l)*c))}function PF(e,t,n,r){if(![e,t,n,r].every(Number.isFinite))throw RangeError(`a haze sample needs finite x, y, time and seed, saw (${e}, ${t}, ${n}, ${r})`);let i=e+n*AF,a=t+n*jF;return NF(i/8,a/8,r)*.65+NF(i/3+11,a/3+7,r+1)*.35}function FF(e,t,n,r){if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray)||e.length!==t*n*4)throw RangeError(`haze needs a pixel buffer of ${t*n*4} bytes`);if(!Number.isFinite(r.time)||!Number.isFinite(r.seed))throw RangeError(`haze needs a finite time and seed, saw (${r.time}, ${r.seed})`);if(!Number.isFinite(r.density)||r.density<0||r.density>1)throw RangeError(`haze needs density between 0 and 1, saw ${r.density}`);let i=r.drift??{x:0,y:0};if(!Number.isFinite(i.x)||!Number.isFinite(i.y))throw RangeError(`haze needs a finite drift, saw (${i.x}, ${i.y})`);for(let a=0;a<n;a++)for(let n=0;n<t;n++){let o=Math.round(255*r.density*PF(n+i.x*r.time,a+i.y*r.time,r.time,r.seed));e.set([255,255,255,o],(a*t+n)*4)}}var IF=class extends wl{constructor(e){if(!Number.isFinite(e.width)||e.width<=0)throw RangeError(`a haze sheet needs width above 0, saw ${e.width}`);if(!Number.isFinite(e.height)||e.height<=0)throw RangeError(`a haze sheet needs height above 0, saw ${e.height}`);let t=e.cellsX??64,n=e.cellsY??36;if(!Number.isInteger(t)||t<1)throw RangeError(`a haze sheet needs integer cellsX of at least 1, saw ${t}`);if(!Number.isInteger(n)||n<1)throw RangeError(`a haze sheet needs integer cellsY of at least 1, saw ${n}`);let r=e.density??.5;if(!Number.isFinite(r)||r<0||r>1)throw RangeError(`a haze sheet needs density between 0 and 1, saw ${r}`);let i=e.drift??{x:.25,y:0};if(!Number.isFinite(i.x)||!Number.isFinite(i.y))throw RangeError(`a haze sheet needs a finite drift, saw (${i.x}, ${i.y})`);if(e.seed!==void 0&&!Number.isFinite(e.seed))throw RangeError(`a haze sheet needs a finite seed, saw ${e.seed}`);let a=document.createElement(`canvas`);a.width=t,a.height=n;let o=a.getContext(`2d`);if(!o)throw Error(`HazeLayer needs a 2D canvas context`);super(q.from(a)),this.time=0,this.context=o,this.image=o.createImageData(t,n),this.cellsX=t,this.cellsY=n,this.density=r,this.drift={...i},this.seed=e.seed??1,this.intent=e.intent??`decorative`,this.tint=e.tint??16777215,this.alpha=e.opacity??1,this.scale.set(e.width/t,e.height/n),this.eventMode=`none`,this.refresh()}get elapsed(){return this.time}setDensity(e){if(!Number.isFinite(e)||e<0||e>1)throw RangeError(`a haze sheet needs density between 0 and 1, saw ${e}`);this.density=e}update(e){if(!Number.isFinite(e)||e<0)throw RangeError(`a haze update needs dt of at least 0, saw ${e}`);(!br()||this.intent!==`decorative`)&&(this.time+=e),this.refresh()}refresh(){FF(this.image.data,this.cellsX,this.cellsY,{time:this.time,density:this.density,seed:this.seed,drift:this.drift}),this.context.putImageData(this.image,0,0),this.texture.source.update()}destroy(){super.destroy({texture:!0,textureSource:!0})}};function LF(e){if(!Number.isInteger(e)||e<0||e>16777215)throw RangeError(`a glow needs an integer color between 0x000000 and 0xffffff, saw ${e}`);return[e>>16&255,e>>8&255,e&255]}function RF(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)throw RangeError(`a glow falloff needs a finite distance and a radius above 0, saw (${e}, ${t})`);if(e<=0)return 1;if(e>=t)return 0;let n=1-e/t*(e/t);return n*n}function zF(e,t,n){if(!Number.isInteger(t)||t<1)throw RangeError(`a glow needs an integer size of at least 1, saw ${t}`);if(!(e instanceof Uint8Array||e instanceof Uint8ClampedArray)||e.length!==t*t*4)throw RangeError(`a glow needs a pixel buffer of ${t*t*4} bytes`);if(!Number.isFinite(n.radius)||n.radius<=0)throw RangeError(`a glow needs a radius above 0, saw ${n.radius}`);if(!Number.isFinite(n.intensity)||n.intensity<0||n.intensity>1)throw RangeError(`a glow needs intensity between 0 and 1, saw ${n.intensity}`);let[r,i,a]=LF(n.color),o=(t-1)/2;for(let s=0;s<t;s++)for(let c=0;c<t;c++){let l=RF(Math.hypot(c-o,s-o),n.radius)*n.intensity;e.set([Math.round(r*l),Math.round(i*l),Math.round(a*l),Math.round(255*l)],(s*t+c)*4)}}var BF=class e extends wl{constructor(t){if(!Number.isFinite(t.radius)||t.radius<=0)throw RangeError(`a glow needs a radius above 0, saw ${t.radius}`);let n=t.intensity??1;if(!Number.isFinite(n)||n<0||n>1)throw RangeError(`a glow needs intensity between 0 and 1, saw ${n}`);let r=t.flicker??{amount:0,frequency:1};if(!Number.isFinite(r.amount)||r.amount<0||r.amount>1)throw RangeError(`a glow needs a flicker amount between 0 and 1, saw ${r.amount}`);if(!Number.isFinite(r.frequency)||r.frequency<=0)throw RangeError(`a glow needs a flicker frequency above 0, saw ${r.frequency}`);let i=e.paintCanvas(t.color,t.radius);super(q.from(i)),this.clock=0,this.canvas=i,this.color=t.color,this.radius=t.radius,this.peak=n,this.flickerAmount=r.amount,this.flickerFrequency=r.frequency,this.intent=t.intent??`decorative`,this.blendMode=`add`,this.anchor.set(.5),this.eventMode=`none`,this.alpha=this.peak}get elapsed(){return this.clock}setColor(e){LF(e),this.color=e,this.repaint()}setRadius(e){if(!Number.isFinite(e)||e<=0)throw RangeError(`a glow needs a radius above 0, saw ${e}`);this.radius=e,this.repaint()}setIntensity(e){if(!Number.isFinite(e)||e<0||e>1)throw RangeError(`a glow needs intensity between 0 and 1, saw ${e}`);this.peak=e}update(e){if(!Number.isFinite(e)||e<0)throw RangeError(`a glow update needs dt of at least 0, saw ${e}`);(!br()||this.intent!==`decorative`)&&(this.clock+=e);let t=1+this.flickerAmount*Math.sin(2*Math.PI*this.flickerFrequency*this.clock);this.alpha=Math.min(1,Math.max(0,this.peak*t))}static paintCanvas(e,t){let n=Math.ceil(t)*2+1,r=document.createElement(`canvas`);r.width=n,r.height=n;let i=r.getContext(`2d`);if(!i)throw Error(`NeonGlow needs a 2D canvas context`);let a=i.createImageData(n,n);return zF(a.data,n,{color:e,radius:t,intensity:1}),i.putImageData(a,0,0),r}repaint(){let t=this.texture;this.canvas=e.paintCanvas(this.color,this.radius),this.texture=q.from(this.canvas),t.destroy(!0)}destroy(){super.destroy({texture:!0,textureSource:!0})}},VF=WF(),HF=new Map(VF.map((e,t)=>[UF(e),t]));function UF(e){let t=e.ne&&e.n&&e.e,n=e.se&&e.s&&e.e,r=e.sw&&e.s&&e.w,i=e.nw&&e.n&&e.w;return+!!e.n|(e.e?2:0)|(e.s?4:0)|(e.w?8:0)|(t?16:0)|(n?32:0)|(r?64:0)|(i?128:0)}function WF(){let e=new Set,t=[];for(let n=0;n<256;n++){let r={n:!!(n&1),e:!!(n&2),s:!!(n&4),w:!!(n&8),ne:!!(n&16),se:!!(n&32),sw:!!(n&64),nw:!!(n&128)},i=UF(r);e.has(i)||(e.add(i),t.push({mask:i,shape:{n:r.n,e:r.e,s:r.s,w:r.w,ne:r.ne&&r.n&&r.e,se:r.se&&r.s&&r.e,sw:r.sw&&r.s&&r.w,nw:r.nw&&r.n&&r.w}}))}return t.sort((e,t)=>e.mask-t.mask),t.map(e=>e.shape)}function GF(e){return HF.get(UF(e))}function KF(e,t,n,r){if(r.length!==VF.length)throw Error(`autotileFrames needs exactly ${VF.length} frames, got ${r.length}`);let i=new Int32Array(e*t);for(let a=0;a<t;a++)for(let t=0;t<e;t++){let o=a*e+t;i[o]=n(t,a)?r[GF({n:n(t,a-1),e:n(t+1,a),s:n(t,a+1),w:n(t-1,a),ne:n(t+1,a-1),se:n(t+1,a+1),sw:n(t-1,a+1),nw:n(t-1,a-1)})]:-1}return i}_e();function qF(e,t,n,r){let i=n*4/r,a=e,o=t;for(let e=0;e<i;e+=1)[a,o]=[-o,a];return{dx:a||0,dy:o||0}}function JF(e,t,n,r){let i=n*6/r,a=e,o=t;for(let e=0;e<i;e+=1){let e=-a-o;[a,o]=[-o,-e]}return{dx:a||0,dy:o||0}}function YF(e,t){let n=t??new Set;return!(e.hasAll&&!e.hasAll.every(e=>n.has(e))||e.hasAny&&!e.hasAny.some(e=>n.has(e))||e.hasNone&&e.hasNone.some(e=>n.has(e)))}function XF(e,t,n,r,i=qF,a=0){let o=e.rotations??0;return e.conditions.every(e=>{let s=o>0?i(e.dx,e.dy,a,o):e;return YF(e,r(t+s.dx,n+s.dy))})}function ZF(e,t,n,r,i={}){let a=i.rotate??qF,o=i.random??new j,s=[];for(let i=0;i<t;i+=1)for(let t=0;t<e;t+=1){let e=-1,c=[];for(let o of n){let n=o.rotations??0,s=n>0?n:1;for(let n=0;n<s;n+=1){if(!XF(o,t,i,r,a,n))continue;let s=o.conditions.length;s>e?(e=s,c=[{rule:o,rotationIndex:n}]):s===e&&c.push({rule:o,rotationIndex:n})}}if(c.length===0)continue;let l=c.length===1?c[0]:c[QF(c.map(e=>e.rule.probability??1),o)],u=l.rule.rotations??0;for(let e of l.rule.images){let n=u>0?a(e.dx??0,e.dy??0,l.rotationIndex,u):{dx:e.dx??0,dy:e.dy??0};s.push({x:t,y:i,ruleId:l.rule.id,image:e.image,dx:n.dx,dy:n.dy,layer:e.layer??0})}}return s}function QF(e,t){let n=e.reduce((e,t)=>e+Math.max(0,t),0);if(n<=0)return 0;let r=t.float()*n;for(let t=0;t<e.length;t+=1)if(r-=Math.max(0,e[t]),r<0)return t;return e.length-1}var $F=class extends J{};function eI(e,t){let n={};for(let r of t){let t=new $F;t.label=r,e.addChild(t),n[r]=t}return n}var tI=class extends Z{dashedLine(e,t,n,r,i=6,a=4){let o=Math.hypot(n-e,r-t);if(o===0||i<=0)return this;let s=(n-e)/o,c=(r-t)/o;for(let n=0;n<o;n+=i+Math.max(0,a)){let r=Math.min(n+i,o);this.moveTo(e+s*n,t+c*n).lineTo(e+s*r,t+c*r)}return this}},nI=class extends jA{},rI=class extends wl{},iI=class extends dA{},aI=wC,oI=class extends $F{constructor(e){super(),this.placements=e.placements,this.project=e.project,this.resolveImage=e.resolveImage??(e=>zN(e,q.EMPTY)),this.rebuild()}setPlacements(e){this.placements=e,this.rebuild()}rebuild(){for(let e of this.removeChildren())e.destroy();for(let e of[...this.placements].sort((e,t)=>e.layer-t.layer)){let t=this.project(e.x,e.y,e.dx,e.dy),n=new rI(this.resolveImage(e.image));n.x=t.x,n.y=t.y,this.addChild(n)}}},sI=[{workload:`sprites`,preferred:`PixiJS WebGL/WebGPU batcher`,fallback:`PixiJS WebGL`,reason:`high-volume textured 2D batches`},{workload:`ui`,preferred:`PixiJS display tree`,fallback:`PixiJS display tree`,reason:`themeable 2D layout and text`},{workload:`custom-shaders`,preferred:`backend-specific GLSL/WGSL only when profiled`,fallback:`PixiJS filters`,reason:`avoid maintaining paired shader sources without a measured gain`},{workload:`particles`,preferred:`PixiJS for 2D, Babylon.js for 3D`,fallback:`instanced sprites/meshes`,reason:`match simulation and depth to the scene`},{workload:`instanced-terrain`,preferred:`Babylon.js thin instances`,fallback:`PixiJS TileMap for 2D`,reason:`depth-tested repeated 3D geometry`},{workload:`voxels`,preferred:`Babylon.js thin instances`,fallback:`batched meshes`,reason:`color-grouped 3D voxels`},{workload:`animated-models`,preferred:`Babylon.js glTF animation groups`,fallback:`billboard sprites`,reason:`standard 3D interchange and animation support`},{workload:`large-3d-worlds`,preferred:`Babylon.js with streaming/culling`,fallback:`partitioned scenes`,reason:`scene graph, depth, and instancing`}];function cI(e={}){let t=e.createCanvas?.()??(typeof document>`u`?null:document.createElement(`canvas`)),n=!!t?.getContext(`webgl2`);return{webgl1:n||!!(t?.getContext(`webgl`)??t?.getContext(`experimental-webgl`)),webgl2:n,webgpu:e.webgpu??!!globalThis.navigator?.gpu,wgsl:e.wgsl??!1}}async function lI(){let e=globalThis.navigator?.gpu;if(!e)return{webgpu:!1,wgsl:!1};try{let t=await(await e.requestAdapter())?.requestDevice();return t?{webgpu:!0,wgsl:(await t.createShaderModule({code:`@compute @workgroup_size(1) fn main() {}`}).getCompilationInfo()).messages.length===0}:{webgpu:!1,wgsl:!1}}catch{return{webgpu:!1,wgsl:!1}}}var uI=536870911,dI={orthogonal:`square`,isometric:`isometric`,staggered:`staggered`};function fI(e,t,n){if(e.frameWidth!==t.tilewidth||e.frameHeight!==t.tileheight)throw Error(`the tileset at firstgid ${n} is cut to ${e.frameWidth}x${e.frameHeight}, but the map is ${t.tilewidth}x${t.tileheight}`)}function pI(e,t,n){let r=-1;for(let n=0;n<t.length&&t[n]<=e;n++)r=n;if(r===-1)throw Error(`layer "${n}" uses gid ${e}, below every tileset's firstgid (${t.join(`, `)})`);return r}function mI(e,t){let n=e.orientation??`orthogonal`,r=dI[n];if(!r)throw Error(`loadTiledMap does not read "${n}" maps yet`);if(r===`staggered`&&(e.staggeraxis??`y`)!==`y`)throw Error(`loadTiledMap only reads Y-axis staggered maps right now, this one is staggered on "${e.staggeraxis}"`);if(r===`staggered`&&(e.staggerindex??`odd`)!==`odd`)throw Error(`loadTiledMap only reads odd-index staggered maps right now, this one staggers "${e.staggerindex}"`);if(e.tilesets.length===0)throw Error(`loadTiledMap needs at least one tileset, this map has none`);let i=[...e.tilesets].sort((e,t)=>e.firstgid-t.firstgid),a,o;if(t instanceof sP){if(e.tilesets.length!==1)throw Error(`loadTiledMap was given one sheet but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);fI(t,e,i[0].firstgid),a=[t],o=[i[0].firstgid]}else{if(t.length!==e.tilesets.length)throw Error(`loadTiledMap was given ${t.length} sheets but this map has ${e.tilesets.length} tilesets - pass one sheet per tileset`);a=i.map(n=>{let r=t.find(e=>e.firstgid===n.firstgid);if(!r)throw Error(`loadTiledMap was given no sheet for the tileset at firstgid ${n.firstgid}`);return fI(r.sheet,e,n.firstgid),r.sheet}),o=i.map(e=>e.firstgid)}let s=new nF({width:e.width,height:e.height,sheet:a,shape:r}),c=[];for(let t of e.layers)if(t.type===`tilelayer`){if(t.encoding&&t.encoding!==`csv`)throw Error(`layer "${t.name}" uses "${t.encoding}" encoding - export tile layers as CSV/plain, not compressed`);let e=(t.data??[]).map(e=>{let n=e&uI;if(n===0)return-1;let r=pI(n,o,t.name);return o.length===1?n-o[0]:$P(r,n-o[r])});s.addLayer(t.name,e)}else if(t.type===`objectgroup`)for(let n of t.objects??[])c.push({...n,tileX:Math.floor(n.x/e.tilewidth),tileY:Math.floor(n.y/e.tileheight)});return{map:s,objects:c}}async function hI(e,t){if(t.mixer&&t.mixer.skeleton!==t.skeleton)throw Error(`SVG skeleton mixer must use the supplied skeleton`);let n=await tP(e),r=new DOMParser().parseFromString(n,`image/svg+xml`),i=r.documentElement;if(r.querySelector(`parsererror`)||i.localName!==`svg`)throw Error(`SVG skeleton needs a valid svg root`);let a=i.getAttribute(`viewBox`)?.trim().split(/[\s,]+/).map(Number)??[0,0,Number(i.getAttribute(`width`)),Number(i.getAttribute(`height`))];if(a.length!==4||!a.every(Number.isFinite)||a[2]<=0||a[3]<=0)throw Error(`SVG skeleton needs a finite viewBox or positive numeric width and height`);let o=new Map;for(let e of i.querySelectorAll(`g[id]`)){if(o.has(e.id))throw Error(`duplicate SVG skeleton group ${e.id}`);o.set(e.id,e)}let s=new Map(pN(t.skeleton).map(e=>[e.name,e])),c=t.bindings??[...o.keys()].filter(e=>s.has(e)).map(e=>({bone:e}));if(!c.length)throw Error(`SVG skeleton found no matching bone groups`);let l=new Set(c.map(e=>e.group??e.bone)),u=new Set,d=[],f=new XMLSerializer;for(let e of c){let n=e.group??e.bone;if(u.has(e.bone))throw Error(`duplicate SVG binding for bone ${e.bone}`);u.add(e.bone);let c=s.get(e.bone);if(!c)throw Error(`SVG binding names no bone ${e.bone}`);let p=o.get(n);if(!p)throw Error(`SVG skeleton missing group ${n}`);let m=e.pivot??t.pivots?.[n]??{x:p.hasAttribute(`data-pivot-x`)?Number(p.getAttribute(`data-pivot-x`)):NaN,y:p.hasAttribute(`data-pivot-y`)?Number(p.getAttribute(`data-pivot-y`)):NaN},h=e.rotation??c.angle;if(![m.x,m.y,h].every(Number.isFinite))throw Error(`SVG skeleton group ${n} needs a finite pivot and rest angle`);let g=Math.max(Math.abs(a[0]-m.x),Math.abs(a[0]+a[2]-m.x)),_=Math.max(Math.abs(a[1]-m.y),Math.abs(a[1]+a[3]-m.y)),v=Math.ceil(Math.hypot(g,_))+1,y=i.cloneNode(!1);y.setAttribute(`viewBox`,`${-v} ${-v} ${v*2} ${v*2}`),y.setAttribute(`width`,String(v*2)),y.setAttribute(`height`,String(v*2));for(let e of i.querySelectorAll(`defs, style`))y.appendChild(e.cloneNode(!0));let b=p.cloneNode(!0);for(let e of b.querySelectorAll(`g[id]`))l.has(e.id)&&e.remove();let x=b;for(let e=p.parentElement;e&&e!==i;e=e.parentElement){let t=e.cloneNode(!1);t.appendChild(x),x=t}let S=r.createElementNS(i.namespaceURI,`g`);S.setAttribute(`id`,`mwg-part`),S.setAttribute(`transform`,`rotate(${-h}) translate(${-m.x} ${-m.y})`),S.appendChild(x),y.appendChild(S),d.push({bone:e.bone,svg:f.serializeToString(y)})}let p=Object.create(null);for(let e of d)p[e.bone]=(await rP(e.svg,{resolution:t.resolution}))[`mwg-part`];let m=new TN(t.skeleton,t.mixer);for(let e of d){let t=m.bind(e.bone,p[e.bone]);t.anchor.set(.5),t.label=e.bone}return m.apply({}),{sprite:m,textures:Object.freeze(p)}}var gI={panelBorder:4,padding:8,spacing:2,direction:`ltr`,font:{family:`ui-monospace, Consolas, "DejaVu Sans Mono", monospace`,size:12,lineHeight:1.4},color:{text:15263984,textDim:9079446,textHighlight:16770688,panelFill:1842214,panelBorder:4868702,selection:3820154,overlay:0},overlayAlpha:.5},_I={panelBorder:6,padding:10,spacing:4,direction:`ltr`,font:{family:gI.font.family,size:14,lineHeight:1.5},color:{text:16777215,textDim:13421772,textHighlight:16776960,panelFill:0,panelBorder:16777215,selection:16776960,overlay:0},overlayAlpha:.85},vI=gI;function Q(){return vI}var $=new p;function yI(e){vI={...gI,...e,font:{...gI.font,...e.font},color:{...gI.color,...e.color}},$.dispatch(vI)}function bI(e){return typeof e==`string`?{text:e}:e}function xI(e,t){return e.align??(t.direction===`rtl`?`right`:`left`)}function SI(e,t=40){let n=Math.max(0,e);return{total:n,speed:Math.max(0,t),revealed:t===0?n:0}}function CI(e,t){return e.revealed=Math.min(e.total,Math.max(0,e.revealed+e.speed*t)),TI(e)}function wI(e){e.revealed=e.total}function TI(e){return e.revealed>=e.total}var EI=class extends jA{constructor(e={}){let t=bI(e),n=Q();super({text:t.text??``,resolution:t.resolution,roundPixels:t.roundPixels,style:new aO({fontFamily:n.font.family,stroke:t.stroke,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:xI(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0})}),this.themeListener=e=>this.restyle(e),this.revealSource=null,this.reveal=null,this.opts=t,$.add(this.themeListener)}setColor(e){this.destroyed||(this.style.fill=e)}setWrapWidth(e){this.destroyed||(this.style.wordWrap=e!==void 0,this.style.wordWrapWidth=e??0)}setText(e){this.destroyed||(this.revealSource=null,this.reveal=null,this.text!==e&&(this.text=e))}showProgressive(e,t){this.destroyed||(this.revealSource=e,this.reveal=SI(e.length,t),this.renderRevealed())}updateReveal(e){if(this.destroyed||!this.reveal)return!0;let t=CI(this.reveal,e);return this.renderRevealed(),t}completeReveal(){!this.destroyed&&this.reveal&&(wI(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||this.revealSource===null)return;let e=this.revealSource.slice(0,Math.floor(this.reveal.revealed));this.text!==e&&(this.text=e)}restyle(e){this.destroyed||(this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=xI(this.opts,e)))}destroy(e){$.remove(this.themeListener),super.destroy(e)}},DI={positive:5627255,negative:16733525,warning:16757575};function OI(e,t){return t>0?e.slice(Math.max(0,e.length-Math.floor(t))):[]}function kI(e,t){let n=0;for(let t of e)n+=t;let r=0;for(;n>t&&r<e.length-1;)n-=e[r++];return r}var AI=class extends J{constructor(e){super(),this.blocks=[],this.options=e,this.maxLines=e.maxLines??3}get entryCount(){return this.blocks.length}get contentHeight(){return this.blocks.reduce((e,t)=>e+t.label.height,0)}lastEntries(e){return OI(this.blocks.map(e=>({text:e.text,level:e.level})),e)}add(e,t=`info`){let n=new EI({text:e,size:this.options.size,color:this.colorOf(t),wrapWidth:this.options.wrapWidth,resolution:this.options.resolution});this.addChild(n),this.blocks.push({label:n,level:t,text:e}),this.trim(),this.layout()}setMaxLines(e){this.maxLines=Math.max(1,Math.floor(e)),this.trim(),this.layout()}setWrapWidth(e){this.options.wrapWidth=e;for(let t of this.blocks)t.label.style.wordWrapWidth=e;this.trim(),this.layout()}clear(){for(let e of this.blocks.splice(0))e.label.destroy()}colorOf(e){let t=this.options.colors?.[e];return t===void 0?e===`info`?Q().color.text:e===`highlight`?Q().color.textHighlight:DI[e]:t}linesOf(e){let t=Number(e.style.lineHeight)||Number(e.style.fontSize)||1;return Math.max(1,Math.round(e.height/t))}trim(){let e=kI(this.blocks.map(e=>this.linesOf(e.label)),this.maxLines);for(let t of this.blocks.splice(0,e))t.label.destroy()}layout(){let e=0;for(let t of this.blocks)t.label.position.set(0,e),e+=t.label.height}};function jI(e,t,n){let r=Math.max(1,Math.floor(e));for(;r>1&&t*r>n;)r--;return r}function MI(e){let t=1;for(let n=e;n;n=n.parent)t*=Math.abs(n.scale.x);return t}function NI(e,t){let n=(e,r)=>{if(e instanceof jA){let n=t*Math.max(1,Math.round(r));e.resolution!==n&&(e.resolution=n)}for(let t of e.children)n(t,r*Math.abs(t.scale.x))};n(e,MI(e))}var PI=``,FI=``,II=``;function LI(e){let t=``;for(let n=0;n<e.length;n++)if(e[n]===`\\`&&n+1<e.length&&(e[n+1]===`*`||e[n+1]===`_`||e[n+1]===`\\`)){let r=e[n+1];t+=r===`*`?PI:r===`_`?FI:II,n++}else t+=e[n];return t}function RI(e){return e.replaceAll(PI,`*`).replaceAll(FI,`_`).replaceAll(II,`\\`)}function zI(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function BI(e,t,n){let r=[],i=0;for(;i<e.length;){if(e[i]!==t){i++;continue}let a=0;for(;e[i+a]===t;)a++;if(!(t===`_`&&zI(e[i-1])&&zI(e[i+a]))){if(n)for(let e=0;e<Math.floor(a/2);e++)r.push(i+e*2);else a%2==1&&r.push(i+a-1)}i+=a}return r}function VI(e,t,n,r,i,a){let o=BI(e,t,n),s=n?2:1;for(let e=0;e+1<o.length;e+=2){let t=o[e],n=o[e+1];i.push({from:t+s,to:n,style:r}),a.push({from:t,to:t+s},{from:n,to:n+s})}}function HI(e){let t=[];for(let n of e){if(!n.text)continue;let e=t[t.length-1];e&&e.bold===n.bold&&e.italic===n.italic?e.text+=n.text:t.push({...n})}return t}function UI(e){let t=LI(e),n=[],r=[];VI(t,`*`,!0,`bold`,n,r),VI(t,`_`,!0,`bold`,n,r),VI(t,`*`,!1,`italic`,n,r),VI(t,`_`,!1,`italic`,n,r);let i=new Set([0,t.length]);for(let e of n)i.add(e.from),i.add(e.to);for(let e of r)i.add(e.from),i.add(e.to);let a=[...i].sort((e,t)=>e-t),o=[];for(let e=0;e+1<a.length;e++){let i=a[e],s=a[e+1];i>=s||r.some(e=>e.from<=i&&s<=e.to)||o.push({text:t.slice(i,s),bold:n.some(e=>e.style===`bold`&&e.from<=i&&s<=e.to),italic:n.some(e=>e.style===`italic`&&e.from<=i&&s<=e.to)})}return HI(o).map(e=>({...e,text:RI(e.text)}))}function WI(e){return UI(e).map(e=>e.text).join(``)}function GI(e,t){let n=[],r=Math.max(0,Math.floor(t));for(let t of e){if(r<=0)break;let e=Math.min(t.text.length,r);n.push({...t,text:t.text.slice(0,e)}),r-=e}return n}var KI=class extends mj{constructor(e={}){let t=bI(e),n=Q(),r=t.tagStyles===void 0?[]:Object.keys(t.tagStyles);super({text:qI(t.text??``,r),resolution:t.resolution,style:new ZA({fontFamily:n.font.family,fontSize:t.size??n.font.size,fontWeight:t.bold?`bold`:`normal`,fill:t.color??n.color.text,lineHeight:(t.size??n.font.size)*n.font.lineHeight,align:xI(t,n),wordWrap:t.wrapWidth!==void 0,wordWrapWidth:t.wrapWidth??0,breakWords:!0,tagStyles:t.tagStyles})}),this.themeListener=e=>this.restyle(e),this.revealSpans=null,this.reveal=null,this.opts=t,this.tags=r,$.add(this.themeListener)}setText(e){this.revealSpans=null,this.reveal=null;let t=qI(e,this.tags);this.text!==t&&(this.text=t)}showProgressive(e,t){this.revealSpans=UI(e),this.reveal=SI(WI(e).length,t),this.renderRevealed()}updateReveal(e){if(!this.reveal)return!0;let t=CI(this.reveal,e);return this.renderRevealed(),t}completeReveal(){this.reveal&&(wI(this.reveal),this.renderRevealed())}renderRevealed(){if(!this.reveal||!this.revealSpans)return;let e=JI(GI(this.revealSpans,this.reveal.revealed),this.tags);this.text!==e&&(this.text=e)}restyle(e){this.style.fontFamily=e.font.family,this.opts.color===void 0&&(this.style.fill=e.color.text),this.opts.size===void 0&&(this.style.fontSize=e.font.size,this.style.lineHeight=e.font.size*e.font.lineHeight),this.opts.align===void 0&&(this.style.align=xI(this.opts,e))}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function qI(e,t){return JI(UI(e),t)}function JI(e,t){return e.map(e=>{let n=YI(e.text,t);return e.italic&&(n=`<i>${n}</i>`),e.bold&&(n=`<b>${n}</b>`),n}).join(``)}function YI(e,t){let n=e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);for(let e of t)n=n.replaceAll(`<${e}>`,`<${e}>`).replaceAll(`</${e}>`,`</${e}>`);return n}var XI=new Set([`b`,`i`,`span`,`br`,`img`]);function ZI(e,t={}){let n=t.variables??{},r=t.tags,i=[],a=[],o={bold:!1,italic:!1},s=``,c=()=>{if(!s)return;let e={text:s,bold:o.bold,italic:o.italic};o.color!==void 0&&(e.color=o.color),o.size!==void 0&&(e.size=o.size),o.tag!==void 0&&(e.tag=o.tag),i.push(e),s=``};for(let t=0;t<e.length;t++){let l=e[t];if(l===`&`){let n=lL(e,t);if(n){s+=n.text,t=n.end;continue}}if(l===`$`){let r=uL(e,t),i=r?n[r.name]:void 0;if(r&&i!==void 0){s+=i,t=r.end;continue}}if(l===`<`){let n=sL(e,t);if(n&&(XI.has(n.name)||r?.has(n.name))){if(n.name===`img`){let r=cL(e,n);if(r){c(),i.push({text:``,bold:!1,italic:!1,image:r.src}),t=r.end;continue}}else if(n.name===`br`){s+=`
|
|
1370
|
-
`,t=n.end;continue}else if(n.closing){let e=a[a.length-1];if(e?.tag===n.name){c(),o=e.style,a.pop(),t=n.end;continue}}else{c(),a.push({tag:n.name,style:o}),o=aL(o,n.name,n.body),t=n.end;continue}}}s+=l}return c(),i}function QI(e,t={}){return ZI(e,t).map(e=>e.image??e.text).join(``)}function $I(e){return e.map(e=>{if(e.image!==void 0)return``;let t=iL(e.text);e.italic&&(t=`<i>${t}</i>`),e.bold&&(t=`<b>${t}</b>`);let n=[e.color===void 0?void 0:`color:${e.color}`,e.size===void 0?void 0:`font-size:${e.size}px`].filter(e=>e!==void 0);return n.length>0&&(t=`<span style="${n.join(`;`)}">${t}</span>`),e.tag!==void 0&&(t=`<${e.tag}>${t}</${e.tag}>`),t}).join(``)}function eL(e,t={}){let n=t.describeImage??(()=>`[image]`);return e.map(e=>e.image===void 0?e.text:n(e.image)).join(``)}function tL(e,t,n){let r=[];for(let t of e)t.image===void 0?t.text.split(`
|
|
1371
|
-
`).forEach((e,n)=>{n>0&&r.push({text:``,bold:t.bold,italic:t.italic,hardBreak:!0});for(let n of e.match(/\S+|\s+/g)??[])r.push({text:n,bold:t.bold,italic:t.italic,color:t.color,size:t.size,tag:t.tag})}):r.push({...t});let i=[],a=[],o=0,s=()=>{for(;a.length>0&&a[a.length-1].text.trim()===``&&!a[a.length-1].image;)o-=t(a[a.length-1]),a.pop();i.push({spans:nL(a),width:Math.max(0,o)}),a=[],o=0};for(let e of r){if(e.hardBreak){s();continue}let r=t(e),i=e.image===void 0&&e.text.trim()===``;o>0&&!i&&o+r>n&&s(),a.push(e),o+=r}return(a.length>0||i.length===0)&&s(),i}function nL(e){let t=[];for(let n of e){let e=t[t.length-1];e&&n.image===void 0&&e.image===void 0&&e.bold===n.bold&&e.italic===n.italic&&e.color===n.color&&e.size===n.size&&e.tag===n.tag?e.text+=n.text:t.push({...n})}return t}function rL(e,t){let n=t.direction??`ltr`,r=t.align??(n===`rtl`?`right`:`left`),i=[];for(let a=0;a<e.length;a++){let o=e[a],s=a*t.lineHeight,c=o.spans.map(e=>t.measure(e)),l=c.reduce((e,t)=>e+t,0),u=r===`left`?0:r===`right`?t.maxWidth-l:(t.maxWidth-l)/2,d=n===`rtl`?u+l:u;for(let e=0;e<o.spans.length;e++){let t=c[e],r=n===`rtl`?d-t:d;d=n===`rtl`?d-t:d+t,i.push({span:o.spans[e],x:r,y:s,width:t})}}return i}function iL(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function aL(e,t,n){if(t===`b`)return{...e,bold:!0};if(t===`i`)return{...e,italic:!0};if(t!==`span`)return{...e,tag:t};let r=oL(n,`color`),i=Number(oL(n,`size`)??``),a={...e};return r&&(a.color=r),Number.isFinite(i)&&i>0&&(a.size=i),a}function oL(e,t){let n=RegExp(`(?:^|\\s)${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`).exec(e);return n?n[1]??n[2]??n[3]:void 0}function sL(e,t){let n=/^<(\/?)([a-zA-Z]+)([^>]*)>/.exec(e.slice(t));if(!n)return null;let r=n[3].trimEnd();return{name:n[2].toLowerCase(),closing:n[1]===`/`,selfClosing:r.endsWith(`/`)&&n[1]===``,body:r.replace(/\/$/,``).trim(),end:t+n[0].length-1}}function cL(e,t){if(t.selfClosing){let e=oL(t.body,`src`);return e?{src:e,end:t.end}:null}let n=e.indexOf(`</img>`,t.end+1);if(n<0)return null;let r=e.slice(t.end+1,n).trim();return r?{src:r,end:n+6-1}:null}function lL(e,t){let n={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`},r=/^&(lt|gt|amp|quot|apos);/.exec(e.slice(t));if(r)return{text:n[r[1]],end:t+r[0].length-1};let i=/^&#(\d+);/.exec(e.slice(t));return i?{text:String.fromCodePoint(Number(i[1])),end:t+i[0].length-1}:null}function uL(e,t){let n=/^\$([A-Za-z_][A-Za-z0-9_]*)/.exec(e.slice(t));return n?{name:n[1],end:t+n[0].length-1}:null}var dL=class extends J{constructor(e={}){super(),this.themeListener=e=>this.rebuild(e),this.opts=e,this.rebuild(Q()),$.add(this.themeListener)}setText(e){this.opts.text=e,this.rebuild(Q())}rebuild(e){for(let e of this.removeChildren())e.destroy();let t=this.opts.lineHeight??e.font.size*e.font.lineHeight,n=this.opts.maxWidth??1/0,r=this.opts.maxWidth??0,i=this.opts.direction??e.direction,a=this.opts.resolveImage??(e=>zN(e,q.EMPTY)),o=pL(),s=n=>this.measurePiece(n,e,t,a,o),c=this.opts.tagStyles,l=rL(tL(ZI(this.opts.text??``,{variables:this.opts.variables,tags:c===void 0?void 0:new Set(Object.keys(c))}),s,n),{measure:s,maxWidth:r,lineHeight:t,direction:i,align:this.opts.align??(this.opts.maxWidth===void 0?`left`:void 0)});for(let n of l){let r=n.span.image===void 0?this.textFor(n.span,e,t):this.spriteFor(n.span.image,t,a);r.x=n.x,r.y=n.y,this.addChild(r)}}measurePiece(e,t,n,r,i){if(e.image!==void 0)return gL(r(e.image),n).width;let a=this.resolvedFont(e,t);return i?(i.font=`${a.italic?`italic `:``}${a.bold?`bold `:``}${a.size}px ${a.family}`,i.measureText(e.text).width):e.text.length*a.size}tagStyle(e){return e===void 0||this.opts.tagStyles===void 0?void 0:this.opts.tagStyles[e]}resolvedFont(e,t){let n=this.tagStyle(e.tag);return{family:typeof n?.fontFamily==`string`?n.fontFamily:t.font.family,size:typeof n?.fontSize==`number`?n.fontSize:e.size??t.font.size,bold:n?.fontWeight===void 0?e.bold:mL(n.fontWeight),italic:n?.fontStyle===void 0?e.italic:hL(n.fontStyle)}}textFor(e,t,n){let r=this.resolvedFont(e,t),i=this.tagStyle(e.tag);return new nI({text:e.text,resolution:this.opts.resolution,style:{fontFamily:r.family,fontSize:r.size,fontWeight:r.bold?`bold`:`normal`,fontStyle:r.italic?`italic`:`normal`,fill:e.color??t.color.text,lineHeight:n,...i}})}spriteFor(e,t,n){let r=n(e),i=gL(r,t),a=new rI(r);return a.width=i.width,a.height=i.height,a}destroy(e){$.remove(this.themeListener),super.destroy(e)}},fL=null;function pL(){return typeof document>`u`?null:(fL??=document.createElement(`canvas`).getContext(`2d`),fL)}function mL(e){if(e===`bold`||e===`bolder`)return!0;if(e===`normal`||e===`lighter`)return!1;let t=Number(e);return Number.isFinite(t)&&t>=600}function hL(e){return e===`italic`||e===`oblique`}function gL(e,t){return{width:(e.width>0?e.width:t)*(t/(e.height>0?e.height:t)),height:t}}var _L=class extends WA{constructor(e={}){let t=bI(e),n=Q();super({text:t.text??``,style:vL(t,n)}),this.themeListener=e=>this.restyle(e),this.opts=t,$.add(this.themeListener)}setText(e){this.text!==e&&(this.text=e)}restyle(e){this.style=vL(this.opts,e)}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function vL(e,t){return{fontFamily:t.font.family,fontSize:e.size??t.font.size,fontWeight:e.bold?`bold`:`normal`,fill:e.color??t.color.text,align:xI(e,t),wordWrap:e.wrapWidth!==void 0,wordWrapWidth:e.wrapWidth??0,breakWords:!0}}var yL=class extends J{constructor(e,t){super();let n=typeof t.border==`number`?{left:t.border,top:t.border,right:t.border,bottom:t.border}:t.border;this.sprite=new kj({texture:e,leftWidth:n.left,topHeight:n.top,rightWidth:n.right,bottomHeight:n.bottom}),this.addChild(this.sprite)}get border(){return{left:this.sprite.leftWidth,top:this.sprite.topHeight,right:this.sprite.rightWidth,bottom:this.sprite.bottomHeight}}resize(e,t){let n=this.border;this.sprite.width=Math.max(e,n.left+n.right),this.sprite.height=Math.max(t,n.top+n.bottom)}},bL=`position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0;`,xL=class{constructor(){this.polite=null,this.assertive=null}region(e){if(typeof document>`u`||!document.body)return null;let t=e?this.assertive:this.polite;if(t)return t;let n=document.createElement(`div`);return n.setAttribute(`aria-live`,e?`assertive`:`polite`),n.setAttribute(`aria-atomic`,`true`),n.setAttribute(`role`,`status`),n.setAttribute(`style`,bL),document.body.appendChild(n),e?this.assertive=n:this.polite=n,n}announce(e,t={}){let n=this.region(t.assertive??!1);n&&(n.textContent=``,n.appendChild(document.createTextNode(e)))}clear(){this.polite&&(this.polite.textContent=``),this.assertive&&(this.assertive.textContent=``)}destroy(){this.polite?.remove(),this.assertive?.remove(),this.polite=null,this.assertive=null}},SL=new xL,CL=class extends J{constructor(e){super(),this.content=new J,this.onClose=new p,this.titleLabel=null,this.closeMark=null,this.innerWidth=0,this.innerHeight=0,this.currentWidth=0,this.currentHeight=0,this.blocker=null,this.themeListener=()=>this.restyle(),this.isClosed=!1,this.motion=null,this.delegate=null,this.onBlockerDown=e=>{e.stopPropagation();let t=e.getLocalPosition(this);this.handleOutsideClick(t.x,t.y)};let t=Q();this.colors={...e.colors},this.modal=e.modal??!0,this.closable=e.closable??!0,this.dims=e.dims??this.modal,this.anchor=e.anchor??`center`,e.blocker===!0&&(this.blocker=new J,this.blocker.eventMode=`static`,this.blocker.on(`pointerdown`,this.onBlockerDown),this.addChild(this.blocker)),this.background=t.panel?new yL(t.panel,{border:t.panelBorder}):new Z,this.addChild(this.background),e.title!==void 0&&(this.titleLabel=new EI({text:e.title,color:this.colors.title??t.color.textHighlight,bold:!0}),this.addChild(this.titleLabel),SL.announce(e.title)),e.closeButton===!0&&this.closable&&(this.closeMark=new EI({text:`✕`,color:this.colors.title??t.color.textHighlight,bold:!0}),this.closeMark.eventMode=`static`,this.closeMark.cursor=`pointer`,this.closeMark.on(`pointertap`,()=>this.close()),this.addChild(this.closeMark)),this.addChild(this.content),this.resize(e.width,e.height),$.add(this.themeListener)}restyle(){this.titleLabel?.setColor(this.colors.title??Q().color.textHighlight),this.closeMark?.setColor(this.colors.title??Q().color.textHighlight),this.resize(this.currentWidth,this.currentHeight)}resize(e,t){this.currentWidth=e,this.currentHeight=t;let n=Q(),r=(this.background instanceof yL?this.background.border.left:2)+n.padding;this.background instanceof yL?(this.background.resize(e,t),this.background.tint=this.colors.background??16777215):this.background.clear().roundRect(0,0,e,t,4).fill({color:this.colors.background??n.color.panelFill}).stroke({color:this.colors.border??n.color.panelBorder,width:1}),this.closeMark&&(this.closeMark.x=n.direction===`rtl`?r:e-r-this.closeMark.width,this.closeMark.y=r);let i=r;this.titleLabel&&(this.titleLabel.x=n.direction===`rtl`?e-r-this.titleLabel.width:r,this.titleLabel.y=r,i=r+this.titleLabel.height+n.padding),this.content.x=r,this.content.y=i,this.innerWidth=Math.max(0,e-r*2),this.innerHeight=Math.max(0,t-i-r)}get contentWidth(){return this.innerWidth}get contentHeight(){return this.innerHeight}setTitle(e){this.titleLabel?.setText(e)}setColors(e){this.colors={...e},this.restyle()}handleAction(e){return this.isClosed?!1:this.delegate?.handleAction(e)?!0:e===`cancel`&&this.closable?(this.close(),!0):!1}get closed(){return this.isClosed}update(e){let t=this.motion;if(!t)return;t.elapsed+=e;let n=t.options.duration??.25,r=Math.min(1,t.elapsed/n);this.applyMotion(t.closing?1-r:r,t),!(r<1)&&(this.motion=null,t.closing?this.close():this.applyMotion(1,t))}applyMotion(e,t){let n=Xj(t.options.animation,e,t.closing),r=t.options.from??{x:t.base.x+this.currentWidth/2,y:t.base.y+this.currentHeight/2};this.scale.set(n.scale),this.alpha=n.alpha,this.position.set(r.x+(t.base.x-r.x)*n.scale,r.y+(t.base.y-r.y)*n.scale+n.offset)}open(e){!e||br()||this.isClosed||(this.motion={options:e,elapsed:0,closing:!1,base:{x:this.x,y:this.y}},this.applyMotion(0,this.motion))}close(e){if(!this.isClosed){if(e&&!br()){let t=this.motion?.base??{x:this.x,y:this.y};this.motion={options:e,elapsed:0,closing:!0,base:t}}else this.isClosed=!0,this.onClose.dispatch(),this.parent?.removeChild(this),this.destroy({children:!0})}}place(e,t){if(this.isClosed)return;let n=this.getLocalBounds(),r=Q().padding*2;this.x=Math.round((e-n.width)/2),this.y=this.anchor===`bottom`?Math.round(t-n.height-r):this.anchor===`top`?r:Math.round((t-n.height)/2),this.fitBlocker(e,t)}fitBlocker(e,t){this.blocker&&(this.blocker.hitArea=new G(-this.x,-this.y,e,t))}handleOutsideClick(e,t){return this.isClosed||e>=0&&t>=0&&e<this.currentWidth&&t<this.currentHeight||!this.closable?!1:(this.close(),!0)}destroy(e){this.isClosed=!0,$.remove(this.themeListener),super.destroy(e)}},wL=class extends J{constructor(){super(),this.windows=[],this.overlay=new Z,this.viewportWidth=0,this.viewportHeight=0,this.listener=e=>this.handleAction(e),this.themeListener=()=>this.drawOverlay(),this.overlay.visible=!1,this.addChild(this.overlay),P.add(this.listener),$.add(this.themeListener)}setViewport(e,t){this.viewportWidth=e,this.viewportHeight=t,this.drawOverlay();for(let n of this.windows)n.place(e,t)}get top(){return this.windows[this.windows.length-1]??null}get isEmpty(){return this.windows.length===0}get depth(){return this.windows.length}push(e){if(e.closed)throw Error(`cannot open a window that was already closed`);return this.windows.push(e),this.addChild(e),e.onClose.add(()=>(this.forget(e),!1)),e.place(this.viewportWidth,this.viewportHeight),this.updateOverlay(),e}pop(){this.top?.close()}closeAll(){for(let e of[...this.windows].reverse())e.close()}forget(e){let t=this.windows.indexOf(e);t!==-1&&this.windows.splice(t,1),this.updateOverlay()}updateOverlay(){let e=this.windows.findIndex(e=>e.dims);e===-1?this.overlay.visible=!1:(this.overlay.visible=!0,this.setChildIndex(this.overlay,Math.max(0,this.getChildIndex(this.windows[e])-1)))}drawOverlay(){let e=Q();this.overlay.clear().rect(0,0,this.viewportWidth,this.viewportHeight).fill({color:e.color.overlay,alpha:e.overlayAlpha})}handleAction(e){return this.top?.handleAction(e)??!1}get blocksWorld(){return this.windows.some(e=>e.modal)}update(e){this.top?.update(e)}destroy(e){P.remove(this.listener),$.remove(this.themeListener),super.destroy(e)}},TL=class{constructor(e){this.list=[],this.current=0,this.hooks=e}get items(){return this.list}get selectedIndex(){return this.current}get selected(){return this.list[this.current]??null}get length(){return this.list.length}reset(e){this.list=e,this.current=e.findIndex(e=>!e.disabled),this.current===-1&&(this.current=0)}swap(e,t){[this.list[e],this.list[t]]=[this.list[t],this.list[e]]}land(e){this.current=e,this.hooks.onChange();let t=this.list[e];t&&this.hooks.onHighlight(t,e)}select(e){e<0||e>=this.list.length||this.list[e].disabled||this.land(e)}confirm(e){let t=this.selected;return!t||t.disabled?!1:(e?.(t,this.current),!0)}step(e,t){if(this.list.length===0)return!1;let n=this.current;for(let r=0;r<t;r++){let t=e(n,this.list.length);if(n=t,!(t<0||t>=this.list.length)&&!this.list[t].disabled)return this.land(t),!0}return!1}},EL=class extends J{constructor(e){super(),this.selection=new TL({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.rows=[],this.rowsLayer=new J,this.highlight=new Z,this.mask_=new Z,this.scroll=0,this.themeListener=()=>this.restyle(),this.checked=new Set,this.ticks=[];let t=Q();this.viewWidth=e.width,this.viewHeight=e.height,this.explicitRowHeight=e.rowHeight!==void 0,this.rowHeight=e.rowHeight??Math.ceil(t.font.size*t.font.lineHeight)+t.spacing,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onToggle=e.onToggle??null,this.multiple=e.multiple??!1,this.addChild(this.highlight),this.addChild(this.rowsLayer),this.addChild(this.mask_),this.rowsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}restyle(){let e=Q();this.explicitRowHeight||(this.rowHeight=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing);let t=e.direction===`rtl`,n=this.selection.items;this.rows.forEach((r,i)=>{r.y=i*this.rowHeight;let a=n[i],o=r.children.find(e=>e instanceof EI);if(o){o.setColor(a.disabled?e.color.textDim:e.color.text);let n=e.spacing+this.checkAdvance()+(a.icon?this.rowHeight:0);o.x=t?this.viewWidth-n-o.width:n,o.y=Math.round((this.rowHeight-o.height)/2)}a.icon&&(a.icon.x=t?this.viewWidth-e.spacing-this.checkAdvance()-this.rowHeight:e.spacing+this.checkAdvance())}),this.updateTicks(),this.refresh()}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.rowHeight))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.rowsLayer.removeChildren();let t=Q(),n=t.direction===`rtl`;e.forEach((e,r)=>{let i=new J;i.y=r*this.rowHeight,i.eventMode=`static`,i.cursor=e.disabled?`default`:`pointer`,i.on(`pointerdown`,()=>this.tapRow(r)),e.icon&&(e.icon.x=n?this.viewWidth-t.spacing-this.checkAdvance()-this.rowHeight:t.spacing+this.checkAdvance(),i.addChild(e.icon));let a=new EI({text:e.text,color:e.disabled?t.color.textDim:t.color.text}),o=t.spacing+this.checkAdvance()+(e.icon?this.rowHeight:0);a.x=n?this.viewWidth-o-a.width:o,a.y=Math.round((this.rowHeight-a.height)/2),i.addChild(a),this.rows.push(i),this.rowsLayer.addChild(i)}),this.selection.reset(e),this.checked.clear(),this.rebuildTicks(),this.scroll=0,this.refresh()}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}move(e){return this.selection.step((t,n)=>(t+e+n)%n,this.selection.length)}select(e){this.selection.select(e)}confirm(){return this.multiple?this.toggleChecked(this.selection.selectedIndex):this.selection.confirm(this.onSelect)}tapRow(e){let t=this.selection.items;e<0||e>=t.length||t[e].disabled||(this.select(e),this.confirm())}handleAction(e){switch(e){case`up`:return this.move(-1);case`down`:return this.move(1);case`confirm`:return this.confirm();default:return!1}}get checkedIndexes(){return[...this.checked].sort((e,t)=>e-t)}isChecked(e){return this.checked.has(e)}setChecked(e,t){let n=this.selection.items[e];n&&!n.disabled&&this.checked.has(e)!==t&&(t?this.checked.add(e):this.checked.delete(e),this.updateTicks(),this.onToggle?.(n,e,t))}toggleChecked(e){let t=this.selection.items[e];return!t||t.disabled?!1:(this.setChecked(e,!this.checked.has(e)),!0)}clearChecked(){this.checked.size!==0&&(this.checked.clear(),this.updateTicks())}checkAdvance(){return this.multiple?this.checkBox()+Q().spacing:0}checkBox(){return Math.max(12,this.rowHeight-8)}rebuildTicks(){if(this.ticks=[],this.multiple){for(let e of this.rows){let t=new Z;e.addChildAt(t,0),this.ticks.push(t)}this.updateTicks()}}updateTicks(){let e=Q(),t=e.direction===`rtl`,n=this.checkBox(),r=Math.round((this.rowHeight-n)/2);this.ticks.forEach((i,a)=>{let o=this.selection.items[a]?.disabled??!0;if(i.clear().rect(0,0,n,n).fill({color:e.color.panelFill}).stroke({color:o?e.color.textDim:e.color.panelBorder,width:2}),this.checked.has(a)){let t=n*.25;i.moveTo(t,n*.55).lineTo(n*.45,n-t).lineTo(n-t,t).stroke({color:o?e.color.textDim:e.color.textHighlight,width:Math.max(2,n*.12),cap:`round`,join:`round`})}i.x=t?this.viewWidth-e.spacing-n:e.spacing,i.y=r})}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=this.selection.length;t<this.scroll?this.scroll=t:t>=this.scroll+e&&(this.scroll=t-e+1),this.scroll=Math.max(0,Math.min(this.scroll,Math.max(0,n-e))),this.rowsLayer.y=-this.scroll*this.rowHeight;let r=Q();n===0?this.highlight.clear():this.highlight.clear().rect(0,(t-this.scroll)*this.rowHeight,this.viewWidth,this.rowHeight).fill({color:r.color.selection})}},DL=class extends J{columnX(e){return(Q().direction===`rtl`?this.columns-1-e:e)*this.cellSize}constructor(e){super(),this.selection=new TL({onChange:()=>this.refresh(),onHighlight:(e,t)=>this.onHighlight?.(e,t)}),this.cells=[],this.cellsLayer=new J,this.highlight=new Z,this.pickupHighlight=new Z,this.mask_=new Z,this.scrollRow=0,this.pickedUp=null,this.pressedIndex=null,this.pressTimer=0,this.themeListener=()=>{let e=Q();this.selection.items.forEach((t,n)=>{let r=this.cells[n];r&&(r.x=this.columnX(n%this.columns),!((t.quantity??1)<=1)&&r.children.find(e=>e instanceof EI)?.setColor(e.color.textHighlight))}),this.refresh()},this.viewWidth=e.width,this.viewHeight=e.height,this.columns=Math.max(1,e.columns),this.cellSize=e.cellSize??Math.floor(this.viewWidth/this.columns),this.longPressDuration=e.longPressDuration??.6,this.onSelect=e.onSelect??null,this.onHighlight=e.onHighlight??null,this.onQuickslot=e.onQuickslot??null,this.onReorder=e.onReorder??null,this.addChild(this.highlight),this.addChild(this.pickupHighlight),this.addChild(this.cellsLayer),this.addChild(this.mask_),this.cellsLayer.mask=this.mask_,this.drawMask(),this.eventMode=`static`,this.on(`wheel`,e=>this.move(0,e.deltaY>0?1:-1)),this.setItems(e.items??[]),$.add(this.themeListener)}destroy(e){$.remove(this.themeListener),super.destroy(e)}drawMask(){this.mask_.clear().rect(0,0,this.viewWidth,this.viewHeight).fill({color:16777215})}get visibleRows(){return Math.max(1,Math.floor(this.viewHeight/this.cellSize))}get rows(){return Math.max(1,Math.ceil(this.selection.length/this.columns))}get selectedIndex(){return this.selection.selectedIndex}get selected(){return this.selection.selected}get length(){return this.selection.length}setItems(e){this.pickedUp=null,this.pressedIndex=null;for(let e of this.cells)e.destroy({children:!0});this.cells=[],this.cellsLayer.removeChildren();let t=Q();e.forEach((e,n)=>{let r=Math.floor(n/this.columns),i=n%this.columns,a=new J;if(a.x=this.columnX(i),a.y=r*this.cellSize,a.eventMode=`static`,a.cursor=e.disabled?`default`:`pointer`,e.icon.x=Math.round((this.cellSize-e.icon.width)/2),e.icon.y=Math.round((this.cellSize-e.icon.height)/2),e.disabled&&(e.icon.alpha=.4),a.addChild(e.icon),(e.quantity??1)>1){let n=new EI({text:String(e.quantity),size:10,color:t.color.textHighlight});n.x=this.cellSize-n.width-2,n.y=this.cellSize-n.height-1,a.addChild(n)}a.on(`pointerdown`,()=>{this.pressedIndex=n,this.pressTimer=0}),a.on(`pointerup`,()=>this.releaseCell(n)),a.on(`pointerupoutside`,()=>this.releaseCell(n)),this.cells.push(a),this.cellsLayer.addChild(a)}),this.selection.reset(e),this.scrollRow=0,this.refresh()}releaseCell(e){this.pressedIndex===e&&(this.pressedIndex=null,this.selection.items[e]?.disabled||this.tapCell(e))}resize(e,t){this.viewWidth=e,this.viewHeight=t,this.drawMask(),this.refresh()}update(e){if(this.pressedIndex===null||(this.pressTimer+=e,this.pressTimer<this.longPressDuration))return;let t=this.pressedIndex;this.pressedIndex=null;let n=this.selection.items[t];n&&!n.disabled&&this.onQuickslot?.(n,t)}tapCell(e){let t=this.selection.items;if(e<0||e>=t.length)return;if(this.pickedUp===null){if(t[e].disabled)return;this.pickedUp=e,this.refresh();return}let n=this.pickedUp;this.pickedUp=null,n!==e&&(this.swapCells(n,e),this.onReorder?.(n,e)),this.refresh()}swapCells(e,t){let n=this.selection.items;this.selection.swap(e,t);let r=this.cells[e],i=this.cells[t],a=r.removeChildren(),o=i.removeChildren();for(let e of o)r.addChild(e);for(let e of a)i.addChild(e);r.cursor=n[e].disabled?`default`:`pointer`,i.cursor=n[t].disabled?`default`:`pointer`}cancelPickup(){this.pickedUp=null,this.refresh()}move(e,t){let n=this.rows,r=this.columns;return this.selection.step(i=>{let a=(Math.floor(i/r)+t+n)%n,o=(i%r+e+r)%r;return a*r+o},n*r)}select(e){this.selection.select(e)}confirm(){return this.selection.confirm(this.onSelect)}handleAction(e){switch(e){case`up`:return this.move(0,-1);case`down`:return this.move(0,1);case`left`:return this.move(Q().direction===`rtl`?1:-1,0);case`right`:return this.move(Q().direction===`rtl`?-1:1,0);case`confirm`:return this.confirm();case`cancel`:return this.pickedUp!==null&&(this.cancelPickup(),!0);default:return!1}}cellRect(e){return{x:this.columnX(e%this.columns),y:Math.floor(e/this.columns)*this.cellSize}}refresh(){let e=this.visibleRows,t=this.selection.selectedIndex,n=Math.floor(t/this.columns);n<this.scrollRow?this.scrollRow=n:n>=this.scrollRow+e&&(this.scrollRow=n-e+1),this.scrollRow=Math.max(0,Math.min(this.scrollRow,Math.max(0,this.rows-e))),this.cellsLayer.y=-this.scrollRow*this.cellSize;let r=Q();if(this.pickupHighlight.clear(),this.pickedUp!==null){let{x:e,y:t}=this.cellRect(this.pickedUp);this.pickupHighlight.rect(e,t,this.cellSize,this.cellSize).stroke({color:r.color.textHighlight,width:2})}if(this.highlight.clear(),this.selection.length>0){let{x:e,y:n}=this.cellRect(t);this.highlight.rect(e,n,this.cellSize,this.cellSize).fill({color:r.color.selection})}}},OL=class{constructor(e){if(this.onChange=new p,this.currentTabIndex=0,this.currentQuery=``,this.rows_=[],this.currentSelectedIndex=0,this.detail=!1,e.tabs.length===0)throw Error(`TabbedList needs at least one tab`);this.tabList=[...e.tabs],this.rowsFor=e.rowsFor,this.pageSize=Math.max(0,Math.floor(e.pageSize??0)),this.labelOf=e.label??(e=>String(e)),this.filterOf=e.filter??((e,t)=>t===``||this.labelOf(e).toLowerCase().includes(t.toLowerCase())),this.disabledOf=e.disabled??(()=>!1),this.recompute()}get tabs(){return this.tabList}get tab(){return this.tabList[this.currentTabIndex]}get query(){return this.currentQuery}get rows(){return this.rows_}get pageCount(){return this.pageSize<=0?1:Math.max(1,Math.ceil(this.rows_.length/this.pageSize))}get page(){return this.pageSize<=0?0:Math.floor(this.currentSelectedIndex/this.pageSize)}get pageRows(){if(this.pageSize<=0)return this.rows_;let e=this.page*this.pageSize;return this.rows_.slice(e,e+this.pageSize)}get selectedIndex(){return this.currentSelectedIndex}get selected(){return this.rows_[this.currentSelectedIndex]??null}get detailOpen(){return this.detail}selectTab(e){let t=this.tabList.findIndex(t=>t.id===e);t===-1||this.tabList[t].disabled||t!==this.currentTabIndex&&(this.currentTabIndex=t,this.recompute(),this.emit())}nextTab(e=1){if(e===0)return;let t=e>0?1:-1,n=this.currentTabIndex;for(let r=0;r<Math.abs(e);r++)do n=(n+t+this.tabList.length)%this.tabList.length;while(this.tabList[n].disabled&&n!==this.currentTabIndex);n!==this.currentTabIndex&&(this.currentTabIndex=n,this.recompute(),this.emit())}setQuery(e){e!==this.currentQuery&&(this.currentQuery=e,this.recompute(),this.emit())}move(e){if(e===0||this.rows_.length===0)return;let t=e>0?1:-1,n=this.currentSelectedIndex;for(let r=0;r<Math.abs(e);r++){let e=n;do e+=t;while(e>=0&&e<this.rows_.length&&this.disabledOf(this.rows_[e]));if(e<0||e>=this.rows_.length)break;n=e}n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}setPage(e){let t=Math.max(0,Math.min(this.pageCount-1,Math.floor(e)));if(this.pageSize<=0)return;let n=this.firstSelectableOnPage(t);n!==this.currentSelectedIndex&&(this.currentSelectedIndex=n,this.emit())}nextPage(e){this.setPage(this.page+e)}openDetail(){return this.selected===null||this.disabledOf(this.selected)?!1:(this.detail||(this.detail=!0,this.emit()),!0)}closeDetail(){this.detail&&(this.detail=!1,this.emit())}firstSelectableOnPage(e){let t=e*this.pageSize,n=Math.min(this.rows_.length,t+this.pageSize);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e]))return e;return Math.min(t,Math.max(0,this.rows_.length-1))}firstSelectable(e){for(let t=e;t<this.rows_.length;t++)if(!this.disabledOf(this.rows_[t]))return t;return 0}recompute(){let e=this.rowsFor(this.tab.id).filter(e=>this.filterOf(e,this.currentQuery));this.rows_=e,this.currentSelectedIndex=e.length===0?0:this.firstSelectable(0),this.detail=!1}emit(){this.onChange.dispatch()}};function kL(e,t,n={}){let r={},i=t.replace(/\r/g,``).split(`
|
|
1372
|
-
`),a=null,o=``,s=[],c=!1,l=()=>{if(a){if(r[a]!==void 0)throw Error(`Duplicate FTL message: ${a}`);if(s.length){if(!c)throw Error(`FTL select expression is not closed: ${a}`);let t=o.trim().match(/^\{\s*\$([\w-]+)\s*->\s*$/)?.[1];if(!t)throw Error(`Invalid FTL selector: ${o}`);r[a]=jL(e,t,s)}else r[a]=AL(o);a=null,o=``,s=[],c=!1}};for(let e of i){if(!e.trim()||e.trimStart().startsWith(`#`))continue;let t=e.match(/^([\w-]+)\s*=\s*(.*)$/);if(t){l(),a=t[1],o=t[2];continue}if(!a)throw Error(`FTL continuation has no message: ${e}`);if(e.trim()===`}`){if(!s.length||c)throw Error(`Unexpected FTL select terminator: ${e}`);c=!0;continue}if(c)throw Error(`FTL content follows a closed select expression: ${e}`);let n=e.match(/^\s*(\*)?\[([^\]]+)\]\s*(.*)$/);if(n)s.push({key:n[2],value:n[3],default:!!n[1]});else if(/^\s+/.test(e))s.length?s[s.length-1].value+=` ${e.trim()}`:o+=` ${e.trim()}`;else throw Error(`Invalid FTL line: ${e}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:r}}function AL(e){return e.replace(/\{\s*\$([\w-]+)\s*(?:!([sra]))?\s*(?::\s*([^{}]*?))?\s*\}/g,(e,t,n,r)=>`{${t}${n?`!${n}`:``}${r===void 0?``:`:${r.trim()}`}}`).trim()}function jL(e,t,n){let r=n.filter(e=>e.default);if(r.length!==1)throw Error(`FTL select expressions need exactly one default variant`);let i=r[0],a=new Intl.PluralRules(e);return{format(e={}){let r=e[t],o=n.find(e=>e.key===String(r)),s=typeof r==`number`?a.select(r):``;return AL((o??n.find(e=>e.key===s)??i).value)}}}function ML(e,t,n={}){let r=n.domain??`messages`,i=r===`messages`?``:`${r}:`,a={},o=t.replace(/\r\n?/g,`
|
|
1373
|
-
`).split(`
|
|
1374
|
-
`),s=null,c=``,l=()=>{if(s){if(s.id===void 0){if(s.str!==void 0||s.plurals.size>0||s.context!==void 0)throw Error(`PO entry has a translation but no msgid`);s=null,c=``}else u(s),s=null,c=``}},u=t=>{let n=t.id;if(n===``||/(^|,)\s*fuzzy\s*(,|$)/.test(c))return;if(t.plural!==void 0&&t.plurals.size===0)throw Error(`PO message "${n}" has a plural but no msgstr[N] forms`);let r=i+(t.context?`${t.context}\u0004${n}`:n);if(a[r]!==void 0)throw Error(`Duplicate PO message: ${r}`);if(t.plurals.size>0){if([...t.plurals.values()].every(e=>e===``))return;let i=new Intl.PluralRules(e).resolvedOptions().pluralCategories,o={};for(let[r,a]of[...t.plurals].sort((e,t)=>e[0]-t[0])){let t=i[r];if(t===void 0)throw Error(`PO message "${n}" has plural form ${r}, but ${e} declares only ${i.length}`);o[t]=a}a[r]=o}else t.str!==void 0&&t.str!==``&&(a[r]=t.str)};for(let e=0;e<o.length;e++){let t=o[e],n=t.trim();if(n===``){l();continue}if(n.startsWith(`#,`)){c+=`${c===``?``:`,`}${n.slice(2).trim()}`;continue}if(n.startsWith(`#`))continue;let r=t.match(/^(msgctxt|msgid_plural|msgid|msgstr(?:\[(\d+)\])?)\s+(.*)$/);if(!r)throw Error(`Invalid PO line ${e+1}: ${t}`);let i=r[1],a=r[2]===void 0?void 0:Number(r[2]),u=NL(o,e,r[3]);if(e=u.next-1,s?(i===`msgctxt`||i===`msgid`)&&s.id!==void 0&&(l(),s={plurals:new Map}):s={plurals:new Map},i===`msgctxt`)s.context=u.text;else if(i===`msgid`)s.id=u.text;else if(i===`msgid_plural`)s.plural=u.text;else if(i===`msgstr`)s.str=u.text;else if(a!==void 0)s.plurals.set(a,u.text);else throw Error(`Invalid PO keyword on line ${e+1}: ${i}`)}return l(),{locale:e,direction:n.direction??(/^(ar|he|fa|ur)(?:-|$)/i.test(e)?`rtl`:`ltr`),messages:a}}function NL(e,t,n){if(!n.trim().startsWith(`"`))throw Error(`PO string must start with a quote on line ${t+1}: ${n}`);let r=PL(n.trim(),t),i=t+1;for(;i<e.length&&e[i].trim().startsWith(`"`);)r+=PL(e[i].trim(),i),i++;return{text:r,next:i}}function PL(e,t){let n=e.match(/^"((?:[^"\\]|\\.)*)"/);if(!n)throw Error(`Invalid PO string on line ${t+1}: ${e}`);return FL(n[1])}function FL(e){return e.replace(/\\(.)/g,(e,t)=>{switch(t){case`n`:return`
|
|
1375
|
-
`;case`t`:return` `;case`r`:return`\r`;case`"`:return`"`;case`\\`:return`\\`;case`a`:return`\x07`;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;default:return t}})}var IL=/\{sound:([^{}\r\n]+)\}/g;function LL(e){let t=[],n=``,r=0,i;for(IL.lastIndex=0;(i=IL.exec(e))!==null;){n+=e.slice(r,i.index);let a=i[1].trim();a===``?n+=i[0]:t.push({path:a,index:n.length}),r=i.index+i[0].length}return n+=e.slice(r),{text:n,cues:t}}function RL(e){return LL(e).text}function zL(){return{format(e,t){let n=e.params;if(t===`audio`){let t=`${e.type}.audio`;return ez(t)?HR(t,n):``}let r=`${e.type}.${t}`;return ez(r)?UR(r,n):UR(e.type,n)}}}function BL(e,t){return new Intl.NumberFormat(BR(),t).format(e)}function VL(e,t){return new Intl.DateTimeFormat(BR(),t).format(e)}function HL(e,t){return new Intl.ListFormat(BR(),t).format(e)}var UL=/\{(?!sound:)(\w+(?:\.\w+)*)(=)?(?:!([sra]))?(?::([^{}]*))?\}/g;function WL(e){let t=[];UL.lastIndex=0;let n=0,r;for(;(r=UL.exec(e))!==null;){r.index>n&&t.push(e.slice(n,r.index));let i=r[1],a=r[3],o=r[4];t.push({raw:r[0],token:i,debug:r[2]===`=`,conv:a,spec:o}),n=r.index+r[0].length}return n<e.length&&t.push(e.slice(n)),t}function GL(e){return`${e.debug?`=`:``}${e.conv?`!${e.conv}`:``}${e.spec===void 0?``:`:${e.spec}`}`}function KL(e,t){let n=new Map,r=new Map;for(let t of WL(e))typeof t!=`string`&&n.set(t.token,GL(t));for(let e of WL(t))typeof e!=`string`&&r.set(e.token,GL(e));return{missing:[...n.keys()].filter(e=>!r.has(e)),extra:[...r.keys()].filter(e=>!n.has(e)),changed:[...n].flatMap(([e,t])=>{let n=r.get(e);return n!==void 0&&n!==t?[{token:e,base:t,target:n}]:[]})}}var qL=/^(?:(.)?([<>=^]))?([+\- ])?(z)?(#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?$/,JL={b:2,o:8,x:16,X:16},YL={b:`0b`,o:`0o`,x:`0x`,X:`0X`},XL=new Set([`f`,`F`,`e`,`E`,`g`,`G`,`%`,`n`]);function ZL(e){return Number.isNaN(e)?`nan`:e===1/0?`inf`:e===-1/0?`-inf`:Object.is(e,-0)?`-0.0`:String(e)}function QL(e,t,n=3,r=`\\d`){return e.replace(RegExp(`\\B(?=(${r}{${n}})+(?!${r}))`,`g`),t)}function $L(e,t){let n=/^(\d+)/.exec(e);return n?QL(n[1],t)+e.slice(n[1].length):e}function eR(e,t,n,r){if(e.length>=t)return e;let i=n.repeat(t-e.length);return r===`<`?e+i:r===`^`?i.slice(0,Math.floor(i.length/2))+e+i.slice(Math.floor(i.length/2)):i+e}function tR(e){return e.replace(/([eE][+-])(\d)$/,`$10$2`)}function nR(e,t,n,r,i){let a=t===0?1:t;if(e===0)return r?`0.${`0`.repeat(a-1)}`:`0`;let o=Math.floor(Math.log10(e)),s;return o>=-4&&o<(i??a)?(s=e.toFixed(a-1-o),r||(s=s.replace(/(\.\d*?)0+$/,`$1`).replace(/\.$/,``))):(s=tR(e.toExponential(a-1)),r||(s=s.replace(/(\.\d*?)0+(e|$)/,`$1$2`).replace(/\.e/i,`e`))),n?s.toUpperCase():s}function rR(e){let t=`,`,n=`.`;for(let r of new Intl.NumberFormat(e).formatToParts(1000.5))r.type===`group`&&(t=r.value),r.type===`decimal`&&(n=r.value);return{group:t,decimal:n}}function iR(e,t,n,r,i,a){return eR(a===void 0?e:e.slice(0,a),i,t??(r?`0`:` `),n??`<`)}function aR(e,t,n=`en`){if(t===``)return typeof e==`number`?ZL(e):e;let r=qL.exec(t);if(!r)return;let[i,a,o,s,c,l,u,d,f,p]=r.slice(1),m=f===void 0?void 0:Number(f),h=u===void 0?0:Number(u);if(typeof e==`string`)return o||s||c||d||a===`=`||p!==void 0&&p!==`s`?void 0:iR(e,i,a,l,h,m);if(p===`s`)return;if(p===`c`){if(o||c||l||d||m!==void 0)return;let t=Math.trunc(e);return t<0||t>1114111?void 0:eR(String.fromCodePoint(t),h,i??` `,a??`>`)}if(!Number.isFinite(e)){if(p!==void 0&&!XL.has(p))return;let t=Number.isNaN(e)?`nan`:`inf`;return(p===`F`||p===`E`||p===`G`)&&(t=t.toUpperCase()),p===`%`&&(t+=`%`),eR((e<0?`-`:o===`+`?`+`:o===` `?` `:``)+t,h,i??` `,a??`>`)}let g=e<0||Object.is(e,-0);s&&e===0&&(g=!1);let _=Math.abs(e),v=d===`,`?`,`:d===`_`?`_`:``,y;if(p===void 0){if(m!==void 0){if(Number.isInteger(_))return;y=nR(_,m,!1,!!c,m-1)}else y=ZL(_);v&&(y=$L(y,v))}else if(p===`d`){if(m!==void 0||!Number.isInteger(_))return;y=String(Math.trunc(_)),v&&(y=QL(y,v))}else if(p in JL){if(m!==void 0||!Number.isInteger(_)||d===`,`)return;y=Math.trunc(_).toString(JL[p]),p===`X`&&(y=y.toUpperCase()),v&&(y=QL(y,v,4,`[0-9a-fA-F]`)),c&&(y=YL[p]+y)}else if(p===`n`){if(d||m!==void 0&&Number.isInteger(_))return;if(Number.isInteger(_))y=new Intl.NumberFormat(n).format(Math.trunc(_));else{let{group:e,decimal:t}=rR(n),r=nR(_,m??6,!1,!!c),i=r.split(`e`)[0],a=r.slice(i.length);y=$L(i,e).replace(`.`,t)+a}}else if(p===`f`||p===`F`)y=_.toFixed(m??6),v&&(y=$L(y,v));else if(p===`e`||p===`E`)y=tR(_.toExponential(m??6)),p===`E`&&(y=y.toUpperCase()),v&&(y=$L(y,v));else if(p===`g`||p===`G`)y=nR(_,m??6,p===`G`,!!c),v&&(y=$L(y,v));else{let e=_*100;y=(Number.isFinite(e)?e.toFixed(m??6):`inf`)+`%`,v&&Number.isFinite(e)&&(y=$L(y,v))}let b=g?`-`:o===`+`?`+`:o===` `?` `:``,x=i??(l&&!a?`0`:` `),S=a??(l&&!a?`=`:`>`);return S===`=`?b+eR(y,h-b.length,x,`>`):eR(b+y,h,x,S)}function oR(e,t){let n=new Set(Object.keys(e.messages)),r=new Set(Object.keys(t.messages));return{missing:[...n].filter(e=>!r.has(e)),extra:[...r].filter(e=>!n.has(e))}}function sR(e){let t=[];for(let[n,r]of Object.entries(e.messages))typeof r==`string`?r===``&&t.push({key:n,kind:`empty-message`,detail:`message resolves to an empty string`}):cR(r)&&r.other===void 0&&t.push({key:n,kind:`plural-missing-other`,detail:`plural forms have no "other" branch`});return t}function cR(e){return typeof e==`object`&&!!e&&!(`format`in e)}function lR(e){let t=[];for(let[n,r]of Object.entries(e.messages))n.endsWith(`.audio`)&&(typeof r==`string`?r===``&&t.push({key:n,kind:`empty-audio-path`,detail:`an empty audio entry already means "no sound"; remove the key instead`}):t.push({key:n,kind:`audio-not-a-path`,detail:`an audio entry must be a plain path string, not plural forms or a select message`}));return t}function uR(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`format`in e)try{return e.format()}catch{return``}let t=e;return t.other??Object.values(t)[0]??``}function dR(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(e,t)=>t),r=Array(t.length+1);for(let i=1;i<=e.length;i++){r[0]=i;for(let a=1;a<=t.length;a++){let o=e[i-1]===t[a-1]?0:1;r[a]=Math.min(n[a]+1,r[a-1]+1,n[a-1]+o)}[n,r]=[r,n]}return n[t.length]}function fR(e,t=.8){let n=Object.entries(e.messages).map(([e,t])=>[e,uR(t)]).filter(([,e])=>e.length>0),r=[];for(let e=0;e<n.length;e++)for(let i=e+1;i<n.length;i++){let[a,o]=n[e],[s,c]=n[i],l=Math.max(o.length,c.length),u=dR(o,c),d=l===0?1:1-u/l;d>=t&&r.push({a,b:s,distance:u,similarity:d})}return r.sort((e,t)=>t.similarity-e.similarity)}function pR(e,t){let n=new Set(t),r=Object.keys(e.messages),i=r.filter(e=>!n.has(e));return{totalKeys:r.length,usedKeys:r.length-i.length,unusedKeys:i}}function mR(e,t){let n=Object.keys(e.messages);if(n.length===0)return 1;let{missing:r}=oR(e,t);return(n.length-r.length)/n.length}function hR(e){let t={},n=0;for(let r of Object.values(e.messages))if(!(typeof r==`string`||typeof r==`object`&&r&&`format`in r)){n++;for(let e of Object.keys(r))t[e]=(t[e]??0)+1}return{pluralKeys:n,formsPresent:t}}function gR(e,t,n){if(!(t in e.messages))throw Error(`mergeCatalogKeys: "${t}" is not a key in this catalog`);if(!(n in e.messages))throw Error(`mergeCatalogKeys: "${n}" is not a key in this catalog`);if(t===n)throw Error(`mergeCatalogKeys: survivingKey and mergedKey must be different keys`);let r={...e.messages};return delete r[n],{...e,messages:r}}function _R(e,t){return{base:e,target:t}}var vR=`.audio`;function yR(e){return e.endsWith(vR)}function bR(e){return[...new Set([...Object.keys(e.base.messages),...Object.keys(e.target.messages)])].filter(e=>!yR(e)).sort()}function xR(e){if(e===void 0)return;let t=uR(e);return t===``?void 0:t}var SR=[`log`,`compact`,`accessibility`,`debug`];function CR(e){let t=e.lastIndexOf(`.`);if(!(t<=0||!SR.includes(e.slice(t+1))))return`${e.slice(0,t)}${vR}`}function wR(e,t){let n=e.base.messages[t],r=e.target.messages[t],i=n!==void 0&&r!==void 0?`ok`:n===void 0?`extra`:`missing`,a=[`${t}${vR}`],o=CR(t);o&&a.push(o);let s,c,l=!1;for(let t of a){let n=xR(e.target.messages[t]);if(n!==void 0){s=n,c=t;break}let r=xR(e.base.messages[t]);if(r!==void 0){s=r,c=t,l=!0;break}}return{key:t,baseText:n===void 0?``:uR(n),targetText:r===void 0?``:uR(r),status:i,sound:s,soundKey:c,soundInherited:l}}function TR(e,t){let n=`${t}${vR}`;return n in e.target.messages||n in e.base.messages?n:CR(t)??n}function ER(e,t={}){let n=t.query?.toLowerCase()??``;return bR(e).map(t=>wR(e,t)).filter(e=>!t.missingOnly||e.status===`missing`).filter(e=>n===``||e.key.toLowerCase().includes(n)||e.baseText.toLowerCase().includes(n)||e.targetText.toLowerCase().includes(n))}function DR(e,t,n){let r=e.target.messages[t]??e.base.messages[t],i=n;if(r!==void 0&&typeof r==`object`&&!(`format`in r))try{let e=JSON.parse(n);typeof e==`object`&&e&&!Array.isArray(e)&&(i=e)}catch{}return{...e,target:{...e.target,messages:{...e.target.messages,[t]:i}}}}function OR(e,t){let n=e.base.messages[t];if(n===void 0)throw Error(`copyFromBase: "${t}" is not a key in the base catalog`);return{...e,target:{...e.target,messages:{...e.target.messages,[t]:n}}}}function kR(e,t){if(!(t in e.target.messages))throw Error(`deleteTargetKey: "${t}" is not a key in the target catalog`);let n={...e.target.messages};return delete n[t],{...e,target:{...e.target,messages:n}}}function AR(e,t,n){let r={...e.target.messages},i=TR(e,t);return n===``?delete r[i]:r[i]=n,{...e,target:{...e.target,messages:r}}}function jR(e){let t=e=>({...e,messages:Object.fromEntries(Object.entries(e.messages).filter(([e])=>!yR(e)))});return mR(t(e.base),t(e.target))}function MR(e){return{base:e.target,target:e.base}}var NR=l({AUDIO_SUFFIX:()=>vR,catalogCompleteness:()=>mR,catalogUsage:()=>pR,copyFromBase:()=>OR,createCatalogFormatter:()=>zL,createEditSession:()=>_R,cueKeyFor:()=>TR,deleteTargetKey:()=>kR,diffCatalogKeys:()=>oR,diffPlaceholders:()=>KL,direction:()=>VR,findSimilarMessages:()=>fR,formatDate:()=>VL,formatList:()=>HL,formatNumber:()=>BL,formatSpec:()=>aR,has:()=>ez,isAudioKey:()=>yR,levenshteinDistance:()=>dR,locale:()=>BR,mergeCatalogKeys:()=>gR,messageText:()=>uR,nonBreakingUnit:()=>XR,parseFTL:()=>kL,parsePo:()=>ML,parseSoundMarkers:()=>LL,pluralFormCoverage:()=>hR,reset:()=>cz,sessionCompleteness:()=>jR,sessionKeys:()=>bR,sessionRow:()=>wR,sessionRows:()=>ER,setActive:()=>zR,setBase:()=>RR,setTargetSound:()=>AR,setTargetText:()=>DR,stripSoundMarkers:()=>RL,swapSession:()=>MR,t:()=>UR,tRaw:()=>HR,tokenizeMessage:()=>WL,typographic:()=>YR,validateCatalog:()=>sR,validateMessageAudio:()=>lR}),PR=null,FR=null,IR=null,LR=null;function RR(e){PR=e}function zR(e){FR=e,IR=e?new Intl.PluralRules(e.locale):null}function BR(){return(FR??PR)?.locale??`en`}function VR(){return(FR??PR)?.direction??`ltr`}function HR(e,t){let n=FR?.messages[e]??PR?.messages[e];if(n===void 0)return e;let r=typeof n==`string`?n:nz(n)?n.format(t):tz(n,t?.count);return t?rz(r,t):r}function UR(e,t){if(!ez(e))return e;let n=HR(e,t),r=(FR??PR)?.typography===!1?n:YR(n,BR());return VR()===`rtl`?`${r}`:r}var WR=` `,GR=`\xA0`,KR=[`Chapitre`,`Tome`,`Livre`,`Partie`,`Section`,`Article`,`Acte`,`Scène`,`Niveau`,`Manche`,`Round`,`Étape`,`Volume`,`Figure`,`Page`,`Numéro`],qR=[`Nr`,`Dr`,`Bd`,`Kap`,`Art`,`Abb`,`Str`,`Tel`],JR=[`kg`,`g`,`mg`,`t`,`km`,`m`,`cm`,`mm`,`l`,`ml`,`h`,`min`,`s`,`%`,`°C`,`€`];function YR(e,t=BR()){let n=t.split(`-`)[0].toLowerCase(),r=e;return(n===`fr`||n===`it`||n===`nl`)&&(r=r.replace(/([\p{L}])'(?=[\p{L}])/gu,`$1’`)),n===`fr`&&(r=ZR(r)),n===`de`&&(r=QR(r)),r}function XR(e,t,n=BR()){let r=n.split(`-`)[0].toLowerCase();return`${e}${r===`fr`?WR:r===`de`?GR:` `}${t}`}function ZR(e){let t=e.replace(/\s?([;!?])/g,`${WR}$1`).replace(/«\s?/g,`«${WR}`).replace(/\s?»/g,`${WR}»`);t=t.replace(/(?<!\{soun)(\p{L})\s?:/gu,`$1${WR}:`);let n=RegExp(`\\b(${KR.join(`|`)})\\s+(?=\\d)`,`g`);return t.replace(n,`$1${GR}`)}function QR(e){let t=RegExp(`(\\d)\\s+(?=(?:${JR.map($R).join(`|`)})(?![\\p{L}\\p{N}]))`,`gu`),n=RegExp(`\\b(${qR.join(`|`)})\\.\\s+`,`g`);return e.replace(t,`$1${GR}`).replace(n,`$1.${GR}`)}function $R(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function ez(e){return FR?.messages[e]!==void 0||PR?.messages[e]!==void 0}function tz(e,t){return t===void 0?e.other??Object.values(e)[0]??``:e[(IR??(LR??=new Intl.PluralRules(`en`))).select(t)]??e.other??``}function nz(e){return`format`in e}function rz(e,t){return WL(e).map(e=>typeof e==`string`?e:az(e,t)).join(``)}function iz(e,t){let n=e[t];if(typeof n==`string`||typeof n==`number`)return n;let r=e;for(let e of t.split(`.`)){if(typeof r!=`object`)return;r=r[e]}return typeof r==`string`||typeof r==`number`?r:void 0}function az(e,t){let n=iz(t,e.token);if(n===void 0)return e.raw;try{let t=e.conv===void 0?n:oz(n,e.conv),r=e.spec===void 0?String(t):aR(t,e.spec,BR());return r===void 0?e.raw:e.debug?`${e.token}=${r}`:r}catch{return e.raw}}function oz(e,t){if(t===`s`)return String(e);if(typeof e==`number`){let n=aR(e,``,`en`)??String(e);return t===`a`?sz(n):n}let n=`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}'`;return t===`a`?sz(n):n}function sz(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;t+=e>127?e>65535?`\\U${e.toString(16).padStart(8,`0`)}`:`\\u${e.toString(16).padStart(4,`0`)}`:n}return t}function cz(){PR=null,FR=null,IR=null}var lz=class extends CL{constructor(e){super({width:e.width,height:e.height,modal:!0,closable:!1,dims:e.dims,blocker:e.blocker??!0,anchor:e.anchor??`bottom`}),this.pageIndex=0,this.reveal=SI(0),this.pageText=``,this.pageCues=[],this.nextCue=0,this.portrait=null,this.portraitLayer=new J,this.choiceList=null,this.finished=!1,this.autoAdvanceElapsed=0,this.messageThemeListener=()=>this.restyleMessage(),this.pages=e.pages.map(e=>typeof e==`string`?{text:e}:e),this.speed=e.speed??40,this.mode=e.mode??`adv`,this.autoAdvance=e.autoAdvance,this.choices=e.choices??[],this.onDone=e.onDone??null,this.onSound=e.onSound??null,this.announce=e.announce??!0;let t=Q();this.content.addChild(this.portraitLayer),this.speakerLabel=new EI({color:t.color.textHighlight,bold:!0}),this.content.addChild(this.speakerLabel),this.body=new EI({wrapWidth:this.contentWidth}),this.content.addChild(this.body),this.prompt=new EI({text:`▼`,color:t.color.textDim}),this.prompt.visible=!1,this.content.addChild(this.prompt),this.showPage(0),$.add(this.messageThemeListener)}restyleMessage(){let e=Q();this.speakerLabel.setColor(e.color.textHighlight),this.prompt.setColor(e.color.textDim)}destroy(e){$.remove(this.messageThemeListener),super.destroy(e)}showPage(e){let t=this.pages[e],n=Q(),r=n.direction===`rtl`;this.portraitLayer.removeChildren(),this.portrait=null;let i=0,a=this.contentWidth;t.portrait&&(this.portrait=new wl(t.portrait),r&&(this.portrait.x=this.contentWidth-this.portrait.width),this.portraitLayer.addChild(this.portrait),a=this.contentWidth-this.portrait.width-n.padding,i=r?0:this.portrait.width+n.padding),this.speakerLabel.visible=this.mode===`adv`&&t.speaker!==void 0,this.speakerLabel.x=i,this.speakerLabel.setText(t.speaker??``),this.body.x=i,this.body.y=this.mode===`adv`&&t.speaker!==void 0?this.speakerLabel.height+n.spacing:0,this.body.style.wordWrapWidth=Math.max(16,a);let o=LL(t.text);this.pageText=o.text,this.pageCues=o.cues,this.nextCue=0,this.announce&&SL.announce(t.speaker===void 0?this.pageText:`${t.speaker}: ${this.pageText}`),this.reveal=SI(this.pageText.length,this.speed),this.autoAdvanceElapsed=0,this.playRevealedSounds(),this.renderBody(),this.prompt.visible=!1,this.prompt.x=r?0:this.contentWidth-this.prompt.width,this.prompt.y=this.contentHeight-this.prompt.height}renderBody(){if(this.mode===`adv`){this.body.setText(this.pageText.slice(0,Math.floor(this.reveal.revealed)));return}let e=this.pages.slice(0,this.pageIndex).map(e=>this.formatLine(e,LL(e.text).text)),t=this.pages[this.pageIndex];e.push(this.formatLine(t,this.pageText.slice(0,Math.floor(this.reveal.revealed)))),this.body.setText(e.join(`
|
|
1376
|
-
|
|
1377
|
-
`))}formatLine(e,t){return e.speaker===void 0?t:`${e.speaker}: ${t}`}playRevealedSounds(){let e=Math.floor(this.reveal.revealed);for(;this.nextCue<this.pageCues.length&&this.pageCues[this.nextCue].index<=e;)this.onSound?.(this.pageCues[this.nextCue].path),this.nextCue++}get pageComplete(){return TI(this.reveal)}update(e){this.finished||(this.pageComplete?(this.prompt.visible=!this.choiceList,!(this.autoAdvance===void 0||this.choiceList)&&(this.autoAdvanceElapsed+=e,this.autoAdvanceElapsed>=this.autoAdvance&&(this.autoAdvanceElapsed=0,this.advance()))):(CI(this.reveal,e),this.playRevealedSounds(),this.renderBody()))}handleAction(e){return this.delegate?super.handleAction(e):e===`confirm`?this.pageComplete?(this.advance(),!0):(wI(this.reveal),this.playRevealedSounds(),this.renderBody(),!0):!1}advance(){this.pageIndex<this.pages.length-1?(this.pageIndex++,this.showPage(this.pageIndex)):this.choices.length>0?this.showChoices():this.finish(void 0)}showChoices(){let e=Q(),t=this.choices.map(e=>({text:e.text,disabled:e.disabled,value:e.value??e.text}));this.announce&&SL.announce(this.choices.map(e=>e.text).join(`, `));let n=Math.ceil(e.font.size*e.font.lineHeight)+e.spacing,r=t.length*n,i=this.body.y+this.body.height+e.padding,a=i+r-this.contentHeight;a>0&&this.grow(a),this.choiceList=new EL({width:this.contentWidth,height:r,items:t,onSelect:e=>this.finish(e.value)}),this.choiceList.y=i,this.content.addChild(this.choiceList),this.delegate=this.choiceList,this.prompt.visible=!1}grow(e){let t=this.getLocalBounds();this.resize(t.width,t.height+e),this.y=Math.max(0,this.y-e)}finish(e){this.finished||(this.finished=!0,this.onDone?.(e),this.close())}},uz=class{constructor(e={}){this.goalColumn=null,this.multiline=e.multiline??!1,this.text=this.limit(this.shape(e.value??``)),this.maxLength=e.maxLength,this.mask=e.mask??!1,this.maskCharacter=e.maskCharacter??`•`,this.caretIndex=this.text.length,this.anchor=this.caretIndex}get value(){return this.text}get maskedValue(){return this.mask?this.text.split(``).map(e=>e===`
|
|
1378
|
-
`?`
|
|
1379
|
-
`:this.maskCharacter).join(``):this.text}get length(){return this.text.length}get caret(){return this.caretIndex}get selectionStart(){return Math.min(this.caretIndex,this.anchor)}get selectionEnd(){return Math.max(this.caretIndex,this.anchor)}get hasSelection(){return this.caretIndex!==this.anchor}get selectedText(){return this.text.slice(this.selectionStart,this.selectionEnd)}setValue(e){this.text=this.limit(this.shape(e)),this.caretIndex=this.text.length,this.anchor=this.caretIndex,this.goalColumn=null}setCaret(e,t=!1){this.caretIndex=Math.max(0,Math.min(this.text.length,e)),this.goalColumn=null,t||(this.anchor=this.caretIndex)}insert(e){e.length!==0&&this.replaceSelection(e)}backspace(){this.hasSelection?this.replaceSelection(``):this.caretIndex!==0&&(this.text=this.text.slice(0,this.caretIndex-1)+this.text.slice(this.caretIndex),this.setCaret(this.caretIndex-1))}deleteForward(){this.hasSelection?this.replaceSelection(``):this.caretIndex>=this.text.length||(this.text=this.text.slice(0,this.caretIndex)+this.text.slice(this.caretIndex+1),this.setCaret(this.caretIndex))}moveCaret(e,t=!1){this.setCaret(this.caretIndex+e,t)}moveToStart(e=!1){this.setCaret(0,e)}moveToEnd(e=!1){this.setCaret(this.text.length,e)}selectAll(){this.anchor=0,this.caretIndex=this.text.length,this.goalColumn=null}clearSelection(){this.anchor=this.caretIndex}replaceSelection(e){let t=this.selectionStart,n=this.selectionEnd,r=this.text.slice(0,t)+this.text.slice(n),i=this.shape(e),a=this.maxLength!==void 0&&r.length+i.length>this.maxLength?i.slice(0,Math.max(0,this.maxLength-r.length)):i;this.text=this.text.slice(0,t)+a+this.text.slice(n),this.setCaret(t+a.length)}shape(e){return e.replace(/\r\n|\r|\n/g,this.multiline?`
|
|
1380
|
-
`:``)}get lineCount(){return this.multiline?this.text.split(`
|
|
1381
|
-
`).length:1}get caretLine(){return this.text.slice(0,this.caretIndex).split(`
|
|
1382
|
-
`).length-1}lineRange(e){let t=Math.max(0,Math.min(this.lineCount-1,e)),n=0;for(let e=0;e<t;e++)n=this.text.indexOf(`
|
|
1383
|
-
`,n)+1;let r=this.text.indexOf(`
|
|
1384
|
-
`,n);return[n,r===-1?this.text.length:r]}moveCaretLine(e,t=!1){let[n]=this.lineRange(this.caretLine),r=this.goalColumn??this.caretIndex-n,[i,a]=this.lineRange(this.caretLine+e);this.setCaret(i+Math.min(r,a-i),t),this.goalColumn=r}limit(e){return this.maxLength!==void 0&&e.length>this.maxLength?e.slice(0,this.maxLength):e}},dz=class e extends J{constructor(t){super(),this.onClick=new p,this.onPress=new p,this.onRelease=new p,this.state=`idle`,this.selected_=!1,this.themeListener=()=>this.draw(),this.width_=t.width,this.height_=t.height,this.disabled_=t.disabled??!1,this.colors={...t.colors},this.skin=t.skin,this.labelOptions=t.label??{};let n=Q();this.background=e.createBackground(this.skin,n),this.addChild(this.background),this.icon=t.icon??null,this.iconPlain=this.icon,this.iconSelected=t.iconSelected??null,this.tooltip_=t.tooltip,this.icon&&this.addChild(this.icon),this.labelText=t.text===void 0?null:new EI({align:`center`,...this.labelOptions,text:t.text}),this.labelText&&this.addChild(this.labelText),t.onClick&&this.onClick.add(t.onClick),t.onPress&&this.onPress.add(t.onPress),t.onRelease&&this.onRelease.add(t.onRelease),this.eventMode=`static`,this.on(`pointerover`,()=>this.setState(`hover`)),this.on(`pointerout`,()=>this.setState(`idle`)),this.on(`pointerdown`,()=>{this.setState(`pressed`),this.onPress.dispatch()}),this.on(`pointerup`,()=>{let e=this.state===`pressed`;this.setState(`hover`),e&&(this.onRelease.dispatch(),this.onClick.dispatch())}),this.on(`pointerupoutside`,()=>{let e=this.state===`pressed`;this.setState(`idle`),e&&this.onRelease.dispatch()}),this.setState(this.disabled_?`disabled`:`idle`),$.add(this.themeListener)}static createBackground(e,t){return e?new yL(e.texture,{border:e.border}):t.panel?new yL(t.panel,{border:t.panelBorder}):new Z}resize(e,t){this.width_=e,this.height_=t,this.draw()}setText(e){e===void 0?(this.labelText?.destroy(),this.labelText=null):this.labelText?this.labelText.setText(e):(this.labelText=new EI({align:`center`,...this.labelOptions,text:e}),this.addChild(this.labelText)),this.layoutContent()}setIcon(e){this.iconPlain=e,this.showIcon(this.selected_&&this.iconSelected?this.iconSelected:e)}setSelectedIcon(e){this.iconSelected=e,this.showIcon(this.selected_&&e?e:this.iconPlain)}showIcon(e){e!==this.icon&&(this.icon&&this.removeChild(this.icon),this.icon=e,e&&this.addChild(e),this.draw())}get tooltip(){return typeof this.tooltip_==`function`?this.tooltip_():this.tooltip_}setTooltip(e){this.tooltip_=e}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.setState(e?`disabled`:`idle`)}get selected(){return this.selected_}setSelected(e){this.selected_!==e&&(this.selected_=e,this.iconSelected&&this.showIcon(e?this.iconSelected:this.iconPlain),this.draw())}setColors(e){this.colors={...e},this.draw()}setState(e){this.disabled_&&e!==`disabled`||(this.state=e,this.cursor=this.disabled_?`default`:`pointer`,this.eventMode=this.disabled_?`none`:`static`,this.draw())}layoutContent(){let e=Q().direction===`rtl`;if(this.icon&&!this.labelText)this.icon.x=Math.round((this.width_-this.icon.width)/2),this.icon.y=Math.round((this.height_-this.icon.height)/2);else if(this.icon&&this.labelText){let t=Q().spacing,n=this.icon.width+t+this.labelText.width,r=Math.round((this.width_-n)/2);this.icon.x=e?r+this.labelText.width+t:r,this.icon.y=Math.round((this.height_-this.icon.height)/2),this.labelText.x=e?r:r+this.icon.width+t,this.labelText.y=Math.round((this.height_-this.labelText.height)/2)}else this.labelText&&(this.labelText.x=Math.round((this.width_-this.labelText.width)/2),this.labelText.y=Math.round((this.height_-this.labelText.height)/2))}draw(){let e=Q(),t=this.state===`pressed`?10066329:this.state===`hover`?14540253:this.state===`disabled`?7829367:16777215;if(this.background instanceof yL)this.background.resize(this.width_,this.height_),this.background.tint=this.selected_?this.colors.selection??e.color.selection:this.colors.background??this.skin?.tints?.[this.state]??t;else{let t=this.state===`pressed`||this.selected_?this.colors.selection??e.color.selection:this.colors.background??e.color.panelFill;this.background.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:t,alpha:this.state===`disabled`?.5:1}).stroke({color:this.colors.border??e.color.panelBorder,width:1})}this.labelText?.setColor(this.disabled_?this.colors.disabledText??e.color.textDim:this.colors.text??this.labelOptions.color??e.color.text),this.icon&&(this.icon.alpha=this.disabled_?.4:1),this.layoutContent()}destroy(e){$.remove(this.themeListener),super.destroy(e)}},fz=e=>e.split(``).map(e=>({label:e})),pz={rows:[fz(`QWERTYUIOP`),fz(`ASDFGHJKL`),fz(`ZXCVBNM`),fz(`1234567890`),[{label:`Bksp`,action:`backspace`},{label:`Left`,action:`left`},{label:`Right`,action:`right`},{label:`Space`,text:` `,span:3},{label:`OK`,action:`confirm`},{label:`Esc`,action:`cancel`}]]};function mz(e){e.action===void 0?we(e.text??e.label):Te(e.action)}function hz(e,t){let n=[],r=0;for(let i of e.rows){let e=i.reduce((e,t)=>e+(t.span??1),0),a=(t.width-t.gap*(e-1))/e,o=0;for(let e of i){let i=e.span??1,s=a*i+t.gap*(i-1);n.push({key:e,x:o,y:r,width:s,height:t.keyHeight}),o+=s+t.gap}r+=t.keyHeight+t.gap}return n}var gz=class extends J{constructor(e,t){super();let n=Q().spacing,r=Math.max(Q().font.size*2,18),i=0;for(let a of hz(e,{width:t.width,keyHeight:r,gap:n})){let e=new dz({width:a.width,height:a.height,text:a.key.label,onClick:()=>mz(a.key)});e.position.set(a.x,a.y),this.addChild(e),i=Math.max(i,a.y+a.height)}this.laidOutHeight=i}get contentHeight(){return this.laidOutHeight}},_z=.5,vz=class extends CL{constructor(e){super({width:e.width,height:e.height,title:e.title,modal:!0,closable:!1,dims:e.dims,blocker:e.blocker??!0,anchor:e.anchor??`center`}),this.preview=``,this.promptError=null,this.keyboard=null,this.messageLabel=null,this.caretBar=new Z,this.measurer=new EI,this.canMeasureCaret=typeof document<`u`,this.blinkOn=!0,this.blinkElapsed=0,this.promptThemeListener=()=>this.restylePrompt(),this.textListener=e=>!this.closed&&(this.edit(()=>this.model.insert(e)),!0),this.compositionListener=e=>!this.closed&&(e.phase===`end`?this.edit(()=>{this.preview=``,this.model.insert(e.text)}):(this.preview=e.phase===`start`?``:e.text,this.render()),!0),this.model=new uz({value:e.initialValue??``,maxLength:e.maxLength}),this.validate=e.validate,this.onConfirm=e.onConfirm,this.onCancel=e.onCancel,this.announce=e.announce??!0,this.announcer=e.announcer??SL;let t=Q();this.lineHeight=t.font.size*t.font.lineHeight;let n=t.spacing;e.message!==void 0&&(this.messageLabel=new EI({text:e.message}),this.content.addChild(this.messageLabel)),this.valueY=this.messageLabel?this.lineHeight+n:0,this.valueLabel=new EI,this.valueLabel.y=this.valueY,this.content.addChild(this.valueLabel),this.previewLabel=new EI({color:t.color.textDim}),this.previewLabel.y=this.valueY+this.lineHeight+n,this.content.addChild(this.previewLabel),this.errorLabel=new EI({color:t.color.textHighlight}),this.errorLabel.y=this.previewLabel.y+this.lineHeight+n,this.content.addChild(this.errorLabel),this.content.addChild(this.caretBar),e.keyboard&&(this.keyboard=new gz(e.keyboard,{width:this.contentWidth}),this.keyboard.y=this.errorLabel.y+this.lineHeight+n,this.content.addChild(this.keyboard),this.resize(e.width,e.height+this.keyboard.contentHeight+n)),Se.add(this.textListener),F.add(this.compositionListener),$.add(this.promptThemeListener),this.render(),this.announce&&e.message!==void 0&&this.announcer.announce(e.message)}get value(){return this.model.value}get caretIndex(){return this.model.caret}get error(){return this.promptError}handleAction(e){if(this.delegate)return super.handleAction(e);if(this.closed)return!1;switch(e){case`left`:return this.model.moveCaret(-1),this.render(),!0;case`right`:return this.model.moveCaret(1),this.render(),!0;case`backspace`:return this.edit(()=>this.model.backspace()),!0;case`delete`:return this.edit(()=>this.model.deleteForward()),!0;case`confirm`:return this.confirm(),!0;case`cancel`:return this.onCancel?.(),this.close(),!0;default:return!1}}update(e){this.blinkElapsed+=e,!(this.blinkElapsed<_z)&&(this.blinkElapsed=0,this.blinkOn=!this.blinkOn,this.caretBar.visible=this.blinkOn&&this.canMeasureCaret)}destroy(e){Se.remove(this.textListener),F.remove(this.compositionListener),$.remove(this.promptThemeListener),this.measurer.destroy(),super.destroy(e)}edit(e){let t=this.model.value;e(),this.model.value!==t&&(this.promptError=null),this.render()}confirm(){let e=this.validate?.(this.model.value)??null;e?(this.promptError=e,this.render(),this.announce&&this.announcer.announce(e,{assertive:!0})):(this.onConfirm(this.model.value),this.close())}restylePrompt(){let e=Q();this.previewLabel.setColor(e.color.textDim),this.errorLabel.setColor(e.color.textHighlight),this.render()}render(){this.valueLabel.setText(this.model.value),this.measurer.setText(this.model.value.slice(0,this.model.caret));let e=0;if(this.canMeasureCaret)try{e=this.measurer.width}catch{this.canMeasureCaret=!1}this.caretBar.clear().rect(this.valueLabel.x+e,this.valueY,2,this.lineHeight).fill({color:Q().color.text}),this.caretBar.visible=this.blinkOn&&this.canMeasureCaret,this.previewLabel.setText(this.preview),this.previewLabel.visible=this.preview.length>0,this.errorLabel.setText(this.promptError??``),this.errorLabel.visible=this.promptError!==null}},yz=/[A-Za-z0-9]/;function bz(e,t){let{lineHeight:n,columnHeight:r}=t,i=t.rotate??yz,a=[],o=0,s=0;for(let t of e){if(t===`
|
|
1385
|
-
`){o++,s=0;continue}s*n>=r&&(o++,s=0);let e=i.test(t),c=o===0?0:-o*n;a.push({char:t,x:e?c-n/2:c,y:e?s*n+n/2:s*n,rotate:e}),s++}return a}var xz=class extends J{constructor(e){super(),this.themeListener=e=>this.build(e),this.opts=e,this.build(Q()),$.add(this.themeListener)}build(e){this.removeChildren().forEach(e=>e.destroy());let t=this.opts.size??e.font.size,n=Math.ceil(t*e.font.lineHeight),r=bz(this.opts.text,{lineHeight:n,columnHeight:this.opts.columnHeight,rotate:this.opts.rotate});for(let n of r){let r=new jA({text:n.char,style:{fontFamily:e.font.family,fontSize:t,fill:this.opts.color??e.color.text}});n.rotate&&(r.anchor.set(.5),r.rotation=Math.PI/2),r.x=n.x,r.y=n.y,this.addChild(r)}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function Sz(e,t=0,n=1){return n>t?Math.max(0,Math.min(1,(e-t)/(n-t))):0}function Cz(e,t=0,n=1,r=0){let i=t+Math.max(0,Math.min(1,e))*(n-t);if(!(r>0))return i;let a=(String(r).split(`.`)[1]??``).length,o=t+Math.round((i-t)/r)*r;return Number(Math.max(t,Math.min(n,o)).toFixed(a))}var wz=class extends J{constructor(e){super(),this.onChange=new p,this.track=new Z,this.fill=new Z,this.knob=new Z,this.dragging=!1,this.themeListener=()=>this.draw(),this.handleDown=e=>{this.disabled_||(this.dragging=!0,this.setFraction(this.fractionAt(this.toLocal(e.global).x)))},this.handleMove=e=>{this.dragging&&!this.disabled_&&this.setFraction(this.fractionAt(this.toLocal(e.global).x))},this.handleUp=()=>{this.dragging=!1},this.width_=e.width,this.height_=e.height??6,this.knobSize=e.knobSize??Math.max(12,this.height_*2),this.min=e.min??0,this.max=e.max??1,this.step=e.step??0,this.value_=this.snap(e.value??this.min),this.disabled_=e.disabled??!1,this.addChild(this.track),this.addChild(this.fill),this.addChild(this.knob),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointerdown`,this.handleDown),this.on(`pointermove`,this.handleMove),this.on(`pointerup`,this.handleUp),this.on(`pointerupoutside`,this.handleUp),$.add(this.themeListener)}get value(){return this.value_}get fraction(){return Sz(this.value_,this.min,this.max)}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){let t=this.snap(e);t===this.value_?this.draw():(this.value_=t,this.draw(),this.onChange.dispatch(t))}setFraction(e){this.setValue(Cz(e,this.min,this.max,this.step))}resize(e,t){this.width_=e,this.height_=t,this.draw()}get trackLength(){return Math.max(0,this.width_-this.knobSize)}snap(e){return Cz(Sz(e,this.min,this.max),this.min,this.max,this.step)}fractionAt(e){return this.trackLength>0?Math.max(0,Math.min(1,(e-this.knobSize/2)/this.trackLength)):0}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight,n=e.color.panelFill,r=(this.knobSize-this.height_)/2;this.track.clear().roundRect(0,r,this.width_,this.height_,this.height_/2).fill({color:n});let i=this.knobSize/2+this.fraction*this.trackLength;this.fill.clear(),i>this.knobSize/2&&this.fill.roundRect(this.knobSize/2,r,i-this.knobSize/2,this.height_,this.height_/2).fill({color:t}),this.knob.clear().circle(i,this.knobSize/2,this.knobSize/2).fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},Tz=class extends J{constructor(e={}){super(),this.onChange=new p,this.box=new Z,this.themeListener=()=>this.draw(),this.handleTap=()=>{this.disabled_||this.toggle()},this.size_=e.size??20,this.checked_=e.checked??!1,this.disabled_=e.disabled??!1,this.addChild(this.box),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get checked(){return this.checked_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setChecked(e){e===this.checked_?this.draw():(this.checked_=e,this.draw(),this.onChange.dispatch(e))}toggle(){this.setChecked(!this.checked_)}resize(e){this.size_=e,this.draw()}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;if(this.box.clear().roundRect(0,0,this.size_,this.size_,4).fill({color:e.color.panelFill}).stroke({color:this.disabled_?e.color.textDim:e.color.panelBorder,width:2}),this.checked_){let e=this.size_*.25;this.box.moveTo(e,this.size_*.55).lineTo(this.size_*.45,this.size_-e).lineTo(this.size_-e,e).stroke({color:t,width:Math.max(2,this.size_*.12),cap:`round`,join:`round`})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}},Ez=class extends J{constructor(e={}){super(),this.onChange=new p,this.options_=[],this.rows=[],this.circles=[],this.selected_=-1,this.themeListener=()=>this.draw(),this.size_=e.size??20,this.gap_=e.gap??8,this.buildRows(e.options??[]),this.selected_=this.defaultSelection(e.selected),this.draw(),$.add(this.themeListener)}get selected(){return this.selected_}get selectedOption(){return this.options_[this.selected_]??null}get length(){return this.options_.length}get rowHeight(){return this.size_+this.gap_}setOptions(e,t){this.buildRows(e),this.selected_=this.defaultSelection(t),this.draw()}select(e){let t=this.options_[e];t&&!t.disabled&&(e===this.selected_?this.draw():(this.selected_=e,this.draw(),this.onChange.dispatch(e)))}move(e){let t=this.options_.length;if(t===0)return!1;let n=this.selected_;for(let r=0;r<t;r++){n=(n+e+t)%t;let r=this.options_[n];if(r&&!r.disabled)return this.select(n),!0}return!1}handleAction(e){switch(e){case`up`:case`left`:return this.move(-1);case`down`:case`right`:return this.move(1);default:return!1}}tapRow(e){this.select(e)}defaultSelection(e){if(e!==void 0){let t=this.options_[e];if(t&&!t.disabled)return e}let t=this.options_.findIndex(e=>!e.disabled);return t===-1?-1:t}buildRows(e){for(let e of this.rows)e.destroy({children:!0});this.rows=[],this.circles=[],this.options_=[...e],this.removeChildren(),e.forEach((e,t)=>{let n=new J;n.y=t*this.rowHeight,n.eventMode=`static`,n.cursor=e.disabled?`default`:`pointer`,n.on(`pointertap`,()=>this.tapRow(t));let r=new Z;n.addChild(r),this.circles.push(r);let i=new EI({text:e.text});n.addChild(i),this.rows.push(n),this.addChild(n)})}draw(){let e=Q(),t=e.direction===`rtl`;this.rows.forEach((n,r)=>{let i=this.options_[r].disabled,a=this.circles[r];a.clear().circle(this.size_/2,this.size_/2,this.size_/2-1).fill({color:e.color.panelFill}).stroke({color:i?e.color.textDim:e.color.panelBorder,width:2}),r===this.selected_&&a.circle(this.size_/2,this.size_/2,Math.max(2,this.size_*.28)).fill({color:i?e.color.textDim:e.color.textHighlight});let o=this.size_+e.spacing,s=n.children.find(e=>e instanceof EI),c=s?.width??0;s&&(s.setColor(i?e.color.textDim:e.color.text),s.y=Math.round((this.size_-s.height)/2)),t?(s&&(s.x=0),a.x=c+e.spacing):(a.x=0,s&&(s.x=o))})}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function Dz(e,t,n,r,i=1,a=!1){if(!(r>n))return n;let o=i>0?i:1,s=(String(o).split(`.`)[1]??``).length,c=Math.round((e-n)/o)+Math.round(t),l=Math.round((r-n)/o)+1,u=c;return u=a?(u%l+l)%l:Math.max(0,Math.min(l-1,u)),Number((n+u*o).toFixed(s))}var Oz=class extends J{constructor(e={}){super(),this.onChange=new p,this.face=new Z,this.themeListener=()=>this.draw(),this.handleTap=e=>{this.disabled_||(this.toLocal(e.global).y<this.height_/2?this.increment():this.decrement())},this.width_=e.width??24,this.height_=e.height??32,this.min=e.min??0,this.max=e.max??9,this.step=e.step??1,this.wrap=e.wrap??!1,this.disabled_=e.disabled??!1,this.value_=Dz(e.value??this.min,0,this.min,this.max,this.step,!1),this.addChild(this.face),this.draw(),this.eventMode=`static`,this.cursor=`pointer`,this.on(`pointertap`,this.handleTap),$.add(this.themeListener)}get value(){return this.value_}get disabled(){return this.disabled_}setDisabled(e){this.disabled_=e,this.cursor=e?`default`:`pointer`,this.draw()}setValue(e){this.commit(Dz(e,0,this.min,this.max,this.step,this.wrap))}increment(){this.commit(Dz(this.value_,1,this.min,this.max,this.step,this.wrap))}decrement(){this.commit(Dz(this.value_,-1,this.min,this.max,this.step,this.wrap))}resize(e,t){this.width_=e,this.height_=t,this.draw()}commit(e){e===this.value_?this.draw():(this.value_=e,this.draw(),this.onChange.dispatch(e))}draw(){let e=Q(),t=this.disabled_?e.color.textDim:e.color.textHighlight;this.face.clear().roundRect(0,0,this.width_,this.height_,4).fill({color:e.color.panelFill}).stroke({color:e.color.panelBorder,width:1});let n=this.width_/2,r=Math.min(this.width_/4,this.height_/5);this.face.moveTo(n-r,r*1.6).lineTo(n,r*.6).lineTo(n+r,r*1.6).closePath().fill({color:t}),this.face.moveTo(n-r,this.height_-r*1.6).lineTo(n,this.height_-r*.6).lineTo(n+r,this.height_-r*1.6).closePath().fill({color:t})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},kz=class{constructor(e){this.onChange=new p,this.open_=!1,this.options_=[...e.options],this.disabled_=e.disabled??!1;let t=e.selectedIndex??this.firstEnabled();this.current=this.options_[t]?.disabled?this.firstEnabled():t,this.highlight_=this.current}get options(){return this.options_}get selectedIndex(){return this.current}get selected(){return this.options_[this.current]??null}get isOpen(){return this.open_}get disabled(){return this.disabled_}get highlight(){return this.highlight_}setDisabled(e){this.disabled_=e,e&&(this.open_=!1)}setOptions(e){this.options_=[...e],this.current=this.firstEnabled(),this.highlight_=this.current,this.open_=!1}open(){this.disabled_||this.open_||(this.open_=!0,this.highlight_=this.current)}close(){this.open_=!1}toggleOpen(){this.open_?this.close():this.open()}move(e){if(!this.open_||this.options_.length===0)return;let t=this.options_.length,n=this.highlight_;for(let r=0;r<t;r++)if(n=((n+e)%t+t)%t,!this.options_[n].disabled){this.highlight_=n;return}}setHighlight(e){e<0||e>=this.options_.length||this.options_[e].disabled||(this.highlight_=e)}confirm(){if(!this.open_)return!1;let e=this.options_[this.highlight_];return!e||e.disabled?!1:(this.open_=!1,this.highlight_!==this.current&&(this.current=this.highlight_,this.onChange.dispatch({option:e,index:this.current})),!0)}cancel(){this.open_=!1,this.highlight_=this.current}firstEnabled(){let e=this.options_.findIndex(e=>!e.disabled);return e===-1?0:e}};function Az(e,t,n){return Math.max(0,Math.min(Math.max(0,t-n),e))}var jz=class{constructor(e=.92,t=8){this.velocity=0,this.dragging=!1,this.travelled=0,this.lastY=0,this.lastTime=0,this.friction=e,this.minSpeed=t}start(e,t){this.dragging=!0,this.velocity=0,this.travelled=0,this.lastY=e,this.lastTime=t}move(e,t){if(!this.dragging)return 0;let n=this.lastY-e,r=t-this.lastTime;return r>0&&(this.velocity=this.velocity*.4+n/r*.6),this.travelled+=Math.abs(n),this.lastY=e,this.lastTime=t,n}end(){this.dragging=!1,Math.abs(this.velocity)<this.minSpeed&&(this.velocity=0)}step(e){if(this.dragging||this.velocity===0)return 0;let t=this.velocity*e;return this.velocity*=(1-this.friction)**e,Math.abs(this.velocity)<this.minSpeed&&(this.velocity=0),t}stop(){this.velocity=0}},Mz=class extends J{constructor(e){super(),this.onChange=new p,this.content=new J,this.maskShape=new Z,this.track=new Z,this.thumb=new Z,this.dragMoved=!1,this.thumbGrab=null,this.themeListener=()=>this.draw(),this.handleWheel=e=>{this.scrollBy(e.deltaY)},this.width_=e.width,this.maxHeight_=e.height,this.auto=e.autoHeight??!1,this.lineHeight=e.lineHeight??24,this.drag=e.touch?new jz:null,this.contentHeight_=Math.max(0,e.contentHeight??0),this.height_=this.fit(),this.offset_=Az(e.offset??0,this.contentHeight_,this.height_),this.addChild(this.content),this.addChild(this.maskShape),this.addChild(this.track),this.addChild(this.thumb),this.content.mask=this.maskShape,this.eventMode=`static`,this.on(`wheel`,this.handleWheel),this.drag&&(this.on(`pointerdown`,e=>this.dragStart(e.global.y,performance.now()/1e3)),this.on(`globalpointermove`,e=>this.dragMove(e.global.y,performance.now()/1e3)),this.on(`pointerup`,()=>this.dragEnd()),this.on(`pointerupoutside`,()=>this.dragEnd()),this.on(`pointerupcapture`,e=>{this.dragMoved&&e.stopPropagation()})),this.track.eventMode=`static`,this.thumb.eventMode=`static`,this.thumb.on(`pointerdown`,e=>{e.stopPropagation(),this.thumbDragStart(e.global.y)}),this.thumb.on(`globalpointermove`,e=>this.thumbDragMove(e.global.y)),this.thumb.on(`pointerup`,()=>this.thumbGrab=null),this.thumb.on(`pointerupoutside`,()=>this.thumbGrab=null),this.track.on(`pointerdown`,e=>{e.stopPropagation(),this.scrollToThumbCentre(this.toLocal(e.global).y)}),this.draw(),$.add(this.themeListener)}get offset(){return this.offset_}get contentHeight(){return this.contentHeight_}get viewportHeight(){return this.height_}fit(){return this.auto?Math.min(this.maxHeight_,this.contentHeight_):this.maxHeight_}get maxOffset(){return Math.max(0,this.contentHeight_-this.height_)}get scrollable(){return this.maxOffset>0}setContentHeight(e){this.contentHeight_=Math.max(0,e),this.height_=this.fit(),this.setOffset(Az(this.offset_,this.contentHeight_,this.height_))}resize(e,t){this.width_=e,this.maxHeight_=t,this.height_=this.fit(),this.setOffset(Az(this.offset_,this.contentHeight_,this.height_))}scrollBy(e){this.setOffset(Az(this.offset_+e,this.contentHeight_,this.height_))}scrollTo(e){this.setOffset(Az(e,this.contentHeight_,this.height_))}scrollIntoView(e,t){e<this.offset_?this.scrollTo(e):e+t>this.offset_+this.height_&&this.scrollTo(e+t-this.height_)}handleKey(e){let t=Math.max(this.lineHeight,this.height_-this.lineHeight);switch(e){case`ArrowUp`:return this.scrollBy(-this.lineHeight),!0;case`ArrowDown`:return this.scrollBy(this.lineHeight),!0;case`PageUp`:return this.scrollBy(-t),!0;case`PageDown`:return this.scrollBy(t),!0;case`Home`:return this.scrollTo(0),!0;case`End`:return this.scrollTo(this.maxOffset),!0;default:return!1}}dragStart(e,t){this.drag?.start(e,t),this.dragMoved=!1}dragMove(e,t){let n=this.drag;if(!n?.dragging)return;let r=n.move(e,t);!this.dragMoved&&n.travelled<6||(this.dragMoved=!0,this.scrollBy(r))}dragEnd(){this.drag?.end()}get dragged(){return this.dragMoved}update(e){let t=this.drag;if(!t)return;let n=this.offset_;this.scrollBy(t.step(e)),this.offset_===n&&t.velocity!==0&&t.stop()}get thumbMetrics(){let e=Math.max(6,this.height_/Math.max(1,this.contentHeight_)*this.height_);return{y:this.maxOffset===0?0:this.offset_/this.maxOffset*(this.height_-e),height:e}}thumbDragStart(e){this.thumbGrab={y:e,offset:this.offset_}}thumbDragMove(e){if(!this.thumbGrab)return;let t=this.height_-this.thumbMetrics.height;t<=0||this.scrollTo(this.thumbGrab.offset+(e-this.thumbGrab.y)/t*this.maxOffset)}scrollToThumbCentre(e){let t=this.height_-this.thumbMetrics.height;t<=0||this.scrollTo((e-this.thumbMetrics.height/2)/t*this.maxOffset)}setOffset(e){e===this.offset_?this.draw():(this.offset_=e,this.draw(),this.onChange.dispatch(e))}draw(){let e=Q();if(this.content.y=-this.offset_,this.maskShape.clear().rect(0,0,this.width_,this.height_).fill({color:16777215}),this.track.clear(),this.thumb.clear(),!this.scrollable)return;let t=this.width_-6;this.track.roundRect(t,0,6,this.height_,3).fill({color:e.color.panelFill});let{y:n,height:r}=this.thumbMetrics;this.thumb.roundRect(t,n,6,r,3).fill({color:e.color.textHighlight})}destroy(e){$.remove(this.themeListener),super.destroy(e)}},Nz=class extends J{constructor(e){super(),this.list=new J,this.backdrop=new Z,this.box=null,this.listHeight=0,this.themeListener=()=>this.refresh(),this.model=new kz(e),this.rowHeight=e.rowHeight??28,this.maxRows=Math.max(1,e.maxVisibleRows??8),this.width_=e.autoWidth?Math.max(e.width,...this.model.options.map(e=>this.labelWidth(e.label))):e.width,this.head=new dz({width:this.width_,height:this.rowHeight,text:``,disabled:this.model.disabled,onClick:()=>{this.model.toggleOpen(),this.refresh()}}),this.list.y=this.rowHeight,this.list.addChild(this.backdrop),this.addChild(this.head,this.list),this.refresh(),$.add(this.themeListener)}measureLabel(e){try{let t=new aO({fontFamily:Q().font.family,fontSize:Q().font.size});return QD.measureText(e,t).width}catch{return e.length*Q().font.size*.6}}labelWidth(e){return Math.ceil(this.measureLabel(e))+2*Q().padding+16}get viewWidth(){return this.width_}get visibleRows(){return Math.min(this.maxRows,this.model.options.length)}get scroller(){return this.box}fitBelow(e,t){let n=Math.floor((t-e-this.rowHeight)/this.rowHeight);return Math.max(1,Math.min(this.maxRows,n))}refresh(){let e=this.model;if(this.head.setText(`${e.selected?.label??``} ▾`),this.head.setDisabled(e.disabled),this.box?.destroy({children:!0}),this.box=null,this.list.visible=e.isOpen,this.backdrop.clear(),!e.isOpen)return;let t=this.visibleRows;this.listHeight=t*this.rowHeight;let n=Q();this.backdrop.rect(0,0,this.width_,this.listHeight).fill({color:n.color.panelFill,alpha:1}).stroke({color:n.color.panelBorder,width:1});let r=new Mz({width:this.width_,height:this.listHeight,contentHeight:e.options.length*this.rowHeight,touch:!0,lineHeight:this.rowHeight}),i=this.width_-(r.scrollable?8:0);e.options.forEach((t,n)=>{let a=new dz({width:i,height:this.rowHeight,text:t.label,disabled:t.disabled,onClick:()=>{e.setHighlight(n),e.confirm(),this.refresh()}});a.y=n*this.rowHeight,a.setSelected(n===e.highlight),r.content.addChild(a)}),r.scrollIntoView(e.highlight*this.rowHeight,this.rowHeight),this.box=r,this.list.addChild(r)}handleKey(e){let t=this.model;if(t.disabled)return!1;if(!t.isOpen)return e!==`Enter`&&e!==` `&&e!==`ArrowDown`?!1:(t.open(),this.refresh(),!0);let n=t.options.length;switch(e){case`Escape`:t.cancel();break;case`Enter`:case` `:t.confirm();break;case`ArrowUp`:t.move(-1);break;case`ArrowDown`:t.move(1);break;case`PageUp`:t.setHighlight(Math.max(0,t.highlight-this.maxRows));break;case`PageDown`:t.setHighlight(Math.min(n-1,t.highlight+this.maxRows));break;case`Home`:t.setHighlight(0);break;case`End`:t.setHighlight(n-1);break;default:return!1}return this.refresh(),!0}handleOutsideClick(e,t){if(!this.model.isOpen)return!1;let n=this.toLocal(new Gi(e,t));return n.x>=0&&n.x<=this.width_&&n.y>=0&&n.y<=this.rowHeight+this.listHeight?!1:(this.model.cancel(),this.refresh(),!0)}destroy(e){$.remove(this.themeListener),super.destroy(e)}},Pz=class{constructor(e){this.onChange=new p,this.current=0,this.sortKey_=null,this.ascending=!0,this.columns_=[...e.columns],this.rows_=[...e.rows??[]],this.pageSize_=e.pageSize??0,this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get columns(){return this.columns_}get rows(){return this.rows_}get pageSize(){return this.pageSize_}get sortKey(){return this.sortKey_}get sortAscending(){return this.ascending}get selectedIndex(){return this.current}get selected(){return this.rows_[this.current]??null}get page(){return this.pageSize_>0?Math.floor(this.current/this.pageSize_):0}get pageCount(){return this.pageSize_>0?Math.max(1,Math.ceil(this.rows_.length/this.pageSize_)):1}get pageRows(){if(this.pageSize_<=0)return this.rows_;let e=this.page*this.pageSize_;return this.rows_.slice(e,e+this.pageSize_)}setRows(e){this.rows_=[...e],this.current=this.firstEnabled(),this.onChange.dispatch()}setColumns(e){this.columns_=[...e],this.sortKey_&&!this.columns_.some(e=>e.key===this.sortKey_)&&(this.sortKey_=null),this.onChange.dispatch()}setPageSize(e){this.pageSize_=Math.max(0,e),this.onChange.dispatch()}sortBy(e){let t=this.columns_.find(t=>t.key===e);if(!t)return;this.sortKey_===e?this.ascending=!this.ascending:(this.sortKey_=e,this.ascending=!0);let n=t.compare??((t,n)=>Iz(Fz(t,e),Fz(n,e)));this.rows_.sort((e,t)=>(this.ascending?1:-1)*n(e,t)),this.current=this.firstEnabled(),this.onChange.dispatch()}select(e){e<0||e>=this.rows_.length||this.disabledOf(this.rows_[e])||(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows_.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows_[n])){this.current=n,this.onChange.dispatch();return}}}setPage(e){if(this.pageSize_<=0)return;let t=Math.max(0,Math.min(this.pageCount-1,e))*this.pageSize_,n=Math.min(t+this.pageSize_,this.rows_.length);for(let e=t;e<n;e++)if(!this.disabledOf(this.rows_[e])){this.current=e,this.onChange.dispatch();return}}nextPage(e=1){this.setPage(this.page+e)}firstEnabled(){let e=this.rows_.findIndex(e=>!this.disabledOf(e));return e===-1?0:e}};function Fz(e,t){return e&&typeof e==`object`?e[t]:void 0}function Iz(e,t){return e===t?0:e===void 0?-1:t===void 0?1:typeof e==`number`&&typeof t==`number`?e-t:String(e).localeCompare(String(t))}var Lz=class{constructor(e){this.onChange=new p,this.expanded=new Set,this.current=0,this.roots_=e.roots;for(let t of e.expanded??[])this.expanded.add(t);this.disabledOf=e.disabled??(()=>!1),this.current=this.firstEnabled()}get roots(){return this.roots_}get rows(){let e=[],t=(n,r)=>{for(let i of n){let n=(i.children?.length??0)>0,a=n&&this.expanded.has(i.id);e.push({node:i,depth:r,expanded:a,hasChildren:n}),a&&t(i.children,r+1)}};return t(this.roots_,0),e}get selectedIndex(){return this.current}get selected(){return this.rows[this.current]?.node??null}isExpanded(e){return this.expanded.has(e)}expand(e){this.expanded.has(e)||(this.expanded.add(e),this.onChange.dispatch())}collapse(e){if(!this.expanded.has(e))return;let t=this.rows[this.current]?.node.id;if(this.expanded.delete(e),t!==void 0&&!this.rows.some(e=>e.node.id===t)){let t=this.rows.findIndex(t=>t.node.id===e);t>=0&&(this.current=t)}this.onChange.dispatch()}toggle(e){this.expanded.has(e)?this.collapse(e):this.expand(e)}expandAll(){let e=t=>{for(let n of t)n.children?.length&&(this.expanded.add(n.id),e(n.children))};e(this.roots_),this.onChange.dispatch()}collapseAll(){this.expanded.clear(),this.select(0),this.onChange.dispatch()}select(e){let t=this.rows[e];t&&!this.disabledOf(t.node)&&(this.current=e,this.onChange.dispatch())}move(e){let t=this.rows.length;if(t===0)return;let n=this.current;for(let r=0;r<t;r++){if(n+=e,n<0||n>=t)return;if(!this.disabledOf(this.rows[n].node)){this.current=n,this.onChange.dispatch();return}}}firstEnabled(){let e=this.rows.findIndex(e=>!this.disabledOf(e.node));return e===-1?0:e}};function Rz(e){switch(e){case`top`:case`bottom`:return{x:.5,y:e===`top`?0:1};case`left`:case`right`:return{x:e===`left`?0:1,y:.5};case`top-left`:return{x:0,y:0};case`top-right`:return{x:1,y:0};case`bottom-left`:return{x:0,y:1};case`bottom-right`:return{x:1,y:1};default:return{x:.5,y:.5}}}function zz(e,t,n={width:0,height:0}){let r=e.margin??0,i=t.x+r,a=t.y+r,o=Math.max(0,t.width-r*2),s=Math.max(0,t.height-r*2);if(e.anchor===`fill`){let t=i+(e.offsetX??0),n=a+(e.offsetY??0);return{x:t,y:n,width:e.width??Math.max(0,i+o-t),height:e.height??Math.max(0,a+s-n)}}let c=Rz(e.anchor??`center`),l=e.alignX??c.x,u=e.alignY??c.y,d=e.width??n.width,f=e.height??n.height;return{x:i+l*Math.max(0,o-d)+(e.offsetX??0),y:a+u*Math.max(0,s-f)+(e.offsetY??0),width:d,height:f}}var Bz=class{constructor(e){this.spec=e}get columns(){return this.spec.columns}get rows(){return this.spec.rows}columnSizes(e){return Vz(this.spec.columns,e,this.gap)}rowSizes(e){return Vz(this.spec.rows,e,this.gap)}rect(e,t,n,r={}){let i=this.columnSizes(n.width),a=this.rowSizes(n.height),o=r.columnSpan??1,s=r.rowSpan??1;return{x:n.x+Uz(i,t,this.gap),y:n.y+Uz(a,e,this.gap),width:Wz(i,t,o,this.gap),height:Wz(a,e,s,this.gap)}}get gap(){return this.spec.gap??0}};function Vz(e,t,n){let r=n*Math.max(0,e.length-1),i=Math.max(0,t-r),a=e.reduce((e,t)=>e+(t.size??0),0),o=e.reduce((e,t)=>e+(t.grow??0),0),s=Math.max(0,i-a),c=0;return e.map((t,n)=>{if(t.size!==void 0)return t.size;if(!t.grow||o===0)return 0;let r=n===Hz(e)?s-c:Math.floor(s*t.grow/o);return c+=r,r})}function Hz(e){for(let t=e.length-1;t>=0;t--)if(e[t].grow)return t;return-1}function Uz(e,t,n){let r=0;for(let i=0;i<t&&i<e.length;i++)r+=e[i]+n;return r}function Wz(e,t,n,r){let i=0;for(let a=t;a<t+n&&a<e.length;a++)i+=e[a],a>t&&(i+=r);return Math.max(0,i)}function Gz(e,t,n={}){let r=n.gap??0,i=n.align??`start`,a=Array(e.length),o=0,s=[],c=0,l=0,u=()=>{if(s.length===0)return;let n=Math.max(0,t-c),u=i===`center`?n/2:i===`end`?n:0;for(let t of s)a[t]={x:u,y:o},u+=e[t].width+r;o+=l+r,s=[],c=0,l=0};return e.forEach((e,n)=>{let i=s.length===0?e.width:c+r+e.width;s.length>0&&i>t&&u(),c=s.length===0?e.width:c+r+e.width,l=Math.max(l,e.height),s.push(n)}),u(),{positions:a,height:Math.max(0,o-r)}}var Kz=[`idle`,`hover`,`pressed`,`disabled`,`selected`,`focused`],qz=class e{constructor(){this.map=new Map}static{this.ANY=`*`}define(e,t,n){let r=this.map.get(e)??{};r[t]={...r[t],...n},this.map.set(e,r)}has(e){return this.map.has(e)}widgets(){return[...this.map.keys()]}resolve(t,n=`idle`){return this.map.get(t)?.[n]??this.map.get(t)?.idle??this.map.get(e.ANY)?.[n]??this.map.get(e.ANY)?.idle??{}}statesOf(e){let t=this.map.get(e);return t?Kz.filter(e=>t[e]!==void 0):[]}static from(t){let n=new e;for(let[e,r]of Object.entries(t))if(Jz(r))for(let t of Kz){let i=r[t];i&&n.define(e,t,i)}else n.define(e,`idle`,r);return n}};function Jz(e){return Kz.some(t=>e[t]!==void 0)}var Yz=class extends J{constructor(e){super(),this.capturing=null,this.onKeyCaptured=e=>this.capturing?(e.preventDefault(),e.code===`Escape`?this.cancelCapture():this.finishCapture(this.capturing,e.code),!0):!1,this.actions=[...e.actions],this.labelFor=e.label??(e=>e),this.onConflict=e.onConflict??(()=>!0),this.list=new EL({width:e.width,height:e.height,rowHeight:e.rowHeight,items:this.rows()}),this.addChild(this.list)}rows(){return this.actions.map(e=>({text:this.rowText(e),value:e,disabled:this.capturing!==null&&this.capturing!==e}))}rowText(e){if(this.capturing===e)return`${this.labelFor(e)}: press a key...`;let t=Ie(e);return`${this.labelFor(e)}: ${t.length?t.join(`, `):`(unbound)`}`}refresh(){let e=this.list.selectedIndex;this.list.setItems(this.rows()),this.list.select(e)}startCapture(e){this.capturing=e,this.refresh(),queueMicrotask(()=>{this.capturing===e&&xe.add(this.onKeyCaptured)})}cancelCapture(){xe.remove(this.onKeyCaptured),this.capturing=null,this.refresh()}finishCapture(e,t){xe.remove(this.onKeyCaptured),this.capturing=null;let n=Pe(t).filter(t=>t!==e);if(n.length>0&&!this.onConflict(t,e,n))this.refresh();else{for(let e of n)Me(e,Ie(e).filter(e=>e!==t));Me(e,[t]),this.refresh()}}get isCapturing(){return this.capturing!==null}handleAction(e){if(this.capturing)return!0;if(e===`confirm`){let e=this.list.selected?.value;return e&&this.startCapture(e),!0}return this.list.handleAction(e)}destroy(e){xe.remove(this.onKeyCaptured),super.destroy(e)}},Xz=class extends J{constructor(e){super(),this.highlight=new Z,this.main=new J,this.rebindLayer=new J,this.rows=[],this.selected=0,this.rebind=null,this.themeListener=()=>this.drawHighlight(),this.settings=e.settings,this.width_=e.width??320,this.rowHeight=e.rowHeight??36,this.labels={music:`Music`,sfx:`Sound effects`,muted:`Mute`,zoom:`Zoom`,controls:`Controls...`,reset:`Reset to defaults`,rebindHint:`Keys (cancel: back)`,...e.labels},this.zoomMin=e.zoomMin??.5,this.zoomMax=e.zoomMax??4,this.zoomStep=e.zoomStep??.25,this.customRows=e.custom??[],this.actionsOption=e.actions,this.onConflict=e.onConflict,this.addChild(this.highlight),this.addChild(this.main),this.addChild(this.rebindLayer),this.rebindLayer.visible=!1,this.buildMain(),this.refresh(),this.drawHighlight(),$.add(this.themeListener)}get selectedRow(){return this.rows[this.selected]?.id??``}get isRebinding(){return this.rebind!==null}handleAction(e){if(this.rebind)return e===`cancel`&&!this.rebind.isCapturing?(this.closeRebind(),!0):this.rebind.handleAction(e);let t=this.rows[this.selected];if(!t)return!1;switch(e){case`up`:return this.select((this.selected+this.rows.length-1)%this.rows.length),!0;case`down`:return this.select((this.selected+1)%this.rows.length),!0;case`left`:return t.adjust(-1),!0;case`right`:return t.adjust(1),!0;case`confirm`:return t.activate(),!0;default:return!1}}refresh(){for(let e of this.rows)e.refresh()}select(e){this.selected=e,this.drawHighlight()}drawHighlight(){this.rows.length===0?this.highlight.clear():this.highlight.clear().rect(0,this.selected*this.rowHeight,this.width_,this.rowHeight).fill({color:Q().color.selection})}buildMain(){let e=this.settings.current;this.addSliderRow(`music`,this.labels.music,0,100,1,10,Math.round(e.musicVolume*100),e=>this.settings.setMusicVolume(e/100)),this.addSliderRow(`sfx`,this.labels.sfx,0,100,1,10,Math.round(e.sfxVolume*100),e=>this.settings.setSfxVolume(e/100)),this.addToggleRow(`muted`,this.labels.muted,e.muted,e=>this.settings.setMuted(e)),this.addSliderRow(`zoom`,this.labels.zoom,this.zoomMin,this.zoomMax,this.zoomStep,this.zoomStep,e.zoom,e=>this.settings.setZoom(e));for(let e of this.customRows)this.addCustomRow(e);this.addActionRow(`controls`,this.labels.controls,()=>this.openRebind()),this.addActionRow(`reset`,this.labels.reset,()=>{this.settings.reset(),this.refresh()}),this.main.children.forEach((e,t)=>{e.y=t*this.rowHeight})}addSliderRow(e,t,n,r,i,a,o,s){let c=new J,l=new EI({text:t});l.y=10;let u=new wz({width:140,min:n,max:r,step:i,value:o});u.x=this.width_-148,u.y=10,c.addChild(l,u),this.main.addChild(c);let d=()=>{l.setText(`${t}: ${u.value}`)};d(),u.onChange.add(e=>{s(e),d()}),this.rows.push({id:e,root:c,adjust:e=>u.setValue(u.value+e*a),activate:()=>{},refresh:()=>{u.setValue(this.readSlider(e)),d()}})}readSlider(e){let t=this.settings.current;switch(e){case`music`:return Math.round(t.musicVolume*100);case`sfx`:return Math.round(t.sfxVolume*100);case`zoom`:return t.zoom;default:return 0}}addToggleRow(e,t,n,r){let i=new J,a=new EI({text:t});a.y=10;let o=new Tz({checked:n});o.x=this.width_-28,o.y=8,i.addChild(a,o),this.main.addChild(i),o.onChange.add(r),this.rows.push({id:e,root:i,adjust:()=>o.toggle(),activate:()=>o.toggle(),refresh:()=>o.setChecked(this.readToggle(e))})}readToggle(e){return e===`muted`?this.settings.current.muted:this.settings.getCustom(e.slice(7),!1)===!0}addCustomRow(e){let t=`custom:${e.key}`;if(e.kind===`boolean`){let n=this.settings.getCustom(e.key,!1);this.addToggleRow(t,e.label,n===!0,t=>this.settings.setCustom(e.key,t))}else if(e.kind===`number`){let n=this.settings.getCustom(e.key,e.min),r=typeof n==`number`?n:e.min,i=e.step??0,a=i>0?i:(e.max-e.min)/20,o=new J,s=new EI({text:e.label});s.y=10;let c=new wz({width:140,min:e.min,max:e.max,step:e.step??0,value:r});c.x=this.width_-148,c.y=10,o.addChild(s,c),this.main.addChild(o);let l=()=>{s.setText(`${e.label}: ${c.value}`)};l(),c.onChange.add(t=>{this.settings.setCustom(e.key,t),l()}),this.rows.push({id:t,root:o,adjust:e=>c.setValue(c.value+e*a),activate:()=>{},refresh:()=>{let t=this.settings.getCustom(e.key,e.min);c.setValue(typeof t==`number`?t:e.min),l()}})}else{let n=e.options,r=new J,i=new EI({text:e.label});i.y=10;let a=new Oz({min:0,max:n.length-1,step:1,value:0,wrap:!0});a.x=this.width_-32,a.y=2,r.addChild(i,a),this.main.addChild(r);let o=e=>{let t=typeof e==`string`?n.indexOf(e):-1;return t>=0?t:0},s=()=>{i.setText(`${e.label}: ${n[a.value]}`)};a.setValue(o(this.settings.getCustom(e.key,n[0]))),s(),a.onChange.add(t=>{this.settings.setCustom(e.key,n[t]),s()}),this.rows.push({id:t,root:r,adjust:e=>e>0?a.increment():a.decrement(),activate:()=>a.increment(),refresh:()=>{a.setValue(o(this.settings.getCustom(e.key,n[0]))),s()}})}}addActionRow(e,t,n){let r=new J,i=new dz({width:this.width_-16,height:28,text:t,onClick:n});i.x=8,i.y=4,r.addChild(i),this.main.addChild(r),this.rows.push({id:e,root:r,adjust:()=>{},activate:n,refresh:()=>{}})}openRebind(){let e=this.actionsOption??Object.keys(this.settings.current.bindings),t=new EI({text:this.labels.rebindHint}),n=new Yz({width:this.width_,height:Math.max(1,e.length)*this.rowHeight,actions:e,onConflict:this.onConflict});t.y=0,n.y=this.rowHeight,this.rebindLayer.addChild(t,n),this.rebindLayer.visible=!0,this.main.visible=!1,this.highlight.visible=!1,this.rebind=n}closeRebind(){this.settings.setBindings(Le()),this.rebindLayer.removeChildren(),this.rebind?.destroy(),this.rebind=null,this.rebindLayer.visible=!1,this.main.visible=!0,this.highlight.visible=!0}destroy(e){$.remove(this.themeListener),this.rebind?.destroy(),this.rebind=null,super.destroy(e)}},Zz=class extends J{constructor(e){if(super(),this.emptyLayer=new J,this.filledLayer=new J,this.maskShape=new Z,this.themeListener=()=>this.draw(),e.filledTexture===void 0!=(e.emptyTexture===void 0))throw Error(`a Meter takes filledTexture and emptyTexture together, or neither`);this.count_=$z(e.count),this.size_=e.size??16,this.gap_=e.gap??4,this.value_=Qz(e.value??this.count_,this.count_),this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.emptyColor_=e.emptyColor,this.filledTexture=e.filledTexture,this.emptyTexture=e.emptyTexture,this.addChild(this.emptyLayer),this.addChild(this.filledLayer),this.addChild(this.maskShape),this.filledLayer.mask=this.maskShape,this.draw(),$.add(this.themeListener)}get value(){return this.value_}get count(){return this.count_}get color(){return this.fillColor}setValue(e,t=this.count_){this.count_=$z(t),this.value_=Qz(e,this.count_),this.draw()}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}resize(e,t=this.gap_){this.size_=e,this.gap_=t,this.draw()}get totalWidth(){return this.count_*this.size_+(this.count_-1)*this.gap_}iconX(e){let t=e*(this.size_+this.gap_);return Q().direction===`rtl`?this.totalWidth-t-this.size_:t}draw(){let e=Q();this.explicitColor||(this.fillColor=e.color.textHighlight);let t=this.emptyColor_??e.color.panelFill;this.emptyLayer.removeChildren(),this.filledLayer.removeChildren();for(let e=0;e<this.count_;e++){let n=this.iconX(e);this.emptyLayer.addChild(this.icon(n,t,this.emptyTexture,!1)),this.filledLayer.addChild(this.icon(n,this.fillColor,this.filledTexture,!0))}let n=this.totalWidth*(this.count_>0?this.value_/this.count_:0),r=e.direction===`rtl`?this.totalWidth-n:0;this.maskShape.clear().rect(r,0,n,this.size_).fill({color:16777215})}icon(e,t,n,r){if(n){let i=new wl(n);return i.x=e,i.width=this.size_,i.height=this.size_,r&&this.explicitColor&&(i.tint=t),i}let i=new Z,a=this.size_/2;return i.circle(e+a,a,a).fill({color:t}),i}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function Qz(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,e)):t}function $z(e){return Number.isFinite(e)?Math.max(1,Math.floor(e)):1}var eB=class extends J{constructor(e){super(),this.track=new Z,this.fill=new Z,this.themeListener=()=>this.draw(),this.width_=e.width,this.height_=e.height,this.explicitColor=e.color!==void 0,this.fillColor=e.color??Q().color.textHighlight,this.fraction=tB((e.value??1)/(e.max??1)),this.fillTexture=e.fillTexture,this.backgroundTexture=e.backgroundTexture,this.background_=e.background,this.roundUpToPixel=e.roundUpToPixel??!1,this.addChild(this.track),this.addChild(this.fill),this.draw(),$.add(this.themeListener)}get value(){return this.fraction}setValue(e,t=1){this.fraction=tB(t>0?e/t:0),this.draw()}get color(){return this.fillColor}setColor(e){this.explicitColor=!0,this.fillColor=e,this.draw()}get background(){return this.background_??Q().color.panelFill}setBackground(e){this.background_=e,this.draw()}resize(e,t){this.width_=e,this.height_=t,this.draw()}draw(){let e=Q();if(this.explicitColor||(this.fillColor=e.color.textHighlight),this.track.clear().rect(0,0,this.width_,this.height_),this.track.fill(this.backgroundTexture?{texture:this.backgroundTexture}:{color:this.background}),this.fill.clear(),this.fraction>0){let t=this.width_*this.fraction,n=this.roundUpToPixel?Math.ceil(t):t,r=e.direction===`rtl`?this.width_-n:0;this.fill.rect(r,0,n,this.height_),this.fill.fill(this.fillTexture?this.explicitColor?{texture:this.fillTexture,color:this.fillColor}:{texture:this.fillTexture}:{color:this.fillColor})}}destroy(e){$.remove(this.themeListener),super.destroy(e)}};function tB(e){return Math.max(0,Math.min(1,e))}function nB(e,t){return t<=0?1-e:t>=1||e<=t?1:1-(e-t)/(1-t)}function rB(e,t,n=!1){return n||e<=0?0:-t*e}function iB(e,t,n){return n<=0?e:Math.max(e,Math.min(n,t))}var aB=class extends J{constructor(e){super(),this.rising=new J,this.elapsed=0,this.done=!1,this.duration=e.duration??.8,this.rise=e.rise??24,this.hold=Math.min(1,Math.max(0,e.hold??0));let t=new EI({text:e.text,color:e.color,size:e.size});t.anchor.set(.5),this.rising.addChild(t),this.addChild(this.rising)}get finished(){return this.done}get riseOffset(){return this.rising.y}ageAtLeast(e){this.elapsed=iB(this.elapsed,this.duration,e)}update(e){if(this.done)return;this.elapsed=Math.min(this.duration,this.elapsed+e);let t=this.duration>0?this.elapsed/this.duration:1;this.rising.y=rB(t,this.rise,br()),this.alpha=nB(t,this.hold),t>=1&&(this.done=!0,this.parent?.removeChild(this),this.destroy({children:!0}))}},oB=4;function sB(e){return Math.max(0,e)/5}function cB(e,t,n=4){let r=t.y-t.height/2;return e.y+e.height/2+n<=r?e.y:r-e.height/2-n}function lB(e,t,n=4){let r=[];if(t.key===void 0)return r;let i=t;for(let a=e.length-1;a>=0;a--){let o=e[a];if(o.key!==t.key)continue;let s=cB(o,i,n);if(s===o.y)break;r.push({index:a,y:s,ageAtLeast:sB(r.length+1)}),i={...o,y:s}}return r}var uB=class extends J{constructor(...e){super(...e),this.live=[]}push(e){let t=new aB({text:e.text,color:e.color,size:e.size,duration:e.duration,rise:e.rise,hold:e.hold});e.scale!==void 0&&t.scale.set(e.scale);let n={key:e.key,x:e.x,y:e.y,height:t.height};for(let e of lB(this.live.map(e=>e.entry),n)){let t=this.live[e.index];t.entry.y=e.y,t.popup.y=e.y,t.popup.ageAtLeast(e.ageAtLeast)}return t.position.set(e.x,e.y),this.addChild(t),this.live.push({popup:t,entry:n}),t}update(e){for(let{popup:t}of this.live)t.update(e);for(let e=this.live.length-1;e>=0;e--)this.live[e].popup.finished&&this.live.splice(e,1)}get count(){return this.live.length}clear(){for(let{popup:e}of this.live)this.removeChild(e),e.destroy({children:!0});this.live.length=0}},dB=class extends J{constructor(e={}){super(),this.queue=[],this.current=null,this.phase=`fadeIn`,this.elapsed=0,this.fadeIn=e.fadeIn??.25,this.hold=e.hold??1,this.fadeOut=e.fadeOut??1.75,this.scaleFrom=e.scaleFrom??2}show(e){this.queue.push(e),this.current||this.start(this.queue.shift())}get isBusy(){return this.current!==null||this.queue.length>0}start(e){this.current=e,this.phase=`fadeIn`,this.elapsed=0,this.addChild(e),e.alpha=this.fadeIn>0?0:1,e.scale.set(this.fadeIn>0?this.scaleFrom:1)}update(e){let t=this.current;if(!t)return;if(this.elapsed+=e,this.phase===`fadeIn`){let e=this.fadeIn,n=e>0?Math.min(1,this.elapsed/e):1,r=Er.easeOutCubic(n);t.alpha=r,t.scale.set(this.scaleFrom+(1-this.scaleFrom)*r),n>=1&&this.advance();return}if(this.phase===`hold`){this.elapsed>=this.hold&&this.advance();return}let n=this.fadeOut,r=n>0?Math.min(1,this.elapsed/n):1;t.alpha=1-r,r>=1&&this.finish()}advance(){this.phase=this.phase===`fadeIn`?`hold`:`fadeOut`,this.elapsed=0}finish(){let e=this.current;if(!e)return;this.removeChild(e),e.destroy({children:!0}),this.current=null;let t=this.queue.shift();t&&this.start(t)}},fB=class extends J{constructor(e={}){super(),this.viewWidth=0,this.viewHeight=0,this.panelWidth=0,this.panelHeight=0,this.pending=null,this.waited=0,this.delay=e.delay??.4,this.maxWidth=e.maxWidth??200,this.offsetX=e.offset?.x??12,this.offsetY=e.offset?.y??16,this.margin=e.margin??4,this.panel=new CL({width:0,height:0,modal:!1,closable:!1,dims:!1}),this.body=new EI({text:``,wrapWidth:this.maxWidth}),this.panel.content.addChild(this.body),this.addChild(this.panel),this.visible=!1}setViewport(e,t){this.viewWidth=e,this.viewHeight=t,this.visible&&this.place()}hover(e,t,n,r=this.delay){this.pending&&this.pending.text===e?(this.pending.x=t,this.pending.y=n,this.visible&&this.place()):(this.pending={text:e,x:t,y:n,delay:r},this.waited=0,this.visible=!1)}leave(){this.pending=null,this.waited=0,this.visible=!1}get isShowing(){return this.visible}get text(){return this.pending?.text??null}get panelPosition(){return{x:this.panel.x,y:this.panel.y}}get size(){return{width:this.panelWidth,height:this.panelHeight}}update(e){if(!this.pending||this.visible||(this.waited+=e,this.waited<this.pending.delay))return!1;this.body.setText(this.pending.text);let t=Q(),n=(t.panel?t.panelBorder:2)+t.padding,r=this.measureBody();return this.panelWidth=Math.ceil(r.width)+n*2,this.panelHeight=Math.ceil(r.height)+n*2,this.panel.resize(this.panelWidth,this.panelHeight),this.visible=!0,this.place(),!0}measureBody(){return{width:this.body.width,height:this.body.height}}place(){let e=this.pending;if(!e)return;let t=this.panelWidth,n=this.panelHeight,r=e.x+this.offsetX,i=e.y+this.offsetY;this.viewWidth>0&&(r+t+this.margin>this.viewWidth&&(r=e.x-this.offsetX-t),r=Math.max(this.margin,Math.min(r,Math.max(this.margin,this.viewWidth-t-this.margin)))),this.viewHeight>0&&(i+n+this.margin>this.viewHeight&&(i=e.y-this.offsetY-n),i=Math.max(this.margin,Math.min(i,Math.max(this.margin,this.viewHeight-n-this.margin)))),this.panel.x=r,this.panel.y=i}},pB=class extends J{constructor(e={}){super(),this.targets=[],this.tooltip=e.tooltip??new fB,this.longPress=e.longPress??.5,this.addChild(this.tooltip)}add(e){return this.targets.push(e),()=>{let t=this.targets.indexOf(e);t>=0&&this.targets.splice(t,1)}}addButton(e){return this.add({bounds:()=>{let t=e.getBounds();return{x:t.x,y:t.y,width:t.width,height:t.height}},text:()=>e.tooltip,active:()=>{for(let t=e;t;t=t.parent)if(!t.visible)return!1;return!0}})}targetAt(e,t){for(let n=this.targets.length-1;n>=0;n--){let r=this.targets[n];if(r.active&&!r.active())continue;let i=r.bounds();if(e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height)return r.text()===void 0?null:r}return null}pointerMove(e,t){let n=this.targetAt(e,t)?.text();n?this.tooltip.hover(n,e,t):this.tooltip.leave()}pointerDown(e,t){let n=this.targetAt(e,t)?.text();n?this.tooltip.hover(n,e,t,this.longPress):this.tooltip.leave()}pointerUp(){this.tooltip.leave()}attach(e){let t=e=>this.pointerMove(e.x,e.y),n=e=>this.pointerDown(e.x,e.y),r=()=>this.pointerUp();return e.move.add(t),e.down.add(n),e.up.add(r),()=>{e.move.remove(t),e.down.remove(n),e.up.remove(r)}}update(e){return this.tooltip.update(e)}},mB=class extends J{constructor(e){super(),this.topics=e.topics;let t=e.listWidth??Math.floor(e.width/3),n=e.width-t-Q().spacing,r=Q().direction===`rtl`;this.list=new EL({width:t,height:e.height,items:this.topics.map(e=>({text:e.title})),onHighlight:(e,t)=>this.showBody(t),onSelect:(e,t)=>this.showBody(t)}),this.list.x=r?e.width-t:0,this.addChild(this.list),this.body=new EI({wrapWidth:n}),this.body.x=r?0:t+Q().spacing,this.addChild(this.body),this.topics.length>0&&this.showBody(this.list.selectedIndex)}showBody(e){this.body.setText(this.topics[e]?.body??``)}handleAction(e){return this.list.handleAction(e)}},hB=class e extends J{constructor(t){super(),this.text=new EI({text:e.format(t.stats),wrapWidth:t.width}),this.addChild(this.text)}setStats(t,n){this.text.setText(e.format(t)),n!==void 0&&(this.text.style.wordWrapWidth=n)}static format(e){return e.map(e=>`${e.label}: ${e.value}`).join(`
|
|
1386
|
-
`)}},gB=class extends J{constructor(e){super(),this.backdrop=new Z,this.progress=new eB({width:240,height:10,value:0}),this.width_=e.width,this.height_=e.height,this.onRetry=e.onRetry,this.onCancel=e.onCancel,this.title=new EI({text:e.title??`Loading`,size:18,bold:!0,align:`center`}),this.status=new EI({text:`Preparing...`,align:`center`}),this.addChild(this.backdrop,this.title,this.status,this.progress),this.layout()}setSnapshot(e){let t=e.total>0?e.completed/e.total:0;this.progress.setValue(t),e.status===`failed`?this.status.setText(`Loading failed. Retry or cancel.`):e.status===`cancelled`?this.status.setText(`Loading cancelled.`):e.status===`ready`?this.status.setText(`Ready`):this.status.setText(e.current?`Loading ${e.current}...`:`Preparing...`)}bind(e){this.setSnapshot(e.snapshot);let t=e=>this.setSnapshot(e);return e.changed.add(t),()=>e.changed.remove(t)}retry(){this.onRetry?.()}cancel(){this.onCancel?.()}resize(e,t){this.width_=e,this.height_=t,this.layout()}layout(){let e=Q().color;this.backdrop.clear().rect(0,0,this.width_,this.height_).fill({color:e.overlay,alpha:.92});let t=this.width_/2,n=this.height_/2;this.title.anchor.set(.5),this.status.anchor.set(.5),this.title.position.set(t,n-36),this.status.position.set(t,n-8),this.progress.position.set(t-120,n+16)}};function _B(e,t={}){return n=>new Promise(r=>{e.push(new lz({width:t.width??480,height:t.height??120,speed:t.speed??45,pages:[{text:n.text,speaker:n.speaker,portrait:n.portrait}],choices:n.choices,anchor:t.anchor??`bottom`,onDone:e=>r(e)}))})}function vB(e){let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function yB(e){return .2126*vB(e>>16&255)+.7152*vB(e>>8&255)+.0722*vB(e&255)}function bB(e,t){let[n,r]=[yB(e),yB(t)].sort((e,t)=>t-e);return(n+.05)/(r+.05)}function xB(e,t,n=`AA`,r=!1){let i=n===`AAA`?r?4.5:7:r?3:4.5;return bB(e,t)>=i}function SB(e,t,n,r=`…`){if(n(e)<=t)return e;let i=0,a=e.length;for(;i<a;){let o=Math.ceil((i+a)/2);n(e.slice(0,o).trimEnd()+r)<=t?i=o:a=o-1}return i===0?r:e.slice(0,i).trimEnd()+r}function CB(e,t,n,r,i=`…`){let a=[],o=``;for(let n of e.split(/\s+/).filter(Boolean)){let e=o?`${o} ${n}`:n;r(e)<=t||!o?o=e:(a.push(o),o=n)}if(o&&a.push(o),a.length<=n)return a.map(e=>SB(e,t,r,i));let s=a.slice(0,n),c=a.slice(n-1).join(` `);return s[n-1]=SB(c+i,t,r,i),s}function wB(e,t,n,r=40,i=1){let a=e-t;if(a<=0)return 0;let o=a/r,s=2*(i+o),c=(n%s+s)%s;return c<i?0:c<i+o?(c-i)*r:c<2*i+o?a:a-(c-2*i-o)*r}var TB=class extends J{constructor(e){super(),this.body=new EI({...e.label,text:e.text??``,wrapWidth:e.width-10}),this.box=new Mz({width:e.width,height:e.maxHeight,autoHeight:!0,touch:e.touch??!0,keyboard:!0}),this.box.content.addChild(this.body),this.addChild(this.box),this.measure()}measureHeight(){return this.body.height}measure(){this.box.setContentHeight(this.measureHeight())}setText(e){this.body.setText(e),this.measure(),this.box.scrollTo(0)}update(e){this.box.update(e)}},EB=class extends J{constructor(e){super(),this.clip=new Z,this.source=``,this.fullWidth=0,this.time=0,this.width_=e.width,this.speed=e.speed??40,this.pause=e.pause??1,this.labelOptions=e.label??{},this.body=new EI({...this.labelOptions,text:``}),this.clip.rect(0,0,e.width,4096).fill({color:16777215}),this.addChild(this.body,this.clip),this.body.mask=this.clip,this.setText(e.text??``)}measureWidth(e){let t=new EI({...this.labelOptions,text:e}),n=t.width;return t.destroy(),n}setText(e){this.source=e,this.fullWidth=this.measureWidth(e),this.time=0,this.apply()}apply(){br()?(this.body.setText(SB(this.source,this.width_,e=>this.measureWidth(e))),this.body.x=0):(this.body.setText(this.source),this.body.x=-wB(this.fullWidth,this.width_,this.time,this.speed,this.pause))}get shift(){return 0-this.body.x}update(e){this.time+=e,this.apply()}},DB={farLeft:.12,left:.28,center:.5,right:.72,farRight:.88},OB=class extends J{constructor(e,t){super(),this.backdropLayer=new J,this.actorLayer=new J,this.backdrop=null,this.outgoingBackdrop=null,this.actors=new Map,this.definitions=new Map,this.focused=null,this.tweener=new Dr,this.dimAmount=.45,this.stageWidth=e,this.stageHeight=t,this.addChild(this.backdropLayer),this.addChild(this.actorLayer)}defineCharacter(e,t){this.definitions.set(e,t)}resize(e,t){this.stageWidth=e,this.stageHeight=t;for(let e of[this.backdrop,this.outgoingBackdrop])e&&this.fitBackdrop(e);for(let e of this.actors.values())this.placeActor(e)}setBackdrop(e,t=.4){this.outgoingBackdrop?.destroy();let n=this.backdrop;this.outgoingBackdrop=n;let r=new wl(e);this.fitBackdrop(r),this.backdrop=r,this.backdropLayer.addChild(r);let i=()=>{this.outgoingBackdrop===n&&(n?.destroy(),this.outgoingBackdrop=null)};return t<=0?(i(),Promise.resolve()):(r.alpha=0,this.tweener.tween(t,e=>{r.alpha=e}).then(i))}fitBackdrop(e){let t=e.texture,n=Math.max(this.stageWidth/t.width,this.stageHeight/t.height);e.scale.set(n),e.x=Math.round((this.stageWidth-t.width*n)/2),e.y=Math.round((this.stageHeight-t.height*n)/2)}show(e,t={}){let n=this.definitions.get(e);if(!n)throw Error(`no character defined as "${e}"`);let r=t.expression??Object.keys(n.expressions)[0],i=this.actors.get(e);if(i)return t.at!==void 0&&(i.slot=this.slotOf(t.at)),this.setExpression(e,r),this.placeActor(i),Promise.resolve();let a=new CM(n.sheet.get(n.expressions[r])),o={id:e,sprite:a,definition:n,slot:this.slotOf(t.at??`center`),expression:r};this.actors.set(e,o),this.actorLayer.addChild(a),this.placeActor(o),this.applyFocus();let s=t.fade??.25;return s<=0?Promise.resolve():(a.alpha=0,this.tweener.tween(s,e=>{a.alpha=e}))}hide(e,t=.25){let n=this.actors.get(e);return n?(this.actors.delete(e),this.focused===e&&(this.focused=null),this.applyFocus(),t<=0?(n.sprite.destroy(),Promise.resolve()):this.tweener.tween(t,e=>{n.sprite.alpha=1-e}).then(()=>n.sprite.destroy())):Promise.resolve()}hideAll(e=.25){return Promise.all([...this.actors.keys()].map(t=>this.hide(t,e))).then(()=>void 0)}setExpression(e,t){let n=this.actors.get(e);if(!n)return;let r=n.definition.expressions[t];if(r===void 0)throw Error(`character "${e}" has no expression "${t}"`);n.expression=t,n.sprite.texture=n.definition.sheet.get(r)}focus(e){this.focused=e,this.applyFocus()}applyFocus(){let e=Math.round(255*(1-this.dimAmount)),t=e<<16|e<<8|e;for(let e of this.actors.values()){let n=this.focused!==null&&e.id!==this.focused;e.sprite.tint=n?t:16777215}}slotOf(e){return typeof e==`number`?e:DB[e]}placeActor(e){let t=e.definition,n=(t.height??.7)*this.stageHeight,r=n/t.sheet.frameHeight;e.sprite.scale.set(r),e.sprite.x=Math.round(e.slot*this.stageWidth-t.sheet.frameWidth*r/2),e.sprite.y=Math.round((t.baseline??.92)*this.stageHeight-n)}update(e){this.tweener.update(e)}get isBusy(){return this.tweener.isBusy}},kB=class{constructor(e){this.state={answers:{}},this.cancelled=!1,this.historyLog=[],this.seenLines=new Set,this.skipSeen=!1,this.options=e}cancel(){this.cancelled=!0}get history(){return this.historyLog}async showLast(){let e=this.historyLog.at(-1);if(!e)return!1;let{windows:t}=this.options;return await new Promise(n=>{t.push(new lz({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:0,pages:[{text:e.text,speaker:e.speaker}],dims:!1,anchor:`bottom`,onDone:()=>n()}))}),!0}async run(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)throw Error(`a "goto ${e}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async step(e){let{stage:t}=this.options;if(`backdrop`in e)await t.setBackdrop(this.options.backdrop(e.backdrop),e.fade);else if(`show`in e)await t.show(e.show,{at:e.at,expression:e.expression,fade:e.fade});else if(`hide`in e)await t.hide(e.hide,e.fade);else if(`hideAll`in e)await t.hideAll(e.fade);else if(`expression`in e)t.setExpression(e.of,e.expression);else if(`say`in e)await this.speak(e.say,e.as,e.speaker),this.recordHistory(e.say,e.as,e.speaker);else{if(`ask`in e){let t=await this.speak(e.ask,e.as,e.speaker,e.choices);return this.recordHistory(e.ask,e.as,e.speaker,t),e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`goto`in e)return e.goto;`wait`in e?await new Promise(t=>setTimeout(t,e.wait*1e3)):`call`in e&&await e.call(this.state)}}recordHistory(e,t,n,r){let i=n??(t?this.options.displayName?.(t)??t:void 0);this.seenLines.add(AB(t,e)),this.historyLog.push({text:e,speaker:i,chosen:r})}speak(e,t,n,r){let{stage:i,windows:a}=this.options;i.focus(t??null);let o=n??(t?this.options.displayName?.(t)??t:void 0),s=this.skipSeen&&!r&&this.seenLines.has(AB(t,e));return new Promise(t=>{a.push(new lz({width:this.options.boxWidth??480,height:this.options.boxHeight??120,speed:s?0:this.options.speed??45,autoAdvance:s?0:void 0,mode:this.options.mode,pages:[{text:e,speaker:o}],choices:r,dims:!1,anchor:`bottom`,onDone:e=>t(e)}))})}};function AB(e,t){return`${e??``}\u0000${t}`}function jB(e){let{story:t,start:n,title:r}=Gr(e);return r===void 0?{story:t,start:n}:{story:t,start:n,title:r}}function MB(e){return Wr(e).map(e=>e.speaker===void 0?{say:e.text}:{say:e.text,as:e.speaker})}function NB(e,t={}){let n={},r=e=>{for(let t of e)`say`in t?n[t.say]=t.say:`ask`in t&&(n[t.ask]=t.ask)};if(Array.isArray(e))r(e);else for(let t of Object.values(e))r(t);return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}var PB=class{constructor(e){this.onChange=new p,this.onMusic=new p,this.index=0,this.beats=e}get length(){return this.beats.length}get position(){return this.index}get current(){return this.beats[this.index]??null}get done(){return this.beats.length===0||this.index>=this.beats.length-1}get music(){return this.current?.music??null}goTo(e){let t=Math.max(0,Math.min(this.beats.length-1,e));this.index=t,this.report()}advance(){return!this.done&&(this.goTo(this.index+1),!0)}back(){return this.index!==0&&(this.goTo(this.index-1),!0)}skip(){this.goTo(this.beats.length-1)}restart(){this.goTo(0)}report(){let e=this.current;e&&this.onChange.dispatch(e),this.onMusic.dispatch(this.music)}},FB=class extends J{constructor(e){super(),this.backdrop=new wl(q.EMPTY),this.handleAdvance=()=>{this.advance()},this.handleBeat=e=>{this.applyBeat(e)},this.sequence=e.sequence,this.textureFor=e.textureFor??(()=>null),this.playMusic=e.playMusic??(()=>{}),this.width_=e.width,this.height_=e.height,this.titleLabel=new EI({text:``,color:Q().color.textHighlight}),this.textLabel=new EI({text:``,wrapWidth:this.width_*.8}),this.addChild(this.backdrop),this.addChild(this.titleLabel),this.addChild(this.textLabel),this.eventMode=`static`,this.on(`pointertap`,this.handleAdvance),this.sequence.onChange.add(this.handleBeat),this.sequence.onMusic.add(this.playMusic),this.applyBeat(this.sequence.current)}get current(){return this.sequence.current}advance(){return this.sequence.advance()}skip(){this.sequence.skip()}resize(e,t){this.width_=e,this.height_=t,this.applyBeat(this.current)}applyBeat(e){if(!e){this.backdrop.visible=!1;return}let t=e.image?this.textureFor(e.image):null;if(this.backdrop.visible=t!==null,t){this.backdrop.texture=t;let e=Math.max(this.width_/t.width,this.height_/t.height);this.backdrop.scale.set(e),this.backdrop.x=(this.width_-t.width*e)/2,this.backdrop.y=(this.height_-t.height*e)/2}this.titleLabel.setText(e.title??``),this.titleLabel.x=this.width_*.1,this.titleLabel.y=this.height_*.12,this.textLabel.setText(e.text),this.textLabel.x=this.width_*.1,this.textLabel.y=this.height_*.24,this.textLabel.style.wordWrapWidth=this.width_*.8}destroy(e){this.sequence.onChange.remove(this.handleBeat),this.sequence.onMusic.remove(this.playMusic),super.destroy(e)}},IB=[[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[0,1]],LB=[[1,1],[1,0],[0,-1],[-1,0],[-1,1],[0,1]];function RB(e){return e===4?sr:lr}var zB={passable:!1,transparent:!1},BB={passable:!0,transparent:!0},VB=class e{constructor(e,t,n,r=0,i=`square`,a){if(this.rooms=[],this.width=e,this.shape=i,this.height=t,a!==void 0&&(!Number.isFinite(a)||a<0))throw Error(`viewDistance must be a finite non-negative number`);this.viewDistance=a,this.kinds=n,this.terrain=new Uint8Array(e*t).fill(r)}get cellCount(){return this.width*this.height}index(e,t){return nr(this.width,e,t)}xOf(e){return rr(this.width,e)}yOf(e){return ir(this.width,e)}inside(e,t){return tr(this.width,this.height,e,t)}neighbors(e,t,n=8){return this.shape===`hex`?Jn(e,t):RB(n).map(([n,r])=>({x:e+n,y:t+r}))}forEachNeighbor(e,t,n,r){let i=this.shape===`hex`?e&1?LB:IB:RB(n);for(let[n,a]of i)r(e+n,t+a)}insideWithBorder(e,t){return e>0&&t>0&&e<this.width-1&&t<this.height-1}get(e,t){return this.inside(e,t)?this.terrain[this.index(e,t)]:0}set(e,t,n){this.inside(e,t)&&(this.terrain[this.index(e,t)]=n)}kindAt(e,t){return this.kinds[this.get(e,t)]??zB}passable(e,t){return this.inside(e,t)&&this.kindAt(e,t).passable}transparent(e,t){return this.inside(e,t)&&this.kindAt(e,t).transparent}fillRect(e,t){for(let n=e.top;n<=e.bottom;n++)for(let r=e.left;r<=e.right;r++)this.set(r,n,t)}passableCells(){let e=[];for(let t=0;t<this.terrain.length;t++)this.kinds[this.terrain[t]]?.passable&&e.push(t);return e}toJSON(){return{width:this.width,height:this.height,shape:this.shape,terrain:[...this.terrain],rooms:this.rooms.map(e=>({...e})),...this.viewDistance===void 0?{}:{viewDistance:this.viewDistance}}}static fromJSON(t,n){let r=new e(n.width,n.height,t,0,n.shape,n.viewDistance);return r.terrain.set(n.terrain.slice(0,r.terrain.length)),r.rooms=n.rooms.map(e=>({...e})),r}};function HB(e){return{x:Math.floor((e.left+e.right)/2),y:Math.floor((e.top+e.bottom)/2)}}function UB(e,t,n=0){return!(e.right+n<t.left||t.right+n<e.left||e.bottom+n<t.top||t.bottom+n<e.top)}_e();var WB={id:`hall`,paint:(e,t,n)=>e.fillRect(t,n)};function GB(e){return Math.min(e.right-e.left+1,e.bottom-e.top+1)}function KB(e){return Math.max(e.right-e.left+1,e.bottom-e.top+1)}function qB(e,t){let n=GB(t),r=KB(t);return e.filter(e=>n>=(e.minSize??0)&&r<=(e.maxSize??1/0))}function JB(e,t){let n=qB(e,t);if(n.length===0)return null;let r=ie(n.map(e=>e.weight??1));return r===null?null:n[r]}_e();var YB=[{passable:!1,transparent:!1},{passable:!0,transparent:!0}];function XB(e){let{width:t,height:n,rooms:r=14,minRoomSize:i=4,maxRoomSize:a=10,extraCorridors:o=3,wall:s=0,floor:c=1,kinds:l=[],hooks:u,builders:d}=e,f=new VB(t,n,[...YB,...l],s,e.shape),p=[],m=[],h=[],g=0;for(let e=0;e<r*6&&p.length<r;e++){let e=ne(i,a),r=ne(i,a),o=O(1,Math.max(2,t-e-1)),s=O(1,Math.max(2,n-r-1)),l={left:o,top:s,right:o+e-1,bottom:s+r-1};if(l.right>=t-1||l.bottom>=n-1||p.some(e=>UB(l,e,2))){g++;continue}p.push(l);let m=(d?.length?JB(d,l):null)??WB;m.paint(f,l,c),h.push(m.id),u?.onRoomPlaced?.(l,p.length-1)}for(let e=1;e<p.length;e++){QB(f,HB(p[e-1]),HB(p[e]),c);let t={a:e-1,b:e,extra:!1};m.push(t),u?.onCorridorCarved?.(t,p[e-1],p[e])}for(let e=0;e<o&&p.length>2;e++){let e=O(p.length),t=O(p.length);if(e!==t){QB(f,HB(p[e]),HB(p[t]),c);let n={a:e,b:t,extra:!0};m.push(n),u?.onCorridorCarved?.(n,p[e],p[t])}}return f.rooms=p,{level:f,graph:m,retries:g,roomBuilders:h}}function ZB(e){return XB(e).level}function QB(e,t,n,r){let i=A(.5);if(e.shape===`hex`){let a=i?{x:n.x,y:t.y}:{x:t.x,y:n.y};for(let i of[...Zn(t,a),...Zn(a,n)])e.insideWithBorder(i.x,i.y)&&e.set(i.x,i.y,r)}else i?($B(e,t.x,n.x,t.y,!0,r),$B(e,t.y,n.y,n.x,!1,r)):($B(e,t.y,n.y,t.x,!1,r),$B(e,t.x,n.x,n.y,!0,r))}function $B(e,t,n,r,i,a){let o=t<=n?1:-1;for(let s=t;s!==n+o;s+=o){let t=i?s:r,n=i?r:s;e.insideWithBorder(t,n)&&e.set(t,n,a)}}function eV(e,t=new Set){let n=e.passableCells().filter(e=>!t.has(e));return n.length>0?n[O(n.length)]:null}function tV(e,t){let n=null,r=-1;for(let i of e.rooms){let a=HB(i),o=e.shape===`hex`?Yn(a,t):(a.x-t.x)**2+(a.y-t.y)**2;o>r&&(r=o,n=i)}return n}_e();function nV(e,t){return[[e,t-1],[e,t+1],[e-1,t],[e+1,t]]}function rV(e,t){return Jn(e,t).map(e=>[e.x,e.y])}var iV=2/Math.sqrt(3);function aV(e,t,n,r){let i=$n(e,t,iV,1),a=$n(n,r,iV,1);return(i.x-a.x)**2+(i.y-a.y)**2}function oV(e){let{width:t,height:n}=e;if(t<5||n<5)throw Error(`a cave needs at least 5x5 cells`);if(e.chambers.length<1)throw Error(`a cave needs at least one chamber`);let r=e.wall??0,i=e.floor??1,a=e.kinds??[],o=e.shape??`square`,s=o===`hex`,c=s?rV:nV,l=(e,t,n,r)=>s?Yn({x:e,y:t},{x:n,y:r}):Math.abs(e-n)+Math.abs(t-r),u=(e,t,n,r)=>s?aV(e,t,n,r):(e-n)**2+(t-r)**2;if(e.random===void 0&&e.seed===void 0)throw Error(`a cave needs a seed or a random source`);let d=e.random,f=e=>O(e,void 0,d),p=new VB(t,n,[...YB,...a],r,o),m=(e,n)=>n*t+e,h=(e,t)=>p.insideWithBorder(e,t),g=new Uint8Array(t*n),_=(e,t)=>{h(e,t)&&(g[m(e,t)]=1)};d===void 0&&w(e.seed);try{let r=new Map,a=new Map;for(let i of e.chambers){if(i.size<1)throw Error(`cave chamber ${i.id} needs at least one cell`);let e=ne(Math.max(1,i.xRange[0]),Math.min(t-2,i.xRange[1]),d),o=ne(Math.max(1,i.yRange[0]),Math.min(n-2,i.yRange[1]),d);r.set(i.id,{x:e,y:o});let s=[{x:e,y:o}],u=new Set([m(e,o)]),p=[],g=(e,t)=>{for(let[n,r]of c(e,t))h(n,r)&&!u.has(m(n,r))&&(u.add(m(n,r)),p.push([n,r]))};for(g(e,o);s.length<i.size&&p.length;){let t=0;if(f(100)<(i.jagged??0))t=f(p.length);else{let n=1/0;for(let r=0;r<p.length;r++){let i=l(p[r][0],p[r][1],e,o);i<n&&(n=i,t=r)}}let[n,r]=p.splice(t,1)[0];s.push({x:n,y:r}),g(n,r)}for(let e of s)_(e.x,e.y);a.set(i.id,s)}let o=(e,r,i,a)=>{let o=e.x,s=e.y;for(let e=0;e<t*n&&(o!==r.x||s!==r.y);e++){if(_(o,s),i>1)for(let[e,t]of c(o,s).slice(0,i-1))_(e,t);let e=c(o,s).filter(([e,t])=>h(e,t)),t=e[0];if(f(100)<a)t=e[f(e.length)];else{let n=1/0;for(let i of e){let e=u(i[0],i[1],r.x,r.y);e<n&&(n=e,t=i)}}[o,s]=t}_(r.x,r.y)};for(let t of e.chambers)for(let e of t.passages){let n=r.get(t.id),i=r.get(e.to);if(!n||!i)throw Error(`cave passage ${t.id} -> ${e.to} names no chamber`);f(100)>=(e.chance??100)||o(n,i,Math.max(1,e.width??1),e.windiness??0)}let s=e.mustBeClear??[];for(let e of s){_(e.x,e.y);for(let[t,n]of c(e.x,e.y))_(t,n)}let v=r.get(e.chambers[0].id);if(v){let e=()=>{let e=new Set([m(v.x,v.y)]),t=[[v.x,v.y]];for(;t.length;){let[n,r]=t.pop();for(let[i,a]of c(n,r))h(i,a)&&g[m(i,a)]&&!e.has(m(i,a))&&(e.add(m(i,a)),t.push([i,a]))}return e};for(let t of[...r.values(),...s])h(t.x,t.y)&&!e().has(m(t.x,t.y))&&o(t,v,1,15)}let y=new Set,b=[];for(let t of e.starts??[]){let e=r.get(t.chamber);if(!e)throw Error(`cave start ${t.side} names no chamber`);if(_(e.x,e.y),y.add(m(e.x,e.y)),t.ring)for(let[t,n]of c(e.x,e.y))h(t,n)&&(_(t,n),y.add(m(t,n)));b.push({side:t.side,x:e.x,y:e.y})}let x=[],S=e.villageDensity??0;if(S>0){let e=[];for(let t=0;t<g.length;t++)g[t]&&!y.has(t)&&e.push(t);let n=Math.floor(e.length*S/1e3);for(let r=0;r<n&&e.length;r++){let n=f(e.length),r=e.splice(n,1)[0];x.push({x:r%t,y:Math.floor(r/t)})}}for(let e=0;e<g.length;e++)g[e]&&p.set(e%t,Math.floor(e/t),i);return{level:p,chambers:[...a.entries()].map(([e,t])=>({id:e,centre:r.get(e),cells:t})),starts:b,villages:x}}finally{d===void 0&&T()}}_e();function sV(e,t,n,r,i){let a=e=>Math.max(2,Math.ceil(e/r)+2),o=a(t),s=a(n),c=new Float64Array(o*s);for(let t=0;t<c.length;t++)c[t]=e();let l=e=>e*e*(3-2*e),u=Array(t*n).fill(0);for(let e=0;e<3;e++){let a=1<<e,d=1/(a*a);for(let e=0;e<n;e++)for(let n=0;n<t;n++){let f=(i?n*cV:n)/r*a,p=(i?e+(n&1)/2:e)/r*a,m=Math.floor(f)%(o-1),h=Math.floor(p)%(s-1),g=l(f-Math.floor(f)),_=l(p-Math.floor(p)),v=(e,t)=>c[(h+t)%s*o+(m+e)%o],y=v(0,0)*(1-g)+v(1,0)*g,b=v(0,1)*(1-g)+v(1,1)*g;u[e*t+n]+=(y*(1-_)+b*_)*d}}for(let e=0;e<u.length;e++)u[e]/=1.3125;return u}var cV=Math.sqrt(3)/2,lV=[[0,-1],[0,1],[-1,0],[1,0],[-1,-1],[1,-1],[-1,1],[1,1]];function uV(e,t,n,r){if(e)for(let e of Jn(t,n))r(e.x,e.y,!1);else for(let[e,i]of lV)r(t+e,n+i,e!==0&&i!==0)}var dV={plains:1,forest:3,hills:5,desert:2,swamp:6,water:24,mountains:40};function fV(e){let{width:t,height:n}=e;if(t<16||n<16)throw Error(`an overworld needs at least 16x16 tiles`);let r=e.seaLevel??.4;if(!(r>0&&r<1))throw Error(`seaLevel must be between 0 and 1`);let i=e.noiseScale??6,a=e.shape===`hex`,o=(e,n)=>n*t+e,s=(e,r)=>e>=0&&r>=0&&e<t&&r<n;w(e.seed);try{let c=sV(()=>D(),t,n,i,a),l=sV(()=>D(),t,n,i*1.5,a),u=Array(t*n),d=(e,t)=>{let n=o(e,t),i=c[n],a=l[n];return i<r?`water`:i>.78?`mountains`:i>.62?`hills`:a<.3?`desert`:a>.72?i<r+.08?`swamp`:`forest`:`plains`};for(let e=0;e<n;e++)for(let n=0;n<t;n++)u[o(n,e)]=d(n,e);let f=new Set,p=[],m=e.rivers??Math.max(1,Math.floor(t*n/600)),h=[];for(let e=0;e<u.length;e++)c[e]>.7&&u[e]!==`water`&&h.push(e);for(let e=0;e<m*4&&p.length<m&&h.length!==0;e++){let e=h[O(h.length)],r=[],i=e%t,l=Math.floor(e/t),d=new Set;for(let e=0;e<t+n;e++){let e=o(i,l);if(f.has(e)||u[e]===`water`){r.length>0&&r.push({x:i,y:l});break}r.push({x:i,y:l}),d.add(e);let t;if(uV(a,i,l,(e,n)=>{if(!s(e,n))return;let r={x:e,y:n,up:c[o(e,n)]};(!t||r.up<t.up)&&(t=r)}),!t||t.up>=c[o(i,l)]){u[o(i,l)]=`water`;break}[i,l]=[t.x,t.y]}if(r.length>=2){for(let e of r)f.add(o(e.x,e.y));p.push(r)}}let g=[],_=(e,t)=>{if(a)return Qn({x:e,y:t},3).some(e=>s(e.x,e.y)&&u[o(e.x,e.y)]===`water`);for(let n=-3;n<=3;n++)for(let r=-3;r<=3;r++){let i=e+r,a=t+n;if(s(i,a)&&u[o(i,a)]===`water`)return!0}return!1},v=(e,t,n)=>g.every(r=>(a?Yn(r,{x:e,y:t}):Math.abs(r.x-e)+Math.abs(r.y-t))>=n),y=e.settlements??Math.max(2,Math.floor(t*n/500));for(let e=0;e<y*60&&g.length<y;e++){let e=O(t),r=O(n),i=u[o(e,r)];i!==`plains`&&i!==`hills`&&i!==`forest`||!_(e,r)||v(e,r,8)&&g.push({x:e,y:r,kind:i===`hills`?`castle`:`town`})}for(let e of g)e.kind===`town`&&O(2)===0&&(e.kind=`village`);let b=[],x=g[0];if(x){let e=[x],r=g.slice(1);for(;r.length;){let i;for(let o of r)for(let r of e){let e=pV(u,t,n,r,o,a);e&&(!i||e.length<i.path.length)&&(i={path:e,to:o})}if(!i)break;b.push(i.path),e.push(i.to),r.splice(r.indexOf(i.to),1)}}let S=[],C=e.pointsOfInterest??Math.max(1,Math.floor(t*n/900));for(let e=0;e<C*40&&S.length<C;e++){let e=O(t),r=O(n),i=u[o(e,r)];if(i===`water`||i===`mountains`||!v(e,r,6))continue;let a=[`ruin`,`shrine`,`dungeon`],s=a[O(a.length)];S.push({x:e,y:r,kind:s,leadsTo:`overworld-${s}-${S.length}`})}let ee=Math.max(2,e.regionSize??12),w=Math.ceil(t/ee),T=Array(t*n);for(let e=0;e<n;e++)for(let n=0;n<t;n++)T[o(n,e)]=Math.floor(e/ee)*w+Math.floor(n/ee);return{terrain:u,elevation:c,moisture:l,rivers:p,roads:b,settlements:g,pointsOfInterest:S,regions:T,regionColumns:w}}finally{T()}}function pV(e,t,n,r,i,a){let o=(e,n)=>n*t+e,s=(e,r)=>e>=0&&r>=0&&e<t&&r<n,c=t*n,l=new Float64Array(c).fill(1/0),u=new Int32Array(c).fill(-1),d=o(r.x,r.y),f=o(i.x,i.y);l[d]=0;let p=[d],m=new Uint8Array(c),h=e=>{for(;;){let t=e*2+1,n=t+1,r=e;if(t<p.length&&l[p[t]]<l[p[r]]&&(r=t),n<p.length&&l[p[n]]<l[p[r]]&&(r=n),r===e)return;[p[e],p[r]]=[p[r],p[e]],e=r}},g=()=>{let e=p[0],t=p.pop();return p.length&&(p[0]=t,h(0)),m[e]=0,e},_=e=>{p.push(e),m[e]=1;let t=p.length-1;for(;t>0;){let e=t-1>>1;if(l[p[e]]<=l[p[t]])break;[p[t],p[e]]=[p[e],p[t]],t=e}};for(;p.length;){let n=g();if(n===f){let e=[];for(let n=f;n!==-1;n=u[n])e.push({x:n%t,y:Math.floor(n/t)});return e.reverse()}uV(a,n%t,Math.floor(n/t),(t,r,i)=>{if(!s(t,r))return;let a=o(t,r);if(l[n]===1/0)return;let c=dV[e[a]]*(i?1.5:1);l[n]+c<l[a]&&(l[a]=l[n]+c,u[a]=n,m[a]||_(a))})}}var mV=class e{constructor(){this.defs=new Map,this.placed=new Map}define(e,t){this.defs.set(e,t)}place(e,t){if(!this.defs.has(t))throw Error(`FeatureLayer.place: no definition for kind "${t}"`);this.placed.set(e,t)}has(e){return this.placed.has(e)}kindAt(e){return this.placed.get(e)}remove(e){this.placed.delete(e)}inspect(e,t){this.defAt(e)?.inspect?.(e,t)}interact(e,t){let n=this.defAt(e);n&&(n.interact&&n.interact(e,t)===!1||(n.consequence?.(e,t),n.persistent===!1&&this.remove(e)))}defAt(e){let t=this.placed.get(e);return t===void 0?void 0:this.defs.get(t)}toJSON(){return{cells:[...this.placed.entries()]}}static fromJSON(t,n){let r=new e;for(let[e,n]of t)r.define(e,n);for(let[e,t]of n.cells)r.place(e,t);return r}};_e();function hV(e,t=[],n=!0){let r=[],i=e.map(e=>e.value);t.forEach((e,t)=>{if(e.enabled===!1){r.push({step:`rare`,index:t,outcome:`deferred`});return}let n=A(e.chance);r.push({step:`rare`,index:t,outcome:n?`added`:`skipped`}),n&&i.push(e.value)});for(let t=0;t<e.length;t++){let n=e[t].alternative;if(!n)continue;let a=A(n.chance);r.push({step:`alternative`,index:t,outcome:a?`swapped`:`kept`}),a&&(i[t]=n.value)}return n&&(oe(i),r.push({step:`shuffle`,index:-1,outcome:`shuffled`})),{roster:i,trace:r}}function gV(e,t){return e.length===t.length&&e.every((e,n)=>e.a===t[n].a&&e.b===t[n].b&&e.extra===t[n].extra)}function _V(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function vV(e,t){if(e.length!==t.length)return!1;let n=[...e].sort((e,t)=>e[0]-t[0]),r=[...t].sort((e,t)=>e[0]-t[0]);return n.every(([e,t],n)=>e===r[n][0]&&t===r[n][1])}function yV(e,t){let n=[];return e.retries!==t.retries&&n.push({stage:`graph`,field:`retries`,expected:e.retries,actual:t.retries}),gV(e.graph,t.graph)||n.push({stage:`graph`,field:`graph`,expected:e.graph,actual:t.graph}),(e.width!==t.width||e.height!==t.height||!_V(e.terrain,t.terrain))&&n.push({stage:`paint`,field:`terrain`,expected:e.terrain,actual:t.terrain}),(e.roomBuilders.length!==t.roomBuilders.length||e.roomBuilders.some((e,n)=>e!==t.roomBuilders[n]))&&n.push({stage:`paint`,field:`roomBuilders`,expected:e.roomBuilders,actual:t.roomBuilders}),vV(e.features,t.features)||n.push({stage:`paint`,field:`features`,expected:e.features,actual:t.features}),JSON.stringify(e.content)!==JSON.stringify(t.content)&&n.push({stage:`paint`,field:`content`,expected:e.content,actual:t.content}),e.rngDraws!==t.rngDraws&&n.push({stage:`paint`,field:`rngDraws`,expected:e.rngDraws,actual:t.rngDraws}),n}function bV(e,t=2){let n=e(),r=[];for(let i=1;i<t;i++)r.push(...yV(n,e()));return r}var xV=23283064365386963e-26;new class e{constructor(){this._seed=0,this._s0=0,this._s1=0,this._s2=0,this._c=0}getSeed(){return this._seed}setSeed(e){return e=e<1?1/e:e,this._seed=e,this._s0=(e>>>0)*xV,e=e*69069+1>>>0,this._s1=e*xV,e=e*69069+1>>>0,this._s2=e*xV,this._c=1,this}getUniform(){let e=2091639*this._s0+this._c*xV;return this._s0=this._s1,this._s1=this._s2,this._c=e|0,this._s2=e-this._c,this._s2}getUniformInt(e,t){let n=Math.max(e,t),r=Math.min(e,t);return Math.floor(this.getUniform()*(n-r+1))+r}getNormal(e=0,t=1){let n,r,i;do n=2*this.getUniform()-1,r=2*this.getUniform()-1,i=n*n+r*r;while(i>1||i==0);return e+n*Math.sqrt(-2*Math.log(i)/i)*t}getPercentage(){return 1+Math.floor(this.getUniform()*100)}getItem(e){return e.length?e[Math.floor(this.getUniform()*e.length)]:null}shuffle(e){let t=[],n=e.slice();for(;n.length;){let e=n.indexOf(this.getItem(n));t.push(n.splice(e,1)[0])}return t}getWeightedValue(e){let t=0;for(let n in e)t+=e[n];let n=this.getUniform()*t,r,i=0;for(r in e)if(i+=e[r],n<i)return r;return r}getState(){return[this._s0,this._s1,this._s2,this._c]}setState(e){return this._s0=e[0],this._s1=e[1],this._s2=e[2],this._c=e[3],this}clone(){return new e().setState(this.getState())}}().setSeed(Date.now());var SV=class{getContainer(){return null}setOptions(e){this._options=e}},CV=class extends SV{constructor(){super(),this._ctx=document.createElement(`canvas`).getContext(`2d`)}schedule(e){requestAnimationFrame(e)}getContainer(){return this._ctx.canvas}setOptions(e){super.setOptions(e);let t=`${e.fontStyle?`${e.fontStyle} `:``} ${e.fontSize}px ${e.fontFamily}`;this._ctx.font=t,this._updateSize(),this._ctx.font=t,this._ctx.textAlign=`center`,this._ctx.textBaseline=`middle`}clear(){let e=this._ctx.globalCompositeOperation;this._ctx.globalCompositeOperation=`copy`,this._ctx.fillStyle=this._options.bg,this._ctx.fillRect(0,0,this._ctx.canvas.width,this._ctx.canvas.height),this._ctx.globalCompositeOperation=e}eventToPosition(e,t){let n=this._ctx.canvas,r=n.getBoundingClientRect();return e-=r.left,t-=r.top,e*=n.width/r.width,t*=n.height/r.height,e<0||t<0||e>=n.width||t>=n.height?[-1,-1]:this._normalizedEventToPosition(e,t)}};function wV(e){return e.charAt(0).toUpperCase()+e.substring(1)}function TV(e,...t){let n=TV.map;return e.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi,function(r,i,a,o){if(e.charAt(o-1)==`%`)return r.substring(1);if(!t.length)return r;let s=t[0],c=(i||a).split(`,`),l=c.shift()||``,u=n[l.toLowerCase()];if(!u)return r;s=t.shift();let d=s[u].apply(s,c),f=l.charAt(0);return f!=f.toLowerCase()&&(d=wV(d)),d})}TV.map={s:`toString`};var EV=class e extends CV{constructor(){super(),this._spacingX=0,this._spacingY=0,this._canvasCache={}}setOptions(e){super.setOptions(e),this._canvasCache={}}draw(t,n){e.cache?this._drawWithCache(t):this._drawNoCache(t,n)}_drawWithCache(e){let[t,n,r,i,a]=e,o=``+r+i+a,s;if(o in this._canvasCache)s=this._canvasCache[o];else{let e=this._options.border;s=document.createElement(`canvas`);let t=s.getContext(`2d`);if(s.width=this._spacingX,s.height=this._spacingY,t.fillStyle=a,t.fillRect(e,e,s.width-e,s.height-e),r){t.fillStyle=i,t.font=this._ctx.font,t.textAlign=`center`,t.textBaseline=`middle`;let e=[].concat(r);for(let n=0;n<e.length;n++)t.fillText(e[n],this._spacingX/2,Math.ceil(this._spacingY/2))}this._canvasCache[o]=s}this._ctx.drawImage(s,t*this._spacingX,n*this._spacingY)}_drawNoCache(e,t){let[n,r,i,a,o]=e;if(t){let e=this._options.border;this._ctx.fillStyle=o,this._ctx.fillRect(n*this._spacingX+e,r*this._spacingY+e,this._spacingX-e,this._spacingY-e)}if(!i)return;this._ctx.fillStyle=a;let s=[].concat(i);for(let e=0;e<s.length;e++)this._ctx.fillText(s[e],(n+.5)*this._spacingX,Math.ceil((r+.5)*this._spacingY))}computeSize(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}computeFontSize(e,t){let n=Math.floor(e/this._options.width),r=Math.floor(t/this._options.height),i=this._ctx.font;this._ctx.font=`100px `+this._options.fontFamily;let a=Math.ceil(this._ctx.measureText(`W`).width);this._ctx.font=i;let o=a/100*r/n;return o>1&&(r=Math.floor(r/o)),Math.floor(r/this._options.spacing)}_normalizedEventToPosition(e,t){return[Math.floor(e/this._spacingX),Math.floor(t/this._spacingY)]}_updateSize(){let e=this._options,t=Math.ceil(this._ctx.measureText(`W`).width);this._spacingX=Math.ceil(e.spacing*t),this._spacingY=Math.ceil(e.spacing*e.fontSize),e.forceSquareRatio&&(this._spacingX=this._spacingY=Math.max(this._spacingX,this._spacingY)),this._ctx.canvas.width=e.width*this._spacingX,this._ctx.canvas.height=e.height*this._spacingY}};EV.cache=!1;var DV={4:[[0,-1],[1,0],[0,1],[-1,0]],8:[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]],6:[[-1,-1],[1,-1],[2,0],[1,1],[-1,1],[-2,0]]},OV=class{constructor(e,t={}){this._lightPasses=e,this._options=Object.assign({topology:8},t)}_getCircle(e,t,n){let r=[],i,a,o;switch(this._options.topology){case 4:a=1,o=[0,1],i=[DV[8][7],DV[8][1],DV[8][3],DV[8][5]];break;case 6:i=DV[6],a=1,o=[-1,1];break;case 8:i=DV[4],a=2,o=[-1,1];break;default:throw Error(`Incorrect topology for FOV computation`)}let s=e+o[0]*n,c=t+o[1]*n;for(let e=0;e<i.length;e++)for(let t=0;t<n*a;t++)r.push([s,c]),s+=i[e][0],c+=i[e][1];return r}},kV=class extends OV{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l;for(let u=1;u<=n;u++){let n=this._getCircle(e,t,u),d=360/n.length;for(let e=0;e<n.length;e++)if(s=n[e][0],c=n[e][1],a=d*(e-.5),o=a+d,l=!this._lightPasses(s,c),this._visibleCoords(Math.floor(a),Math.ceil(o),l,i)&&r(s,c,u,1),i.length==2&&i[0]==0&&i[1]==360)return}}_visibleCoords(e,t,n,r){if(e<0){let i=this._visibleCoords(0,t,n,r),a=this._visibleCoords(360+e,360,n,r);return i||a}let i=0;for(;i<r.length&&r[i]<e;)i++;if(i==r.length)return n&&r.push(e,t),!0;let a=0;if(i%2){for(;i<r.length&&r[i]<t;)i++,a++;return a!=0&&(n&&(a%2?r.splice(i-a,a,t):r.splice(i-a,a)),!0)}for(;i<r.length&&r[i]<t;)i++,a++;return e==r[i-a]&&a==1?!1:(n&&(a%2?r.splice(i-a,a,e):r.splice(i-a,a,e,t)),!0)}},AV=class extends OV{compute(e,t,n,r){if(r(e,t,0,1),!this._lightPasses(e,t))return;let i=[],a,o,s,c,l,u;for(let d=1;d<=n;d++){let n=this._getCircle(e,t,d),f=n.length;for(let e=0;e<f;e++)if(a=n[e][0],o=n[e][1],c=[e?2*e-1:2*f-1,2*f],l=[2*e+1,2*f],s=!this._lightPasses(a,o),u=this._checkVisibility(c,l,s,i),u&&r(a,o,d,u),i.length==2&&i[0][0]==0&&i[1][0]==i[1][1])return}}_checkVisibility(e,t,n,r){if(e[0]>t[0])return(this._checkVisibility(e,[e[1],e[1]],n,r)+this._checkVisibility([0,1],t,n,r))/2;let i=0,a=!1;for(;i<r.length;){let t=r[i],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&!(i%2)&&(a=!0);break}i++}let o=r.length,s=!1;for(;o--;){let e=r[o],n=t[0]*e[1]-e[0]*t[1];if(n>=0){n==0&&o%2&&(s=!0);break}}let c=!0;if((i==o&&(a||s)||a&&s&&i+1==o&&o%2||i>o&&i%2)&&(c=!1),!c)return 0;let l,u=o-i+1;if(u%2){if(i%2){let e=r[i];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,t)}else{let t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u,e)}}else if(i%2){let e=r[i],t=r[o];l=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]),n&&r.splice(i,u)}else return n&&r.splice(i,u,e,t),1;let d=(t[0]*e[1]-e[0]*t[1])/(e[1]*t[1]);return l/d}},jV=[[-1,0,0,1],[0,-1,1,0],[0,-1,-1,0],[-1,0,0,-1],[1,0,0,-1],[0,1,-1,0],[0,1,1,0],[1,0,0,1]],MV={DiscreteShadowcasting:kV,PreciseShadowcasting:AV,RecursiveShadowcasting:class extends OV{compute(e,t,n,r){r(e,t,0,1);for(let i=0;i<jV.length;i++)this._renderOctant(e,t,jV[i],n,r)}compute180(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8,o=(r-2+8)%8,s=(r+1+8)%8;this._renderOctant(e,t,jV[o],n,i),this._renderOctant(e,t,jV[a],n,i),this._renderOctant(e,t,jV[r],n,i),this._renderOctant(e,t,jV[s],n,i)}compute90(e,t,n,r,i){i(e,t,0,1);let a=(r-1+8)%8;this._renderOctant(e,t,jV[r],n,i),this._renderOctant(e,t,jV[a],n,i)}_renderOctant(e,t,n,r,i){this._castVisibility(e,t,1,1,0,r+1,n[0],n[1],n[2],n[3],i)}_castVisibility(e,t,n,r,i,a,o,s,c,l,u){if(!(r<i))for(let d=n;d<=a;d++){let n=-d-1,f=-d,p=!1,m=0;for(;n<=0;){n+=1;let h=e+n*o+f*s,g=t+n*c+f*l,_=(n-.5)/(f+.5),v=(n+.5)/(f-.5);if(!(v>r)){if(_<i)break;if(n*n+f*f<a*a&&u(h,g,d,1),!p)!this._lightPasses(h,g)&&d<a&&(p=!0,this._castVisibility(e,t,d+1,r,_,a,o,s,c,l,u),m=v);else{if(!this._lightPasses(h,g)){m=v;continue}p=!1,r=m}}}if(p)break}}}};.5*(Math.sqrt(3)-1),(3-Math.sqrt(3))/6;var NV=class{constructor(e,t,n,r={}){this._toX=e,this._toY=t,this._passableCallback=n,this._options=Object.assign({topology:8},r),this._dirs=DV[this._options.topology],this._options.topology==8&&(this._dirs=[this._dirs[0],this._dirs[2],this._dirs[4],this._dirs[6],this._dirs[1],this._dirs[3],this._dirs[5],this._dirs[7]])}_getNeighbors(e,t){let n=[];for(let r=0;r<this._dirs.length;r++){let i=this._dirs[r],a=e+i[0],o=t+i[1];this._passableCallback(a,o)&&n.push([a,o])}return n}},PV={Dijkstra:class extends NV{constructor(e,t,n,r){super(e,t,n,r),this._computed={},this._todo=[],this._add(e,t,null)}compute(e,t,n){let r=e+`,`+t;if(r in this._computed||this._compute(e,t),!(r in this._computed))return;let i=this._computed[r];for(;i;)n(i.x,i.y),i=i.prev}_compute(e,t){for(;this._todo.length;){let n=this._todo.shift();if(n.x==e&&n.y==t)return;let r=this._getNeighbors(n.x,n.y);for(let e=0;e<r.length;e++){let t=r[e],i=t[0],a=t[1];i+`,`+a in this._computed||this._add(i,a,n)}}}_add(e,t,n){let r={x:e,y:t,prev:n};this._computed[e+`,`+t]=r,this._todo.push(r)}},AStar:class extends NV{constructor(e,t,n,r={}){super(e,t,n,r),this._todo=[],this._done={}}compute(e,t,n){for(this._todo=[],this._done={},this._fromX=e,this._fromY=t,this._add(this._toX,this._toY,null);this._todo.length;){let n=this._todo.shift(),r=n.x+`,`+n.y;if(r in this._done)continue;if(this._done[r]=n,n.x==e&&n.y==t)break;let i=this._getNeighbors(n.x,n.y);for(let e=0;e<i.length;e++){let t=i[e],r=t[0],a=t[1];r+`,`+a in this._done||this._add(r,a,n)}}let r=this._done[e+`,`+t];if(r)for(;r;)n(r.x,r.y),r=r.prev}_add(e,t,n){let r=this._distance(e,t),i={x:e,y:t,prev:n,g:n?n.g+1:0,h:r},a=i.g+i.h;for(let e=0;e<this._todo.length;e++){let t=this._todo[e],n=t.g+t.h;if(a<n||a==n&&r<t.h){this._todo.splice(e,0,i);return}}this._todo.push(i)}_distance(e,t){switch(this._options.topology){case 4:return Math.abs(e-this._fromX)+Math.abs(t-this._fromY);case 6:let n=Math.abs(e-this._fromX),r=Math.abs(t-this._fromY);return r+Math.max(0,(n-r)/2);case 8:return Math.max(Math.abs(e-this._fromX),Math.abs(t-this._fromY))}}}};function FV(e,t){return dr(e,t)}function IV(e,t){let n=[],r=e.x,i=e.y,a=Math.abs(t.x-e.x),o=-Math.abs(t.y-e.y),s=e.x<t.x?1:-1,c=e.y<t.y?1:-1,l=a+o;for(;n.push({x:r,y:i}),r!==t.x||i!==t.y;){let e=l*2;e>=o&&(l+=o,r+=s),e<=a&&(l+=a,i+=c)}return n}function LV(e,t,n,r={}){let i=e.shape===`hex`?Zn(t,n):IV(t,n),a=r.stop??`opaque`,o=[],s=null;for(let t of i)if(o.push(t),o.length!==1&&a!==`none`&&(a===`outside`&&!e.inside(t.x,t.y)||a===`opaque`&&e.inside(t.x,t.y)&&!e.transparent(t.x,t.y)||a===`impassable`&&e.inside(t.x,t.y)&&!e.passable(t.x,t.y))){s=t;break}return{cells:o,stop:s}}function RV(e,t,n){let r=e.shape===`hex`?Zn(t,n):IV(t,n);for(let t=1;t<r.length-1;t++)if(!e.transparent(r[t].x,r[t].y))return!1;return!0}function zV(e,t,n,r){return!((e.shape===`hex`?Yn(t,n):FV(t,n))>r.range||(r.requireLineOfSight??!0)&&!RV(e,t,n))}function BV(e,t,n){switch(n.kind){case`single`:return[t];case`line`:return IV(e,t);case`cone`:return UV(e,t,n.width);case`burst`:{let e=[],r=n.radius;for(let n=-r;n<=r;n++)for(let i=-r;i<=r;i++)i*i+n*n>r*r||e.push({x:t.x+i,y:t.y+n});return e}}}function VV(e,t,n,r){return e.shape===`hex`?r.kind===`single`?[{...n}]:r.kind===`line`?Zn(t,n):r.kind===`burst`?Qn(n,r.radius):HV(t,n,r.width):BV(t,n,r)}function HV(e,t,n){let r=Yn(e,t);if(r===0)return[{...e}];let i=Zn(e,t),a=[];for(let t=1;t<=r;t++){let o=i[t],s=Math.round(t/r*n);for(let n of Qn(o,s))Yn(e,n)===t&&a.push(n)}return a}function UV(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.max(Math.abs(r),Math.abs(i));if(a===0)return[{...e}];let o=Math.sign(r),s=Math.sign(i),c=r!==0&&i!==0?o:s,l=r!==0&&i!==0?-s:o,u=[];for(let t=1;t<=a;t++){let r=e.x+o*t,i=e.y+s*t,d=Math.round(t/a*n);for(let e=-d;e<=d;e++)u.push({x:r+c*e,y:i+l*e})}return u}var WV=.5;function GV(e){return e<0?-Math.round(-e):Math.round(e)}function KV(e,t,n,r){if(!Number.isFinite(r.degrees)||r.degrees<0)throw Error(`a cone sector needs a finite non-negative angle in degrees`);if(!Number.isFinite(r.range)||r.range<0)throw Error(`a cone sector needs a finite non-negative range`);let i=n.x-t.x,a=n.y-t.y;if(i===0&&a===0)return[{...t}];let o=Math.atan2(a,i),s=r.degrees*Math.PI/360,c=Math.max(1,Math.round(r.degrees/WV)),l=r.stop??`opaque`,u=new Set,d=[];for(let n=0;n<=c;n++){let i=o-s+2*s*n/c,a={x:t.x+GV(Math.cos(i)*r.range),y:t.y+GV(Math.sin(i)*r.range)};for(let n of LV(e,t,a,{stop:l}).cells){if(n.x===t.x&&n.y===t.y||!e.inside(n.x,n.y))continue;let r=e.index(n.x,n.y);u.has(r)||(u.add(r),d.push({x:n.x,y:n.y}))}}return d}function qV(e,t,n,r){let i=new Set,a=[],o=t;for(let t=0;t<n;t++){let t=-1,n=r+1;for(let a=0;a<e.length;a++){if(i.has(a))continue;let s=FV(o,e[a]);s<=r&&s<n&&(n=s,t=a)}if(t===-1)break;i.add(t),a.push(e[t]),o=e[t]}return a}function JV(e,t,n=1){for(let n of t)if(e<=n.max)return n.multiplier;return n}function YV(e,t){return t.length===0?1:t[Math.min(e,t.length-1)]}function XV(e,t,n,r){let i=[];for(let a=1;a<=r;a++){let r={x:t.x+n.x*a,y:t.y+n.y*a};if(!e.passable(r.x,r.y))break;i.push(r)}return i}var ZV=class{constructor(e,t){if(this.onMove=new p,this.onConfirm=new p,this.onCancel=new p,!Number.isFinite(t.range)||t.range<0)throw Error(`targeting range must be a finite non-negative number`);this.level=e,this.origin={...t.origin},this.range=t.range,this.requireLineOfSight=t.requireLineOfSight??!0,this.validate=t.validate,this.shape=t.shape??{kind:`single`},this.cursor={...t.cursor??t.origin}}get target(){return{...this.cursor}}get distance(){return this.level.shape===`hex`?Yn(this.origin,this.cursor):FV(this.origin,this.cursor)}get inRange(){return this.distance<=this.range}get inSight(){return RV(this.level,this.origin,this.cursor)}get valid(){return!this.inRange||this.requireLineOfSight&&!this.inSight?!1:!this.validate||this.validate(this.cursor)}move(e,t){if(this.level.shape===`hex`){let n=this.level.neighbors(this.cursor.x,this.cursor.y).find(n=>n.x-this.cursor.x===e&&n.y-this.cursor.y===t);n&&this.moveTo(n)}else this.moveTo({x:this.cursor.x+e,y:this.cursor.y+t})}moveTo(e){this.level.inside(e.x,e.y)&&(this.cursor={x:e.x,y:e.y},this.onMove.dispatch({...this.cursor}))}setShape(e){this.shape=e}preview(){return this.valid?VV(this.level,this.origin,this.cursor,this.shape):[]}confirm(){if(!this.valid)return null;let e={origin:{...this.origin},target:{...this.cursor},shape:this.shape,cells:this.preview()};return this.onConfirm.dispatch(e),e}cancel(){this.onCancel.dispatch()}},QV=class{constructor(e){this.visible=new Set,this.explored=new Set,this.light=new Map,this.level=e,this.fov=e.shape===`hex`?null:new MV.PreciseShadowcasting((t,n)=>e.transparent(t,n))}update(e,t,n=this.level.viewDistance??Math.max(this.level.width,this.level.height),r){if(this.visible.clear(),this.light.clear(),r){this.updateFromHeight(e,t,n,r);return}if(this.fov){this.fov.compute(e,t,n,(e,t,n,r)=>{if(!this.level.inside(e,t))return;let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r)});return}let i={x:e,y:t};for(let e of Qn(i,n)){if(!this.level.inside(e.x,e.y))continue;let t=Zn(i,e);t.slice(1,-1).some(e=>!this.level.inside(e.x,e.y)||!this.level.transparent(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}}lightCell(e,t,n,r){let i=this.level.index(e,t);this.visible.add(i),this.explored.add(i),this.light.set(i,r===0?1:Math.max(0,1-n/(r+1)))}updateFromHeight(e,t,n,r){let i=r.height??r.heights.heightAt(e,t),a={x:e,y:t};if(this.level.shape===`hex`)for(let e of Qn(a,n)){if(!this.level.inside(e.x,e.y))continue;let t=Zn(a,e);this.heightBlocked(t,r.heights,i,r.heights.heightAt(e.x,e.y))||this.lightCell(e.x,e.y,t.length-1,n)}else for(let o=t-n;o<=t+n;o++)for(let t=e-n;t<=e+n;t++){if(!this.level.inside(t,o)||FV(a,{x:t,y:o})>n)continue;let e=IV(a,{x:t,y:o});this.heightBlocked(e,r.heights,i,r.heights.heightAt(t,o))||this.lightCell(t,o,e.length-1,n)}}heightBlocked(e,t,n,r){let i=Math.max(n,r);for(let n=1;n<e.length-1;n++){let r=e[n];if(!this.level.inside(r.x,r.y)||!this.level.transparent(r.x,r.y)||t.heightAt(r.x,r.y)>i)return!0}return!1}isVisible(e,t){return this.visible.has(this.level.index(e,t))}isExplored(e,t){return this.explored.has(this.level.index(e,t))}lightAt(e,t){return this.light.get(this.level.index(e,t))??0}reset(){this.visible.clear(),this.explored.clear(),this.light.clear()}revealAll(){for(let e=0;e<this.level.cellCount;e++)this.explored.add(e)}},$V=class{constructor(e){this.level=e,this.heights=new Int32Array(e.cellCount)}heightAt(e,t){return this.level.inside(e,t)?this.heights[this.level.index(e,t)]:0}set(e,t,n){if(!Number.isInteger(n))throw Error(`a cell's height must be a whole number, got ${n}`);this.level.inside(e,t)&&(this.heights[this.level.index(e,t)]=n)}},eH=class{constructor(e){this.level=e}passable(e){let t=e.blocked;return(e,n)=>this.level.passable(e,n)?!t?.has(this.level.index(e,n)):!1}stepper(e){let t=this.passable(e),n=e.heights;if(!n)return(e,n,r,i)=>this.level.inside(e,n)&&this.level.inside(r,i)&&t(r,i);let r=e.climb??1;if(!Number.isInteger(r)||r<0)throw Error(`a climb limit must be a non-negative whole number, got ${e.climb}`);return(e,i,a,o)=>this.level.inside(e,i)&&this.level.inside(a,o)&&t(a,o)&&n.heightAt(a,o)-n.heightAt(e,i)<=r}find(e,t,n={}){if(this.level.shape===`hex`||n.heights){let r=this.distanceMap(t,n),i=[],a=e;for(let e=0;e<this.level.cellCount;e++){let e=this.descend(a,r,n);if(!e||(i.push(e),e.x===t.x&&e.y===t.y))break;a=e}return i}let r=new PV.AStar(t.x,t.y,this.passable(n),{topology:n.topology??8}),i=[];return r.compute(e.x,e.y,(e,t)=>i.push({x:e,y:t})),i.slice(1)}step(e,t,n={}){return this.find(e,t,n)[0]??null}distanceMap(e,t={}){let n=new Int32Array(this.level.cellCount).fill(-1),r=this.passable(t),i=this.stepper(t);if(!r(e.x,e.y))return n;let a=[this.level.index(e.x,e.y)];n[a[0]]=0;for(let e=0;e<a.length;e++){let r=a[e],o=this.level.xOf(r),s=this.level.yOf(r),c=n[r]+1;this.level.forEachNeighbor(o,s,t.topology??8,(e,t)=>{if(!i(e,t,o,s))return;let r=this.level.index(e,t);n[r]===-1&&(n[r]=c,a.push(r))})}return n}descend(e,t,n={}){let r=this.stepper(n),i=t[this.level.index(e.x,e.y)];if(i<=0)return null;let a=null,o=i;return this.level.forEachNeighbor(e.x,e.y,n.topology??8,(n,i)=>{if(!r(e.x,e.y,n,i))return;let s=t[this.level.index(n,i)];s!==-1&&s<o&&(o=s,a={x:n,y:i})}),a}autoExplore(e,t,n={}){let r=this.passable(n),i=this.stepper(n);if(!r(e.x,e.y))return[];let a=new Map,o=new Set([this.level.index(e.x,e.y)]),s=[e];for(let e=0;e<s.length;e++){let r=s[e];if(e>0&&!t.isExplored(r.x,r.y))return this.reconstruct(a,r);this.level.forEachNeighbor(r.x,r.y,n.topology??8,(e,t)=>{if(!i(r.x,r.y,e,t))return;let n=this.level.index(e,t);o.has(n)||(o.add(n),a.set(n,r),s.push({x:e,y:t}))})}return[]}reconstruct(e,t){let n=[t],r=e.get(this.level.index(t.x,t.y));for(;r;)n.push(r),r=e.get(this.level.index(r.x,r.y));return n.reverse()}},tH=class e{constructor(){this.entries=[],this.sequence=0,this.now=0}get size(){return this.entries.length}get actors(){return this.entries.map(e=>e.actor)}has(e){return this.entries.some(t=>t.actor===e)}add(e,t=0,n=e.priority??0){if(!Number.isFinite(t)||t<0)throw Error(`scheduler delay must be finite and non-negative`);if(!Number.isFinite(n))throw Error(`scheduler priority must be finite`);this.entries.push({actor:e,time:this.now+t,sequence:this.sequence++,priority:n}),this.sort()}remove(e){let t=this.entries.findIndex(t=>t.actor===e);t!==-1&&this.entries.splice(t,1)}clear(){this.entries.length=0,this.now=0,this.sequence=0}peek(){let e=this.entries[0];return e?(this.now=Math.max(this.now,e.time),e.actor):null}spend(e){let t=this.entries[0];if(!t)return;let n=t.actor.speed??1;t.time=this.now+e/(n>0?n:1),t.sequence=this.sequence++,this.sort()}postpone(e,t){let n=this.entries.find(t=>t.actor===e);n&&(n.time+=t,n.sequence=this.sequence++,this.sort())}timeOf(e){return this.entries.find(t=>t.actor===e)?.time??null}toJSON(e){return{now:this.now,sequence:this.sequence,entries:this.entries.map(t=>({id:e(t.actor),time:t.time,sequence:t.sequence,...t.priority===0?{}:{priority:t.priority}}))}}static restore(t,n){let r=new e;return r.now=t.now,r.sequence=t.sequence,r.entries=t.entries.map(e=>({actor:n(e.id),time:e.time,sequence:e.sequence,priority:e.priority??0})),r.sort(),r}sort(){this.entries.sort((e,t)=>e.time-t.time||t.priority-e.priority||e.sequence-t.sequence)}};_e();function nH(e,t,n,r,i,a={}){let o=a.sightRadius??6,s=a.fleeBelow??0;if((a.disposition??`hostile`)!==`hostile`&&a.provoked!==!0)return{state:`wander`,step:rH(e,n,a)};let c=new QV(e);return c.update(n.x,n.y,o),c.isVisible(i.x,i.y)?r<=s?{state:`flee`,step:iH(e,n,i,a)}:{state:`hunt`,step:t.step(n,i,a)}:{state:`wander`,step:rH(e,n,a)}}function rH(e,t,n){return re(aH(e,t,n))}function iH(e,t,n,r){let i=aH(e,t,r),a=null,o=oH(t,n);for(let e of i){let t=oH(e,n);t>o&&(o=t,a=e)}return a}function aH(e,t,n){let r=n.blocked,i=[];for(let[a,o]of RB(n.topology??8)){let n={x:t.x+a,y:t.y+o};e.passable(n.x,n.y)&&(r?.has(e.index(n.x,n.y))||i.push(n))}return i}function oH(e,t){return(e.x-t.x)**2+(e.y-t.y)**2}var sH=class e{constructor(e){this.revealedKind=new Map,this.discovered=new Set,this.level=e}conceal(e,t,n,r){let i=this.level.index(e,t);this.revealedKind.set(i,r),this.discovered.delete(i),this.level.set(e,t,n)}isSecret(e,t){let n=this.level.index(e,t);return this.revealedKind.has(n)&&!this.discovered.has(n)}isDiscovered(e,t){return this.discovered.has(this.level.index(e,t))}discover(e,t){if(!this.isSecret(e,t))return!1;let n=this.level.index(e,t);return this.discovered.add(n),this.level.set(e,t,this.revealedKind.get(n)),!0}toJSON(){return{revealed:[...this.revealedKind],discovered:[...this.discovered]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.revealed)r.revealedKind.set(e,t);for(let e of n.discovered)r.discovered.add(e);return r}},cH=class e{constructor(e){this.openKind=new Map,this.closedKind=new Map,this.lockedBy=new Map,this.open_=new Map,this.level=e}place(e,t,n){let r=this.level.index(e,t);this.openKind.set(r,n.open),this.closedKind.set(r,n.closed),this.open_.set(r,n.startOpen??!1),n.locked===void 0?this.lockedBy.delete(r):this.lockedBy.set(r,n.locked),this.level.set(e,t,this.open_.get(r)?n.open:n.closed)}isDoor(e,t){return this.open_.has(this.level.index(e,t))}isOpen(e,t){return this.open_.get(this.level.index(e,t))===!0}isLocked(e,t){return this.lockedBy.has(this.level.index(e,t))}requiredKey(e,t){return this.lockedBy.get(this.level.index(e,t))}open(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||this.open_.get(n)||this.lockedBy.has(n)?!1:(this.open_.set(n,!0),this.level.set(e,t,this.openKind.get(n)),!0)}close(e,t){let n=this.level.index(e,t);return!this.open_.has(n)||!this.open_.get(n)?!1:(this.open_.set(n,!1),this.level.set(e,t,this.closedKind.get(n)),!0)}unlock(e,t){let n=this.level.index(e,t);return this.lockedBy.has(n)?(this.lockedBy.delete(n),!0):!1}toJSON(){let e=[];for(let[t,n]of this.openKind)e.push({cell:t,open:n,closed:this.closedKind.get(t),locked:this.lockedBy.get(t),isOpen:this.open_.get(t)===!0});return{doors:e}}static fromJSON(t,n){let r=new e(t);for(let e of n.doors){let n=t.xOf(e.cell),i=t.yOf(e.cell);r.place(n,i,{open:e.open,closed:e.closed,locked:e.locked,startOpen:e.isOpen})}return r}},lH=class e{constructor(e=[]){this.current=0;for(let t=1;t<e.length;t++)if(e[t]>=e[t-1])throw Error(`boss phase thresholds must descend`);this.thresholds=e}get phase(){return this.current}check(e){let t=0;for(;t<this.thresholds.length&&e<=this.thresholds[t];)t++;let n=[];for(;this.current<t;)this.current++,n.push(this.current);return n}reset(){this.current=0}toJSON(){return{phase:this.current}}static fromJSON(t,n){let r=new e(t);return r.current=n.phase,r}},uH=class e{constructor(e){this.remaining=new Map,this.cooldowns=new Map(Object.entries(e))}advance(e=1){for(let[t,n]of this.remaining)n<=e?this.remaining.delete(t):this.remaining.set(t,n-e)}ready(){let e=[];for(let t of this.cooldowns.keys())this.remaining.has(t)||e.push(t);return e}use(e){let t=this.cooldowns.get(e);return t===void 0||this.remaining.has(e)?!1:(t>0&&this.remaining.set(e,t),!0)}toJSON(){return{remaining:[...this.remaining]}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.remaining)r.remaining.set(e,t);return r}},dH=class extends S{modifyDamage(e,t,n){let r={attacker:e,defender:t,amount:n,prevented:!1};return this.emit(`beforeDamage`,r),r.amount=Math.max(0,r.amount),r.amount===0&&(r.prevented=!0),r}},fH=class{constructor(e){this.detected=!1,this.radius=e.radius}get isDetected(){return this.detected}checkDetection(e,t){if(this.detected)return!1;let n=t.some(t=>FV(e,t)<=this.radius);return n&&(this.detected=!0),n}reset(){this.detected=!1}},pH=class e{constructor(e){this.streak=0,this.lastTurn=-1/0,this.window=e}get count(){return this.streak}trigger(e){return this.streak=e-this.lastTurn<=this.window?this.streak+1:1,this.lastTurn=e,this.streak}isActive(e){return e-this.lastTurn<=this.window}reset(){this.streak=0,this.lastTurn=-1/0}toJSON(){return{streak:this.streak,lastTurn:this.lastTurn}}static fromJSON(t,n){let r=new e(t);return r.streak=n.streak,r.lastTurn=n.lastTurn,r}},mH=class e{constructor(e){if(this.index=-1,this.remaining=0,e.length===0)throw Error(`a multi-stage ability needs at least one stage`);this.stages=e}get active(){return this.index>=0}get stage(){return this.index>=0?this.stages[this.index]:null}start(){return!this.active&&(this.index=0,this.remaining=this.stages[0].duration,!0)}advance(){return!this.active||(this.remaining--,this.remaining>0)?null:(this.index++,this.index>=this.stages.length?(this.index=-1,`done`):(this.remaining=this.stages[this.index].duration,this.stages[this.index].name))}cancel(){this.index=-1,this.remaining=0}toJSON(){return{index:this.index,remaining:this.remaining}}static fromJSON(t,n){let r=new e(t);return r.index=n.index,r.remaining=n.remaining,r}},hH=class e{constructor(e){if(this.index=0,this.state=`idle`,typeof e.damage!=`function`&&!Number.isFinite(e.damage))throw Error(`beam damage must be a finite number or a function`);if(typeof e.damage==`number`&&e.damage<0)throw Error(`beam damage must be non-negative`);if(this.options=e,this.shape=e.shape??(e.fronts?`fronts`:`line`),e.fronts){let t=e.fronts([{...e.from}],0);this.fronts=t.length?[t.map(e=>({...e}))]:[]}else this.fronts=VV(e.level,e.from,e.target,{kind:`line`}).slice(1).map(e=>[{...e}])}get active(){return this.state===`active`}get done(){return this.state===`done`||this.state===`blocked`||this.state===`cancelled`}get beamShape(){return this.shape}get currentPath(){return this.fronts.flat().map(e=>({...e}))}start(){return this.state===`idle`&&(this.state=this.fronts.length===0?`done`:`active`,!0)}advance(){if(this.state!==`active`)return this.inactiveStep();let e=this.fronts[this.index]??[],t=Math.max(0,this.fronts.length-this.index-1),n=[],r=[],i=0;for(let a of e){let e={cell:{...a},step:this.index,remaining:t};if(!this.blocked(a,e)){n.push({...a}),this.options.onCell?.({...a},e);for(let t of this.options.targetsAt?.(a)??[]){let n=typeof this.options.damage==`function`?this.options.damage(t,e):this.options.damage;if(!Number.isFinite(n)||n<0)throw Error(`beam damage callback must return a non-negative finite number`);i+=n,r.push(t),this.options.applyDamage?.(t,n,e)}}}let a=this.index;if(this.index++,this.options.fronts&&n.length>0){let e=this.options.fronts(n.map(e=>({...e})),this.index);e.length&&this.fronts.push(e.map(e=>({...e})))}return n.length===0?this.state=`blocked`:this.index>=this.fronts.length&&(this.state=`done`),{status:n.length===0?`blocked`:this.state,cell:n[0]?{...n[0]}:null,cells:n.map(e=>({...e})),step:a,remaining:t,targets:[...r],damage:i}}cancel(){(this.state===`active`||this.state===`idle`)&&(this.state=`cancelled`)}toJSON(){return{state:this.state,fronts:this.fronts.map(e=>e.map(e=>({...e}))),index:this.index,shape:this.shape}}static fromJSON(t,n){let r=n.shape??(t.fronts?`fronts`:`line`);if(t.shape!==void 0&&t.shape!==r)throw Error(`beam save is shape "${r}", not "${t.shape}"`);let i=Object.create(e.prototype);return i.options=t,i.shape=r,i.fronts=n.fronts?n.fronts.map(e=>e.map(e=>({...e}))):(n.path??[]).map(e=>[{...e}]),i.index=n.index,i.state=n.state,i}blocked(e,t){let n=this.options.blocker??(this.options.stopAtOpaque===!1?`none`:`terrain`),r=!1;return n===`terrain`?r=!this.options.level.inside(e.x,e.y)||!this.options.level.transparent(e.x,e.y):n!==`none`&&(r=n({...e},t)===!0),r||this.options.isBlocked?.({...e},t)===!0}inactiveStep(){return{status:this.state,cell:null,cells:[],step:this.index,remaining:Math.max(0,this.fronts.length-this.index),targets:[],damage:0}}};_e();function gH(e,t={}){return(t.within?[...t.within]:yH(e.cellCount)).filter(n=>!(t.occupied?.has(n)||t.terrain&&!t.terrain.has(e.terrain[n])))}function _H(e,t,n){let r=new Set([t]),i=[t];for(let t=0;t<Math.max(0,n);t++){let t=[];for(let n of i)e.forEachNeighbor(e.xOf(n),e.yOf(n),8,(n,i)=>{if(!e.inside(n,i))return;let a=e.index(n,i);r.has(a)||(r.add(a),t.push(a))});i=t}return r.delete(t),[...r]}function vH(e,t){let n=[...new Set(e)];oe(n);let r=n.slice(0,Math.max(0,t));return{cells:r,trace:{requested:t,available:n.length,selected:r}}}function yH(e){let t=Array(e);for(let n=0;n<e;n++)t[n]=n;return t}var bH=l({AbilityCycle:()=>uH,BossPhases:()=>lH,CombatHooks:()=>dH,DUNGEON_KINDS:()=>YB,Doors:()=>cH,Elevation:()=>$V,FLOOR:()=>BB,FeatureLayer:()=>mV,FieldOfView:()=>QV,Level:()=>VB,MultiStageAbility:()=>mH,MultiTurnBeam:()=>hH,Pathfinder:()=>eH,Scheduler:()=>tH,Secrets:()=>sH,Stealth:()=>fH,TargetingController:()=>ZV,TriggerTracker:()=>pH,WALL:()=>zB,areaFalloffMultiplier:()=>YV,ballistica:()=>LV,canTarget:()=>zV,candidateCells:()=>gH,cellsNear:()=>_H,chainTargets:()=>qV,chebyshevDistance:()=>FV,checkDeterminism:()=>bV,compareDungeonArtifacts:()=>yV,coneCells:()=>UV,coneSector:()=>KV,decideMonsterAI:()=>nH,eligibleBuilders:()=>qB,findFreeCell:()=>eV,furthestRoom:()=>tV,generateCave:()=>oV,generateDungeon:()=>ZB,generateDungeonGraph:()=>XB,generateOverworld:()=>fV,hallBuilder:()=>WB,hasLineOfSight:()=>RV,hexConeCells:()=>HV,knockbackPath:()=>XV,neighbourOffsets:()=>RB,pickBuilder:()=>JB,rangeMultiplier:()=>JV,rectCenter:()=>HB,rectsOverlap:()=>UB,resolveArea:()=>BV,resolveAreaOnLevel:()=>VV,rollRoster:()=>hV,selectDistinctCells:()=>vH,traceLine:()=>IV});function xH(e,t){let n=e=>t.filter(t=>t.op===e).sort((e,t)=>(e.order??0)-(t.order??0)),r=e;for(let e of n(`add`))r+=e.value;for(let e of n(`multiply`))r*=e.value;for(let e of n(`set`))r=e.value;return r}var SH=class e{constructor(e){this.modifiers=[],this.cache=null,this.baseValues={...e.base},this.derived=e.derived??[]}base(e){return this.baseValues[e]??0}setBase(e,t){this.baseValues[e]=t,this.cache=null}addModifier(e){this.modifiers.push(e),this.cache=null}removeModifier(e){let t=this.modifiers.indexOf(e);t!==-1&&this.modifiers.splice(t,1),this.cache=null}removeModifiersFrom(e){this.modifiers=this.modifiers.filter(t=>t.source!==e),this.cache=null}get(e){return this.resolveAll()[e]??0}resolveAll(){if(this.cache)return this.cache;let e={...this.baseValues};for(let t of Object.keys(e))e[t]=xH(e[t],this.modifiersFor(t));for(let t of this.derived)e[t.name]=xH(t.from(e),this.modifiersFor(t.name));return this.cache=e,e}modifiersFor(e){return this.modifiers.filter(t=>t.stat===e)}toJSON(){return{base:{...this.baseValues}}}static fromJSON(t,n){let r=new e(t);return r.baseValues={...t.base,...n.base},r.cache=null,r}};function CH(e,t,n){return{maxLevel:n,experienceFor:n=>n<=1?0:Math.round(e*(n-1)**t)}}var wH=class e{constructor(e,t={}){this.curve=e,this.level=t.level??1,this.experience=t.experience??this.curve.experienceFor(this.level)}get experienceToNext(){return this.level>=this.curve.maxLevel?null:this.curve.experienceFor(this.level+1)-this.experience}addExperience(e){this.experience+=e;let t=0;for(;this.level<this.curve.maxLevel&&this.experience>=this.curve.experienceFor(this.level+1);)this.level++,t++;return t}toJSON(){return{level:this.level,experience:this.experience}}static fromJSON(t,n){return new e(t,n)}};_e();function TH(e,t,n=()=>ne(1,20)){return e+n()>=t}var EH=class e{constructor(e,t={}){this.available=0,this.stats=e,this.capFor=t.cap??(()=>1/0),this.costFor=t.cost??(()=>1)}get points(){return this.available}grant(e){this.available+=e}canSpend(e){return this.nextRankCost(e)!==null}spend(e){let t=this.nextRankCost(e);if(t===null)return!1;let n=this.stats.base(e);return this.available-=t,this.stats.setBase(e,n+1),!0}nextRankCost(e){let t=this.stats.base(e);if(t>=this.capFor(e))return null;let n=this.costFor(e,t+1);return this.available>=n?n:null}toJSON(){return{points:this.available}}static fromJSON(t,n,r){let i=new e(t,n);return i.available=r.points,i}},DH=class e{constructor(e,t=null,n={}){this.worn=new Map,this.names=new Set(e),this.stats=t,this.isSlotLocked=n.locked??(()=>!1)}get(e){return this.worn.get(e)}isLocked(e){let t=this.worn.get(e);return t!==void 0&&this.isSlotLocked(e,t)}equip(e,t){if(this.assertSlot(e),this.isLocked(e))return;let n=this.unequip(e);return this.wear(e,t),n}wear(e,t){this.worn.set(e,t);for(let e of t.modifiers??[])this.stats?.addModifier({...e,source:t})}unequip(e){let t=this.worn.get(e);if(t&&!this.isSlotLocked(e,t))return this.worn.delete(e),this.stats?.removeModifiersFrom(t),t}get slots(){return[...this.names]}assertSlot(e){if(!this.names.has(e))throw Error(`no such equipment slot: "${e}"`)}toJSON(e){return{worn:[...this.worn].map(([t,n])=>[t,e(n)])}}static fromJSON(t,n){let r=new e(t.slots,t.stats??null,{locked:t.locked});for(let[e,i]of n.worn)r.assertSlot(e),r.wear(e,t.resolve(i));return r}},OH=class e{constructor(e={}){this.slots=[],this.capacity=e.capacity}get items(){return this.slots}get totalWeight(){return this.slots.reduce((e,t)=>e+this.weightOf(t),0)}weightOf(e){return(e.weight??0)*e.quantity+(e.contents?.totalWeight??0)}find(e,t){return this.slots.find(n=>n.id===e&&(t===void 0||n.instanceId===t))}add(e){if(!Number.isFinite(e.quantity)||e.quantity<=0||e.weight!==void 0&&(!Number.isFinite(e.weight)||e.weight<0)||this.capacity!==void 0&&this.totalWeight+this.weightOf(e)>this.capacity)return!1;if(e.stackable){let t=this.slots.find(t=>t.id===e.id&&t.stackable&&t.instanceId===e.instanceId);if(t)return t.quantity+=e.quantity,!0}return this.slots.push({...e}),!0}remove(e,t,n){if(t!==void 0&&(!Number.isFinite(t)||t<=0))return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r];i.quantity-=t??i.quantity,i.quantity<=0&&this.slots.splice(r,1)}take(e,t=1,n){if(!Number.isFinite(t)||t<=0)return;let r=this.slots.findIndex(t=>t.id===e&&(n===void 0||t.instanceId===n));if(r===-1)return;let i=this.slots[r],a=Math.min(Math.floor(t),i.quantity);if(a<=0)return;let o={...i,quantity:a};return i.quantity-=a,i.quantity<=0&&this.slots.splice(r,1),o}toJSON(){return{capacity:this.capacity,slots:this.slots.map(e=>({id:e.id,quantity:e.quantity,instanceId:e.instanceId,identified:e.identified,cursed:e.cursed,blessed:e.blessed,level:e.level,affix:e.affix,durability:e.durability,maxDurability:e.maxDurability,contents:e.contents?.toJSON()}))}}static fromJSON(t,n){let r=new e({capacity:n.capacity});return r.slots=n.slots.map(n=>{let r=t.get(n.id);if(!r)throw Error(`Inventory.fromJSON: no definition for item "${n.id}"`);let{contents:i,...a}=n,o={...r,...kH(a),id:n.id,quantity:n.quantity};return i&&(o.contents=e.fromJSON(t,i)),o}),r}};function kH(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function AH(e,t){return t.matches?t.matches(e):t.category===void 0?typeof t.id==`string`?e.id===t.id:(t.id??[]).includes(e.id):e.category===t.category}function jH(e){return e.matches!==void 0||e.category!==void 0||e.id!==void 0}function MH(e,t){let n=new Map;for(let t of e.items)n.set(t,t.quantity);let r=new Map;for(let i of t.ingredients){if(!jH(i))throw Error(`recipe ingredient must name an id, a category, or a matches predicate`);if(!Number.isFinite(i.quantity)||i.quantity<=0)throw Error(`recipe ingredient quantity must be a positive number`);let t=i.quantity;for(let a of e.items){if(t<=0)break;let e=n.get(a)??0;if(e<=0||!AH(a,i))continue;let o=Math.min(e,t);n.set(a,e-o),t-=o,r.set(a,(r.get(a)??0)+o)}if(t>0)return!1}for(let[t,n]of r)e.remove(t.id,n,t.instanceId);if(e.add(t.result))return!0;for(let[t,n]of r)e.add({...t,quantity:n});return!1}function NH(e,t){let n=e.add({duration:t.duration,tick:e=>t.tick?.(e),onExpire:t.onExpire});return{cancel:()=>{e.remove(n),t.onExpire()}}}function PH(e,t,n){let r=Symbol(`statusEffect`);for(let t of n.modifiers)e.addModifier({...t,source:r});return NH(t,{duration:n.duration,tick:n.tick,onExpire:()=>e.removeModifiersFrom(r)})}_e();function FH(e,t={}){let n=e.entries.filter(e=>e.weight>0&&(t.curse===void 0||!!e.curse===t.curse)&&(t.predicate?.(e)??!0));if(n.length===0)return null;let r=ie(n.map(e=>e.weight));return r===null?null:n[r]}function IH(e){return e.affix}function LH(e,t){let n=e.affix!==void 0;e.affix=t.id,t.curse?e.cursed=!0:n&&(e.cursed=!1)}function RH(e){e.affix!==void 0&&(e.cursed=!1),delete e.affix}function zH(e,t){e.affix===void 0?RH(t):(t.affix=e.affix,t.cursed=e.cursed??!1)}function BH(e,t){return!(e.trigger!==t.trigger||e.kinds&&(t.kind===void 0||!e.kinds.includes(t.kind)))}function VH(e){e.identified=!0}function HH(e,t,n=`keep`){return Number.isFinite(t)?(e.level=(e.level??0)+t,n===`remove`&&RH(e),e.level):e.level??0}function UH(e,t){return e.maxDurability===void 0?!1:!Number.isFinite(t)||t<=0?(e.durability??e.maxDurability)<=0:(e.durability=Math.max(0,(e.durability??e.maxDurability)-t),e.durability<=0)}function WH(e,t){e.maxDurability!==void 0&&(!Number.isFinite(t)||t<=0||(e.durability=Math.min(e.maxDurability,(e.durability??e.maxDurability)+t)))}function GH(e,t,n){let r=new Map;for(let t of Object.keys(n.fields))r.set(t,e[t]),e[t]=n.fields[t];return NH(t,{duration:n.duration,tick:n.tick,onExpire:()=>{for(let[t,n]of r)e[t]=n}})}var KH=class e{constructor(e){this.progress=0,this.max=e.max,this.regenRate=e.regenRate,this.value=e.current??e.max}get current(){return this.value}canAfford(e){return this.value>=e}spend(e){return this.canAfford(e)?(this.value-=e,!0):!1}refund(e=1){let t=Math.min(e,this.max-this.value);return this.value+=t,t}advance(e=1){if(!(this.value>=this.max)){for(this.progress+=e;this.progress>=this.regenRate&&this.value<this.max;)this.progress-=this.regenRate,this.value++;this.value>=this.max&&(this.progress=0)}}toJSON(){return{current:this.value,progress:this.progress}}static fromJSON(t,n){let r=new e({...t,current:n.current});return r.progress=n.progress,r}};_e();function qH(e){if(e.entries.length===0||!A(e.chance??1))return null;let t=ie(e.entries.map(e=>e.weight));if(t===null)return null;let n=e.entries[t];return{id:n.id,quantity:n.quantity??1}}var JH=class e{constructor(e){this.grantedTiers=0,this.balance=0,this.choices=new Map,this.track=e}get points(){return this.balance}openTiers(e){let t=[];return this.track.tiers.forEach((n,r)=>{e>=n.threshold&&t.push(r)}),t}grant(e){let t=0;for(;this.grantedTiers<this.track.tiers.length&&e>=this.track.tiers[this.grantedTiers].threshold;){let e=this.track.tiers[this.grantedTiers];e.kind===`points`&&(this.balance+=e.points??0,t+=e.points??0),this.grantedTiers++}return t}spend(e){return this.balance<e?!1:(this.balance-=e,!0)}choose(e,t,n){let r=this.track.tiers[e];if(!r)throw Error(`no such advancement tier: ${e}`);if(r.kind===`points`)throw Error(`tier ${e} grants points, it has no choice`);if(n<r.threshold)throw Error(`tier ${e} has not opened yet`);if(this.choices.has(e))throw Error(`tier ${e} is already decided`);if(!(r.options??[]).some(e=>e.id===t))throw Error(`tier ${e} has no option "${t}"`);this.choices.set(e,t)}choice(e){return this.choices.get(e)??null}toJSON(){return{grantedTiers:this.grantedTiers,balance:this.balance,choices:[...this.choices]}}static fromJSON(t,n){let r=new e(t);r.grantedTiers=n.grantedTiers,r.balance=n.balance;for(let[e,t]of n.choices)r.choices.set(e,t);return r}};function YH(e,t){return t.map(t=>({stat:t.stat,op:t.op,value:t.base+t.perLevel*e}))}_e();function XH(e){if(e.labels.length<e.kinds.length)throw Error(`not enough appearances: ${e.kinds.length} kinds but only ${e.labels.length} labels`);let t=[...e.labels];for(let e=t.length-1;e>0;e--){let n=O(0,e+1);[t[e],t[n]]=[t[n],t[e]]}let n=new Map;return e.kinds.forEach((e,r)=>n.set(e,t[r])),n}var ZH=class e{constructor(e){this.assigned=new Map,this.tables=e}appearanceOf(e,t){let n=this.assigned.get(e);if(!n){let t=this.tables[e];if(!t)throw Error(`no such appearance category: "${e}"`);n=XH(t),this.assigned.set(e,n)}let r=n.get(t);if(r===void 0)throw Error(`"${t}" is not in appearance category "${e}"`);return r}toJSON(){return{assigned:[...this.assigned].map(([e,t])=>[e,[...t]])}}static fromJSON(t,n){let r=new e(t);for(let[e,t]of n.assigned)r.assigned.set(e,new Map(t));return r}};function QH(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=t.find(r);if(!s||s.quantity<i)return!1;let c=o.buy*i;return e.base(a.currency)<c?!1:(t.remove(r,i),n.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)-c),!0):(t.add({...s,quantity:i}),!1))}function $H(e,t,n,r,i,a){let o=a.prices.get(r);if(!o)return!1;let s=n.find(r);return!s||s.quantity<i?!1:(n.remove(r,i),t.add({...s,quantity:i})?(e.setBase(a.currency,e.base(a.currency)+o.sell*i),!0):(n.add({...s,quantity:i}),!1))}function eU(e){let t=Array.isArray(e)?e:[e];for(let e of t)if(!Number.isFinite(e.amount)||e.amount<0)throw Error(`a resource cost must be a non-negative number, "${e.stat}" costs ${e.amount}`);return t}function tU(e){let t=new Map;for(let n of e)t.set(n.stat,(t.get(n.stat)??0)+n.amount);return t}function nU(e,t){return[...tU(eU(t))].every(([t,n])=>e.base(t)>=n)}function rU(e,t){let n=tU(eU(t));if(![...n].every(([t,n])=>e.base(t)>=n))return!1;for(let[t,r]of n)e.setBase(t,e.base(t)-r);return!0}function iU(e,t,n=1){for(let[r,i]of tU(eU(t)))e.setBase(r,e.base(r)+i*n)}function aU(e,t,n,r){return rU(e,t)?n.refund(Math.floor(t.amount/r)):0}var oU=class e{constructor(){this.layers=[]}add(e,t=0){e<=0||this.layers.push({amount:e,decayPerTick:t})}get total(){return this.layers.reduce((e,t)=>e+t.amount,0)}get layerCount(){return this.layers.length}absorb(e){let t=e,n=0;for(;t>0&&this.layers.length>0;){let e=this.layers[this.layers.length-1],r=Math.min(e.amount,t);e.amount-=r,t-=r,n+=r,e.amount<=0&&this.layers.pop()}return n}advance(e=1){for(let t=this.layers.length-1;t>=0;t--){let n=this.layers[t];n.decayPerTick&&(n.amount-=n.decayPerTick*e,n.amount<=0&&this.layers.splice(t,1))}}clear(){this.layers=[]}toJSON(){return{layers:this.layers.map(e=>({...e}))}}static fromJSON(t){let n=new e;return n.layers=t.layers.map(e=>({...e})),n}};_e();function sU(e,t,n){return oe([...t]).slice(0,Math.min(n,t.length)).map(t=>{let n=Symbol(`trait:${t.name}`);for(let r of t.modifiers)e.addModifier({...r,source:n});return{trait:t,source:n}})}var cU=class{constructor(){this.affected=new Map}update(e,t){let n=new Set(e),r=e.filter(e=>!!e.aura),i=new Set(r);for(let i of r){let r=this.affected.get(i);r||(r=new Map,this.affected.set(i,r));for(let n of e){if(n===i)continue;let e=t(i,n),a=r.get(n);if(e&&!a){let e=Symbol(`aura:${i.aura.name}`);for(let t of i.aura.modifiers)n.stats.addModifier({...t,source:e});r.set(n,e)}else!e&&a&&(n.stats.removeModifiersFrom(a),r.delete(n))}for(let[e,t]of[...r])n.has(e)||(e.stats.removeModifiersFrom(t),r.delete(e))}for(let[e,t]of[...this.affected])if(!i.has(e)){for(let[e,n]of t)e.stats.removeModifiersFrom(n);this.affected.delete(e)}}},lU=class e{constructor(e){if(this.points=new Map,e.some(e=>!e.id||!Number.isFinite(e.threshold)||e.threshold<0))throw Error(`support levels need an id and a non-negative threshold`);this.levels=[...e].sort((e,t)=>e.threshold-t.threshold)}get(e,t){return this.points.get(uU(e,t))??0}level(e,t){let n=this.get(e,t),r=null;for(let e of this.levels){if(e.threshold>n)break;r=e}return r}add(e,t,n){if(!e||!t||e===t)throw Error(`support needs two different named units`);if(!Number.isFinite(n))throw Error(`support amount must be finite, got ${n}`);let r=this.level(e,t),i=uU(e,t),a=Math.max(0,(this.points.get(i)??0)+n);return this.points.set(i,a),{a:e,b:t,points:a,previousLevel:r,level:this.level(e,t)}}toJSON(){return{pairs:[...this.points].map(([e,t])=>{let[n,r]=e.split(`\0`);return[n,r,t]})}}static fromJSON(t,n){let r=new e(t);for(let[e,t,i]of n.pairs){if(!e||!t||e===t||!Number.isFinite(i)||i<0)throw Error(`invalid support save data`);let n=uU(e,t);if(r.points.has(n))throw Error(`invalid support save data: duplicate pair "${e}" / "${t}"`);r.points.set(n,i)}return r}};function uU(e,t){return[e,t].sort().join(`\0`)}var dU=new Set([`id`,`growth`,`level`,`startingAffix`,`startingItem`,`lowHpReaction`]);function fU(e,t={},n){let r=new SH({base:_U(e)}),i;e.growth!==void 0&&(i=new wH(gU(e,t),{level:e.level??1}));let a;if(e.startingItem!==void 0){let n=t.items?.[e.startingItem];if(!n)throw Error(`entity template "${e.id}": unknown starting item "${e.startingItem}"`);if(a=n(),e.startingAffix!==void 0){let n=t.affixes?.[e.startingAffix];if(!n)throw Error(`entity template "${e.id}": unknown affix "${e.startingAffix}"`);LH(a,n)}}else if(e.startingAffix!==void 0)throw Error(`entity template "${e.id}": a starting affix needs a starting item to carry it`);let o=new Dn,s={id:e.id,stats:r,progression:i,item:a,reactions:o};if(e.lowHpReaction!==void 0){if(!n)throw Error(`entity template "${e.id}": names a lowHpReaction threshold but no onLowHp callback was given`);let t=e.lowHpReaction;o.add({id:`low-hp`,when:e=>e.hp/e.maxHp<=t,action:()=>n(s)})}return s}function pU(e,t={},n){return e.map(e=>fU(e,t,n))}function mU(e){let t={stats:e.stats.toJSON()};return e.progression&&(t.progression=e.progression.toJSON()),e.item&&(t.item=e.item),t}function hU(e,t,n,r){let i=fU(e,t,r);if(i.stats=SH.fromJSON({base:_U(e)},n.stats),n.progression!==void 0){if(!i.progression)throw Error(`entity template "${e.id}": save data has progression but the row names no growth curve`);i.progression=wH.fromJSON(gU(e,t),n.progression)}return n.item!==void 0&&(i.item=n.item),i}function gU(e,t){let n=t.growthCurves?.[e.growth??``];if(!n)throw Error(`entity template "${e.id}": unknown growth curve "${e.growth}"`);return n}function _U(e){let t={};for(let[n,r]of Object.entries(e))if(!dU.has(n)){if(typeof r!=`number`)throw Error(`entity template "${e.id}": stat "${n}" must be a number, got ${typeof r}`);t[n]=r}return t}var vU=l({Advancement:()=>JH,Appearances:()=>ZH,AuraField:()=>cU,Barrier:()=>oU,Charges:()=>KH,EquipmentSlots:()=>DH,Inventory:()=>OH,Progression:()=>wH,SkillPoints:()=>EH,StatBlock:()=>SH,SupportLedger:()=>lU,affixOf:()=>IH,applyAffix:()=>LH,applyItemStatusEffect:()=>GH,applyStatusEffect:()=>PH,assignAppearances:()=>XH,assignTraits:()=>sU,buildEntities:()=>pU,buildEntity:()=>fU,buy:()=>QH,canAfford:()=>nU,composeModifiers:()=>xH,convertToCharges:()=>aU,copyAffix:()=>zH,craft:()=>MH,damageItem:()=>UH,enchant:()=>HH,fromEntitySaveState:()=>hU,identify:()=>VH,matchesContext:()=>BH,powerCurve:()=>CH,refund:()=>iU,removeAffix:()=>RH,repairItem:()=>WH,rollAffix:()=>FH,rollLoot:()=>qH,scaledModifiers:()=>YH,sell:()=>$H,skillCheck:()=>TH,spend:()=>rU,toEntitySaveState:()=>mU}),yU=class{constructor(){this.factories=new Map,this.loaded=new Map,this.currentId=null}define(e,t,n={}){this.factories.set(e,{create:t,persistent:n.persistent??!0})}enter(e,t){let n=this.factories.get(e);if(!n)throw Error(`no such map: "${e}"`);let r=this.loaded.get(e);return(!r||!n.persistent)&&(r=n.create(),this.loaded.set(e,r)),this.currentId=e,this.lastSpawn=t,r}get current(){return this.currentId?this.loaded.get(this.currentId)??null:null}get currentMapId(){return this.currentId}get spawn(){return this.lastSpawn}isLoaded(e){return this.loaded.has(e)}isPersistent(e){return this.factories.get(e)?.persistent??!0}unload(e){if(e===this.currentId)throw Error(`cannot unload the current map: "${e}"`);this.loaded.delete(e)}},bU=class{constructor(){this.locations=new Map}add(e){this.locations.set(e.id,e)}remove(e){this.locations.delete(e)}get(e){return this.locations.get(e)}at(e,t){for(let n of this.locations.values())if(n.x===e&&n.y===t)return n}get all(){return[...this.locations.values()]}},xU=class{constructor(){this.turn=0,this.effects=new Map}add(e){let t=Symbol();return this.effects.set(t,{...e}),t}remove(e){this.effects.delete(e)}has(e){return this.effects.has(e)}advance(e=1){this.turn+=e;for(let[t,n]of this.effects)n.tick(this.turn),n.duration!==void 0&&(n.duration-=e,n.duration<=0&&(this.effects.delete(t),n.onExpire?.()))}};_e();function SU(e){if(e.entries.length===0||!A(e.rate))return null;let t=ie(e.entries.map(e=>e.weight));return t===null?null:e.entries[t].value}var CU=class e{constructor(e={}){if(this.changed=new p,this.dayLength=e.dayLength??120,!(this.dayLength>0))throw Error(`an environment day must be longer than zero seconds`);if(this.boundaries=e.phaseBoundaries??[.2,.7,.8],this.boundaries[0]<=0||this.boundaries[0]>=this.boundaries[1]||this.boundaries[1]>=this.boundaries[2]||this.boundaries[2]>=1)throw Error(`environment phase boundaries must be ascending fractions strictly between 0 and 1`);if(this.seconds_=e.startSeconds??0,this.weather_=e.startWeather??`clear`,!Number.isFinite(this.seconds_))throw Error(`environment startSeconds must be finite`)}get day(){return Math.floor(this.seconds_/this.dayLength)}get seconds(){return this.seconds_}get weather(){return this.weather_}get phase(){let e=(this.seconds_%this.dayLength+this.dayLength)%this.dayLength/this.dayLength;return e<this.boundaries[0]?`dawn`:e<this.boundaries[1]?`day`:e<this.boundaries[2]?`dusk`:`night`}get night(){return this.phase===`night`}update(e){if(!Number.isFinite(e)||e<0)throw Error(`environment update must be non-negative, got ${e}`);this.seconds_+=e;let t=this.toJSON();return this.changed.dispatch(t),t}setWeather(e){if(!e)throw Error(`weather needs a non-empty id`);this.weather_=e;let t=this.toJSON();return this.changed.dispatch(t),t}toJSON(){return{day:this.day,seconds:this.seconds_,phase:this.phase,weather:this.weather_}}static fromJSON(t,n){return new e({...t,startSeconds:n.seconds,startWeather:n.weather})}},wU=class e{constructor(e){if(e.sides.length===0)throw Error(`SideTurns needs at least one side`);if(e.schedule.length===0)throw Error(`SideTurns needs a non-empty schedule`);let t=e.round??1,n=e.sideIndex??0,r=e.timeIndex??0;if(!Number.isInteger(t)||t<1)throw Error(`SideTurns round must be a positive integer`);if(n<0||n>=e.sides.length)throw Error(`SideTurns side index ${n} is outside ${e.sides.length} sides`);if(r<0||r>=e.schedule.length)throw Error(`SideTurns time index ${r} is outside ${e.schedule.length} times`);this.sides=[...e.sides],this.schedule=[...e.schedule],this.areas=e.areas??[],this.state={round:t,sideIndex:n,timeIndex:r}}get round(){return this.state.round}get side(){return this.sides[this.state.sideIndex]}get timeIndex(){return this.state.timeIndex}get timeOfDay(){return this.schedule[this.state.timeIndex]}get snapshot(){return{...this.state}}timeOfDayAt(e,t){for(let n of this.areas)if(n.contains(e,t))return n.times[this.state.timeIndex]??this.timeOfDay;return this.timeOfDay}lawfulBonusAt(e,t,n){return TU(e,this.timeOfDayAt(t,n).lawfulBonus)}advance(){let e=!1;return this.state.sideIndex++,this.state.sideIndex>=this.sides.length&&(this.state.sideIndex=0,this.state.round++,this.state.timeIndex=(this.state.timeIndex+1)%this.schedule.length,e=!0),{side:this.side,round:this.state.round,newRound:e}}toJSON(){return this.snapshot}static fromJSON(t,n){return new e({...t,round:n.round,sideIndex:n.sideIndex,timeIndex:n.timeIndex})}};function TU(e,t){switch(e){case`lawful`:return t;case`chaotic`:return-t;default:return 0}}var EU=l({EnvironmentClock:()=>CU,Overworld:()=>bU,SideTurns:()=>wU,TurnClock:()=>xU,World:()=>yU,alignmentBonus:()=>TU,rollEncounter:()=>SU});_e();function DU(e,t,n={}){let r=n.pick??O,i=0;return t.forEach((t,n)=>{OU(t,t.name??`#${n+1}`,e.shape);let a=kU(e,t);if(i+=a.length,a.length!==0)for(let[n,i]of a){let a=t.outputs[r(t.outputs.length)];for(let[r,o]of Object.entries(a))for(let a=0;a<t.height;a++)for(let s=0;s<t.width;s++){let c=o[a*t.width+s];c!==-1&&e.setTile(r,n+s,i+a,c)}}}),i}function OU(e,t,n){if(e.topology&&(n===`square`||n===`hex`)&&e.topology!==n)throw Error(`automap rule "${t}" targets ${e.topology} cells, but the map is ${n}`);if(!Number.isInteger(e.width)||e.width<=0||!Number.isInteger(e.height)||e.height<=0)throw Error(`automap rule "${t}" needs a positive width and height`);if(e.outputs.length===0)throw Error(`automap rule "${t}" has no outputs - a rule that matches and writes nothing is a mistake`);let r=e.width*e.height;for(let[n,i]of Object.entries(e.input))if(i.length!==r)throw Error(`automap rule "${t}" input "${n}" has ${i.length} cells, but the pattern is ${r}`);e.outputs.forEach((e,n)=>{for(let[i,a]of Object.entries(e))if(a.length!==r)throw Error(`automap rule "${t}" output ${n+1} "${i}" has ${a.length} cells, but the pattern is ${r}`)})}function kU(e,t){let n=[];for(let r=0;r+t.height<=e.heightInTiles;r++)for(let i=0;i+t.width<=e.widthInTiles;i++)AU(e,t,i,r)&&n.push([i,r]);return n}function AU(e,t,n,r){for(let[i,a]of Object.entries(t.input))for(let o=0;o<t.height;o++)for(let s=0;s<t.width;s++){let c=a[o*t.width+s];if(c!==-1&&e.getTile(i,n+s,r+o)!==c)return!1}return!0}var jU=class e{constructor(){this.switches=new Map,this.variables=new Map}switch(e){return this.switches.get(e)??!1}setSwitch(e,t){this.switches.set(e,t)}variable(e){return this.variables.get(e)??0}setVariable(e,t){this.variables.set(e,t)}toJSON(){return{switches:[...this.switches],variables:[...this.variables]}}static fromJSON(t){let n=new e;for(let[e,r]of t.switches)n.setSwitch(e,r);for(let[e,r]of t.variables)n.setVariable(e,r);return n}};function MU(e,t){return`switch`in e?t.switch(e.switch)===e.equals:t.variable(e.variable)>=e.atLeast}function NU(e,t){let n;for(let r of e.pages)(r.conditions??[]).every(e=>MU(e,t))&&(n=r);return n}var PU=class{constructor(e){this.cancelled=!1,this.options=e,this.state={game:e.game,answers:{}}}cancel(){this.cancelled=!0}async run(e){let t=await this.runList(e);if(t!==void 0){if(this.options.onUnknownCommand)return this.options.onUnknownCommand({goto:t}),this.state;throw Error(`a "goto ${t}" only runs inside runStory, not a straight run`)}return this.state}async runStory(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this event story has no passage named "${t}"`);let n=e[t],r=0;for(;r<n.length&&!this.cancelled;){let t=await this.step(n[r]);if(r++,t!==void 0){if(!Object.prototype.hasOwnProperty.call(e,t))throw Error(`this event story has no passage named "${t}"`);n=e[t],r=0}}return this.state}async runList(e){for(let t of e){if(this.cancelled)break;let e=await this.step(t);if(e!==void 0)return e}}async step(e){if(`say`in e)await this.speak(e.say,e.speaker,e.portrait);else{if(`ask`in e){let t=await this.speak(e.ask,e.speaker,e.portrait,e.choices);return e.store&&(this.state.answers[e.store]=t),e.choices.find(e=>(e.value??e.text)===t)?.goto}if(`wait`in e)await new Promise(t=>setTimeout(t,e.wait*1e3));else if(`setSwitch`in e)this.state.game.setSwitch(e.setSwitch,e.value);else if(`setVariable`in e)this.state.game.setVariable(e.setVariable,e.value);else if(`addVariable`in e){let t=this.state.game.variable(e.addVariable);this.state.game.setVariable(e.addVariable,t+e.amount)}else{if(`if`in e){let t=MU(e.if,this.state.game);return this.runList(t?e.then:e.else??[])}if(`move`in e)await this.options.move?.(e.move.target,e.move.steps);else{if(`goto`in e)return e.goto;`call`in e?await e.call(this.state):this.options.onUnknownCommand?.(e)}}}}speak(e,t,n,r){return this.options.present({text:e,speaker:t,portrait:n,choices:r})}};function FU(e,t){t&&e.has?.(t)&&e.play?.(t)}var IU=class{constructor(e,t,n,r){this.facing=`down`,this.target=null,this.progress=0,this.sprite=e,this.x=this.fromX=t,this.y=this.fromY=n,this.tileWidth=r.tileWidth,this.tileHeight=r.tileHeight,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.target!==null}turnTo(e,t){this.target||(this.facing=LU(e,t),this.playIdle())}moveBy(e,t){return!this.target&&(this.facing=LU(e,t),this.fromX=this.x,this.fromY=this.y,this.target={x:this.x+e,y:this.y+t},this.progress=0,this.playWalk(),!0)}jumpBy(e,t){return!this.target&&(this.facing=LU(e,t),this.x+=e,this.y+=t,this.fromX=this.x,this.fromY=this.y,this.place(),this.playIdle(),!0)}update(e){this.sprite.update?.(e),this.target&&(this.progress=Math.min(1,this.progress+this.speed*e),this.sprite.x=RU(this.fromX,this.target.x,this.progress)*this.tileWidth,this.sprite.y=RU(this.fromY,this.target.y,this.progress)*this.tileHeight,this.progress>=1&&(this.x=this.target.x,this.y=this.target.y,this.target=null,this.playIdle()))}place(){this.sprite.x=this.x*this.tileWidth,this.sprite.y=this.y*this.tileHeight}playWalk(){FU(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){FU(this.sprite,this.options.idleAnimation?.(this.facing))}};function LU(e,t){return e>0?`right`:e<0?`left`:t>0?`down`:`up`}function RU(e,t,n){return e+(t-e)*n}var zU=[`up`,`down`,`left`,`right`],BU={up:{dx:0,dy:-1},down:{dx:0,dy:1},left:{dx:-1,dy:0},right:{dx:1,dy:0}},VU={up:{around:`down`,left90:`left`,right90:`right`},down:{around:`up`,left90:`right`,right90:`left`},left:{around:`right`,left90:`down`,right90:`up`},right:{around:`left`,left90:`up`,right90:`down`}},HU=class{constructor(e,t,n={}){this.index=0,this.waiting=0,this.mover=e,this.route=t,this.options=n}get done(){return!this.route.repeat&&this.index>=this.route.steps.length}update(e){if(this.mover.isMoving||this.done||this.waiting>0&&(this.waiting=Math.max(0,this.waiting-e),this.waiting>0))return;this.index>=this.route.steps.length&&(this.index=0);let t=this.route.steps[this.index];(this.runStep(t)||this.route.skippable)&&this.index++}runStep(e){if(`turn`in e){let{dx:t,dy:n}=this.resolveTurn(e);return this.mover.turnTo(t,n),!0}if(`wait`in e)return this.waiting=e.wait,!0;if(`jump`in e)return this.attempt(e.jump.dx,e.jump.dy,(e,t)=>this.mover.jumpBy(e,t));if(`step`in e)return this.attempt(e.step.dx,e.step.dy,(e,t)=>this.mover.moveBy(e,t));let{dx:t,dy:n}=this.resolveDirection(e);return this.attempt(t,n,(e,t)=>this.mover.moveBy(e,t))}resolveDirection(e){return e.dir===`random`?BU[this.pickDirection()]:e.dir===`forward`?BU[this.mover.facing]:e.dir===`backward`?BU[VU[this.mover.facing].around]:e.dir===`toward`||e.dir===`away`?this.resolveAim(e.dir,e):BU[e.dir]}resolveTurn(e){if(e.turn===`random`)return BU[this.pickDirection()];if(e.turn===`around`||e.turn===`left90`||e.turn===`right90`)return BU[VU[this.mover.facing][e.turn]];if(e.turn===`toward`||e.turn===`away`){let t=this.resolveAim(e.turn,e);return t.dx===0&&t.dy===0?BU[this.mover.facing]:t}return BU[e.turn]}resolveAim(e,t){let n=`target`in t?t.target():t,r=e===`toward`?1:-1,i=n.x-this.mover.x,a=n.y-this.mover.y;return Math.abs(i)>=Math.abs(a)?{dx:r*Math.sign(i)||0,dy:0}:{dx:0,dy:r*Math.sign(a)||0}}attempt(e,t,n){return e===0&&t===0?!0:this.options.canMove&&!this.options.canMove(e,t)?!1:n(e,t)}pickDirection(){let e=this.options.random??Math.random;return zU[Math.floor(e()*zU.length)]}},UU=class{constructor(e,t,n,r={}){this.facing=0,this.moving=!1,this.sprite=e,this.x=t,this.y=n,this.speed=r.speed??4,this.options=r,this.place(),this.playIdle()}get isMoving(){return this.moving}move(e,t,n){let r=Math.hypot(e,t);r>0?(this.facing=Math.atan2(t,e),this.x+=e/r*this.speed*n,this.y+=t/r*this.speed*n,this.moving||(this.moving=!0,this.playWalk())):this.moving&&(this.moving=!1,this.playIdle()),this.place(),this.sprite.update?.(n)}turnTo(e,t){this.moving||e===0&&t===0||(this.facing=Math.atan2(t,e),this.playIdle())}place(){this.sprite.x=this.x,this.sprite.y=this.y}playWalk(){FU(this.sprite,this.options.walkAnimation?.(this.facing))}playIdle(){FU(this.sprite,this.options.idleAnimation?.(this.facing))}};function WU(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function GU(e,t){let n=e.x-t.x,r=e.y-t.y,i=e.radius+t.radius;return n*n+r*r<i*i}function KU(e,t){let n=kn(e.x,t.x,t.x+t.width),r=kn(e.y,t.y,t.y+t.height),i=e.x-n,a=e.y-r;return i*i+a*a<e.radius*e.radius}function qU(e,t,n,r){let{tileSize:i,isSolid:a}=r;if(!(i>0))throw Error(`collision tileSize must be positive`);let o=JU(e.x,e.y,e.width,e.height,t,i,a,!0);return{x:o,y:JU(o,e.y,e.width,e.height,n,i,a,!1)}}function JU(e,t,n,r,i,a,o,s){if(i===0)return s?e:t;let c=s?e:t,l=s?n:r,u=c+i,d=Math.floor((s?t:e)/a),f=Math.floor(((s?t+r:e+n)-1e-6)/a),p=(e,t)=>s?o(e,t):o(t,e);if(i>0){let e=Math.floor((c+l-1e-6)/a),t=Math.floor((u+l-1e-6)/a);for(let n=e+1;n<=t;n++)for(let e=d;e<=f;e++)if(p(n,e))return n*a-l}else{let e=Math.floor(c/a),t=Math.floor(u/a);for(let n=e-1;n>=t;n--)for(let e=d;e<=f;e++)if(p(n,e))return(n+1)*a}return u}var YU=class e{constructor(){this.definitions=new Map,this.stageIndex=new Map,this.tracked=null}define(e){this.definitions.set(e.id,e)}track(e){e!==null&&this.require(e),this.tracked=e}trackedQuest(){return this.tracked!==null&&this.status(this.tracked)===`active`?this.tracked:null}trackedLocation(){let e=this.trackedQuest();return e?this.currentStage(e)?.location??null:null}markerFor(e,t){return e.some(e=>this.status(e)===`active`&&this.stageSatisfied(e,t))?`turnIn`:e.some(e=>this.status(e)===`available`)?`offer`:`none`}canStart(e){return(this.require(e).requires??[]).every(e=>this.status(e)===`complete`)}start(e){if(!this.canStart(e))throw Error(`quest "${e}" cannot start yet - a prerequisite is incomplete`);this.stageIndex.set(e,0)}status(e){let t=this.require(e),n=this.stageIndex.get(e);return n===void 0?this.canStart(e)?`available`:`unavailable`:n>=t.stages.length?`complete`:`active`}currentStage(e){return this.status(e)===`active`?this.require(e).stages[this.stageIndex.get(e)]:null}progress(e,t){let n=this.currentStage(e);return n?.counter?Math.min(1,t.variable(n.counter.variable)/n.counter.target):null}advanceStage(e,t){return this.stageSatisfied(e,t)?(this.stageIndex.set(e,this.stageIndex.get(e)+1),!0):!1}stageSatisfied(e,t){let n=this.currentStage(e);return n?n.condition?MU(n.condition,t):!n.counter||t.variable(n.counter.variable)>=n.counter.target:!1}require(e){let t=this.definitions.get(e);if(!t)throw Error(`no such quest: "${e}"`);return t}toJSON(){return{stageIndex:[...this.stageIndex],tracked:this.tracked}}static fromJSON(t,n){let r=new e;for(let e of t)r.define(e);for(let[e,t]of n.stageIndex)r.stageIndex.set(e,t);return n.tracked&&(r.tracked=n.tracked),r}};function XU(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.questId);e||(e={id:r.questId,stages:[]},r.requires!==void 0&&(e.requires=r.requires),n.set(r.questId,e),t.push(r.questId)),e.stages.push(ZU(e.id,r))}return t.map(e=>n.get(e))}function ZU(e,t){if(t.conditionSwitch!==void 0&&t.conditionVariable!==void 0)throw Error(`quest "${e}": a stage row cannot name both a condition switch and a condition variable`);let n={};if(t.conditionSwitch!==void 0){if(t.conditionEquals===void 0)throw Error(`quest "${e}": conditionSwitch needs a conditionEquals`);n.condition={switch:t.conditionSwitch,equals:t.conditionEquals}}else if(t.conditionVariable!==void 0){if(t.conditionAtLeast===void 0)throw Error(`quest "${e}": conditionVariable needs a conditionAtLeast`);n.condition={variable:t.conditionVariable,atLeast:t.conditionAtLeast}}if(t.counterVariable!==void 0){if(t.counterTarget===void 0)throw Error(`quest "${e}": counterVariable needs a counterTarget`);n.counter={variable:t.counterVariable,target:t.counterTarget}}if(t.description!==void 0&&(n.description=t.description),t.locationMap!==void 0||t.locationX!==void 0||t.locationY!==void 0){if(t.locationX===void 0||t.locationY===void 0)throw Error(`quest "${e}": a stage location needs both locationX and locationY`);n.location={x:t.locationX,y:t.locationY},t.locationMap!==void 0&&(n.location.map=t.locationMap)}return n}var QU=class{constructor(e){this.name=e}},$U=4,eW=8,tW=new WeakMap;function nW(e){return tW.get(e)}function rW(e,t){return tW.set(e,t),e}var iW=1e3,aW=class{constructor(e){this.pos=0,this.depth=0,this.symbols=[],this.objects=[],this.bytes=e}byte(){if(this.pos>=this.bytes.length)throw Error(`Marshal: unexpected end of input`);return this.bytes[this.pos++]}take(e){if(e<0)throw Error(`Marshal: negative length`);let t=this.bytes.subarray(this.pos,this.pos+e);if(t.length<e)throw Error(`Marshal: unexpected end of input`);return this.pos+=e,t}readFixnum(){let e=this.byte()<<24>>24;if(e===0)return 0;if(e>=5&&e<=127)return e-5;if(e<=-5&&e>=-128)return e+5;if(e>0){let t=0;for(let n=0;n<e;n++)t|=this.byte()<<8*n;return t>>>0}let t=-e,n=0;for(let e=0;e<t;e++)n|=this.byte()<<8*e;return(n>>>0)-2**(8*t)}readBytes(){return this.take(this.readFixnum())}readSymbol(){let e=new TextDecoder().decode(this.readBytes());return this.symbols.push(e),e}readSymbolLink(){let e=this.readFixnum(),t=this.symbols[e];if(t===void 0)throw Error(`Marshal: symbol link ${e} out of range`);return t}readSymbolValue(){let e=String.fromCharCode(this.byte());if(e===`:`)return this.readSymbol();if(e===`;`)return this.readSymbolLink();throw Error(`Marshal: expected a symbol, got tag "${e}"`)}link(e){return this.objects.push(e),e}readBignum(){let e=String.fromCharCode(this.byte())===`-`?-1:1,t=this.readFixnum(),n=0,r=1;for(let e=0;e<t;e++)n+=(this.byte()|this.byte()<<8)*r,r*=65536;return e*n}readFloat(){let e=new TextDecoder().decode(this.readBytes());return e===`inf`?1/0:e===`-inf`?-1/0:e===`nan`?NaN:Number(e)}readArray(){let e=[];this.link(e);let t=this.readFixnum();for(let n=0;n<t;n++)e.push(this.readValue());return e}readHash(e){let t=new Map;this.link(t);let n=this.readFixnum();for(let e=0;e<n;e++)t.set(this.readValue(),this.readValue());return e&&tW.set(t,this.readValue()),t}readIvars(e){let t={};for(let n=0;n<e;n++)t[this.readSymbolValue()]=this.readValue();return t}readObject(){let e={class:``,ivars:{}};return this.link(e),e.class=this.readSymbolValue(),e.ivars=this.readIvars(this.readFixnum()),e}readIvarWrapped(){let e=this.readValue();return this.readIvars(this.readFixnum()),e}readUserDefined(){let e={class:``,raw:new Uint8Array};return this.link(e),e.class=this.readSymbolValue(),e.raw=this.readBytes().slice(),e}readUserMarshal(){let e={class:``,value:null};return this.link(e),e.class=this.readSymbolValue(),e.value=this.readValue(),e}readValue(){if(++this.depth>iW)throw Error(`Marshal: values nested more than ${iW} deep`);try{return this.readTagged()}finally{this.depth--}}readTagged(){let e=String.fromCharCode(this.byte());switch(e){case`0`:return null;case`T`:return!0;case`F`:return!1;case`i`:return this.readFixnum();case`l`:return this.link(this.readBignum());case`f`:return this.link(this.readFloat());case`:`:return this.readSymbol();case`;`:return this.readSymbolLink();case`"`:return this.link(new TextDecoder().decode(this.readBytes()));case`[`:return this.readArray();case`{`:return this.readHash(!1);case`}`:return this.readHash(!0);case`o`:return this.readObject();case`I`:return this.readIvarWrapped();case`u`:return this.readUserDefined();case`U`:return this.readUserMarshal();case`@`:{let e=this.readFixnum(),t=this.objects[e];if(t===void 0)throw Error(`Marshal: object link ${e} out of range`);return t}default:throw Error(`Marshal: unsupported tag "${e}" (0x${e.charCodeAt(0).toString(16)})`)}}readDocument(){let e=this.byte(),t=this.byte();if(e!==$U||t>eW)throw Error(`Marshal: unsupported version ${e}.${t} (expected ${$U}.${eW} or lower)`);return this.readValue()}};function oW(e){return new aW(e).readDocument()}function sW(e){return typeof e==`object`&&!!e&&`class`in e&&`ivars`in e}function cW(e){let t=[$U,eW];return lW(t,e),new Uint8Array(t)}function lW(e,t){if(t==null)e.push(uW(`0`));else if(t===!0)e.push(uW(`T`));else if(t===!1)e.push(uW(`F`));else if(t instanceof QU)e.push(uW(`:`)),dW(e,t.name);else if(typeof t==`number`)Number.isInteger(t)&&Math.abs(t)<2**30?(e.push(uW(`i`)),fW(e,t)):(e.push(uW(`f`)),dW(e,Number.isFinite(t)?String(t):t>0?`inf`:t<0?`-inf`:`nan`));else if(typeof t==`string`)e.push(uW(`"`)),dW(e,t);else if(Array.isArray(t)){e.push(uW(`[`)),fW(e,t.length);for(let n of t)lW(e,n)}else if(t instanceof Map){let n=tW.has(t);e.push(uW(n?`}`:`{`)),fW(e,t.size);for(let[n,r]of t)lW(e,n),lW(e,r);n&&lW(e,tW.get(t))}else if(sW(t)){e.push(uW(`o`)),e.push(uW(`:`)),dW(e,t.class);let n=Object.entries(t.ivars);fW(e,n.length);for(let[t,r]of n)e.push(uW(`:`)),dW(e,t),lW(e,r)}else throw Error(`Marshal: cannot encode a value of type ${typeof t}`)}function uW(e){return e.charCodeAt(0)}function dW(e,t){let n=new TextEncoder().encode(t);fW(e,n.length);for(let t of n)e.push(t)}function fW(e,t){if(t===0)e.push(0);else if(t>0&&t<=122)e.push(t+5);else if(t<0&&t>=-123)e.push(t-5&255);else{if(t>0){for(let n=1;n<=4;n++)if(t<2**(8*n)){e.push(n);for(let r=0;r<n;r++)e.push(t>>>8*r&255);return}}else for(let n=1;n<=4;n++)if(t>=-(2**(8*n))){e.push(-n&255);let r=t+2**(8*n);for(let t=0;t<n;t++)e.push(r>>>8*t&255);return}throw Error(`Marshal: integer ${t} is out of range for a Fixnum`)}}function pW(e){return Wr(e).map(e=>e.speaker===void 0?{say:e.text}:{say:e.text,speaker:e.speaker})}function mW(e,t={}){let n={};for(let t of e)`say`in t?n[t.say]=t.say:`ask`in t&&(n[t.ask]=t.ask);return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function hW(e){let{story:t,start:n,title:r}=Gr(e);return r===void 0?{story:t,start:n}:{story:t,start:n,title:r}}var gW=l({AUTOMAP_EMPTY:()=>-1,EventRunner:()=>PU,FreeMover:()=>UU,GameState:()=>jU,GridMover:()=>IU,MoveRouteRunner:()=>HU,QuestLog:()=>YU,RubySymbol:()=>QU,aabbOverlap:()=>WU,activePage:()=>NU,automap:()=>DU,circleAabbOverlap:()=>KU,circleOverlap:()=>GU,conditionHolds:()=>MU,decodeMarshal:()=>oW,encodeMarshal:()=>cW,extractDialogueCatalog:()=>mW,hashDefaultOf:()=>nW,importTwee:()=>hW,parseDialogueText:()=>pW,questsFromRows:()=>XU,resolveAabbAgainstTiles:()=>qU,withHashDefault:()=>rW}),_W=CH(20,2,100),vW=class{constructor(e){this.species=e.species,this.deriveStats=e.deriveStats,this.progression=new wH(e.species.growth??_W,{level:e.level??1}),this.stats=new SH({base:this.computeBase()})}refreshStats(){let e=this.computeBase();for(let[t,n]of Object.entries(e))this.stats.setBase(t,n)}computeBase(){let e=this.progression.level;return this.deriveStats?this.deriveStats(this.species.baseStats,e):{...this.species.baseStats}}},yW=class{constructor(){this.multipliers=new Map}key(e,t){return`${e}:${t}`}set(e,t,n){this.multipliers.set(this.key(e,t),n)}get(e,t){return this.multipliers.get(this.key(e,t))??1}multiplierFor(e,t){return t.reduce((t,n)=>t*this.get(e,n),1)}},bW=class{constructor(e){this.storage=[],this.active=Array(e).fill(null)}get members(){return this.active}get boxed(){return this.storage}add(e){let t=this.active.indexOf(null);t===-1?this.storage.push(e):this.active[t]=e}store(e){let t=this.active[e];t&&(this.active[e]=null,this.storage.push(t))}withdraw(e,t){if(t<0||t>=this.active.length)return;let n=this.storage[e];if(!n)return;this.storage.splice(e,1);let r=this.active[t];this.active[t]=n,r&&this.storage.push(r)}get activeMembers(){return this.active.filter(e=>e!==null)}};function xW(e){return[...e].sort((e,t)=>(t.priority??0)-(e.priority??0)||t.speed-e.speed)}function SW(e,t){let n=null;for(let r of e)r.at(t)&&(n=r.into);return n}var CW=class{constructor(e,t){this.stages=new Map,this.modifiers=new Map,this.stats=e,this.max=t.max,this.multiplierFor=t.multiplier}get(e){return this.stages.get(e)??0}change(e,t){let n=this.get(e),r=Math.max(-this.max,Math.min(this.max,n+t)),i=r-n;return i===0?0:(this.stages.set(e,r),this.applyModifier(e,r),i)}applyModifier(e,t){let n=this.modifiers.get(e);if(n&&this.stats.removeModifier(n),t===0){this.modifiers.delete(e);return}let r={stat:e,op:`multiply`,value:this.multiplierFor(t)};this.stats.addModifier(r),this.modifiers.set(e,r)}resetAll(){for(let e of this.modifiers.values())this.stats.removeModifier(e);this.modifiers.clear(),this.stages.clear()}};function wW(e,t,n,r=(e,n)=>t.multiplierFor(e.type,n)){if(e.length===0)return null;let i=e[0],a=r(i,n);for(let t of e.slice(1)){let e=r(t,n);e>a&&(a=e,i=t)}return i}function TW(e,t,n,r){let i=null,a=EW(e,n,r);return t.forEach((e,t)=>{let o=EW(e.types,n,r);o<a&&(a=o,i=t)}),i}function EW(e,t,n){return Math.max(...n.map(n=>t.multiplierFor(n,e)))}var DW=class extends S{},OW=class{constructor(){this.conditions=new Map}set(e){this.conditions.set(e.id,{...e})}has(e){return this.conditions.has(e)}get(e){return this.conditions.get(e)}clear(e){this.conditions.delete(e)}get active(){return[...this.conditions.values()]}advance(e=1){for(let[t,n]of this.conditions)n.duration!==void 0&&(n.duration-=e,n.duration<=0&&this.conditions.delete(t))}},kW=class{constructor(e){this.chanceToHit=AW(e.chanceToHit??1),this.strikeDuration=Math.max(0,e.strikeDuration??0),this.totalDamage=Math.max(0,e.damage)*Math.max(0,e.strikes),this.expectedDamage=this.totalDamage*this.chanceToHit,this.defenderHp0=e.defender.hp;let t=[],n=e.defender.hp;for(let r=0;r<=e.strikes;r++)r>0&&(e.hits?.[r-1]??!0)&&(n-=Math.max(0,e.damage)),t.push({strike:r,time:r*this.strikeDuration,attackerHp:e.attacker.hp,defenderHp:Math.max(0,n),defenderDamage:this.defenderHp0-Math.max(0,n)});this.frames=t}get duration(){return this.strikeDuration*(this.frames.length-1)}get defenderKilled(){return this.frames[this.frames.length-1].defenderHp===0}sampleAt(e){let t=this.frames.length-1;if(this.strikeDuration<=0)return this.frames[t];let n=0;for(let r=0;r<=t&&this.frames[r].time<=e+1e-9;r++)n=r;return this.frames[n]}};function AW(e){return Math.max(0,Math.min(1,e))}var jW=class{constructor(e){this.onChange=new p,this.stage_=`attacker`,this.charge=null,this.victim=null,this.highlight_=0,this.units=e.units,this.side=e.side,this.disabledOf=e.disabled??(e=>e.disabled??!1),this.canTarget=e.canTarget??(()=>!0)}get stage(){return this.stage_}get attacker(){return this.charge}get target(){return this.victim}get done(){return this.charge!==null&&this.victim!==null}get candidates(){return this.units.filter(e=>(this.side===void 0||e.side===this.side)&&!this.disabledOf(e))}get targets(){let e=this.charge;return e?this.units.filter(t=>t.id!==e.id&&!this.disabledOf(t)&&(e.side===void 0||t.side!==e.side)&&this.canTarget(e,t)):[]}get highlight(){return this.highlight_}get highlighted(){return this.active()[this.highlight_]??null}move(e){let t=this.active();t.length!==0&&(this.highlight_=((this.highlight_+e)%t.length+t.length)%t.length,this.onChange.dispatch())}select(){let e=this.highlighted;return e?(this.stage_===`attacker`?(this.charge=e,this.stage_=`target`,this.highlight_=0):this.victim=e,this.onChange.dispatch(),!0):!1}back(){if(this.stage_===`attacker`)return;let e=this.charge;this.charge=null,this.victim=null,this.stage_=`attacker`;let t=e?this.candidates.findIndex(t=>t.id===e.id):-1;this.highlight_=t>=0?t:0,this.onChange.dispatch()}reset(){this.charge=null,this.victim=null,this.stage_=`attacker`,this.highlight_=0,this.onChange.dispatch()}active(){return this.stage_===`attacker`?this.candidates:this.targets}},MW=class{constructor(e){this.onChange=new p,this.built=null,this.elapsed_=0,this.handleSelectorChange=()=>{if(this.selector.done&&this.attacker&&this.target){let e=this.damageFor(this.attacker,this.target);this.built=new kW({attacker:{hp:this.attacker.hp??0,name:this.attacker.id},defender:{hp:this.target.hp??0,name:this.target.id},damage:e.damage,strikes:e.strikes,...e.chanceToHit===void 0?{}:{chanceToHit:e.chanceToHit},...e.hits===void 0?{}:{hits:e.hits},strikeDuration:this.strikeDuration}),this.elapsed_=0}else this.built=null;this.onChange.dispatch()},this.damageFor=e.damageFor,this.strikeDuration=e.strikeDuration??0,this.selector=new jW({units:e.units,...e.side===void 0?{}:{side:e.side},...e.disabled===void 0?{}:{disabled:e.disabled},...e.canTarget===void 0?{}:{canTarget:e.canTarget}}),this.selector.onChange.add(this.handleSelectorChange)}get stage(){return this.selector.stage}get attacker(){return this.selector.attacker}get target(){return this.selector.target}get preview(){return this.built}get elapsed(){return this.elapsed_}get finished(){return this.built!==null&&this.elapsed_>=this.built.duration}get frame(){return this.built?this.built.sampleAt(this.elapsed_):null}move(e){this.selector.move(e)}select(){return this.selector.select()}back(){this.selector.back()}update(e){return this.built?(this.elapsed_=Math.min(this.built.duration,this.elapsed_+Math.max(0,e)),this.frame):null}finish(){this.built&&(this.elapsed_=this.built.duration)}reset(){this.selector.reset(),this.built=null,this.elapsed_=0}},NW=class{constructor(){this.onChange=new p,this.planned=[],this.undone=[]}get plans(){return this.planned}get isEmpty(){return this.planned.length===0}get canUndo(){return this.planned.length>0}get canRedo(){return this.undone.length>0}plannedFor(e){return this.planned.find(t=>t.unit===e)}plan(e){let t=this.planned.findIndex(t=>t.unit===e.unit);t>=0?this.planned[t]=e:this.planned.push(e),this.undone=[],this.onChange.dispatch()}undo(){let e=this.planned.pop();return e?(this.undone.push(e),this.onChange.dispatch(),e):null}redo(){let e=this.undone.pop();return e?(this.planned=this.planned.filter(t=>t.unit!==e.unit),this.planned.push(e),this.onChange.dispatch(),e):null}clear(){(this.planned.length!==0||this.undone.length!==0)&&(this.planned=[],this.undone=[],this.onChange.dispatch())}commit(){let e=this.planned;return this.planned=[],this.undone=[],e.length>0&&this.onChange.dispatch(),e}},PW=class e{constructor(){this.counts=new Map}record(e,t,n=1){let r=this.counts.get(e)??new Map;r.set(t,(r.get(t)??0)+n),this.counts.set(e,r)}forType(e,t){return this.counts.get(e)?.get(t)??0}total(e){let t=this.counts.get(e);if(!t)return 0;let n=0;for(let e of t.values())n+=e;return n}breakdown(e){let t=this.counts.get(e);return t?[...t.entries()].map(([e,t])=>({unitType:e,count:t})):[]}toJSON(){return{counts:[...this.counts].map(([e,t])=>[e,[...t]])}}static fromJSON(t){let n=new e;for(let[e,r]of t.counts)n.counts.set(e,new Map(r));return n}},FW=l({AttackDialog:()=>MW,AttackPreview:()=>kW,BattleHooks:()=>DW,BattleStats:()=>PW,Creature:()=>vW,Field:()=>OW,Party:()=>bW,StatStages:()=>CW,TypeMatrix:()=>yW,UnitSelector:()=>jW,Whiteboard:()=>NW,battleOrder:()=>xW,checkEvolution:()=>SW,chooseMove:()=>wW,chooseSwitch:()=>TW});function IW(e){let t=e.charCodeAt(0)-97,n=e.charCodeAt(1)-49;if(t<0||t>7||n<0||n>7||e.length!==2)throw Error(`not a square: "${e}"`);return n*8+t}function LW(e){return String.fromCharCode(97+(e&7))+String.fromCharCode(49+(e>>3))}function RW(e){let t=[];for(let n=7;n>=0;n--){let r=``,i=0;for(let t=0;t<8;t++){let a=e.board[n*8+t];if(!a){i++;continue}i>0&&(r+=String(i),i=0);let o={pawn:`p`,knight:`n`,bishop:`b`,rook:`r`,queen:`q`,king:`k`}[a.kind];r+=a.side===`white`?o.toUpperCase():o}i>0&&(r+=String(i)),t.push(r)}let n=(e.castling.whiteKingside?`K`:``)+(e.castling.whiteQueenside?`Q`:``)+(e.castling.blackKingside?`k`:``)+(e.castling.blackQueenside?`q`:``);return`${t.join(`/`)} ${e.turn===`white`?`w`:`b`} ${n||`-`} ${e.enPassant===null?`-`:LW(e.enPassant)}`}function zW(e){let t=e.trim().split(/\s+/);if(t.length<4)throw Error(`not a FEN string: "${e}"`);let n=Array(64).fill(null),r=t[0].split(`/`);if(r.length!==8)throw Error(`a FEN placement needs 8 ranks: "${e}"`);if(r.forEach((t,r)=>{let i=7-r,a=0;for(let r of t)if(r>=`1`&&r<=`8`)a+=r.charCodeAt(0)-48;else{let o=r===r.toUpperCase()?`white`:`black`,s={p:`pawn`,n:`knight`,b:`bishop`,r:`rook`,q:`queen`,k:`king`}[r.toLowerCase()];if(!s||a>7)throw Error(`bad FEN rank "${t}" in "${e}"`);n[i*8+a]={side:o,kind:s},a++}if(a!==8)throw Error(`bad FEN rank "${t}" in "${e}"`)}),t[1]!==`w`&&t[1]!==`b`)throw Error(`a FEN side is "w" or "b": "${e}"`);let i={whiteKingside:!1,whiteQueenside:!1,blackKingside:!1,blackQueenside:!1};if(t[2]!==`-`)for(let n of t[2])if(n===`K`)i.whiteKingside=!0;else if(n===`Q`)i.whiteQueenside=!0;else if(n===`k`)i.blackKingside=!0;else if(n===`q`)i.blackQueenside=!0;else throw Error(`bad FEN castling "${t[2]}" in "${e}"`);let a=t[3]===`-`?null:IW(t[3]);if(a!==null){let n=t[1]===`w`?5:2;if(HW(a)!==n)throw Error(`bad FEN en passant square "${t[3]}" in "${e}"`)}let o={board:n,turn:t[1]===`w`?`white`:`black`,castling:i,enPassant:a};return ZW(n,`white`),ZW(n,`black`),o}function BW(e){return e===`white`?`black`:`white`}function VW(e){return e&7}function HW(e){return e>>3}function UW(e,t){return e>=0&&e<8&&t>=0&&t<8}function WW(){let e=[`rook`,`knight`,`bishop`,`queen`,`king`,`bishop`,`knight`,`rook`],t=Array(64).fill(null);for(let n=0;n<8;n++)t[n]={side:`white`,kind:e[n]},t[8+n]={side:`white`,kind:`pawn`},t[48+n]={side:`black`,kind:`pawn`},t[56+n]={side:`black`,kind:e[n]};return{board:t,turn:`white`,castling:{whiteKingside:!0,whiteQueenside:!0,blackKingside:!0,blackQueenside:!0},enPassant:null}}function GW(e){return{board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}}var KW=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],qW=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],JW=[[1,1],[-1,1],[-1,-1],[1,-1]],YW=[[1,0],[0,1],[-1,0],[0,-1]];function XW(e,t,n){let r=VW(t),i=HW(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!UW(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of KW){if(!UW(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of qW){if(!UW(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let o=[{steps:JW,kinds:[`bishop`,`queen`]},{steps:YW,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of o)for(let[o,s]of t){let t=r+o,c=i+s;for(;UW(t,c);){let r=e[c*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,c+=s}}return!1}function ZW(e,t){let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n}function QW(e,t){return XW(e.board,ZW(e.board,t),BW(t))}function $W(e,t){let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=VW(t),a=HW(t),o=o=>{for(let[s,c]of o){let o=i+s,l=a+c;for(;UW(o,l);){let i=l*8+o,a=e.board[i];if(!a)r.push({from:t,to:i});else{a.side!==n.side&&r.push({from:t,to:i});break}o+=s,l+=c}}};switch(n.kind){case`pawn`:{let o=n.side===`white`?1:-1,s=n.side===`white`?1:6,c=n.side===`white`?7:0;if(UW(i,a+o)&&!e.board[(a+o)*8+i]){let n=(a+o)*8+i;if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),a===s&&!e.board[(a+2*o)*8+i]&&r.push({from:t,to:(a+2*o)*8+i})}for(let s of[-1,1]){if(!UW(i+s,a+o))continue;let l=(a+o)*8+i+s,u=e.board[l];if(u&&u.side!==n.side){if(a+o===c)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:a*8+i+s})}break}case`knight`:for(let[o,s]of KW){if(!UW(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];(!l||l.side!==n.side)&&r.push({from:t,to:c})}break;case`bishop`:o(JW);break;case`rook`:o(YW);break;case`queen`:o(JW),o(YW);break;case`king`:{for(let[o,s]of qW){if(!UW(i+o,a+s))continue;let c=(a+s)*8+i+o,l=e.board[c];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:c})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!QW(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!XW(e.board,o+5,BW(n.side))&&!XW(e.board,o+6,BW(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!XW(e.board,o+3,BW(n.side))&&!XW(e.board,o+2,BW(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r}function eG(e,t){let n=e.board[t.from];if(!n)throw Error(`no piece on ${LW(t.from)} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[tG(n.side,t.from)]=!1);let i=e.board[t.to];if(i&&i.kind===`rook`&&r(i.side,t.to)&&(e.castling[tG(i.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=BW(n.side)}function tG(e,t){let n=VW(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`}function nG(e){let t=[];for(let n=0;n<64;n++)if(e.board[n]&&e.board[n]?.side===e.turn)for(let r of $W(e,n)){let n=GW(e);eG(n,r),!QW(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t}function rG(e,t){let n=e.board[t.from];if(!n||n.side!==e.turn)throw Error(`no ${e.turn} piece on ${LW(t.from)} to move`);let r=$W(e,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!r)throw Error(`${LW(t.from)}-${LW(t.to)} is not a legal move here`);let i=GW(e);if(eG(i,r),QW(i,e.turn))throw Error(`${LW(t.from)}-${LW(t.to)} leaves the king in check`);eG(e,r)}function iG(e){return nG(e).length>0?`ongoing`:QW(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`}var aG=1e5;function oG(e,t,n){if(!Number.isInteger(n.depth)||n.depth<1)throw RangeError(`depth must be a positive integer`);let r=n.maxNodes??aG;if(!Number.isInteger(r)||r<1)throw RangeError(`maxNodes must be a positive integer`);let i=e.currentPlayer(t),a=0,o=0,s,c=(t,l,u,d)=>{if(n.signal?.aborted)return s=`cancelled`,0;if(++a>r)return s=`budget-exceeded`,0;let f=e.currentPlayer(t)===i;if(n.onNode?.(l,f),l===0||e.isTerminal(t))return e.evaluate(t,i);let p=e.moves(t);if(!p.length)return e.evaluate(t,i);let m=f?-1/0:1/0;for(let n of p){let r=c(e.apply(t,n),l-1,u,d);if(s)return r;if(f?(m=Math.max(m,r),u=Math.max(u,m)):(m=Math.min(m,r),d=Math.min(d,m)),d<=u){o++;break}}return m},l=e.moves(t),u=null,d=e.evaluate(t,i);if(!e.isTerminal(t)&&l.length){let r=e.currentPlayer(t)===i,a=r?-1/0:1/0,o=-1/0,f=1/0;for(let i of l){let l=c(e.apply(t,i),n.depth-1,o,f);if(s)break;(u===null||(r?l>a:l<a))&&(u=i,a=l),r?o=Math.max(o,a):f=Math.min(f,a)}u!==null&&(d=a)}return{move:s?null:u,score:d,depth:n.depth,nodes:a,cutoffs:o,status:s??`complete`,state:t}}function sG(e,t){return e.moves(t).map(n=>({move:n,child:e.apply(t,n)}))}function cG(e,t){let n=null,r=t?-1/0:1/0;for(let{move:i,score:a}of e)(n===null||(t?a>r:a<r))&&(n=i,r=a);return n}function lG(){return globalThis.process?.getBuiltinModule?.(`node:worker_threads`)}function uG(){let e=globalThis.process?.getBuiltinModule?.(`node:worker_threads`)?.parentPort??null,t=globalThis,n=e=>{let t=[],n=new Set,r=e=>{if(typeof e!=`object`||!e||n.has(e))return;if(n.add(e),ArrayBuffer.isView(e)){let n=e.buffer;n instanceof ArrayBuffer&&!t.includes(n)&&t.push(n);return}if(e instanceof ArrayBuffer){t.includes(e)||t.push(e);return}if(Array.isArray(e)){for(let t of e)r(t);return}let i=Object.getPrototypeOf(e);if(i===Object.prototype||i===null)for(let t of Object.values(e))r(t)};return r(e),t},r=(n,r=[])=>{e?e.postMessage(n,r):t.postMessage(n,r)},i=async e=>{try{let t=await Function(`return (${e.code});`)()(...e.args);r({ok:!0,value:t},n(t))}catch(e){let t=e;r({ok:!1,message:String(t?.message??e),stack:typeof t?.stack==`string`?t.stack:void 0})}};e?e.on(`message`,e=>void i(e)):t.onmessage=e=>void i(e.data)}var dG=e=>{if(typeof Worker>`u`||typeof Blob>`u`||typeof URL>`u`||typeof URL.createObjectURL!=`function`)return null;let t=URL.createObjectURL(new Blob([`(${uG.toString()})()`],{type:`text/javascript`})),n;try{n=new Worker(t)}catch(e){throw URL.revokeObjectURL(t),e}return n.onmessage=t=>e.reply(t.data),n.onerror=t=>e.fail(Error(t.message||`the worker failed to run`)),n.onmessageerror=()=>e.fail(Error(`the worker sent a reply that could not be deserialized`)),{post:(e,t)=>n.postMessage(e,t),terminate:()=>{n.terminate(),URL.revokeObjectURL(t)}}},fG=e=>{let t=lG();if(!t)return null;let n=new t.Worker(`(${uG.toString()})()`,{eval:!0});return n.on(`message`,t=>e.reply(t)),n.on(`error`,t=>e.fail(t instanceof Error?t:Error(String(t)))),n.on(`messageerror`,()=>e.fail(Error(`the worker sent a reply that could not be deserialized`))),n.on(`exit`,t=>e.fail(Error(`the worker exited with code ${t} before answering`))),{post:(e,t)=>n.postMessage(e,t),terminate:()=>void n.terminate()}};function pG(e){let t=Error(e.message);return e.stack&&(t.stack=e.stack),t}function mG(e,t,n={}){return new Promise((r,i)=>{if(n.signal?.aborted){i(n.signal.reason);return}let a=!1,o,s,c=e=>{a||(a=!0,o!==void 0&&clearTimeout(o),n.signal?.removeEventListener(`abort`,l),s?.terminate(),e())};function l(){c(()=>i(n.signal.reason))}let u={reply:e=>c(()=>{e.ok?r(e.value):i(pG(e))}),fail:e=>c(()=>i(e))};try{s=dG(u)??fG(u)}catch(e){i(e);return}if(!s)i(Error(`spawn() needs Web Workers or node:worker_threads, and this environment offers neither`));else{n.timeout!==void 0&&n.timeout>0&&(o=setTimeout(()=>c(()=>i(Error(`the task did not answer within ${n.timeout} ms`))),n.timeout)),n.signal?.addEventListener(`abort`,l,{once:!0});try{s.post({code:e.toString(),args:t??[]},n.transfer??[])}catch(e){c(()=>i(e))}}})}var hG=1e5,gG={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0};function _G(e,t={}){return vG(e,t).move}function vG(e,t={}){let n=oG(SG,e,{depth:Math.max(1,Math.floor(t.depth??3)),maxNodes:t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes))});return{move:n.move,score:n.score,nodes:n.nodes}}async function yG(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?1e5:Math.max(1,Math.floor(t.maxNodes)),i=t.jobs??bG();if(!Number.isInteger(i)||i<1)throw RangeError(`jobs must be a positive integer`);if(t.signal?.aborted)throw t.signal.reason;let a=SG.currentPlayer(e),o=sG(SG,e);if(SG.isTerminal(e)||!o.length)return{move:null,score:SG.evaluate(e,a),nodes:0};let s=Math.max(1,Math.min(i,o.length)),c=Array(o.length),l=0,u=!1,d=0,f=t.signal?{signal:t.signal}:{};if(await Promise.all(Array.from({length:s},async()=>{for(;;){let e=d++;if(e>=o.length)return;let t=await mG(xG,[o[e].child,a,n-1,r],f);l+=t.nodes,t.budgetExceeded?u=!0:c[e]={move:o[e].move,score:t.score}}})),u)return{move:null,score:SG.evaluate(e,a),nodes:l};let p=c.filter(e=>e!==void 0),m=cG(p,!0);return{move:m,score:p.find(e=>e.move===m)?.score??SG.evaluate(e,a),nodes:l}}function bG(){let e=globalThis,t=e.navigator?.hardwareConcurrency;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8);try{let t=e.process?.getBuiltinModule?.(`node:os`)?.availableParallelism?.();if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8)}catch{}return 4}function xG(e,t,n,r){let i={pawn:100,knight:320,bishop:330,rook:500,queen:900,king:0},a=e=>e===`white`?`black`:`white`,o=e=>e&7,s=e=>e>>3,c=(e,t)=>e>=0&&e<8&&t>=0&&t<8,l=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],u=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],d=[[1,1],[-1,1],[-1,-1],[1,-1]],f=[[1,0],[0,1],[-1,0],[0,-1]],p=(e,t,n)=>{let r=o(t),i=s(t),a=n===`white`?i-1:i+1;for(let t of[-1,1]){if(!c(r+t,a))continue;let i=e[a*8+r+t];if(i&&i.side===n&&i.kind===`pawn`)return!0}for(let[t,a]of l){if(!c(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`knight`)return!0}for(let[t,a]of u){if(!c(r+t,i+a))continue;let o=e[(i+a)*8+r+t];if(o&&o.side===n&&o.kind===`king`)return!0}let p=[{steps:d,kinds:[`bishop`,`queen`]},{steps:f,kinds:[`rook`,`queen`]}];for(let{steps:t,kinds:a}of p)for(let[o,s]of t){let t=r+o,l=i+s;for(;c(t,l);){let r=e[l*8+t];if(r){if(r.side===n&&a.includes(r.kind))return!0;break}t+=o,l+=s}}return!1},m=(e,t)=>{let n=e.findIndex(e=>e!==null&&e.side===t&&e.kind===`king`);if(n===-1)throw Error(`a position without a ${t} king cannot be judged`);return n},h=(e,t)=>p(e.board,m(e.board,t),a(t)),g=(e,t)=>{let n=e.board[t];if(!n||n.side!==e.turn)return[];let r=[],i=o(t),m=s(t),g=a=>{for(let[o,s]of a){let a=i+o,l=m+s;for(;c(a,l);){let i=l*8+a,c=e.board[i];if(!c)r.push({from:t,to:i});else{c.side!==n.side&&r.push({from:t,to:i});break}a+=o,l+=s}}};switch(n.kind){case`pawn`:{let a=n.side===`white`?1:-1,o=n.side===`white`?1:6,s=n.side===`white`?7:0;if(c(i,m+a)&&!e.board[(m+a)*8+i]){let n=(m+a)*8+i;if(m+a===s)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:n,promotion:e});else r.push({from:t,to:n}),m===o&&!e.board[(m+2*a)*8+i]&&r.push({from:t,to:(m+2*a)*8+i})}for(let o of[-1,1]){if(!c(i+o,m+a))continue;let l=(m+a)*8+i+o,u=e.board[l];if(u&&u.side!==n.side){if(m+a===s)for(let e of[`knight`,`bishop`,`rook`,`queen`])r.push({from:t,to:l,promotion:e});else r.push({from:t,to:l})}else!u&&l===e.enPassant&&r.push({from:t,to:l,enPassantTake:m*8+i+o})}break}case`knight`:for(let[a,o]of l){if(!c(i+a,m+o))continue;let s=(m+o)*8+i+a,l=e.board[s];(!l||l.side!==n.side)&&r.push({from:t,to:s})}break;case`bishop`:g(d);break;case`rook`:g(f);break;case`queen`:g(d),g(f);break;case`king`:{for(let[a,o]of u){if(!c(i+a,m+o))continue;let s=(m+o)*8+i+a,l=e.board[s];l&&l.side===n.side||l&&l.kind===`king`||r.push({from:t,to:s})}let o=n.side===`white`?0:56,s=n.side===`white`?{king:e.castling.whiteKingside,queen:e.castling.whiteQueenside}:{king:e.castling.blackKingside,queen:e.castling.blackQueenside};t===o+4&&!h(e,n.side)&&(s.king&&!e.board[o+5]&&!e.board[o+6]&&!p(e.board,o+5,a(n.side))&&!p(e.board,o+6,a(n.side))&&r.push({from:t,to:o+6,castle:`kingside`}),s.queen&&!e.board[o+3]&&!e.board[o+2]&&!e.board[o+1]&&!p(e.board,o+3,a(n.side))&&!p(e.board,o+2,a(n.side))&&r.push({from:t,to:o+2,castle:`queenside`}));break}}return r},_=(e,t)=>{let n=e.board[t.from];if(!n)throw Error(`no piece on ${t.from} to move`);let r=(e,t)=>{let n=e===`white`?0:56;return t===n||t===n+7},i=(e,t)=>{let n=o(t)===7;return e===`white`?n?`whiteKingside`:`whiteQueenside`:n?`blackKingside`:`blackQueenside`};n.kind===`king`&&(n.side===`white`?e.castling.whiteKingside=e.castling.whiteQueenside=!1:e.castling.blackKingside=e.castling.blackQueenside=!1),n.kind===`rook`&&r(n.side,t.from)&&(e.castling[i(n.side,t.from)]=!1);let s=e.board[t.to];if(s&&s.kind===`rook`&&r(s.side,t.to)&&(e.castling[i(s.side,t.to)]=!1),e.board[t.to]=t.promotion?{side:n.side,kind:t.promotion}:n,e.board[t.from]=null,t.enPassantTake!==void 0&&(e.board[t.enPassantTake]=null),t.castle){let r=n.side===`white`?0:56;t.castle===`kingside`?(e.board[r+5]=e.board[r+7],e.board[r+7]=null):(e.board[r+3]=e.board[r],e.board[r]=null)}e.enPassant=n.kind===`pawn`&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.turn=a(n.side)},v=e=>({board:e.board.map(e=>e?{side:e.side,kind:e.kind}:null),turn:e.turn,castling:{...e.castling},enPassant:e.enPassant}),y=e=>{let t=[];for(let n=0;n<64;n++)if(e.board[n]&&e.board[n]?.side===e.turn)for(let r of g(e,n)){let n=v(e);_(n,r),!h(n,e.turn)&&t.push({from:r.from,to:r.to,...r.promotion?{promotion:r.promotion}:{}})}return t},b=e=>y(e).length>0?`ongoing`:h(e,e.turn)?e.turn===`white`?`black-wins`:`white-wins`:`stalemate`,x=(e,t)=>{let n=e.board[t.to];return(t.promotion?i[t.promotion]:0)*10+(n?i[n.kind]:0)},S=(e,t)=>t.slice().sort((t,n)=>x(e,n)-x(e,t)),C=(e,t)=>{let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*i[t.kind]);return t===1?n:-n},ee=(e,t)=>{let n=b(e);return n===`stalemate`||!h(e,e.turn)?0:(n===`white-wins`?1:-1)===t?1e5:-1e5},w=e=>b(e)===`ongoing`?C(e,t):ee(e,t),T=0,E=!1,te=(e,n,i,a)=>{if(++T>r)return E=!0,0;let o=(e.turn===`white`?1:-1)===t;if(n===0||b(e)!==`ongoing`)return w(e);let s=S(e,y(e));if(!s.length)return w(e);let c=o?-1/0:1/0;for(let t of s){let r=v(e),s=g(r,t.from).find(e=>e.to===t.to&&(e.promotion??null)===(t.promotion??null));if(!s)throw Error(`a legal move stopped being legal: ${t.from}-${t.to}`);_(r,s);let l=te(r,n-1,i,a);if(E)return l;if(o?(c=Math.max(c,l),i=Math.max(i,c)):(c=Math.min(c,l),a=Math.min(a,c)),a<=i)break}return c};return{score:te(e,n,-1/0,1/0),nodes:T,budgetExceeded:E}}var SG={currentPlayer:e=>e.turn===`white`?1:-1,moves:e=>TG(e,nG(e)),apply:(e,t)=>{let n=GW(e);return rG(n,t),n},isTerminal:e=>iG(e)!==`ongoing`,evaluate:(e,t)=>iG(e)===`ongoing`?CG(e,t):wG(e,t)};function CG(e,t){let n=0;for(let t of e.board)t&&(n+=(t.side===`white`?1:-1)*gG[t.kind]);return t===1?n:-n}function wG(e,t){let n=iG(e);return n===`stalemate`||!QW(e,e.turn)?0:(n===`white-wins`?1:-1)===t?hG:-1e5}function TG(e,t){return t.slice().sort((t,n)=>EG(e,n)-EG(e,t))}function EG(e,t){let n=e.board[t.to];return(t.promotion?gG[t.promotion]:0)*10+(n?gG[n.kind]:0)}function DG(e,t){return e.positions[RW(t)]??null}var OG={q:`queen`,r:`rook`,b:`bishop`,n:`knight`};function kG(e){let t=/^([a-h][1-8])([a-h][1-8])([qrbn])?$/.exec(e);if(!t)throw Error(`not a UCI move: "${e}"`);let n=t[3]?OG[t[3]]:void 0;return n?{from:IW(t[1]),to:IW(t[2]),promotion:n}:{from:IW(t[1]),to:IW(t[2])}}var AG={pawn:0,knight:1,bishop:2,rook:3,queen:4,king:5},jG=[`queen`,`rook`,`bishop`,`knight`],MG=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],NG=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],PG=[[1,1],[-1,1],[-1,-1],[1,-1]],FG=[[1,0],[0,1],[-1,0],[0,-1]];function IG(e){return 1n<<BigInt(e)}function LG(e){return Math.log2(Number(e))}function RG(e){return Array.from({length:64},(t,n)=>{let r=n&7,i=n>>3,a=0n;for(let[t,n]of e){let e=r+t,o=i+n;e>=0&&e<8&&o>=0&&o<8&&(a|=IG(o*8+e))}return a})}var zG=RG(MG),BG=RG(NG);function VG(e,t){return e.pieces[t]|e.pieces[t+1]|e.pieces[t+2]|e.pieces[t+3]|e.pieces[t+4]|e.pieces[t+5]}function HG(e,t){let n=IG(t);for(let t=0;t<12;t++)if(e.pieces[t]&n)return t;return-1}function UG(e,t,n){let r=n?0:6,i=t&7,a=t>>3,o=n?a-1:a+1;for(let t of[-1,1]){let n=i+t;if(o>=0&&o<8&&n>=0&&n<8&&e.pieces[r]&IG(o*8+n))return!0}if(zG[t]&e.pieces[r+1]||BG[t]&e.pieces[r+5])return!0;let s=[{steps:PG,kinds:[2,4]},{steps:FG,kinds:[3,4]}];for(let{steps:t,kinds:n}of s)for(let[o,s]of t){let t=i+o,c=a+s;for(;t>=0&&t<8&&c>=0&&c<8;){let i=HG(e,c*8+t);if(i!==-1){if(i>=r&&i<r+6&&n.includes(i-r))return!0;break}t+=o,c+=s}}return!1}function WG(e,t){return e===`white`?t?1:2:t?4:8}function GG(e){let t=Array(12).fill(0n),n=[-1,-1];if(e.board.forEach((e,r)=>{if(!e)return;let i=(e.side===`white`?0:6)+AG[e.kind];t[i]|=IG(r),e.kind===`king`&&(n[e.side===`white`?0:1]=r)}),n[0]===-1||n[1]===-1)throw Error(`a position without both kings cannot go on bitboards`);return{pieces:t,turn:e.turn,castling:+!!e.castling.whiteKingside|(e.castling.whiteQueenside?2:0)|(e.castling.blackKingside?4:0)|(e.castling.blackQueenside?8:0),enPassant:e.enPassant,halfmove:0,kings:n}}function KG(){return GG(WW())}function qG(e){let t=e.turn===`white`,n=t?0:6,r=VG(e,n),i=VG(e,n===0?6:0),a=r|i,o=[],s=[];for(let c=0;c<64;c++){if(!(r&IG(c)))continue;let l=-1;for(let t=0;t<6;t++)if(e.pieces[n+t]&IG(c)){l=t;break}s.length=0,JG(e,c,l,a,i,s);for(let n of s){let r=YG(e,n);UG(e,e.kings[+!t],!t)||o.push({...n}),XG(e,n,r)}}return o}function JG(e,t,n,r,i,a){let o=e.turn===`white`,s=t&7,c=t>>3,l=(e,n)=>{a.push(n?{from:t,to:e,promotion:n}:{from:t,to:e})},u=e=>{for(let[t,n]of e){let e=s+t,a=c+n;for(;e>=0&&e<8&&a>=0&&a<8;){let o=a*8+e,s=IG(o);if(!(r&s))l(o);else{i&s&&l(o);break}e+=t,a+=n}}};switch(n){case 0:{let n=o?8:-8,a=o?1:6,u=o?7:0,d=t+n;if(d>=0&&d<64&&!(r&IG(d))){if(d>>3===u)for(let e of jG)l(d,e);else{l(d);let e=t+2*n;c===a&&!(r&IG(e))&&l(e)}}for(let r of[-1,1]){let a=s+r;if(a<0||a>7)continue;let o=t+n+r;if(!(o<0||o>=64)){if(i&IG(o)){if(o>>3===u)for(let e of jG)l(o,e);else l(o)}else o===e.enPassant&&l(o)}}break}case 1:{let n=zG[t]&~VG(e,o?0:6);for(;n;){let e=n&-n;l(LG(e)),n^=e}break}case 2:u(PG);break;case 3:u(FG);break;case 4:u(PG),u(FG);break;case 5:{let n=BG[t]&~VG(e,o?0:6);for(n&=~e.pieces[o?11:5];n;){let e=n&-n;l(LG(e)),n^=e}let i=o?0:56,a=e.castling,s=o?a&1:a&4,c=o?a&2:a&8;t===i+4&&!UG(e,t,!o)&&(s&&!(r&IG(i+5))&&!(r&IG(i+6))&&!UG(e,i+5,!o)&&!UG(e,i+6,!o)&&l(i+6),c&&!(r&IG(i+3))&&!(r&IG(i+2))&&!(r&IG(i+1))&&!UG(e,i+3,!o)&&!UG(e,i+2,!o)&&l(i+2));break}}}function YG(e,t){let n=e.turn===`white`,r=+!n,i=r*6,a=IG(t.from),o=IG(t.to),s=-1;for(let t=0;t<6;t++)if(e.pieces[i+t]&a){s=t;break}if(s===-1)throw Error(`no piece on ${t.from} to move`);let c={captured:null,castling:e.castling,enPassant:e.enPassant,halfmove:e.halfmove,kingSquare:e.kings[r]},l=(1-r)*6,u=n?8:-8,d=t.to;s===0&&t.to===e.enPassant&&(d=t.to-u);let f=IG(d);for(let t=0;t<6;t++)if(e.pieces[l+t]&f){c.captured={color:1-r,kind:t},e.pieces[l+t]^=f;break}let p=n?0:56,m=n?56:0;if(s===5&&(e.castling&=~(WG(e.turn,!0)|WG(e.turn,!1))),s===3&&(t.from===p||t.from===p+7)&&(e.castling&=~WG(e.turn,t.from===p+7)),c.captured?.kind===3&&(d===m||d===m+7)&&(e.castling&=~WG(n?`black`:`white`,d===m+7)),e.pieces[i+s]^=a,t.promotion?e.pieces[i+AG[t.promotion]]|=o:e.pieces[i+s]|=o,s===5&&Math.abs(t.to-t.from)===2){let n=i+3;t.to>t.from?e.pieces[n]^=IG(p+7)|IG(p+5):e.pieces[n]^=IG(p)|IG(p+3)}return e.enPassant=s===0&&Math.abs(t.to-t.from)===16?(t.from+t.to)/2:null,e.halfmove=s===0||c.captured?0:e.halfmove+1,s===5&&(e.kings[r]=t.to),e.turn=n?`black`:`white`,c}function XG(e,t,n){e.turn=e.turn===`white`?`black`:`white`;let r=e.turn===`white`,i=+!r,a=i*6,o=IG(t.to),s=t.promotion?0:(()=>{for(let t=0;t<6;t++)if(e.pieces[a+t]&o)return t;throw Error(`nothing on ${t.to} to take back`)})();if(t.promotion?e.pieces[a+AG[t.promotion]]^=o:e.pieces[a+s]^=o,e.pieces[a+s]|=IG(t.from),s===5&&Math.abs(t.to-t.from)===2){let n=r?0:56,i=a+3;t.to>t.from?e.pieces[i]^=IG(n+7)|IG(n+5):e.pieces[i]^=IG(n)|IG(n+3)}if(n.captured){let a=r?8:-8,o=s===0&&t.to===n.enPassant?t.to-a:t.to;e.pieces[(1-i)*6+n.captured.kind]|=IG(o)}e.castling=n.castling,e.enPassant=n.enPassant,e.halfmove=n.halfmove,e.kings[i]=n.kingSquare}function ZG(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`perft depth must be a non-negative integer`);if(t===0)return 1;let n=0;for(let r of qG(e)){let i=YG(e,r);n+=ZG(e,t-1),XG(e,r,i)}return n}function QG(e,t={}){let n=1e6,r=[100,320,330,500,900,0],i=Math.max(1,Math.floor(t.depth??3)),a=t.maxNodes===void 0?5e5:Math.max(1,Math.floor(t.maxNodes)),o=t.timeMs===void 0?-1:Date.now()+Math.max(1,t.timeMs),s={pieces:e.pieces.slice(),turn:e.turn,castling:e.castling,enPassant:e.enPassant,halfmove:e.halfmove,kings:[e.kings[0],e.kings[1]]};function c(e){return 1n<<BigInt(e)}function l(e){return Math.log2(Number(e))}let u=[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]],d=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]],f=[[1,1],[-1,1],[-1,-1],[1,-1]],p=[[1,0],[0,1],[-1,0],[0,-1]];function m(e){return Array.from({length:64},(t,n)=>{let r=n&7,i=n>>3,a=0n;for(let[t,n]of e){let e=r+t,o=i+n;e>=0&&e<8&&o>=0&&o<8&&(a|=c(o*8+e))}return a})}let h=m(u),g=m(d);function _(e){return s.pieces[e]|s.pieces[e+1]|s.pieces[e+2]|s.pieces[e+3]|s.pieces[e+4]|s.pieces[e+5]}function v(e){let t=c(e);for(let e=0;e<12;e++)if(s.pieces[e]&t)return e%6;return-1}function y(e,t){let n=t?0:6,r=e&7,i=e>>3,a=t?i-1:i+1;for(let e of[-1,1]){let t=r+e;if(a>=0&&a<8&&t>=0&&t<8&&s.pieces[n]&c(a*8+t))return!0}if(h[e]&s.pieces[n+1]||g[e]&s.pieces[n+5])return!0;let o=[{steps:f,kinds:[2,4]},{steps:p,kinds:[3,4]}];for(let{steps:e,kinds:n}of o)for(let[a,o]of e){let e=r+a,l=i+o;for(;e>=0&&e<8&&l>=0&&l<8;){let r=v(l*8+e);if(r!==-1){if((()=>{let t=c(l*8+e);for(let e=0;e<12;e++)if(s.pieces[e]&t)return e<6?0:1;return-1})()===+!t&&n.includes(r))return!0;break}e+=a,l+=o}}return!1}let b=0n,x=11400714819323198485n;function S(){x=x+11400714819323198485n&18446744073709551615n;let e=x;return e=(e^e>>30n)*13787848793156543929n&18446744073709551615n,e=(e^e>>27n)*10723151780598845931n&18446744073709551615n,e^e>>31n}let C=Array.from({length:12},()=>Array.from({length:64},()=>S())),ee=S(),w=Array.from({length:16},()=>S()),T=Array.from({length:8},()=>S());function E(){let e=0n;for(let t=0;t<12;t++){let n=s.pieces[t];for(;n;){let r=n&-n;e^=C[t][l(r)],n^=r}}return s.turn===`black`&&(e^=ee),e^=w[s.castling],s.enPassant!==null&&(e^=T[s.enPassant&7]),e}b=E();function te(e,t){return e===`white`?t?1:2:t?4:8}function D(e){let t=s.turn===`white`,n=+!t,r=n*6,i=c(e.from),a=c(e.to),o=-1;for(let e=0;e<6;e++)if(s.pieces[r+e]&i){o=e;break}let l={captured:null,castling:s.castling,enPassant:s.enPassant,halfmove:s.halfmove,kingSquare:s.kings[n],key:b,nullMove:!1},u=(1-n)*6,d=t?8:-8,f=e.to;o===0&&e.to===s.enPassant&&(f=e.to-d);let p=c(f);for(let e=0;e<6;e++)if(s.pieces[u+e]&p){l.captured={color:1-n,kind:e},s.pieces[u+e]^=p;break}let m=t?0:56,h=t?56:0;o===5&&(s.castling&=~(te(s.turn,!0)|te(s.turn,!1))),o===3&&(e.from===m||e.from===m+7)&&(s.castling&=~te(s.turn,e.from===m+7)),l.captured&&l.captured.kind===3&&(f===h||f===h+7)&&(s.castling&=~te(t?`black`:`white`,f===h+7));let g={queen:4,rook:3,bishop:2,knight:1};if(s.pieces[r+o]^=i,e.promotion?s.pieces[r+g[e.promotion]]|=a:s.pieces[r+o]|=a,o===5&&Math.abs(e.to-e.from)===2){let t=r+3;e.to>e.from?s.pieces[t]^=c(m+7)|c(m+5):s.pieces[t]^=c(m)|c(m+3)}return s.enPassant=o===0&&Math.abs(e.to-e.from)===16?(e.from+e.to)/2:null,s.halfmove=o===0||l.captured?0:s.halfmove+1,o===5&&(s.kings[n]=e.to),s.turn=t?`black`:`white`,b=E(),l}function O(e,t){s.turn=s.turn===`white`?`black`:`white`;let n=s.turn===`white`,r=+!n,i=r*6,a=c(e.to),o=e.promotion?0:(()=>{for(let e=0;e<6;e++)if(s.pieces[i+e]&a)return e;return-1})(),l={queen:4,rook:3,bishop:2,knight:1};if(e.promotion?s.pieces[i+l[e.promotion]]^=a:s.pieces[i+o]^=a,s.pieces[i+o]|=c(e.from),o===5&&Math.abs(e.to-e.from)===2){let t=n?0:56,r=i+3;e.to>e.from?s.pieces[r]^=c(t+7)|c(t+5):s.pieces[r]^=c(t)|c(t+3)}if(t.captured){let i=n?8:-8,a=o===0&&e.to===t.enPassant?e.to-i:e.to;s.pieces[(1-r)*6+t.captured.kind]|=c(a)}s.castling=t.castling,s.enPassant=t.enPassant,s.halfmove=t.halfmove,s.kings[r]=t.kingSquare,b=t.key}function ne(){let e={captured:null,castling:s.castling,enPassant:s.enPassant,halfmove:s.halfmove,kingSquare:-1,key:b,nullMove:!0};return s.enPassant=null,s.halfmove+=1,s.turn=s.turn===`white`?`black`:`white`,b=E(),e}function k(e){s.turn=s.turn===`white`?`black`:`white`,s.enPassant=e.enPassant,s.halfmove=e.halfmove,b=e.key}function A(e,t,n,r,i){let a=s.turn===`white`,o=e&7,u=e>>3,d=(t,n)=>{i.push(n?{from:e,to:t,promotion:n}:{from:e,to:t})},m=e=>{for(let[t,i]of e){let e=o+t,a=u+i;for(;e>=0&&e<8&&a>=0&&a<8;){let o=a*8+e,s=c(o);if(!(n&s))d(o);else{r&s&&d(o);break}e+=t,a+=i}}},v=[`queen`,`rook`,`bishop`,`knight`];if(t===0){let t=a?8:-8,i=a?1:6,l=a?7:0,f=e+t;if(f>=0&&f<64&&!(n&c(f))){if(f>>3===l)for(let e of v)d(f,e);else{d(f);let r=e+2*t;u===i&&!(n&c(r))&&d(r)}}for(let n of[-1,1]){let i=o+n;if(i<0||i>7)continue;let a=e+t+n;if(!(a<0||a>=64)){if(r&c(a)){if(a>>3===l)for(let e of v)d(a,e);else d(a)}else a===s.enPassant&&d(a)}}}else if(t===1){let t=h[e]&~_(a?0:6);for(;t;){let e=t&-t;d(l(e)),t^=e}}else if(t===2)m(f);else if(t===3)m(p);else if(t===4)m(f),m(p);else{let t=g[e]&~_(a?0:6);for(t&=~s.pieces[a?11:5];t;){let e=t&-t;d(l(e)),t^=e}let r=a?0:56,i=s.castling,o=a?i&1:i&4,u=a?i&2:i&8;e===r+4&&!y(e,!a)&&(o&&!(n&c(r+5))&&!(n&c(r+6))&&!y(r+5,!a)&&!y(r+6,!a)&&d(r+6),u&&!(n&c(r+3))&&!(n&c(r+2))&&!(n&c(r+1))&&!y(r+3,!a)&&!y(r+2,!a)&&d(r+2))}}function re(){let e=s.turn===`white`,t=e?0:6,n=_(t),r=_(t===0?6:0),i=n|r,a=[],o=[];for(let l=0;l<64;l++){if(!(n&c(l)))continue;let u=-1;for(let e=0;e<6;e++)if(s.pieces[t+e]&c(l)){u=e;break}o.length=0,A(l,u,i,r,o);for(let t of o){let n=D(t);y(s.kings[+!e],!e)||a.push({...t}),O(t,n)}}return a}function ie(e){let t=e?0:6;return s.pieces[t+1]!==0n||s.pieces[t+2]!==0n||s.pieces[t+3]!==0n||s.pieces[t+4]!==0n}function ae(){let e=0,t=0;for(let n=0;n<12;n++){if(n%6==5)continue;let r=s.pieces[n];for(;r;)r&=r-1n,e++,(n%6==1||n%6==2)&&t++}return e===0||e===1&&t===1}function oe(){let e=0,t=0;for(let n=0;n<12;n++){let r=s.pieces[n];for(;r;)r&=r-1n,n%6==4?e++:n%6!=5&&n%6!=0&&t++}return e===0||e===2&&t<=2}function se(e,t,n,r){let i=t&7,a=n?t>>3:7-(t>>3),o=3.5-Math.abs(i-3.5),s=3.5-Math.abs(a-3.5);return e===0?(a-1)*12+Math.max(0,o)*4:e===1?(o+s)*6-12:e===2?(o+s)*4:e===3?(o+s)*2+(a===6?12:0):e===4?(o+s)*2:r?(o+s)*10:-a*10+o*2}function j(){let e=oe(),t=0;for(let n=0;n<12;n++){let i=n<6,a=n%6,o=s.pieces[n];for(;o;){let n=o&-o,s=l(n),c=r[a]+se(a,s,i,e);t+=i?c:-c,o^=n}}return s.turn===`white`?t:-t}let ce=65536,le=Array(ce).fill(-1n),ue=Array(ce).fill(-1),de=Array(ce).fill(0),fe=Array(ce).fill(0),pe=Array(ce).fill(0);function me(e){let t=e.promotion===`queen`?1:e.promotion===`rook`?2:e.promotion===`bishop`?3:e.promotion===`knight`?4:0;return e.from|e.to<<6|t<<12}function he(e,t,n,r){let i=Number(b&BigInt(65535));if(le[i]!==b)return{score:null,move:0};let a=pe[i];if(ue[i]<e)return{score:null,move:a};let o=de[i];o>99e3?o-=r:o<-99e3&&(o+=r);let s=fe[i];return s===0||s===1&&o>=n||s===2&&o<=t?{score:o,move:a}:{score:null,move:a}}function ge(e,t,n,r,i){let a=Number(b&BigInt(65535));if(le[a]===b&&ue[a]>e)return;let o=t;t>99e3?o+=i:t<-99e3&&(o-=i),le[a]=b,ue[a]=e,de[a]=o,fe[a]=n,pe[a]=r}let _e=Array.from({length:64},()=>[0,0]),ve=Array.from({length:2},()=>Array.from({length:64},()=>Array(64).fill(0)));function M(e){let t=s.turn===`white`?6:0,n=c(e);for(let e=4;e>=0;e--)if(s.pieces[t+e]&n)return e;return-1}function N(e,t,n){let i=s.turn===`white`?0:1,a=e.map(e=>{let a=me(e);if(a===t)return 3e6;let o=M(e.to),c=v(e.from),l=e.to===s.enPassant&&c===0;if(o!==-1||l){let t=2e6+(l?r[0]:r[o])*8-c;return e.promotion&&(t+=900),t}return e.promotion?15e5:n<64?_e[n][0]===a?1e6:_e[n][1]===a?9e5:ve[i][e.from][e.to]:0}),o=e.map((e,t)=>t);for(let e=0;e<o.length;e++){let t=e;for(let n=e+1;n<o.length;n++)a[o[n]]>a[o[t]]&&(t=n);[o[e],o[t]]=[o[t],o[e]]}return o}let ye=0,be=!1,P=[];function xe(){return be?!0:ye>a||t.signal?.aborted||o!==-1&&!(ye&2047)&&Date.now()>=o?(be=!0,!0):!1}function Se(e,t,n){if(ye++,xe())return 0;let i=s.turn===`white`;if(s.halfmove>=100||ae())return 0;if(y(s.kings[+!i],!i))return F(1,e,t,n,!1);let a=j();if(a>=t)return t;a>e&&(e=a);let o=re().filter(e=>{if(e.promotion||e.to===s.enPassant&&v(e.from)===0)return!0;let t=i?6:0,n=c(e.to);for(let e=0;e<5;e++)if(s.pieces[t+e]&n)return!0;return!1}),l=N(o,0,Math.min(n,63));for(let i of l){let s=o[i],c=M(s.to);if(a+(c===-1?900:r[c])+200<e)continue;let l=D(s);P.push(b);let u=-Se(-t,-e,n+1);if(P.pop(),O(s,l),be)return 0;if(u>=t)return t;u>e&&(e=u)}return e}function F(e,t,n,r,i){if(ye++,xe())return 0;let a=s.turn===`white`;if(s.halfmove>=100||ae())return 0;let o=0;for(let e of P)if(e===b&&++o>=2)return 0;if(r>=64)return j();if(e<=0)return Se(t,n,r);let c=y(s.kings[+!a],!a),l=he(e,t,n,r);if(l.score!==null)return l.score;if(c)i=!1;else if(i&&e>=3&&ie(a)&&n<99e3){let t=e>4?3:2,i=ne();P.push(b);let a=-F(e-1-t,-n,-n+1,r+1,!1);if(P.pop(),k(i),be)return 0;if(a>=n)return n}let u=re();if(u.length===0)return c?-(1e5-r):0;let d=N(u,l.move,Math.min(r,63)),f=+!a,p=-1e6,m=0,h=2;for(let i=0;i<d.length;i++){let a=u[d[i]],o=me(a),l=M(a.to)!==-1||a.to===s.enPassant&&v(a.from)===0,g=D(a);P.push(b);let _;if(i===0)_=-F(e-1,-n,-t,r+1,!0);else{let o=0;e>=3&&i>=4&&!l&&!a.promotion&&!c&&(o=1),o>0?(_=-F(e-1-o,-t-1,-t,r+1,!0),!be&&_>t&&(_=-F(e-1,-n,-t,r+1,!0))):(_=-F(e-1,-t-1,-t,r+1,!0),!be&&_>t&&_<n&&(_=-F(e-1,-n,-t,r+1,!0)))}if(P.pop(),O(a,g),be)return 0;if(_>p&&(p=_,m=o),_>t&&(t=_,h=+(_>=n),!l&&!a.promotion&&r<64&&(ve[f][a.from][a.to]+=e*e,_e[r][0]!==o&&(_e[r][1]=_e[r][0],_e[r][0]=o))),t>=n)break}return ge(e,p,h,m,r),p}let Ce=re();if(Ce.length===0){let e=s.turn===`white`;return{move:null,score:y(s.kings[+!e],!e)?-1e5:0,nodes:ye,depth:0}}P.push(b);let we={from:Ce[0].from,to:Ce[0].to,...Ce[0].promotion?{promotion:Ce[0].promotion}:{}},Te=-1e6,Ee=0,De=Ce.map(e=>({...e}));for(let e=1;e<=i;e++){let t=-1e6,r=n,i=!1,a=we,o=Te;e>=4&&Ee>0&&(i=!0,t=Te-24,r=Te+24);for(let s=0;s<3;s++){let s=t,c=r,l=a,u=-1e6,d=N(De,me({from:a.from,to:a.to,promotion:a.promotion}),0),f=[];for(let n=0;n<d.length;n++){let i=De[d[n]],a=D(i);P.push(b);let o;if(n===0?o=-F(e-1,-r,-t,1,!0):(o=-F(e-1,-t-1,-t,1,!0),!be&&o>t&&o<r&&(o=-F(e-1,-r,-t,1,!0))),P.pop(),O(i,a),be)break;f.push(i),o>u&&(u=o,l=i),o>t&&(t=o)}if(be)break;for(let e of De)f.includes(e)||f.push(e);if(De=f,a=l,o=u,!i)break;if(u<=s||u>=c)t=-1e6,r=n,i=!1;else break}if(be||(we=a,Te=o,De=[we,...De.filter(e=>e!==we)],Ee=e,Te>99e3||Te<-99e3)||xe())break}return P.pop(),Ee===0?{move:null,score:j(),nodes:ye,depth:0}:{move:we,score:Te,nodes:ye,depth:Ee}}function $G(e){let t=`pieces`in e?e:GG(e);return{pieces:t.pieces.slice(),turn:t.turn,castling:t.castling,enPassant:t.enPassant,halfmove:t.halfmove,kings:[t.kings[0],t.kings[1]]}}function eK(e,t={}){return QG($G(e),{depth:t.depth,maxNodes:t.maxNodes,timeMs:t.timeMs,signal:t.signal})}function tK(){let e=globalThis,t=e.navigator?.hardwareConcurrency;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8);try{let t=e.process?.getBuiltinModule?.(`node:os`)?.availableParallelism?.();if(typeof t==`number`&&Number.isInteger(t)&&t>0)return Math.min(t,8)}catch{}return 4}async function nK(e,t={}){let n=Math.max(1,Math.floor(t.depth??3)),r=t.maxNodes===void 0?5e5:Math.max(1,Math.floor(t.maxNodes)),i=t.jobs??tK();if(!Number.isInteger(i)||i<1)throw RangeError(`jobs must be a positive integer`);if(t.signal?.aborted)throw t.signal.reason;let a=$G(e),o=qG(a);if(!o.length)return{...QG(a,{depth:n,maxNodes:r}),rootScores:[]};let s=Math.max(1,Math.min(i,o.length)),c=o.map(e=>{let t=$G(a);return YG(t,e),t}),l=Array(o.length),u=0,d=0,f=t.signal?{signal:t.signal}:{};await Promise.all(Array.from({length:s},async()=>{for(;;){let e=d++;if(e>=o.length)return;let i=await mG(QG,[c[e],{depth:Math.max(1,n-1),maxNodes:r,timeMs:t.timeMs}],f);u+=i.nodes,l[e]=-i.score}}));let p=0;for(let e=1;e<o.length;e++)(l[e]??-1/0)>(l[p]??-1/0)&&(p=e);let m=o[p];return{move:{from:m.from,to:m.to,...m.promotion?{promotion:m.promotion}:{}},score:l[p]??0,nodes:u,depth:n,rootScores:o.map((e,t)=>({move:{from:e.from,to:e.to,...e.promotion?{promotion:e.promotion}:{}},score:l[t]??0}))}}var rK={queen:`Q`,rook:`R`,bishop:`B`,knight:`N`},iK={Q:`queen`,R:`rook`,B:`bishop`,N:`knight`},aK={pawn:0,knight:1,bishop:2,rook:3,queen:4,king:5};function oK(e){let t={queen:0,rook:1,bishop:2,knight:3};return`K${e.slice().sort((e,n)=>t[e]-t[n]).map(e=>rK[e]).join(``)}K`}var sK=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`;function cK(e){let t=``;for(let n=0;n<e.length;n+=3){let r=e[n],i=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0;t+=sK[r>>2]+sK[(r&3)<<4|i>>4],t+=n+1<e.length?sK[(i&15)<<2|a>>6]:`=`,t+=n+2<e.length?sK[a&63]:`=`}return t}function lK(e){if(e.length%4!=0)throw Error(`tablebase data is not base64: length is not a multiple of 4`);let t=Array(e.length);for(let n=0;n<e.length;n++){if(e[n]===`=`){t[n]=-1;continue}let r=sK.indexOf(e[n]);if(r===-1)throw Error(`tablebase data is not base64: ${e[n]}`);t[n]=r}let n=[];for(let e=0;e<t.length;e+=4){let[r,i,a,o]=[t[e],t[e+1],t[e+2],t[e+3]];if(r===-1||i===-1)throw Error(`tablebase data is not base64: padding inside a quantum`);n.push(r<<2|i>>4),a!==-1&&n.push((i&15)<<4|a>>2),o!==-1&&n.push((a&3)<<6|o)}return new Uint8Array(n)}function uK(e){let t=Array(256).fill(0);for(let n of e)t[n]++;let n=t.map((e,t)=>({count:e,symbol:t})).filter(e=>e.count>0),r=[1,n.length];if(n.length===0)return cK(new Uint8Array([1,0,0,0,0,0]));if(n.length===1){r.push(n[0].symbol,0);let t=new Uint8Array(r.length+4);return t.set(r,0),t[r.length]=e.length&255,t[r.length+1]=e.length>>8&255,t[r.length+2]=e.length>>16&255,t[r.length+3]=e.length>>24&255,cK(t)}let i=dK(n.map(e=>e.count)),a=n.map((e,t)=>({symbol:e.symbol,length:i[t]})).sort((e,t)=>e.symbol-t.symbol);for(let e of a)r.push(e.symbol);for(let e of a)r.push(e.length);let o=fK(a),s=new Map;for(let e=0;e<a.length;e++)s.set(a[e].symbol,o[e]);let c=0;for(let e of n)c+=e.count*s.get(e.symbol).length;let l=new Uint8Array(r.length+4+Math.ceil(c/8));l.set(r,0),l[r.length]=e.length&255,l[r.length+1]=e.length>>8&255,l[r.length+2]=e.length>>16&255,l[r.length+3]=e.length>>24&255;let u=0,d=r.length+4;for(let t of e){let e=s.get(t);for(let t=e.length-1;t>=0;t--)e.code>>t&1&&(l[d+(u>>3)]|=1<<7-(u&7)),u++}return cK(l)}function dK(e){let t=e.length;if(t===0)return[];let n=e.slice(),r=Array(t).fill(0),i=e.map((e,t)=>t),a=[];for(;i.length>1;){i.sort((e,t)=>n[e]-n[t]);let e=i.shift(),t=i.shift();a.push([e,t]),n[e]+=n[t],n[t]=-1,i.push(e)}for(let e=a.length-1;e>=0;e--){let[t,n]=a[e];r[n]=r[t]+1,r[t]++}if(r.some(e=>e>32))throw Error(`tablebase Huffman code too deep`);return r}function fK(e){let t=e.slice().sort((e,t)=>e.length-t.length||e.symbol-t.symbol),n=0,r=t[0].length,i=new Map;for(let e of t)n<<=e.length-r,i.set(e.symbol,{code:n,length:e.length}),n++,r=e.length;return e.map(e=>i.get(e.symbol))}function pK(e){let t=lK(e);if(t.length<2)throw Error(`tablebase data holds no header`);if(t[0]!==1)throw Error(`tablebase data version ${t[0]} is not 1`);let n=t[1];if(2+2*n>t.length)throw Error(`tablebase data ends inside its header`);let r=[],i=[];for(let e=0;e<n;e++)r.push(t[2+e]);for(let e=0;e<n;e++)i.push(t[2+n+e]);let a=2+2*n;if(n===0){if(a+4!==t.length)throw Error(`tablebase data trails its empty header`);return new Uint8Array}if(n===1){if(a+4!==t.length)throw Error(`tablebase data trails its single-symbol header`);let e=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24;return new Uint8Array(e).fill(r[0])}if(a+4>t.length)throw Error(`tablebase data ends before its count`);let o=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24,s=r.map((e,t)=>({symbol:e,length:i[t]})),c=fK(s),l={};for(let e=0;e<s.length;e++){let t=l;for(let n=c[e].length-1;n>=0;n--){let r=c[e].code>>n&1;n===0?r?t.one={symbol:s[e].symbol}:t.zero={symbol:s[e].symbol}:(r?t.one=t.one??{}:t.zero=t.zero??{},t=r?t.one:t.zero)}}let u=new Uint8Array(o),d=0,f=0,p=a+4,m=(t.length-p)*8;for(;d<o;){if(f>=m)throw Error(`tablebase data ends before its count`);let e=l;for(;;){let n=t[p+(f>>3)]>>7-(f&7)&1;if(f++,e=n?e.one:e.zero,!e)throw Error(`tablebase data walks off its Huffman tree`);if(e.symbol!==void 0)break}u[d++]=e.symbol}for(;f<m;f++)if(t[p+(f>>3)]>>7-(f&7)&1)throw Error(`tablebase data does not end in zero padding`);return u}function mK(e){let t=pK(e);if(t.length%2!=0)throw Error(`tablebase distances are not byte pairs`);let n=new Uint16Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=t[2*e]|t[2*e+1]<<8;return n}function hK(e){if(e.version!==1)throw Error(`${e.id}: unknown tablebase version ${String(e.version)}`);if(e.id!==oK(e.white))throw Error(`${e.id}: id does not match its extras`);for(let t of e.white)if(!iK[rK[t]])throw Error(`${e.id}: not a tablebase piece: ${String(t)}`);let t=2+e.white.length,n=1;for(let e=0;e<t;e++)n*=64;if(n*=2,e.positions!==n)throw Error(`${e.id}: claims ${e.positions} positions, holds ${n}`);let r=pK(e.wdl);if(r.length!==n)throw Error(`${e.id}: WDL decodes to ${r.length} positions, needs ${n}`);let i=mK(e.dtm);if(i.length!==n)throw Error(`${e.id}: distances decode to ${i.length} positions, need ${n}`);let a={queen:0,rook:1,bishop:2,knight:3};return{id:e.id,extras:e.white.slice().sort((e,t)=>a[e]-a[t]).map(e=>aK[e]),positions:n,wdl:r,dtm:i}}function gK(e){if(`pieces`in e){let t=[];for(let n=0;n<12;n++){let r=e.pieces[n];for(;r;){let e=r&-r;t.push({kind:n%6,side:n<6?`white`:`black`,square:Math.log2(Number(e))}),r^=e}}return t}let t=[];return e.board.forEach((e,n)=>{e&&t.push({kind:aK[e.kind],side:e.side,square:n})}),t}function _K(e){if(`pieces`in e)return e.castling!==0;let t=e.castling;return t.whiteKingside||t.whiteQueenside||t.blackKingside||t.blackQueenside}function vK(e,t,n=0){if(!Number.isInteger(n)||n<0)throw RangeError(`halfmove must be a non-negative integer`);let r=gK(t),i=r.filter(e=>e.kind===5&&e.side===`white`),a=r.filter(e=>e.kind===5&&e.side===`black`);if(i.length!==1||a.length!==1||r.some(e=>e.kind===0)||r.some(e=>e.kind!==5&&e.side===`black`)||_K(t))return null;let o=r.filter(e=>e.kind!==5).sort((e,t)=>t.kind-e.kind).map(e=>e.kind);if(!o.length)return null;let s={4:`Q`,3:`R`,2:`B`,1:`N`},c=e[`K${o.map(e=>s[e]).join(``)}K`];if(!c)return null;let l=r.find(e=>e.kind===5&&e.side===`white`).square,u=r.find(e=>e.kind===5&&e.side===`black`).square,d=o.map((e,t)=>r.filter(t=>t.kind===e&&t.side===`white`).map(e=>e.square).sort((e,t)=>e-t)[yK(o,e,t)]),f=l;for(let e of d)f=f*64+e;f=f*64+u,f=f*2+ +(t.turn===`black`);let p=c.wdl[f];if(p===0)return null;let m=c.dtm[f],h=p===3?`win`:p===1?`loss`:`draw`;return h!==`draw`&&m>100-n&&(h=`draw`),{outcome:h,dtm:m}}function yK(e,t,n){let r=0;for(let i=0;i<n;i++)e[i]===t&&r++;return r}_e();var bK=class{constructor(e,t,n){if(this.width=e,this.height=t,e<1||t<1)throw Error(`a board needs positive dimensions`);if(n&&n.length!==e*t)throw Error(`board cell count does not match dimensions`);this.cells=n?[...n]:Array(e*t).fill(null)}index(e,t){if(!this.inside(e,t))throw Error(`cell (${e},${t}) is outside the board`);return nr(this.width,e,t)}inside(e,t){return tr(this.width,this.height,e,t)}get(e,t){return this.cells[this.index(e,t)]}set(e,t,n){this.cells[this.index(e,t)]=n}move(e,t){let n=this.get(e.x,e.y);if(n===null)throw Error(`cannot move an empty cell`);return this.set(e.x,e.y,null),this.set(t.x,t.y,n),n}};function xK(){let e=Array(64).fill(null);for(let t=0;t<3;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`black`,king:!1});for(let t=5;t<8;t++)for(let n=0;n<8;n++)(n+t)%2&&(e[t*8+n]={side:`red`,king:!1});return{board:e,turn:`red`,forcedFrom:null}}function SK(e){let t=e.forcedFrom===null?e.board.map((t,n)=>t?.side===e.turn?n:-1).filter(e=>e>=0):[e.forcedFrom],n=t.flatMap(t=>wK(e,t,!0));return n.length>0?n:e.forcedFrom===null?t.flatMap(t=>wK(e,t,!1)):[]}function CK(e,t){if(!SK(e).some(e=>e.from===t.from&&e.to===t.to&&e.captures.length===t.captures.length))throw Error(`illegal checkers move`);let n=e.board[t.from];if(!n)throw Error(`no checkers piece on the source cell`);e.board[t.from]=null;for(let n of t.captures)e.board[n]=null;let r=!n.king&&(n.side===`red`&&Math.floor(t.to/8)===0||n.side===`black`&&Math.floor(t.to/8)===7);e.board[t.to]={...n,king:n.king||r};let i={board:e.board,turn:e.turn,forcedFrom:t.captures.length>0?t.to:null};t.captures.length===0||wK(i,t.to,!0).length===0?(e.turn=e.turn===`red`?`black`:`red`,e.forcedFrom=null):e.forcedFrom=t.to}function wK(e,t,n){let r=e.board[t];if(!r)return[];let i=t%8,a=Math.floor(t/8),o=r.king?[-1,1]:r.side===`red`?[-1]:[1],s=[];for(let c of o)for(let o of[-1,1]){let l=i+o,u=a+c,d=i+o*2,f=a+c*2;if(n){if(d<0||f<0||d>=8||f>=8)continue;let n=u*8+l,i=f*8+d;e.board[n]?.side!==r.side&&e.board[n]&&!e.board[i]&&s.push({from:t,to:i,captures:[n]})}else l>=0&&u>=0&&l<8&&u<8&&!e.board[u*8+l]&&s.push({from:t,to:u*8+l,captures:[]})}return s}function TK(e=9){if(e<2||e>25)throw Error(`Go size must be between 2 and 25`);return{size:e,board:Array(e*e).fill(null),turn:`black`,ko:null,passes:0}}function EK(e,t,n){let r=AK(e,t,n);if(e.board[r]||e.ko===r)throw Error(`Go cell is occupied or forbidden by ko`);let i=[...e.board];i[r]=e.turn;let a=e.turn===`black`?`white`:`black`,o=0,s=null;for(let t of jK(e.size,r)){if(i[t]!==a||NK(i,e.size,t)!==0)continue;let n=MK(i,e.size,t);n.length===1&&(s=n[0]);for(let e of n)i[e]=null;o+=n.length}if(NK(i,e.size,r)===0)throw Error(`suicide is not a legal Go move`);e.ko=o===1&&NK(i,e.size,r)===1?s:null,e.board=i,e.turn=a,e.passes=0}function DK(e){e.turn=e.turn===`black`?`white`:`black`,e.ko=null,e.passes++}function OK(e){return e.passes>=2?`finished`:`ongoing`}function kK(e){let t={black:0,white:0},n=new Set;for(let r=0;r<e.board.length;r++){let i=e.board[r];if(i)t[i]++;else if(!n.has(r)){let i=MK(e.board,e.size,r),a=new Set;for(let t of i)for(let n of jK(e.size,t))e.board[n]&&a.add(e.board[n]);for(let e of i)n.add(e);a.size===1&&(t[[...a][0]]+=i.length)}}return t}function AK(e,t,n){if(t<0||n<0||t>=e.size||n>=e.size)throw Error(`Go cell is outside the board`);return n*e.size+t}function jK(e,t){let n=t%e,r=Math.floor(t/e),i=[];return n>0&&i.push(t-1),n<e-1&&i.push(t+1),r>0&&i.push(t-e),r<e-1&&i.push(t+e),i}function MK(e,t,n){let r=e[n],i=[],a=[n],o=new Set;for(;a.length;){let n=a.pop();if(!(o.has(n)||e[n]!==r)){o.add(n),i.push(n);for(let e of jK(t,n))a.push(e)}}return i}function NK(e,t,n){let r=MK(e,t,n),i=new Set;for(let n of r)for(let r of jK(t,n))e[r]===null&&i.add(r);return i.size}function PK(){let e=Array(24).fill(0);return e[0]=2,e[11]=5,e[16]=3,e[18]=5,e[23]=-2,e[12]=-5,e[7]=-3,e[5]=-5,{points:e,bar:{white:0,black:0},off:{white:0,black:0},turn:`white`}}function FK(){let e=YK(2,6);return e[0]===e[1]?[...e,...e]:e}function IK(e,t){let n=e.turn===`white`?1:-1,r=n===1?[18,23]:[0,5],i=e=>n===1?24-e:e+1,a=!0,o=1/0;for(let t=0;t<24;t++)e.points[t]*n<=0||((t<r[0]||t>r[1])&&(a=!1),o=Math.min(o,i(t)));let s=(e,t)=>{if(!a)return!1;let n=i(e);return t===n||t>n&&n===o},c=[];for(let r of t)if(e.bar[e.turn]>0){let t=e.turn===`white`?r-1:24-r;RK(e,t,n)&&c.push({from:`bar`,to:t,die:r})}else for(let t=0;t<24;t++)if(e.points[t]*n>0){let i=t+r*n;i<0||i>=24?s(t,r)&&c.push({from:t,to:`off`,die:r}):RK(e,i,n)&&c.push({from:t,to:i,die:r})}return c}function LK(e,t){if(!IK(e,[t.die]).some(e=>e.from===t.from&&e.to===t.to))throw Error(`illegal backgammon move`);let n=e.turn===`white`?1:-1;if(t.from===`bar`?e.bar[e.turn]--:e.points[t.from]-=n,t.to===`off`)e.off[e.turn]++;else{if(e.points[t.to]*n<0){let n=e.turn===`white`?`black`:`white`;e.points[t.to]=0,e.bar[n]++}e.points[t.to]+=n}}function RK(e,t,n){return e.points[t]*n>=-1}function zK(e=0){let t=[`clubs`,`diamonds`,`hearts`,`spades`],n=[];for(let e of t)for(let t=1;t<=13;t++)n.push({suit:e,rank:t});return n.concat(Array(e).fill(null).map(()=>({suit:`spades`,rank:1})))}function BK(e){return oe(e)}function VK(e,t,n){if(t<0||n<0||e.length<t*n)throw Error(`not enough cards to deal`);return Array.from({length:t},()=>e.splice(0,n))}function HK(e,t){if(e.length===0)throw Error(`a trick needs at least one play`);let n=e[0].card.suit,r=e=>e.rank===1?14:e.rank;return(t&&e.some(e=>e.card.suit===t)?e.filter(e=>e.card.suit===t):e.filter(e=>e.card.suit===n)).reduce((e,t)=>r(t.card)>r(e.card)?t:e).owner}function UK(e){let t=zK();return e===void 0?BK(t):E(e,()=>BK(t)),{stock:t,waste:[],tableau:Array.from({length:7},(e,n)=>({down:t.splice(0,6-n),up:t.splice(0,1)})),foundations:[[],[],[],[]]}}function WK(e){e.stock.length===0&&(e.stock=e.waste.reverse(),e.waste=[]);let t=e.stock.pop()??null;return t&&e.waste.push(t),t}function GK(e,t,n,r=1){let i=e.tableau[t],a=e.tableau[n],o=i?.up.slice(-r);if(!i||!a||!o?.length||(a.up.length===0?o[0].rank!==13:!JK(o[0],a.up.at(-1))))throw Error(`illegal solitaire tableau move`);i.up.splice(-r,r),a.up.push(...o),i.down.length&&i.up.length===0&&i.up.push(i.down.pop())}function KK(e,t){let n=t===`waste`?e.waste.at(-1):e.tableau[t].up.at(-1);if(!n)throw Error(`no solitaire card to move`);let r=e.foundations.find(e=>e[0]?.suit===n.suit||e.length===0);if(!r||n.rank!==r.length+1)throw Error(`card cannot move to its foundation`);if(t===`waste`)e.waste.pop();else{let n=e.tableau[t];n.up.pop(),n.down.length&&n.up.length===0&&n.up.push(n.down.pop())}r.push(n)}function qK(e){return e.foundations.every(e=>e.length===13)}function JK(e,t){let n=e.suit===`diamonds`||e.suit===`hearts`,r=t.suit===`diamonds`||t.suit===`hearts`;return e.rank===t.rank-1&&n!==r}function YK(e,t){if(!Number.isInteger(e)||e<0||!Number.isInteger(t)||t<1)throw Error(`dice need a non-negative count and positive sides`);return Array.from({length:e},()=>ne(1,t))}function XK(e){let t=/^(\d+)d(\d+)([+-]\d+)?$/i.exec(e.trim());if(!t)throw Error(`bad dice expression: "${e}"`);return YK(Number(t[1]),Number(t[2])).reduce((e,t)=>e+t,Number(t[3]??0))}var ZK=class{constructor(e,t){this.kept=new Set,this.count=e,this.sides=t,this.values=YK(e,t)}reRoll(){for(let e=0;e<this.values.length;e++)this.kept.has(e)||(this.values[e]=ne(1,this.sides))}keep(e){if(e<0||e>=this.count)throw Error(`die index is outside the cup`);this.kept.add(e)}clearKept(){this.kept.clear()}};function QK(e,t){if(e.length!==5||e.some(e=>e<1||e>6))throw Error(`a score sheet needs five d6 values`);let n=new Map;for(let t of e)n.set(t,(n.get(t)??0)+1);let r=e.reduce((e,t)=>e+t,0);if(t===`chance`)return r;if(t===`yahtzee`)return n.size===1?50:0;if(t===`fullHouse`)return[...n.values()].sort().join(`,`)===`2,3`?25:0;if(t===`threeKind`)return[...n.values()].some(e=>e>=3)?r:0;if(t===`fourKind`)return[...n.values()].some(e=>e>=4)?r:0;if(t===`smallStraight`||t===`largeStraight`){let e=[`1234`,`2345`,`3456`],r=[`12345`,`23456`],i=[...n.keys()].sort().join(``);return(t===`smallStraight`?e:r).some(e=>i.includes(e))?t===`smallStraight`?30:40:0}let i=[`ones`,`twos`,`threes`,`fours`,`fives`,`sixes`].indexOf(t)+1;return i>0?(n.get(i)??0)*i:0}function $K(e,t,n=`hex`){if(e<1||t<1)throw Error(`a tactical map needs positive dimensions`);return{width:e,height:t,shape:n,cells:Array.from({length:e*t},()=>({passable:!0,cover:0})),units:[],turn:``,round:1}}function eq(e,t,n){return uq(e,t,n)&&!lq(e,t,n)}function tq(e,t){if(!eq(e,t.x,t.y))throw Error(`tactical unit cannot be placed there`);e.units.push({...t,maxActions:t.maxActions??t.actions}),e.turn||=t.owner}function nq(e,t){let n=cq(e,t);if(n.owner!==e.turn||n.actions<=0)return[];let r=mq(e,n,pq(e,n)),i=[];for(let a=0;a<e.height;a++)for(let o=0;o<e.width;o++){if(o===n.x&&a===n.y||!e.cells[a*e.width+o].passable||lq(e,o,a))continue;let s=hq(e,n,o,a,n.actions,r);s!==null&&i.push({unit:t,x:o,y:a,cost:s})}return i}function rq(e,t){let n=nq(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal tactical move`);let r=cq(e,t.unit);r.x=t.x,r.y=t.y,r.actions-=n.cost}function iq(e,t){let n=cq(e,t);if(n.owner!==e.turn||n.actions<=0)throw Error(`only an active unit can enter overwatch`);n.actions=0,n.overwatch=!0}function aq(e,t,n){let r=cq(e,t),i=[];for(let t of[...e.units]){if(!t.overwatch||t.owner===r.owner||fq(e,t,r)>3)continue;let a=e.cells[r.y*e.width+r.x].cover??0,o=Math.max(0,n-a);if(r.hp=Math.max(0,r.hp-o),t.overwatch=!1,i.push({attacker:t.id,defender:r.id,damage:o,cover:a,killed:r.hp===0}),r.hp===0){e.units=e.units.filter(e=>e!==r);break}}return i}function oq(e,t,n,r){let i=cq(e,t),a=cq(e,n);if(i.owner!==e.turn||i.owner===a.owner)throw Error(`invalid tactical attack`);if(fq(e,i,a)>3)throw Error(`tactical target is out of range`);let o=e.cells[a.y*e.width+a.x].cover??0,s=Math.max(0,r-o);a.hp=Math.max(0,a.hp-s);let c=a.hp===0;return c&&(e.units=e.units.filter(e=>e!==a)),{attacker:t,defender:n,damage:s,cover:o,killed:c}}function sq(e){let t=[...new Set(e.units.map(e=>e.owner))];if(t.length===0)return;let n=t.indexOf(e.turn)+1;n>=t.length&&e.round++,e.turn=t[n%t.length];for(let t of e.units)t.owner===e.turn&&(t.actions=t.maxActions??t.actions,t.overwatch=!1)}function cq(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown tactical unit "${t}"`);return n}function lq(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function uq(e,t,n){return t>=0&&n>=0&&t<e.width&&n<e.height}function dq(e,t,n){return e.shape===`hex`?Jn(t,n):[{x:t-1,y:n},{x:t+1,y:n},{x:t,y:n-1},{x:t,y:n+1}]}function fq(e,t,n){return e.shape===`hex`?Yn(t,n):Math.abs(t.x-n.x)+Math.abs(t.y-n.y)}function pq(e,t){return new Set(e.units.filter(n=>n.owner!==t.owner&&dq(e,t.x,t.y).some(e=>e.x===n.x&&e.y===n.y)).map(e=>e.id))}function mq(e,t,n){let r=new Set;for(let i of e.units)if(!(i.owner===t.owner||n.has(i.id)))for(let t of dq(e,i.x,i.y))r.add(`${t.x},${t.y}`);return r}function hq(e,t,n,r,i,a){let o=[{x:t.x,y:t.y,distance:0}],s=0,c=new Set([`${t.x},${t.y}`]);for(;s<o.length;){let t=o[s++];if(t.x===n&&t.y===r)return t.distance;if(!(t.distance>=i||t.distance>0&&a.has(`${t.x},${t.y}`)))for(let i of dq(e,t.x,t.y)){let a=`${i.x},${i.y}`;uq(e,i.x,i.y)&&!c.has(a)&&e.cells[i.y*e.width+i.x].passable&&(!lq(e,i.x,i.y)||i.x===n&&i.y===r)&&(c.add(a),o.push({x:i.x,y:i.y,distance:t.distance+1}))}}return null}var gq=class{constructor(e,t){if(this.visible=new Map,this.explored=new Map,this.shared=new Map,e<1||t<1)throw Error(`fog needs positive dimensions`);this.width=e,this.height=t}share(e){let t=[...new Set(e)].filter(e=>!!e);if(t.length===0)return;let n=new Set(t);for(let e of t)for(let t of this.shared.get(e)??[])n.add(t);for(let e of n)this.shared.set(e,n)}sync(e,t,n){if(!e)throw Error(`fog needs a faction id`);let r=new Set;for(let e of t)for(let t of n(e))this.inside(t.x,t.y)&&r.add(this.index(t.x,t.y));this.visible.set(e,r);let i=this.explored.get(e)??new Set;for(let e of r)i.add(e);this.explored.set(e,i)}reveal(e,t){if(!e)throw Error(`fog needs a faction id`);let n=this.explored.get(e)??new Set;for(let e of t)this.inside(e.x,e.y)&&n.add(this.index(e.x,e.y));this.explored.set(e,n)}isVisible(e,t,n){return this.seenBy(this.visible,e,this.index(t,n))}sees(e){return(t,n)=>this.isVisible(e,t,n)}isExplored(e,t,n){return this.seenBy(this.explored,e,this.index(t,n))}visibleCells(e){return this.cellsSeenBy(this.visible,e)}exploredCells(e){return this.cellsSeenBy(this.explored,e)}seenBy(e,t,n){let r=this.shared.get(t);if(!r)return e.get(t)?.has(n)??!1;for(let t of r)if(e.get(t)?.has(n))return!0;return!1}cellsSeenBy(e,t){let n=this.shared.get(t);if(!n)return[...e.get(t)??[]];let r=new Set;for(let t of n)for(let n of e.get(t)??[])r.add(n);return[...r].sort((e,t)=>e-t)}inside(e,t){return tr(this.width,this.height,e,t)}index(e,t){return this.inside(e,t)?nr(this.width,e,t):-1}};function _q(e){return{currency:e,pool:[]}}function vq(e,t,n,r){return e.currency<r||!eq(t,n.x,n.y)?!1:(tq(t,n),e.currency-=r,!0)}function yq(e,t,n,r,i){let a=e.pool.findIndex(e=>e.id===n);return a===-1||!eq(t,r,i)?!1:(tq(t,{...e.pool[a],x:r,y:i}),e.pool.splice(a,1),!0)}function bq(e,t,n){let r=t.units.findIndex(e=>e.id===n);if(r===-1)return!1;let{x:i,y:a,...o}=t.units[r];return e.pool.push(o),t.units.splice(r,1),!0}function xq(e,t,n){return e.units.filter(e=>e.owner===t).length*(n.incomePerUnit-n.upkeepPerUnit)}function Sq(e,t,n,r){return e.currency+=xq(t,n,r),e.currency}_e();function Cq(e,t,n,r){if(e<1||t<1)throw Error(`a skirmish map needs positive dimensions`);let i=r??Object.keys(n)[0];if(!i||!n[i])throw Error(`a skirmish map needs at least one terrain kind`);return{width:e,height:t,terrainTable:n,cells:Array.from({length:e*t},()=>({terrain:i})),units:[],turn:``,round:1}}function wq(e,t,n,r,i=!1){if(!Pq(e,t,n))throw Error(`cell is outside the skirmish map`);if(!e.terrainTable[r])throw Error(`unknown skirmish terrain "${r}"`);e.cells[n*e.width+t]=i?{terrain:r,village:!0}:{terrain:r}}function Tq(e,t,n){return Pq(e,t,n)&&Lq(e,t,n)<1/0&&!Fq(e,t,n)}function Eq(e,t){if(!Tq(e,t.x,t.y))throw Error(`skirmish unit cannot be placed there`);e.units.push({...t,remainingMoves:t.moves}),e.turn||=t.owner}function Dq(e,t){let n=Nq(e,t),r=n.remainingMoves??n.moves;if(n.owner!==e.turn||r<=0)return[];let i=new Set(e.units.filter(e=>e.id!==n.id).map(e=>`${e.x},${e.y}`)),a=Rq(e,n,r,i),o=[];for(let s=0;s<e.height;s++)for(let c=0;c<e.width;c++){if(c===n.x&&s===n.y||Lq(e,c,s)===1/0||i.has(`${c},${s}`))continue;let l=a.get(`${c},${s}`);l!==void 0&&l<=r&&o.push({unit:t,x:c,y:s,cost:l})}return o}function Oq(e,t){let n=Dq(e,t.unit).find(e=>e.x===t.x&&e.y===t.y);if(!n)throw Error(`illegal skirmish move`);let r=Nq(e,t.unit);r.x=t.x,r.y=t.y,r.remainingMoves=(r.remainingMoves??r.moves)-n.cost;let i=e.cells[t.y*e.width+t.x];i.village&&(i.owner=r.owner)}function kq(e,t,n){let r=Nq(e,t),i=Nq(e,n);if(r.owner!==e.turn||r.owner===i.owner)throw Error(`invalid skirmish attack`);if(Yn(r,i)!==1)throw Error(`skirmish combat is adjacency-only`);let a=[Aq(e,r,i)];return i.hp>0&&a.push(Aq(e,i,r)),e.units=e.units.filter(e=>e.hp>0),{strikes:a}}function Aq(e,t,n){let r=Iq(e,n.x,n.y).defense,i=A(Math.max(0,Math.min(1,t.hitChance*(1-r)))),a=i?Math.min(t.attack,n.hp):0;return n.hp-=a,{attacker:t.id,defender:n.id,hit:i,damage:a,killed:n.hp<=0}}function jq(e,t,n,r){return n+e.cells.filter(e=>e.village&&e.owner===t).length*r}function Mq(e,t=0){let n=[...new Set(e.units.map(e=>e.owner))];if(n.length===0)return;let r=n.indexOf(e.turn)+1;r>=n.length&&e.round++,e.turn=n[r%n.length];for(let n of e.units){if(n.owner!==e.turn)continue;n.remainingMoves=n.moves;let r=e.cells[n.y*e.width+n.x];r.village&&r.owner===n.owner&&t>0&&(n.hp=Math.min(n.maxHp,n.hp+t))}}function Nq(e,t){let n=e.units.find(e=>e.id===t);if(!n)throw Error(`unknown skirmish unit "${t}"`);return n}function Pq(e,t,n){return tr(e.width,e.height,t,n)}function Fq(e,t,n){return e.units.some(e=>e.x===t&&e.y===n)}function Iq(e,t,n){return e.terrainTable[e.cells[n*e.width+t].terrain]}function Lq(e,t,n){return Iq(e,t,n).moveCost}function Rq(e,t,n,r){let i=[],a=(e,t)=>{[i[e],i[t]]=[i[t],i[e]]},o=e=>{i.push(e);let t=i.length-1;for(;t>0;){let e=t-1>>1;if(i[e].cost<=i[t].cost)break;a(t,e),t=e}},s=()=>{if(i.length===0)return;let e=i[0],t=i.pop();if(i.length>0){i[0]=t;let e=0;for(;;){let t=e*2+1,n=t+1,r=e;if(t<i.length&&i[t].cost<i[r].cost&&(r=t),n<i.length&&i[n].cost<i[r].cost&&(r=n),r===e)break;a(e,r),e=r}}return e},c=new Map([[`${t.x},${t.y}`,0]]);for(o({x:t.x,y:t.y,cost:0});;){let t=s();if(t===void 0)break;let i=`${t.x},${t.y}`;if(!(t.cost>(c.get(i)??1/0)))for(let i of Jn(t.x,t.y)){if(!Pq(e,i.x,i.y))continue;let a=Lq(e,i.x,i.y);if(a===1/0||r.has(`${i.x},${i.y}`))continue;let s=t.cost+a;if(s>n)continue;let l=`${i.x},${i.y}`;s<(c.get(l)??1/0)&&(c.set(l,s),o({x:i.x,y:i.y,cost:s}))}}return c}var zq=l({BoardGrid:()=>bK,DiceCup:()=>ZK,FactionFog:()=>gq,addSkirmishUnit:()=>Eq,addTacticalUnit:()=>tq,applyBackgammonMove:()=>LK,applyCheckersMove:()=>CK,applyMove:()=>rG,applyUpkeep:()=>Sq,armyIncome:()=>xq,backgammonMoves:()=>IK,bankUnit:()=>bq,bitboardFromChess:()=>GG,bitboardMoves:()=>qG,canPlaceSkirmishUnit:()=>Tq,canPlaceTacticalUnit:()=>eq,checkersMoves:()=>SK,chessGame:()=>SG,chooseMove:()=>_G,cloneChess:()=>GW,createDeck:()=>zK,deal:()=>VK,dealSolitaire:()=>UK,drawSolitaire:()=>WK,endSkirmishTurn:()=>Mq,endTacticalTurn:()=>sq,gameResult:()=>iG,goResult:()=>OK,goScore:()=>kK,huffDecode:()=>pK,huffEncode:()=>uK,inCheck:()=>QW,legalMoves:()=>nG,loadTablebaseEnding:()=>hK,makeMove:()=>YG,moveSkirmishUnit:()=>Oq,moveSolitaireTableau:()=>GK,moveSolitaireToFoundation:()=>KK,moveTacticalUnit:()=>rq,parseFen:()=>zW,parseUciMove:()=>kG,passGo:()=>DK,perft:()=>ZG,playGo:()=>EK,positionKey:()=>RW,probeBook:()=>DG,probeTablebase:()=>vK,recall:()=>yq,recruit:()=>vq,rollBackgammonDice:()=>FK,rollDice:()=>YK,rollExpression:()=>XK,scoreDice:()=>QK,search:()=>vG,searchAsync:()=>yG,searchTourney:()=>eK,searchTourneyAsync:()=>nK,setSkirmishTerrain:()=>wq,setTacticalOverwatch:()=>iq,shuffleDeck:()=>BK,skirmishAttack:()=>kq,skirmishIncome:()=>jq,skirmishMoves:()=>Dq,solitaireWon:()=>qK,sq:()=>IW,squareName:()=>LW,startingArmy:()=>_q,startingBackgammon:()=>PK,startingBitboard:()=>KG,startingCheckers:()=>xK,startingChess:()=>WW,startingGo:()=>TK,startingSkirmish:()=>Cq,startingTactics:()=>$K,tablebaseId:()=>oK,tacticalAttack:()=>oq,tacticalMoves:()=>nq,tourneyThink:()=>QG,trickWinner:()=>HK,triggerTacticalOverwatch:()=>aq,unmakeMove:()=>XG});function Bq(e){let t;try{t=IN(e)}catch(t){return console.warn(`${t.message} - "${e}" will be silent`),Vq()}return new Audio(t)}function Vq(){return{play(){},pause(){},currentTime:0,volume:1,loop:!1}}var Hq=new p,Uq=class{constructor(e,t={}){this.next=0,this.suspended_=!1,this.plays=0;let n=Math.max(1,t.poolSize??4),r=t.create??Bq;this.volume=t.volume??1,this.caption=t.caption,this.pool=Array.from({length:n},()=>r(e))}play(e=1,t=1){if(this.suspended_)return;this.plays++;let n=this.pool[this.next];this.next=(this.next+1)%this.pool.length,n.volume=this.volume*e,n.playbackRate=t,n.currentTime=0,Promise.resolve(n.play()).catch(()=>{}),this.caption&&Hq.dispatch({text:this.caption})}stopAll(){for(let e of this.pool)e.pause(),e.currentTime=0}suspend(){this.suspended_=!0,this.stopAll()}resume(){this.suspended_=!1}get isSuspended(){return this.suspended_}};function Wq(e={}){let t=e.waveform??`square`,n=e.frequency??440,r=e.duration??.15,i=e.volume??.3,a=e.decay??8,o=e.sampleRate??22050,s=e.seed??1;if(!(r>0))throw Error(`tone duration must be positive`);if(t!==`noise`&&!(n>0))throw Error(`tone frequency must be positive`);if(!(o>0))throw Error(`tone sample rate must be positive`);let c=Math.max(1,Math.round(r*o)),l=new Float32Array(c);for(let e=0;e<c;e++){let r=e/o,u=a>0?Math.exp(-a*e/c):1,d=2*Math.PI*n*r;l[e]=i*u*qq(t,d,s,e)}return Yq(l,o)}function Gq(e={},t=e=>new Audio(e)){let n=t(Wq(e));return Promise.resolve(n.play()).catch(()=>{}),n}function Kq(e={},t={}){return new Uq(Wq(e),t)}function qq(e,t,n,r){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`sawtooth`:{let e=t/(2*Math.PI);return 2*(e-Math.floor(e))-1}case`triangle`:{let e=t/(2*Math.PI),n=e-Math.floor(e);return 4*Math.abs(n-.5)-1}case`noise`:return Jq(n,r)}}function Jq(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function Yq(e,t){let n=e.length*2,r=new ArrayBuffer(44+n),i=new DataView(r);Xq(i,0,`RIFF`),i.setUint32(4,36+n,!0),Xq(i,8,`WAVE`),Xq(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),Xq(i,36,`data`),i.setUint32(40,n,!0);let a=44;for(let t of e){let e=Math.max(-1,Math.min(1,t));i.setInt16(a,Math.round(e*(e<0?32768:32767)),!0),a+=2}let o=``,s=new Uint8Array(r);for(let e of s)o+=String.fromCharCode(e);return`data:audio/wav;base64,${btoa(o)}`}function Xq(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function Zq(e,t){let[n,r]=e,i=n*4*eJ[t]/r;if(!Number.isInteger(i)||i<1)throw Error(`a ${t} grid does not cut a ${n}/${r} bar into whole slots (it needs ${i})`);return i}function Qq(e,t){return e/eJ[t]}function $q(e){if(typeof e!=`object`||!e)throw Error(`a groove template must be an object`);let{name:t,timeSignature:n,ppq:r,tempoBpm:i,subdivision:a,offsets:o}=e;if(typeof t!=`string`||t.length===0)throw Error(`a groove template needs a non-empty name`);if(!Array.isArray(n)||n.length!==2)throw Error(`groove template "${t}": timeSignature must be [beats, beatValue]`);let[s,c]=n;if(!Number.isInteger(s)||s<1)throw Error(`groove template "${t}": time signature numerator must be a positive integer, got ${String(s)}`);if(!Number.isInteger(c)||c<1||c&c-1)throw Error(`groove template "${t}": time signature denominator must be a power of two, got ${String(c)}`);if(!Number.isInteger(r)||r<1)throw Error(`groove template "${t}": ppq must be a positive integer, got ${String(r)}`);if(!Number.isFinite(i)||i<=0)throw Error(`groove template "${t}": tempoBpm must be greater than 0, got ${String(i)}`);if(a!==`8n`&&a!==`16n`&&a!==`32n`)throw Error(`groove template "${t}": subdivision must be 8n, 16n or 32n, got ${String(a)}`);let l=Qq(r,a);if(!Number.isInteger(l)||l<1)throw Error(`groove template "${t}": ${r} ppq does not cut into whole ${a} ticks (it needs ${String(l)})`);let u=Zq(n,a);if(!Array.isArray(o)||o.length!==u)throw Error(`groove template "${t}": a ${a} grid in ${s}/${c} has ${u} slots, this carries ${Array.isArray(o)?o.length:String(o)}`);o.forEach((e,n)=>{if(typeof e!=`object`||!e)throw Error(`groove template "${t}": slot ${n} must be an object`);if(e.subdivisionIndex!==n)throw Error(`groove template "${t}": slots must run in order, slot ${n} carries ${String(e.subdivisionIndex)}`);if(!Number.isInteger(e.timeOffsetTicks))throw Error(`groove template "${t}": slot ${n} has a fractional timeOffsetTicks (${String(e.timeOffsetTicks)}); ticks are whole numbers`);if(!Number.isFinite(e.velocityFactor)||e.velocityFactor<0)throw Error(`groove template "${t}": slot ${n} has velocityFactor ${String(e.velocityFactor)}, which must be a finite number of at least 0`)})}var eJ,tJ=s((()=>{eJ={"8n":2,"16n":4,"32n":8}}));function nJ(e){let t=e.intensity;if(!Number.isFinite(t)||t<0||t>1)throw Error(`humanization intensity must be between 0 and 1, got ${String(e.intensity)}`);let n=e.timingVarianceMs??xJ;if(!Number.isFinite(n)||n<0)throw Error(`timingVarianceMs must be a finite number of at least 0, got ${String(e.timingVarianceMs)}`);let r=e.velocityVariance??SJ;if(!Number.isFinite(r)||r<0)throw Error(`velocityVariance must be a finite number of at least 0, got ${String(e.velocityVariance)}`);let i=e.style?CJ[e.style]:wJ,a=e.grooveTemplate??null;return a&&$q(a),{intensity:t,timingMs:n,velocityVariance:r,timingScale:i.timing,velocityScale:i.velocity,template:a,warn:e.onWarn??(e=>console.warn(e))}}function rJ(e){let t=[];for(let n of e)n.type===`tempo`&&t.push({tick:n.tick,microsecondsPerQuarter:n.microsecondsPerQuarter});t.sort((e,t)=>e.tick-t.tick);let n=[{tick:0,microsecondsPerQuarter:5e5}];for(let e of t)e.tick===n[n.length-1].tick?n[n.length-1]=e:n.push(e);return n}function iJ(e,t){let n=0,r=e.length-1,i=0;for(;n<=r;){let a=n+r>>1;e[a].tick<=t?(i=a,n=a+1):r=a-1}return 6e7/e[i].microsecondsPerQuarter}function aJ(e,t,n){return e*t*n/6e4}function oJ(e,t,n){return e*6e4/(t*n)}function sJ(e){let t=null;return()=>{if(t!==null){let e=t;return t=null,e}let n=Math.sqrt(-2*Math.log(1-e.float())),r=2*Math.PI*e.float();return t=n*Math.sin(r),n*Math.cos(r)}}function cJ(e){let t=new Uint8Array(256);for(let e=0;e<256;e++)t[e]=e;for(let n=255;n>0;n--){let r=e.int(n+1),i=t[n];t[n]=t[r],t[r]=i}let n=(e,t)=>e&1?t:-t;return e=>{let r=Math.floor(e),i=e-r,a=i*i*i*(i*(i*6-15)+10),o=n(t[r&255],i);return o+a*(n(t[r+1&255],i-1)-o)}}function lJ(e){let t=new Map;for(let n of e.offsets)t.set(n.subdivisionIndex,{ms:oJ(n.timeOffsetTicks,e.ppq,e.tempoBpm),factor:n.velocityFactor});return t}function uJ(e){let t=new Uint8Array(e.length),n=new Map;for(let t=0;t<e.length;t++){let r=e[t];if(r.type!==`noteOn`||r.channel===vJ)continue;let i=n.get(r.channel);i?i.push({index:t,note:r.note}):n.set(r.channel,[{index:t,note:r.note}])}for(let e of n.values())for(let n=1;n<e.length-1;n++)e[n].note>e[n-1].note&&e[n].note>e[n+1].note&&(t[e[n].index]=1);return t}function dJ(e){return e.channel===vJ?yJ.includes(e.note):e.note<bJ}function fJ(e,t,n){let r=nJ(t),i=new j(t.seed),a=sJ(i),o=cJ(i),s=e.ticksPerQuarter,c=rJ(e.events),l=r.template?lJ(r.template):null,u=r.template?Qq(s,r.template.subdivision):0,d=r.template?Zq(r.template.timeSignature,r.template.subdivision):0,f=n===`groove`?uJ(e.events):null,p=[],m=new Map,h=!1;for(let t=0;t<e.events.length;t++){let i=e.events[t];if(i.type===`noteOff`){let e=m.get(TJ(i)),t=e&&e.length>0?e.shift():0;p.push(t===0?{...i}:{...i,tick:i.tick+t});continue}if(i.type!==`noteOn`){p.push({...i});continue}let g=iJ(c,i.tick);r.template&&!h&&Math.abs(g-r.template.tempoBpm)>gJ&&(h=!0,r.warn(`groove template "${r.template.name}" is written at ${r.template.tempoBpm} BPM but this file is at ${g.toFixed(1)} BPM by tick ${i.tick}: its offsets are rescaled to keep the same timing in milliseconds`));let _=aJ(r.timingMs*r.timingScale,s,g),v=a()*_+o(i.tick/s*pJ)*_*mJ;if(n===`groove`&&dJ(i)){let e=aJ(_J,s,g);v=Math.min(e,Math.max(-e,v))}let y;l&&(y=l.get(Math.floor(i.tick/u)%d));let b=Math.round(r.intensity*((y?aJ(y.ms,s,g):0)+v));i.tick+b<0&&(b=-i.tick);let x=Math.round(i.velocity*(1+r.intensity*((y?y.factor:1)-1))+r.intensity*a()*r.velocityVariance*r.velocityScale);f&&f[t]===1&&(x=Math.round(x*(1+r.intensity*hJ))),x=Math.min(127,Math.max(1,x));let S=TJ(i),C=m.get(S);C?C.push(b):m.set(S,[b]),p.push({...i,tick:i.tick+b,velocity:x})}return p.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:s,events:p,loopStartTick:e.loopStartTick}}var pJ,mJ,hJ,gJ,_J,vJ,yJ,bJ,xJ,SJ,CJ,wJ,TJ,EJ=s((()=>{_e(),tJ(),pJ=.25,mJ=.5,hJ=.15,gJ=1,_J=5,vJ=9,yJ=[35,36],bJ=48,xJ=8,SJ=10,CJ={jazz:{timing:1.3,velocity:1.1},rock:{timing:.8,velocity:1.2},classical:{timing:.6,velocity:1.4},funk:{timing:1,velocity:1.3}},wJ={timing:1,velocity:1},TJ=e=>`${e.channel}:${e.note}`})),DJ=l({LiteHumanizer:()=>OJ}),OJ,kJ=s((()=>{EJ(),OJ=class{constructor(){this.tierName=`lite`,this.approximateSizeMb=.05}async initialize(){}async process(e,t){if(t.grooveTemplate)throw Error(`the lite tier applies no groove grid: ask HumanizerFactory for "groove" when a template is in play`);return fJ(e,t,`lite`)}}})),AJ=l({GrooveHumanizer:()=>jJ}),jJ,MJ=s((()=>{EJ(),jJ=class{constructor(){this.tierName=`groove`,this.approximateSizeMb=.5}async initialize(){}async process(e,t){return fJ(e,t,`groove`)}}})),NJ=class e{static async create(t){let n=await e.load(t);return await n.initialize(),n}static async load(e){switch(e){case`lite`:return new(await(Promise.resolve().then(()=>(kJ(),DJ)))).LiteHumanizer;case`groove`:return new(await(Promise.resolve().then(()=>(MJ(),AJ)))).GrooveHumanizer;case`magenta`:throw Error(`the 'magenta' tier is not shipped: it needs @magenta/music and a PerformanceRNN checkpoint, and neither can be fetched from a file:// build`);default:throw Error(`unknown humanizer tier: ${String(e)}`)}}};async function PJ(e,t){let{tier:n,...r}=t,i=n??(r.grooveTemplate?`groove`:`lite`);return(await NJ.create(i)).process(e,r)}var FJ=5e5,IJ=111;function LJ(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=e=>{let n=``;for(let i=0;i<e;i++)n+=String.fromCharCode(t[r+i]);return r+=e,n},a=()=>{let e=n.getUint32(r,!1);return r+=4,e},o=()=>{let e=n.getUint16(r,!1);return r+=2,e},s=()=>{let e=0;for(;;){let n=t[r++];if(e=e<<7|n&127,!(n&128))return e}};if(i(4)!==`MThd`||a()!==6)throw Error(`invalid MIDI header chunk`);let c=o(),l=o(),u=o();if(c!==0&&c!==1)throw Error(`unsupported MIDI format ${c}`);if(u&32768)throw Error(`SMPTE-based MIDI timing is not supported`);let d=u,f=[],p=null;for(let e=0;e<l;e++){let e=i(4),n=a();if(e!==`MTrk`){r+=n;continue}let o=r+n,c=0,l=0;for(;r<o;){c+=s();let e=t[r];if(e<128?e=l:(r++,e<240&&(l=e)),e===255){let e=t[r++],n=s();if(e===81&&n===3){let e=t[r]<<16|t[r+1]<<8|t[r+2];f.push({tick:c,type:`tempo`,microsecondsPerQuarter:e})}r+=n}else if(e===240||e===247)r+=s();else{let n=e&240,i=e&15;if(n===128||n===144){let e=t[r++],a=t[r++],o=n===144&&a>0;f.push({tick:c,type:o?`noteOn`:`noteOff`,note:e,velocity:a,channel:i})}else if(n===176){let e=t[r++],n=t[r++];f.push({tick:c,type:`control`,channel:i,controller:e,value:n}),e===IJ&&p===null&&(p=c)}else if(n===192){let e=t[r++];f.push({tick:c,type:`program`,channel:i,program:e})}else if(n===224){let e=t[r++],n=t[r++];f.push({tick:c,type:`pitchBend`,channel:i,value:(n<<7|e)-8192})}else if(n===160||n===208)r+=n===160?2:1;else throw Error(`unsupported MIDI status byte 0x${e.toString(16)}`)}}}return f.sort((e,t)=>e.tick-t.tick),{ticksPerQuarter:d,events:f,loopStartTick:p}}var RJ=2;function zJ(e){let t=[{tick:0,time:0,microsecondsPerQuarter:FJ}];for(let n of e.events){if(n.type!==`tempo`)continue;let r=t[t.length-1];t.push({tick:n.tick,time:r.time+(n.tick-r.tick)*r.microsecondsPerQuarter/e.ticksPerQuarter/1e6,microsecondsPerQuarter:n.microsecondsPerQuarter})}return t}function BJ(e,t,n){let r=e[0];for(let t of e)if(t.tick<=n)r=t;else break;return r.time+(n-r.tick)*r.microsecondsPerQuarter/t/1e6}function VJ(e){return e.loopStartTick===null?null:BJ(zJ(e),e.ticksPerQuarter,e.loopStartTick)}function HJ(e){let t=zJ(e),n=Array.from({length:16},()=>({program:0,bank:0,volume:100,expression:127,pan:64,bend:0})),r=e=>{let t=n[e]??n[0];return{program:t.program,bank:t.bank,gain:t.volume/127*(t.expression/127),pan:(t.pan-64)/64,...t.bend?{bend:t.bend}:{}}},i=[],a=new Map;for(let o of e.events){if(o.type===`tempo`)continue;if(o.type===`pitchBend`){(n[o.channel]??n[0]).bend=o.value/8192*RJ;continue}if(o.type===`program`){(n[o.channel]??n[0]).program=o.program;continue}if(o.type===`control`){let e=n[o.channel]??n[0];o.controller===0?e.bank=o.value:o.controller===7?e.volume=o.value:o.controller===10?e.pan=o.value:o.controller===11&&(e.expression=o.value);continue}let s=BJ(t,e.ticksPerQuarter,o.tick),c=`${o.channel}:${o.note}`;if(o.type===`noteOn`)a.set(c,{time:s,velocity:o.velocity,voice:r(o.channel)});else{let e=a.get(c);e&&(i.push({time:e.time,duration:Math.max(.01,s-e.time),note:o.note,velocity:e.velocity,channel:o.channel,...e.voice}),a.delete(c))}}for(let[e,t]of a){let[n,r]=e.split(`:`).map(Number);i.push({time:t.time,duration:.3,note:r,velocity:t.velocity,channel:n,...t.voice})}return i.sort((e,t)=>e.time-t.time)}function UJ(e){return 440*2**((e-69)/12)}var WJ=class e{constructor(e,t={}){this.elapsed=0,this.index=0,this.playing=!1,this.notes=HJ(e),this.playFn=t.play??Gq,this.waveform=t.waveform??`square`,this.volume=t.volume??.2}static async create(t,n={}){return new e(n.humanize?await PJ(t,n.humanize):t,n)}play(){this.playing=this.index<this.notes.length}pause(){this.playing=!1}stop(){this.playing=!1,this.elapsed=0,this.index=0}update(e){if(this.playing){for(this.elapsed+=e;this.index<this.notes.length&&this.notes[this.index].time<=this.elapsed;){let e=this.notes[this.index];this.playFn({waveform:this.waveform,frequency:UJ(e.note),duration:e.duration,volume:this.volume*(e.velocity/127)}),this.index++}this.index>=this.notes.length&&(this.playing=!1)}}get isPlaying(){return this.playing}get duration(){let e=this.notes.at(-1);return e?e.time+e.duration:0}},GJ=8e3,KJ=96e3;function qJ(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=Math.round(Math.max(-1,Math.min(1,e[n]))*32767);return t}function JJ(e,t,n,r){let i=Math.max(1,Math.round(e.length*n/t));if(i>r)throw Error(`a decoded sample is longer than a SoundFont sample may be`);let a=new Float32Array(i);for(let r=0;r<a.length;r++){let i=r*t/n,o=Math.floor(i),s=Math.min(o+1,e.length-1);a[r]=e[o]+(e[s]-e[o])*(i-o)}return a}function YJ(e){if(typeof OfflineAudioContext>`u`)throw Error(`no OfflineAudioContext here: pass a decoder of your own to decode a SoundFont 3`);return new OfflineAudioContext(1,1,e)}function XJ(e=YJ,t={}){let n=t.sampleFrames??16777216;return async(t,r)=>{if(!(r>=400&&r<=2e5))throw Error(`a sample rate of ${r} Hz is not one a SoundFont can state`);let i=Math.max(GJ,Math.min(KJ,r)),a=t.slice().buffer,o=await e(i).decodeAudioData(a);if(o.length>n)throw Error(`a decoded sample is longer than a SoundFont sample may be`);let s=o.getChannelData(0);return qJ(o.sampleRate===r?s:JJ(s,o.sampleRate,r,n))}}var ZJ={keyRange:43,velRange:44,instrument:41,sampleId:53,rootKey:58,coarseTune:51,fineTune:52,sampleModes:54,attenuation:48,pan:17,attack:34,hold:35,decay:36,sustain:37,release:38};function QJ(e){return 2**(e/1200)}function $J(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function eY(e,t){let n=``;for(let r=0;r<20;r++){let i=e[t+r];if(i===0)break;n+=String.fromCharCode(i)}return n}function tY(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t=>String.fromCharCode(e[t],e[t+1],e[t+2],e[t+3]);if(n(0)!==`RIFF`||n(8)!==`sfbk`)throw Error(`not a SoundFont 2 file`);let r=new Map,i=new Map,a=(e,o)=>{let s=e;for(;s+8<=o;){let e=n(s),o=t.getUint32(s+4,!0);e===`LIST`?(i.set(n(s+8),{at:s,size:o}),a(s+12,s+8+o)):r.set(e,{at:s+8,size:o}),s+=8+o+(o&1)}};a(12,e.length);for(let e of[`phdr`,`pbag`,`pgen`,`inst`,`ibag`,`igen`,`shdr`,`smpl`])if(!r.has(e))throw Error(`SoundFont is missing "${e}"`);let o=(e,t,n)=>{let i=r.get(e),a=[];for(let e=i.at;e+t<=i.at+i.size;e+=t)a.push(n(e));return a},s=n=>o(n,4,n=>({oper:t.getUint16(n,!0),lo:e[n+2],hi:e[n+3],amount:t.getInt16(n+2,!0)})),c=e=>o(e,4,e=>t.getUint16(e,!0)),l=o(`phdr`,38,n=>({name:eY(e,n),preset:t.getUint16(n+20,!0),bank:t.getUint16(n+22,!0),bag:t.getUint16(n+24,!0)})),u=o(`inst`,22,n=>({name:eY(e,n),bag:t.getUint16(n+20,!0)})),d=o(`shdr`,46,n=>({name:eY(e,n),start:t.getUint32(n+20,!0),end:t.getUint32(n+24,!0),loopStart:t.getUint32(n+28,!0),loopEnd:t.getUint32(n+32,!0),rate:t.getUint32(n+36,!0),rootKey:e[n+40],correction:t.getInt8(n+41),link:t.getUint16(n+42,!0),type:t.getUint16(n+44,!0)})),f=r.get(`smpl`),p=e.slice(f.at,f.at+f.size),m=d.filter(e=>e.end>e.start&&!(e.type&32768)),h=m.some(e=>e.type&16);if(h&&!m.every(e=>e.type&16))throw Error(`SoundFont mixes compressed and plain samples, which it cannot address consistently`);let g=h?p.length:p.length>>1;if(m.some(e=>e.end>g))throw Error(`a sample points outside the sample data: the SoundFont is damaged`);let _=h?new Int16Array:new Int16Array(p.buffer,0,p.length>>1),v=i.get(`INFO`)??null;return{bytes:e,presets:l,presetBags:c(`pbag`),presetGens:s(`pgen`),instruments:u,instBags:c(`ibag`),instGens:s(`igen`),samples:d,smplBytes:p,smpl:_,compressed:h,info:v?e.slice(v.at,v.at+8+v.size+(v.size&1)):null}}function nY(e,t,n){return t.slice(e[n],e[n+1]??t.length)}function rY(e,t,n,r,i){let a=e[r].bag,o=e[r+1]?.bag??t.length-1,s=[],c=null;for(let e=a;e<o;e++){let r=nY(t,n,e),o=new Map;for(let e of r)o.set(e.oper,e);o.has(i)?s.push({gens:o,global:c}):e===a&&(c=o)}return s}function iY(e,t){return e.gens.get(t)??e.global?.get(t)??null}function aY(e,t,n,r=`piano`){return e.get(`${t}:${n}`)??(t===128?e.get(`128:0`):e.get(`0:${n}`))??(r===`piano`?e.get(`0:0`):void 0)}function oY(e,t={}){let n=tY($J(e));if(n.compressed)throw Error(`SoundFont 3 (Ogg Vorbis samples) needs decoding first: use loadSoundFont() or decodeSoundFont(), or convert it with "mwg-soundfonts convert <in.sf3> <out.sf2>"`);let r=new Map,i=new Map,a=e=>{if(r.has(e))return r.get(e);let t=n.samples[e];if(!t||t.end<=t.start||t.type&32768)return r.set(e,null),null;let a=new Float32Array(t.end-t.start);for(let e=0;e<a.length;e++)a[e]=n.smpl[t.start+e]/32768;let o={data:a,rate:t.rate||22050,loopStart:t.loopStart-t.start,loopEnd:t.loopEnd-t.start};return r.set(e,o),i.set(e,{rootKey:t.rootKey===255?60:t.rootKey,correction:t.correction}),o},o=new Map;for(let e=0;e<n.presets.length-1;e++)o.set(`${n.presets[e].bank}:${n.presets[e].preset}`,e);function s(e,r,s,c){let l=aY(o,e,r,t.missingProgram);if(l===void 0)return[];let u=[],d=(e,t,n)=>{let r=iY(e,t);return!r||n>=r.lo&&n<=r.hi};for(let e of rY(n.presets,n.presetBags,n.presetGens,l,ZJ.instrument)){if(!d(e,ZJ.keyRange,s)||!d(e,ZJ.velRange,c))continue;let t=iY(e,ZJ.instrument).amount;if(n.instruments[t+1])for(let r of rY(n.instruments,n.instBags,n.instGens,t,ZJ.sampleId)){if(!d(r,ZJ.keyRange,s)||!d(r,ZJ.velRange,c))continue;let t=iY(r,ZJ.sampleId).amount,n=a(t);if(!n)continue;let o=(t,n=0)=>(iY(r,t)?.amount??n)+(iY(e,t)?.amount??0),l=iY(r,ZJ.rootKey)?.amount,f=iY(r,ZJ.sampleModes)?.amount??0,p=i.get(t);u.push({sample:n,rootKey:l!==void 0&&l>=0?l:p.rootKey,cents:o(ZJ.coarseTune)*100+o(ZJ.fineTune)+p.correction,loop:(f&3)==1||(f&3)==3,gain:10**(-Math.max(0,o(ZJ.attenuation))/200),pan:Math.max(-1,Math.min(1,o(ZJ.pan)/500)),attack:QJ(o(ZJ.attack,-12e3)),hold:QJ(o(ZJ.hold,-12e3)),decay:QJ(o(ZJ.decay,-12e3)),sustain:10**(-Math.max(0,o(ZJ.sustain))/200),release:QJ(o(ZJ.release,-12e3))})}}return u}return{voices:s,hasPreset:(e,t)=>o.has(`${e}:${t}`)||o.has(`0:${t}`),presetCount:o.size}}function sY(e){let t=new Set,n=[];for(let r of e)for(let e of HJ(r)){let r=e.channel===9?128:e.bank,i=`${r}:${e.program}`;t.has(i)||(t.add(i),n.push({bank:r,program:e.program}))}return n}function cY(e,t){let n=new Set(tY($J(e)).presets.slice(0,-1).map(e=>`${e.bank}:${e.preset}`)),r=new Set,i=[];for(let{bank:e,program:a}of t){let t=`${e}:${a}`;r.has(t)||(r.add(t),!(n.has(t)||e!==128&&n.has(`0:${a}`))&&i.push({bank:e,program:a}))}return i}function lY(e){return[e&255,e>>8&255]}function uY(e){return[e&255,e>>8&255,e>>16&255,e>>24&255]}function dY(e){let t=[...e].map(e=>e.charCodeAt(0)&255).slice(0,20);return[...t,...Array(20-t.length).fill(0)]}function fY(e){return[...e].map(e=>e.charCodeAt(0))}function pY(e,t){let n=new Uint8Array(8+t.length+(t.length&1));return n.set(fY(e),0),new DataView(n.buffer).setUint32(4,t.length,!0),n.set(t,8),n}function mY(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function hY(e,t){let n=mY([new Uint8Array(fY(e)),...t]);return mY([new Uint8Array(fY(`LIST`)),new Uint8Array(uY(n.length)),n])}function gY(e){if(e.length===0)throw Error(`mergeSoundFonts needs at least one SoundFont`);let t=e.map(e=>tY($J(e))),n=t[0].compressed;if(t.some(e=>e.compressed!==n))throw Error(`cannot merge a SoundFont 3 with a SoundFont 2: decode it first with decodeSoundFont()`);let r={bytes:new Uint8Array,presets:[],presetBags:[],presetGens:[],instruments:[],instBags:[],instGens:[],samples:[],smplBytes:new Uint8Array,smpl:new Int16Array,compressed:n,info:t[0].info},i=[],a=0;for(let e of t){let t=r.instruments.length,o=r.samples.length,s=r.presetBags.length,c=r.presetGens.length,l=r.instBags.length,u=r.instGens.length,d=n?a:a>>1;r.presets.push(...e.presets.slice(0,-1).map(e=>({...e,bag:e.bag+s}))),r.presetBags.push(...e.presetBags.slice(0,-1).map(e=>e+c)),r.presetGens.push(...e.presetGens.slice(0,e.presetBags[e.presetBags.length-1]).map(e=>e.oper===ZJ.instrument?{...e,amount:e.amount+t}:e)),r.instruments.push(...e.instruments.slice(0,-1).map(e=>({...e,bag:e.bag+l}))),r.instBags.push(...e.instBags.slice(0,-1).map(e=>e+u)),r.instGens.push(...e.instGens.slice(0,e.instBags[e.instBags.length-1]).map(e=>e.oper===ZJ.sampleId?{...e,amount:e.amount+o}:e)),r.samples.push(...e.samples.slice(0,-1).map(e=>({...e,start:e.start+d,end:e.end+d,loopStart:n?e.loopStart:e.loopStart+d,loopEnd:n?e.loopEnd:e.loopEnd+d,link:e.link+o})));let f=n?e.smplBytes:e.smplBytes.subarray(0,e.smplBytes.length&-2);i.push(f),a+=f.length}return r.presetBags.push(r.presetGens.length),r.instBags.push(r.instGens.length),r.presets.push({name:`EOS`,preset:0,bank:0,bag:r.presetBags.length-1}),r.instruments.push({name:`EOS`,bag:r.instBags.length-1}),r.samples.push({name:`EOS`,start:0,end:0,loopStart:0,loopEnd:0,rate:0,rootKey:0,correction:0,link:0,type:0}),r.smplBytes=mY(i),n||(r.smpl=new Int16Array(r.smplBytes.slice().buffer)),xY(r,_Y(r))}function _Y(e){let t=new Set,n=[];for(let r=0;r<e.presets.length-1;r++){let i=`${e.presets[r].bank}:${e.presets[r].preset}`;t.has(i)||(t.add(i),n.push(r))}return n}async function vY(e,t,n={}){let r=n.sampleFrames??16777216,i=n.totalFrames??134217728,a=$J(e),o=tY(a);if(!o.compressed)return a.slice().buffer;let s=tY(new Uint8Array(xY(o,_Y(o)))),c=[],l=new Map,u=0,d=[];for(let e of s.samples){if(!(e.end>e.start)||e.type&32768){d.push(e);continue}let n=`${e.start}:${e.end}`,a=l.get(n);if(!a){if(!(e.rate>=400&&e.rate<=2e5))throw Error(`a sample states ${e.rate} Hz, which no SoundFont does: the font is damaged`);let o=await t(s.smplBytes.subarray(e.start,e.end),e.rate);if(o.length>r||u+o.length>i)throw Error("the decoded sample data is larger than the limits allow: subset the font, or raise `limits`");a={start:u,length:o.length},l.set(n,a),c.push(o),u+=o.length}d.push({...e,start:a.start,end:a.start+a.length,loopStart:a.start+Math.min(e.loopStart,a.length),loopEnd:a.start+Math.min(e.loopEnd,a.length),type:e.type&-17})}let f=new Int16Array(u),p=0;for(let e of c)f.set(e,p),p+=e.length;let m={...s,samples:d,smpl:f,smplBytes:new Uint8Array(f.buffer),compressed:!1};return xY(m,_Y(m))}async function yY(e,t={}){return oY(await vY(e,t.decode??XJ(void 0,t.limits),t.limits),t)}function bY(e,t){let n=tY($J(e)),r=new Map;for(let e=0;e<n.presets.length-1;e++)r.set(`${n.presets[e].bank}:${n.presets[e].preset}`,e);let i=new Set,a=[];for(let{bank:e,program:n}of t){let t=aY(r,e,n);t!==void 0&&!i.has(t)&&(i.add(t),a.push(t))}return a.sort((e,t)=>e-t),xY(n,a)}function xY(e,t){let n=t=>{let n=e.samples[t];return!!n&&n.end>n.start&&!(n.type&32768)},r=(e,t,n)=>e.map(e=>e.oper===t?{oper:t,lo:n.get(e.amount)&255,hi:n.get(e.amount)>>8&255,amount:n.get(e.amount)}:e),i=[],a=new Map;{let n=new Set;for(let r of t){let t=e.presets[r].bag,a=e.presets[r+1]?.bag??e.presetBags.length-1;for(let r=t;r<a;r++){let t=nY(e.presetBags,e.presetGens,r);if(!t.some(e=>e.oper===ZJ.instrument))continue;let a=t.find(e=>e.oper===ZJ.instrument).amount;e.instruments[a+1]&&(n.has(a)||(n.add(a),i.push(a)))}}}let o=new Map(i.map((e,t)=>[e,t]));for(let t of i){let r=e.instruments[t].bag,i=e.instruments[t+1]?.bag??e.instBags.length-1,o=[];for(let t=r;t<i;t++){let r=nY(e.instBags,e.instGens,t);if(!r.some(e=>e.oper===ZJ.sampleId))continue;let i=r.find(e=>e.oper===ZJ.sampleId).amount;n(i)&&o.push(r)}a.set(t,o)}let s=[];{let t=new Set,r=i=>{if(t.has(i)||!n(i))return;t.add(i),s.push(i);let a=e.samples[i].link;a!==i&&r(a)};for(let e of i)for(let t of a.get(e))r(t.find(e=>e.oper===ZJ.sampleId).amount)}let c=new Map(s.map((e,t)=>[e,t])),l=e=>[...lY(e.oper),e.lo,e.hi],u=e=>[...lY(e),...lY(0)],d=[],f=[],p=[];for(let n of t){let t=e.presets[n],i=d.length,a=t.bag,s=e.presets[n+1]?.bag??e.presetBags.length-1;for(let t=a;t<s;t++){let n=nY(e.presetBags,e.presetGens,t);(t===a&&!n.some(e=>e.oper===ZJ.instrument)||n.some(e=>e.oper===ZJ.instrument))&&(d.push(f.length),f.push(...r(n,ZJ.instrument,o)))}p.push({name:t.name,preset:t.preset,bank:t.bank,bag:i})}d.push(f.length);let m=[],h=[],g=[];for(let t of i){let n=m.length,i=a.get(t),o=e.instruments[t].bag,s=e.instruments[t+1]?.bag??e.instBags.length-1;for(let t=o;t<s;t++){let n=nY(e.instBags,e.instGens,t);t===o&&!n.some(e=>e.oper===ZJ.sampleId)&&(m.push(h.length),h.push(...n))}for(let e of i)m.push(h.length),h.push(...r(e,ZJ.sampleId,c));g.push({name:e.instruments[t].name,bag:n})}m.push(h.length);let _=[],v=[];for(let t of s){let n=e.samples[t],r=c.get(t);if(e.compressed){let t=v.length;for(let t=n.start;t<n.end;t++)v.push(e.smplBytes[t]);_.push({...n,start:t,end:t+(n.end-n.start),link:c.get(n.link)??r});continue}let i=v.length/2;for(let t=n.start;t<n.end;t++){let n=e.smpl[t];v.push(n&255,n>>8&255)}_.push({...n,start:i,end:i+(n.end-n.start),loopStart:i+(n.loopStart-n.start),loopEnd:i+(n.loopEnd-n.start),link:c.get(n.link)??r})}let y=e=>[...dY(e.name),...lY(e.preset),...lY(e.bank),...lY(e.bag),...Array(12).fill(0)],b=e.presets[e.presets.length-1],x=pY(`phdr`,[...p.flatMap(y),...y({name:b?.name??`EOS`,preset:0,bank:0,bag:d.length-1})]),S=pY(`pbag`,d.flatMap(u)),C=pY(`pgen`,f.flatMap(l)),ee=pY(`pmod`,Array(10).fill(0)),w=e=>[...dY(e.name),...lY(e.bag)],T=e.instruments[e.instruments.length-1],E=pY(`inst`,[...g.flatMap(w),...w({name:T?.name??`EOS`,bag:m.length-1})]),te=pY(`ibag`,m.flatMap(u)),D=pY(`igen`,h.flatMap(l)),O=pY(`imod`,Array(10).fill(0)),ne=e=>[...dY(e.name),...uY(e.start),...uY(e.end),...uY(e.loopStart),...uY(e.loopEnd),...uY(e.rate),e.rootKey,e.correction&255,...lY(e.link),...lY(e.type)],k={name:``,start:0,end:0,loopStart:0,loopEnd:0,rate:0,rootKey:0,correction:0,link:0,type:0},A=pY(`shdr`,[..._.flatMap(ne),...ne(k)]),re=hY(`sdta`,[pY(`smpl`,v)]),ie=hY(`pdta`,[x,S,ee,C,E,te,O,D,A]),ae=mY([new Uint8Array(fY(`sfbk`)),...e.info?[e.info]:[],re,ie]);return mY([new Uint8Array(fY(`RIFF`)),new Uint8Array(uY(ae.length)),ae]).buffer}var SY=22050,CY=.35,wY=480;function TY(e,t={}){return kY(DY(e,t))}async function EY(e,t={}){return mG(kY,[DY(LJ(e),{soundfont:t.soundFontBytes?oY(t.soundFontBytes,{missingProgram:t.missingProgram}):null,sampleRate:t.sampleRate,gain:t.gain,maxDuration:t.maxDuration})])}function DY(e,t){let n=t.sampleRate??SY,r=t.gain??CY,i=t.maxDuration??wY;if(!(n>0))throw Error(`render sample rate must be positive`);if(!(r>=0))throw Error(`render gain must not be negative`);if(!(i>0))throw Error(`render max duration must be positive`);let a=HJ(e).filter(e=>e.time<i);if(a.length===0)throw Error(`MIDI file has no notes`);let o=t.soundfont??null,s=new Map;return{notes:a.map(e=>({...e,frequency:UJ(e.note),voices:o?OY(o,s,e):void 0})),loopStart:VJ(e),sampleRate:n,gain:r,maxDuration:i}}function OY(e,t,n){let r=n.channel===9?128:n.bank,i=`${r}:${n.program}:${n.note}:${n.velocity>>3}`,a=t.get(i);return a||(a=e.voices(r,n.program,n.note,n.velocity),t.set(i,a)),a}function kY(e){let{sampleRate:t,gain:n,maxDuration:r}=e,i=e.notes,a=i.reduce((e,t)=>Math.max(e,t.time+t.duration),0),o=Math.min(r,a+1.5),s=Math.max(1,Math.ceil(o*t)),c=new Float32Array(s),l=new Float32Array(s),u=Math.min(e.loopStart??0,Math.max(0,o-.1));function d(e){let t=(Math.max(-1,Math.min(1,e))+1)*Math.PI/4;return[Math.cos(t),Math.sin(t)]}function f(e,t,n,r,i,a,o,s){let c=i.sample.data;if(c.length===0)return;let l=2**(((r.note-i.rootKey)*100+i.cents+(r.bend??0)*100)/1200)*i.sample.rate/n;if(!(l>0))return;let u=r.time+r.duration,f=Math.max(.002,i.attack),p=f+i.hold+Math.min(i.decay,30),m=Math.max(.03,Math.min(i.release,4)),h=c.length/i.sample.rate,g=r.channel===9?Math.max(u,r.time+Math.min(2,h)):Math.max(u,r.time+f),_=g-r.time,v=a*i.gain,y=v*i.sustain,[b,x]=d(r.pan+i.pan),S=i.loop&&i.sample.loopEnd>i.sample.loopStart,C=i.sample.loopEnd-i.sample.loopStart,ee=Math.min(s,o+Math.ceil((g+m+.02-r.time)*n)),w=0;for(let a=o;a<ee;a++){let o=a/n-r.time,s;s=o<f?o/f*v:o<f+i.hold?v:o<p?v+(y-v)*((o-f-i.hold)/Math.max(1e-6,p-f-i.hold)):o<_?y:o<_+m?y*(1-(o-_)/m):0,S&&w>=i.sample.loopEnd&&(w=i.sample.loopStart+(w-i.sample.loopStart)%C);let u=Math.floor(w),d=Math.min(1,Math.max(0,w-u)),h;if(!S&&w>=c.length||u<0)h=0;else{let e=c[Math.min(u,c.length-1)];h=e+(c[Math.min(u+1,c.length-1)]-e)*d}e[a]+=h*s*b,t[a]+=h*s*x,w+=l}}function p(e){return e<8?{wave:`triangle`,attack:.005,decay:1.2,sustain:.25,release:.2,detune:0}:e<16?{wave:`sine`,attack:.003,decay:.8,sustain:.1,release:.5,detune:0}:e<24?{wave:`square`,attack:.01,decay:.1,sustain:.7,release:.08,detune:0,cutoff:2500}:e<32?{wave:`sawtooth`,attack:.004,decay:.6,sustain:.15,release:.15,detune:0,cutoff:3e3}:e<40?{wave:`triangle`,attack:.005,decay:.4,sustain:.5,release:.1,detune:0}:e<56?{wave:`sawtooth`,attack:.12,decay:.2,sustain:.8,release:.3,detune:6,cutoff:3500}:e<80?{wave:`sawtooth`,attack:.04,decay:.15,sustain:.75,release:.12,detune:0,cutoff:4500}:e<88?{wave:`square`,attack:.01,decay:.1,sustain:.8,release:.1,detune:0,cutoff:3800}:e<104?{wave:`sawtooth`,attack:.25,decay:.3,sustain:.7,release:.5,detune:8,cutoff:2200}:{wave:`triangle`,attack:.005,decay:.5,sustain:.2,release:.2,detune:0}}function m(e,t){switch(e){case`sine`:return Math.sin(t);case`square`:return Math.sin(t)>=0?1:-1;case`sawtooth`:{let e=t/(2*Math.PI);return 2*(e-Math.floor(e))-1}case`triangle`:{let e=t/(2*Math.PI);return 4*Math.abs(e-Math.floor(e)-.5)-1}}}function h(e,t,n,r,i,a){return e<t?e/t:e<t+n?1-(1-r)*((e-t)/Math.max(1e-6,n)):e<i?r:e<i+a?r*(1-(e-i)/a):0}function g(e,t){let n=Math.imul(e^t,2654435761)>>>0;return n=Math.imul(n^n>>>15,2246822519)>>>0,n=Math.imul(n^n>>>13,3266489917)>>>0,n^=n>>>16,(n>>>0)/4294967295*2-1}function _(e,t,n,r,i,a,o){if(r.channel===9){v(e,t,n,r,i,a,o);return}let s=p(r.program),c=r.frequency*2**((s.detune+(r.bend??0)*100)/1200),l=Math.max(r.duration,s.attack+.01),u=Math.max(.02,s.release),f=Math.min(o,a+Math.ceil((l+u+.02)*n)),[g,_]=d(r.pan),y=s.cutoff!==void 0,b=y?1-Math.exp(-2*Math.PI*Math.min(s.cutoff,c*8+800)/n):0,x=0,S=0,C=2*Math.PI*c/n;for(let o=a;o<f;o++){let a=o/n-r.time,c=m(s.wave,S);S+=C,x=y?x+b*(c-x):c;let d=i*h(a,s.attack,s.decay,s.sustain,l,u);e[o]+=x*d*g,t[o]+=x*d*_}}function v(e,t,n,r,i,a,o){let[s,c]=d(r.pan),l=r.note*7919+a;if(r.note===35||r.note===36||r.note<45){let l=i*1.4,u=Math.min(o,a+Math.ceil(.27*n)),d=0;for(let i=a;i<u;i++){let a=i/n-r.time,o=a<.12?150*(45/150)**(a/.12):45;d+=2*Math.PI*o/n;let u=l*(.001/l)**Math.min(1,a/.22);e[i]+=Math.sin(d)*u*s,t[i]+=Math.sin(d)*u*c}return}let u=r.note===38||r.note===40,f=u?.16:r.note>=49?.5:.06,p=i*(u?.9:.5),m=Math.min(o,a+Math.ceil((f+.02)*n));for(let i=a;i<m;i++){let o=i/n-r.time,u=p*(.001/p)**Math.min(1,o/f),d=g(l,i-a)*u;e[i]+=d*s,t[i]+=d*c}}for(let e of i){let r=Math.floor(e.time*t);if(r>=s)continue;let i=n*Math.max(.02,e.velocity/127*e.gain),a=e.voices??[];if(a.length>0)for(let n of a)f(c,l,t,e,n,i,r,s);else _(c,l,t,e,i,r,s)}return{sampleRate:t,left:c,right:l,loopStart:u,loopEnd:o,duration:o}}function AY(e,t){let n=e.createBuffer(2,Math.max(1,t.left.length),t.sampleRate);return n.getChannelData(0).set(t.left),n.getChannelData(1).set(t.right),n}function jY(e,t={}){let n=new Map,r=t.read??MY;async function i(n){let i=await r(n),a=new Uint8Array(i,0,Math.min(4,i.byteLength));if(a[0]===77&&a[1]===84&&a[2]===104&&a[3]===100){let n=await EY(i,t.midi);return{buffer:AY(e,n),loop:{start:n.loopStart,end:n.loopEnd}}}return{buffer:await e.decodeAudioData(i.slice(0))}}return(e,t)=>{let r=n.get(t);return r||(r=i(t).catch(e=>{throw n.delete(t),e}),n.set(t,r)),r}}async function MY(e){return await WN([e]),GN(e)}var NY=class{constructor(e={}){this.current=null,this.fades=[],this.trackQueue=null,this.playlistFade=1,this.suspended_=!1,this.duckLevel_=1,this.volume=e.volume??1,this.create=e.create??Bq}play(e,t=1){this.trackQueue=null,this.start(e,t,!0)}playTracks(e,t=1){e.length===0?this.stop(t):(this.trackQueue=[...e],this.playlistFade=t,this.startNextTrack())}startNextTrack(){if(!this.trackQueue?.length)return;let e=this.trackQueue.shift();this.trackQueue.push(e),this.start(e,this.playlistFade,!1)}start(e,t,n){let r=this.create(e);r.loop=n,!n&&r.onended!==void 0&&(r.onended=()=>{this.current===r&&this.startNextTrack()});let i=this.current;this.current=r,t<=0?(r.volume=this.volume*this.duckLevel_,Promise.resolve(r.play()).catch(()=>{}),i?.pause()):(r.volume=0,Promise.resolve(r.play()).catch(()=>{}),this.fades.push({audio:r,elapsed:0,duration:t,from:0,to:this.volume*this.duckLevel_,stopAtEnd:!1}),i&&this.fades.push({audio:i,elapsed:0,duration:t,from:i.volume,to:0,stopAtEnd:!0}))}stop(e=1){this.trackQueue=null;let t=this.current;t&&(this.current=null,e<=0?t.pause():this.fades.push({audio:t,elapsed:0,duration:e,from:t.volume,to:0,stopAtEnd:!0}))}suspend(){this.suspended_=!0,this.current?.pause();for(let e of this.fades)e.audio.pause()}resume(){this.suspended_&&(this.suspended_=!1,this.current&&Promise.resolve(this.current.play()).catch(()=>{}))}duck(e=.5,t=.5){let n=Number.isFinite(e)?Math.max(0,Math.min(1,e)):1,r=this.duckLevel_;this.duckLevel_=n;for(let e of this.fades)e.to=r>0?e.to/r*n:this.volume*n;if(this.current){let e=this.volume*n;t<=0?this.current.volume=e:this.fades.push({audio:this.current,elapsed:0,duration:t,from:this.current.volume,to:e,stopAtEnd:!1})}}unduck(e=.5){this.duck(1,e)}get duckLevel(){return this.duckLevel_}get isSuspended(){return this.suspended_}update(e){if(!this.suspended_)for(let t of[...this.fades]){t.elapsed+=e;let n=Math.min(1,t.elapsed/t.duration);t.audio.volume=t.from+(t.to-t.from)*n,n>=1&&(this.fades.splice(this.fades.indexOf(t),1),t.stopAtEnd&&(t.audio.pause(),t.audio.currentTime=0))}}},PY=class{constructor(e){this.states=new Map,this.cues=new Map,this.currentTrack=null,this.music=e}define(e,t){this.states.set(e,t)}enter(e){let t=this.states.get(e);if(!t)throw Error(`Orchestrator: no state defined for "${e}"`);t.track!==this.currentTrack&&(this.music.play(t.track,t.fadeDuration),this.currentTrack=t.track)}on(e,t){this.cues.set(e,t)}trigger(e){this.cues.get(e)?.play()}suspend(){this.music.suspend();for(let e of this.cues.values())e.suspend()}resume(){this.music.resume();for(let e of this.cues.values())e.resume()}};function FY(e,t,n,r,i,a){let o=e.createBufferSource();o.buffer=n,o.playbackRate.value=i;let s=e.createGain();s.gain.value=r;let c=null;return typeof e.createStereoPanner==`function`?(c=e.createStereoPanner(),c.pan.value=a,o.connect(s),s.connect(c),c.connect(t)):(o.connect(s),s.connect(t)),{source:o,gain:s,panner:c}}var IY=class{constructor(e,t){this.source=null,this.gainNode=null,this.pannerNode=null,this.buffer=null,this.params={volume:1,pitch:1,pan:0},this.loopRegion=null,this.repeat=!0,this.startedAt=0,this.offset=0,this.context=e,this.destination=t??e.destination}get isPlaying(){return this.source!==null}get duration(){return this.buffer?.duration??0}play(e,t={}){this.stop();let n=t.volume??1,r=t.pitch??1,i=t.pan??0,{source:a,gain:o,panner:s}=FY(this.context,this.destination,e,n,r,i),c=t.loop??null,l=t.repeat??!0;if(a.loop=l,c&&(a.loopStart=c.start,a.loopEnd=c.end),!l){let e=a;a.onended=()=>{this.source===e&&this.clearNodes()}}this.source=a,this.gainNode=o,this.pannerNode=s,this.buffer=e,this.params={volume:n,pitch:r,pan:i},this.loopRegion=c,this.repeat=l,this.offset=Math.min(Math.max(0,t.pos??0),Math.max(0,e.duration-.001)),this.startedAt=this.context.currentTime,a.start(0,this.offset)}update(e){if(e.volume!==void 0&&(this.params.volume=e.volume),e.pitch!==void 0&&(this.params.pitch=e.pitch),e.pan!==void 0&&(this.params.pan=e.pan),!this.source||!this.gainNode)return;let t=this.context.currentTime;this.gainNode.gain.setTargetAtTime(this.params.volume,t,.02),this.source.playbackRate.value=this.params.pitch,this.pannerNode&&(this.pannerNode.pan.value=this.params.pan)}stop(e=0){let t=this.position(),n=this.source,r=this.gainNode;if(this.clearNodes(),this.offset=t,n)try{if(e>0&&r){let t=this.context.currentTime;r.gain.cancelScheduledValues(t),r.gain.setValueAtTime(r.gain.value,t),r.gain.linearRampToValueAtTime(0,t+e),n.stop(t+e+.02)}else n.stop()}catch{}}position(){if(!this.source||!this.buffer)return this.offset;let e=Math.max(0,this.context.currentTime-this.startedAt)*this.params.pitch,t=this.offset+e;if(this.repeat&&this.duration>0){let e=this.loopRegion?.start??0,n=this.loopRegion?.end??this.buffer.duration;n>e&&t>=n&&(t=e+(t-e)%(n-e))}return t}seek(e){this.restore({...this.state(),pos:e})}state(){return{...this.params,pos:this.position()}}restore(e){let t=this.buffer;this.update({volume:e.volume,pitch:e.pitch,pan:e.pan}),t&&this.source?this.play(t,{volume:e.volume,pitch:e.pitch,pan:e.pan,pos:e.pos,loop:this.loopRegion,repeat:this.repeat}):this.offset=Math.max(0,e.pos)}clearNodes(){this.source&&(this.source.onended=null),this.source=null,this.gainNode=null,this.pannerNode=null}};function LY(e,t,n,r){let i=Number(e);return Math.min(n,Math.max(t,Number.isFinite(i)?i:r))}var RY=class e{constructor(e,t={}){this.tracks={bgm:null,bgs:null},this.saved={bgm:null,bgs:null},this.requests={bgm:0,bgs:0},this.me=null,this.meToken=0,this.suspendedBgm=null,this.seNodes=new Set,this.mixerLevels={bgm:{volume:1,muted:!1},bgs:{volume:1,muted:!1},me:{volume:1,muted:!1},se:{volume:1,muted:!1}},this.context=e,this.destination=t.destination??e.destination,this.load=t.load??jY(e);let n=()=>{let t=e.createGain();return t.connect(this.destination),t};this.kindGains={bgm:n(),bgs:n(),me:n(),se:n()},this.bgmChannel=new IY(e,this.kindGains.bgm),this.bgsChannel=new IY(e,this.kindGains.bgs)}setMixer(e,t){let n=this.mixerLevels[e];t.volume!==void 0&&(n.volume=LY(t.volume,0,1,1)),t.muted!==void 0&&(n.muted=t.muted),this.kindGains[e].gain.value=n.muted?0:n.volume}mixer(e){return{...this.mixerLevels[e]}}playBgm(e){return this.playLoop(`bgm`,e)}playBgs(e){return this.playLoop(`bgs`,e)}stopBgm(){this.requests.bgm++,this.tracks.bgm=null,this.suspendedBgm=null,this.bgmChannel.stop()}stopBgs(){this.requests.bgs++,this.tracks.bgs=null,this.bgsChannel.stop()}fadeOutBgm(e=1){this.requests.bgm++,this.tracks.bgm=null,this.suspendedBgm=null,this.bgmChannel.stop(Math.max(0,e))}fadeOutBgs(e=1){this.requests.bgs++,this.tracks.bgs=null,this.bgsChannel.stop(Math.max(0,e))}currentTrack(e){let t=this.tracks[e];if(t){let n=e===`bgm`?this.bgmChannel:this.bgsChannel;return{...t,pos:n.isPlaying?n.position():t.pos}}return e===`bgm`?this.suspendedBgm:null}saveBgm(){return this.saved.bgm=this.currentTrack(`bgm`),this.saved.bgm}saveBgs(){return this.saved.bgs=this.currentTrack(`bgs`),this.saved.bgs}replayBgm(){return this.saved.bgm?this.playBgm(this.saved.bgm):Promise.resolve()}replayBgs(){return this.saved.bgs?this.playBgs(this.saved.bgs):Promise.resolve()}async playMe(t){let n=e.normalize(t),r=++this.meToken;if(this.stopMeNodes(),!n.name)return;let i=await this.load(`me`,n.name);if(r!==this.meToken||!i)return;let a=this.currentTrack(`bgm`);a&&(this.suspendedBgm=a,this.requests.bgm++,this.bgmChannel.stop(),this.tracks.bgm=null);let{source:o}=FY(this.context,this.kindGains.me,i.buffer,n.volume/100,n.pitch/100,n.pan/100);this.me={source:o,token:r},o.onended=()=>{this.me?.token===r&&this.finishMe()},o.start(0)}stopMe(e=!0){this.stopMeNodes(),e&&this.finishMe()}async playSe(t){let n=e.normalize(t);if(!n.name)return;let r=await this.load(`se`,n.name);if(!r)return;let{source:i}=FY(this.context,this.kindGains.se,r.buffer,n.volume/100,n.pitch/100,n.pan/100),a={source:i};this.seNodes.add(a),i.onended=()=>{this.seNodes.delete(a)},i.start(0)}stopSe(){for(let e of this.seNodes){e.source.onended=null;try{e.source.stop()}catch{}}this.seNodes.clear()}stopAll(){this.requests.bgm++,this.requests.bgs++,this.tracks.bgm=null,this.tracks.bgs=null,this.suspendedBgm=null,this.bgmChannel.stop(),this.bgsChannel.stop(),this.stopMeNodes(),this.stopSe()}snapshot(){return{bgm:this.currentTrack(`bgm`),bgs:this.currentTrack(`bgs`),savedBgm:this.saved.bgm,savedBgs:this.saved.bgs}}restore(e){e&&typeof e==`object`&&(this.saved.bgm=e.savedBgm??null,this.saved.bgs=e.savedBgs??null,e.bgm&&this.playBgm(e.bgm),e.bgs&&this.playBgs(e.bgs))}static normalize(e){return{name:String(e?.name||``),volume:LY(e?.volume,0,100,90),pitch:LY(e?.pitch,10,400,100),pan:LY(e?.pan,-100,100,0),pos:Math.max(0,Number(e?.pos)||0)}}async playLoop(t,n){let r=t===`bgm`?this.bgmChannel:this.bgsChannel,i=e.normalize(n);if(!i.name){this.requests[t]++,this.tracks[t]=null,t===`bgm`&&(this.suspendedBgm=null),r.stop();return}let a=this.tracks[t];if(a&&a.name===i.name&&!(i.pos>0)){this.tracks[t]={...i,pos:0},r.update({volume:i.volume/100,pitch:i.pitch/100,pan:i.pan/100});return}if(t===`bgm`&&this.me){this.requests.bgm++,this.suspendedBgm=i,this.tracks.bgm=null,r.stop();return}let o=++this.requests[t];r.stop(),this.tracks[t]={...i,pos:0};let s=await this.load(t,i.name);o===this.requests[t]&&(s?r.play(s.buffer,{volume:i.volume/100,pitch:i.pitch/100,pan:i.pan/100,pos:i.pos,loop:s.loop??null}):this.tracks[t]=null)}stopMeNodes(){let e=this.me;if(this.me=null,e){e.source.onended=null;try{e.source.stop()}catch{}}}finishMe(){this.me=null;let e=this.suspendedBgm;this.suspendedBgm=null,e&&!this.tracks.bgm&&this.playBgm(e)}},zY=class{constructor(e,t={}){this.onEnded=new p,this.buffer=null,this.loop=null,this.repeat=!1,this.playing=!1,this.paused=!1,this.resumeAt=0,this.context=e,this.channel=new IY(e,t.destination),this.volume_=Math.min(1,Math.max(0,t.volume??1))}load(e){this.stop(),`left`in e?(this.buffer=AY(this.context,e),this.loop={start:e.loopStart,end:e.loopEnd}):(this.buffer=e,this.loop=null)}play(e={}){this.buffer&&(this.repeat=e.repeat??!1,this.paused=!1,this.playing=!0,this.resumeAt=e.pos??0,this.start())}pause(){this.playing&&!this.paused&&(this.resumeAt=this.channel.position(),this.paused=!0,this.channel.stop())}resume(){this.paused&&this.buffer&&(this.paused=!1,this.start())}togglePause(){this.paused?this.resume():this.pause()}stop(){this.channel.stop(),this.playing=!1,this.paused=!1,this.resumeAt=0}get isPlaying(){return this.playing&&!this.paused}get isPaused(){return this.paused}get duration(){return this.buffer?.duration??0}position(){return this.playing?this.paused?this.resumeAt:this.channel.position():0}seek(e){if(!this.buffer)return;let t=Math.min(Math.max(0,e),this.buffer.duration);this.paused?this.resumeAt=t:this.playing&&this.play({pos:t,repeat:this.repeat})}get volume(){return this.volume_}set volume(e){this.volume_=Math.min(1,Math.max(0,e)),this.channel.update({volume:this.volume_})}update(){!this.playing||this.paused||this.channel.isPlaying||(this.playing=!1,this.resumeAt=0,this.onEnded.dispatch())}start(){this.buffer&&this.channel.play(this.buffer,{volume:this.volume_,pos:this.resumeAt,loop:this.loop,repeat:this.repeat})}},BY=65536;function VY(e){let t=UY(e.subarray(0,BY));if(!t)return null;let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=new TextDecoder(`utf-8`),i=7,a=()=>{if(i+4>t.length)return null;let e=n.getUint32(i,!0);return i+=4,i+e<=t.length?e:null},o=a();if(o===null||(i+=o,i+4>t.length))return null;let s=n.getUint32(i,!0);i+=4;let c=null,l=null;for(let e=0;e<s;e++){let e=a();if(e===null)break;let n=r.decode(t.subarray(i,i+e));i+=e;let o=n.indexOf(`=`);if(o<0)continue;let s=n.slice(0,o).toUpperCase(),u=/^\d+$/.test(n.slice(o+1))?Number(n.slice(o+1)):null;u!==null&&(s===`LOOPSTART`?c=u:s===`LOOPLENGTH`&&(l=u))}return c===null?null:{loopStart:c,loopLength:l}}function HY(e,t,n){if(!e||!(t>0))return null;let r=e.loopStart/t,i=e.loopLength?(e.loopStart+e.loopLength)/t:n;return r>=0&&i>r&&r<n?{start:r,end:Math.min(i,n)}:null}function UY(e){let t=[3,118,111,114,98,105,115],n=[],r=0;for(;r+27<=e.length;){if(e[r]!==79||e[r+1]!==103||e[r+2]!==103||e[r+3]!==83)return null;let i=e[r+26],a=r+27+i;if(a>e.length)return null;let o=a;for(let a=0;a<i;a++){let i=e[r+27+a];if(o+i>e.length)return null;for(let t=0;t<i;t++)n.push(e[o+t]);if(o+=i,i<255){if(t.every((e,t)=>n[t]===e))return Uint8Array.from(n);n=[]}}r=o}return null}function WY(e,t={}){let n=t.refDistance??1,r=t.maxDistance??1/0,i=t.rolloff??1;if(!(e>n))return 1;if(!(e<r))return 0;let a=(n/e)**+i;return Math.max(0,Math.min(1,a))}function GY(e,t){let n=t.x-e.x,r=t.y-e.y,i=Math.hypot(n,r);if(i===0)return 0;let a=Math.sin(e.facing),o=Math.cos(e.facing),s=(n*a+r*o)/i;return Math.max(-1,Math.min(1,s))}var KY=class{constructor(e={}){this.x=e.x??0,this.y=e.y??0,this.facing=e.facing??0}moveTo(e,t){this.x=e,this.y=t}face(e){this.facing=e}},qY=class{constructor(e,t={}){this.sound=e,this.x=t.x??0,this.y=t.y??0,this.falloff={refDistance:t.refDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}}moveTo(e,t){this.x=e,this.y=t}gainTo(e){return WY(Math.hypot(this.x-e.x,this.y-e.y),this.falloff)}panTo(e){return GY(e,this)}playFor(e){let t=this.gainTo(e);return t<=0?0:(this.sound.play(t),t)}};kJ(),MJ();var JY=256,YY=64,XY=10,ZY=2,QY=.05,$Y=4,eX=96;function tX(e,t){let n=e.length,r=0;for(let i=1;i<n;i++){let a=n>>1;for(;r&a;)r^=a,a>>=1;if(r^=a,i<r){let n=e[i];e[i]=e[r],e[r]=n,n=t[i],t[i]=t[r],t[r]=n}}for(let r=2;r<=n;r<<=1){let i=-2*Math.PI/r,a=Math.cos(i),o=Math.sin(i),s=r>>1;for(let i=0;i<n;i+=r){let n=1,r=0;for(let c=0;c<s;c++){let l=i+c,u=l+s,d=e[u]*n-t[u]*r,f=e[u]*r+t[u]*n;e[u]=e[l]-d,t[u]=t[l]-f,e[l]+=d,t[l]+=f;let p=n*a-r*o;r=n*o+r*a,n=p}}}}function nX(e,t){if(e.length===0||t<=0)return[];let n=JY/2,r=new Float32Array(e.length+256);r.set(e,n);let i=new Float64Array(JY);for(let e=0;e<JY;e++)i[e]=.5-.5*Math.cos(2*Math.PI*e/255);let a=new Float64Array(JY),o=new Float64Array(JY),s=new Float64Array(JY/2),c=[],l=[],u=0;for(let e=0;e+JY<=r.length;e+=YY){let t=0;for(let n=0;n<JY;n++)a[n]=r[e+n]*i[n],o[n]=0,t+=a[n]*a[n];l.push(u===0?t===0?0:1/0:t/u-1),u=t,tX(a,o);let n=0;for(let e=0;e<JY/2;e++){let t=Math.hypot(a[e],o[e]),r=t-s[e];r>0&&(n+=r),s[e]=t}c.push(n)}let d=[],f=-1/0;for(let e=0;e<c.length;e++){let r=Math.max(0,e-XY),i=Math.min(c.length-1,e+XY),a=i-r+1,o=0;for(let e=r;e<=i;e++)o+=c[e];o/=a;let s=0;for(let e=r;e<=i;e++)s+=(c[e]-o)**2;let u=o+ZY*Math.sqrt(s/a);if(c[e]<=0||c[e]<u||l[e]<QY&&(e===0||l[e-1]<QY)||e>0&&c[e-1]>c[e]||e+1<c.length&&c[e+1]>=c[e]||e-f<$Y)continue;let p=(e*YY+n-eX)/t;d.push(Math.max(0,p)),f=e}return d}tJ();var rX=`extracted`,iX=[4,4],aX=120,oX=120,sX=480;function cX(e){let t=[...e].sort((e,t)=>e-t),n=t.length>>1;return t.length%2==1?t[n]:(t[n-1]+t[n])/2}function lX(e){return Math.round(cX(e))}function uX(e){for(let t of e.events)if(t.type===`tempo`)return Math.round(6e7/t.microsecondsPerQuarter*100)/100;return aX}function dX(e){return e.events.filter(e=>e.type===`noteOn`)}function fX(e){return dX(e).map(e=>e.velocity)}function pX(e,t,n,r,i){let a=e.map((e,t)=>({subdivisionIndex:t,timeOffsetTicks:e.time.length>0?lX(e.time):0,velocityFactor:e.velocity.length>0?i(e):1}));return{name:rX,timeSignature:[...iX],ppq:n,tempoBpm:r,subdivision:t,offsets:a}}var mX=class{async extractFromMidiPair(e,t,n=`16n`){let r=t.ticksPerQuarter,i=Qq(r,n),a=Zq(iX,n),o=r/e.ticksPerQuarter,s=dX(e).map(e=>({channel:e.channel,note:e.note,tick:e.tick*o,velocity:e.velocity})),c=new Set,l=[];for(let e of dX(t)){let t=-1,n=1/0;for(let r=0;r<s.length;r++){let i=s[r];if(c.has(r)||i.channel!==e.channel||i.note!==e.note)continue;let a=Math.abs(i.tick-e.tick);a<n&&(n=a,t=r)}t<0||n>i/2||(c.add(t),l.push({slotTick:s[t].tick,delta:e.tick-s[t].tick,factor:s[t].velocity>0?e.velocity/s[t].velocity:null}))}let u=Array.from({length:a},()=>({time:[],velocity:[]}));for(let e of l){let t=(Math.round(e.slotTick/i)%a+a)%a;u[t].time.push(e.delta),e.factor!==null&&u[t].velocity.push(e.factor)}return pX(u,n,r,uX(t),e=>cX(e.velocity))}async extractFromSingleMidi(e,t=`16n`){let n=e.ticksPerQuarter,r=Qq(n,t),i=Zq(iX,t),a=Array.from({length:i},()=>({time:[],velocity:[]}));for(let t of dX(e)){let e=Math.round(t.tick/r)*r,n=(Math.round(e/r)%i+i)%i;a[n].time.push(t.tick-e),a[n].velocity.push(t.velocity)}let o=cX(fX(e));return pX(a,t,n,uX(e),e=>o<=0?1:cX(e.velocity)/o)}async extractFromAudioBuffer(e,t=`16n`,n=oX){if(!Number.isFinite(n)||n<=0)throw Error(`tempoBpm must be greater than 0, got ${String(n)}`);let r=[];for(let t=0;t<e.numberOfChannels;t++)r.push(e.getChannelData(t));let i=new Float32Array(e.length);for(let e of r)for(let t=0;t<e.length;t++)i[t]+=e[t]/r.length;let a=nX(i,e.sampleRate);if(a.length===0)throw Error(`no onsets detected in the buffer - a groove needs audible attacks, and this audio has none`);let o=sX,s=Qq(o,t),c=Zq(iX,t),l=n*o/60,u=Array.from({length:c},()=>({time:[],velocity:[]}));for(let e of a){let t=e*l,n=Math.round(t/s)*s;u[(Math.round(n/s)%c+c)%c].time.push(t-n)}return pX(u,t,o,n,()=>1)}};tJ();var hX=`mwg-groove:`,gX=36,_X=64,vX=[`8n`,`16n`,`32n`],yX=new TextEncoder;function bX(e){throw Error(`the ${e} format is not shipped: it is an undocumented proprietary container, and a guessed reader could load a different groove than the file holds`)}function xX(e){return[...e].map(e=>e.charCodeAt(0)&127)}function SX(e){let t=[e&127],n=e>>>7;for(;n>0;)t.unshift(n&127|128),n>>>=7;return t}function CX(e,t){return[255,e,...SX(t.length),...t]}function wX(e){$q(e);let{name:t,timeSignature:n,ppq:r,subdivision:i,offsets:a}=e,o=Zq(n,i),s=Qq(r,i);if(r>32767)throw Error(`groove template "${t}": ppq ${r} does not fit MIDI's 15-bit division`);if(gX+o-1>127)throw Error(`groove template "${t}": ${o} slots need pitches up to ${gX+o-1}, past MIDI's top note of 127`);let c=Math.round(6e7/e.tempoBpm);if(c<1||c>16777215)throw Error(`groove template "${t}": tempoBpm ${e.tempoBpm} does not fit MIDI's three-byte tempo (${c} microseconds)`);a.forEach((e,n)=>{if(Math.abs(e.timeOffsetTicks)>=s)throw Error(`groove template "${t}": slot ${n} is offset by ${e.timeOffsetTicks} ticks, outside the +/-${s} the MIDI encoding's one-slot anchor can tell from a slot shift`);let r=Math.round(_X*e.velocityFactor);if(r<1||r>127)throw Error(`groove template "${t}": slot ${n} has velocityFactor ${e.velocityFactor}, outside the ${1/_X} to ${127/_X} the MIDI encoding can store at ${1/_X} per velocity unit`)});let l=[{tick:0,bytes:CX(81,[c>>16&255,c>>8&255,c&255])},{tick:0,bytes:CX(88,[n[0],Math.log2(n[1]),24,8])},{tick:0,bytes:CX(1,[...yX.encode(hX+t)])}];a.forEach((e,t)=>{let n=s*(t+1)+e.timeOffsetTicks,r=n+Math.max(1,Math.floor(s/4));l.push({tick:n,bytes:[144,gX+t,Math.round(_X*e.velocityFactor)]}),l.push({tick:r,bytes:[128,gX+t,0]})}),l.sort((e,t)=>e.tick-t.tick);let u=[],d=0;for(let e of l)u.push(...SX(e.tick-d),...e.bytes),d=e.tick;return u.push(0,255,47,0),new Uint8Array([...xX(`MThd`),0,0,0,6,0,0,0,1,r>>8&255,r&255,...xX(`MTrk`),u.length>>>24&255,u.length>>>16&255,u.length>>>8&255,u.length&255,...u])}function TX(e,t){for(let n of vX)try{if(Zq(e,n)===t)return n}catch{}throw Error(`a ${t}-slot groove in ${e[0]}/${e[1]} is not one of the 8n, 16n or 32n grids`)}function EX(e){let t=typeof e==`string`?yX.encode(e):e,n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=0,i=(e,n)=>{if(r+e>t.length)throw Error(`truncated MIDI file while reading ${n}`)},a=(e,n)=>{i(e,n);let a=``;for(let n=0;n<e;n++)a+=String.fromCharCode(t[r+n]);return r+=e,a},o=e=>(i(1,e),t[r++]),s=e=>{i(2,e);let t=n.getUint16(r);return r+=2,t},c=e=>{i(4,e);let t=n.getUint32(r);return r+=4,t},l=e=>{let t=0;for(let n=0;n<4;n++){let n=o(e);if(t=t<<7|n&127,!(n&128))return t}throw Error(`a variable-length quantity in ${e} runs past four bytes`)};if(a(4,`the file header`)!==`MThd`)throw Error(`not a Standard MIDI File: the MThd header is missing`);let u=c(`the header length`);if(u<6)throw Error(`MThd is ${u} bytes, expected at least 6`);let d=s(`the format`),f=s(`the track count`),p=s(`the division`);if(r+=u-6,d>1)throw Error(`MIDI format ${d} is not a file this reader understands`);if(p&32768)throw Error(`SMPTE time in the division carries no tick grid to read a groove from`);if(f!==1)throw Error(`an mwg groove file holds one track, this one has ${f}`);if(a(4,`the track header`)!==`MTrk`)throw Error(`the MTrk track header is missing`);let m=c(`the track length`),h=r+m;if(h>t.length)throw Error(`truncated MIDI file: the track runs past the end of the data`);let g=0,_=0,v=null,y=null,b=null,x=!1,S=new Map;for(;r<h;){g+=l(`a delta time`);let e=t[r];if(e<128){if(_===0)throw Error(`data at tick ${g} follows a delta time with no running status to read it under`);e=_}else r++,e<240&&(_=e);if(e===255){let e=o(`a meta type`),n=l(`a meta length`);i(n,`a meta event`);let a=r;if(e===81&&n===3)v=t[a]<<16|t[a+1]<<8|t[a+2];else if(e===88&&n>=2)y=[t[a],2**t[a+1]];else if((e===1||e===3)&&n>0){let e=``;for(let r=0;r<n;r++)e+=String.fromCharCode(t[a+r]);e.startsWith(hX)&&(b=e.slice(11))}r+=n,e===47&&(x=!0),_=0;continue}if(e===240||e===247){r+=l(`a sysex length`),_=0;continue}let n=e&240;if(n===144||n===128){let e=o(`a note number`),t=o(`a note velocity`);if(n===144&&t>0){if(S.has(e))throw Error(`pitch ${e} carries more than one note-on, which no groove encodes`);S.set(e,{tick:g,velocity:t})}}else if(n===176||n===224)i(2,`a controller or bend event`),r+=2;else if(n===192||n===208)i(1,`a program or channel-aftertouch event`),r+=1;else throw Error(`unexpected status byte 0x${e.toString(16)} at tick ${g}`)}if(!x)throw Error(`the track has no end-of-track meta, so the file is incomplete`);if(b===null)throw Error(`no ${hX} text meta: this file was not written as a groove`);if(y===null)throw Error(`no time-signature meta: an mwg groove file always carries one`);let C=p,ee=S.size,w=TX(y,ee),T=Qq(C,w),E=[];for(let e=0;e<ee;e++){let t=S.get(gX+e);if(!t)throw Error(`slot ${e} is missing: expected a note on pitch ${gX+e}`);E.push({subdivisionIndex:e,timeOffsetTicks:t.tick-T*(e+1),velocityFactor:t.velocity/_X})}let te={name:b,timeSignature:y,ppq:C,tempoBpm:v===null?120:Math.round(6e7/v*100)/100,subdivision:w,offsets:E};return $q(te),te}function DX(e){let t=typeof e==`string`?e:new TextDecoder().decode(e),n;try{n=JSON.parse(t)}catch(e){throw Error(`not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`a groove JSON export must be an object`);return $q(n),n}var OX=class{async exportFormat(e,t){switch(t){case`json`:return $q(e),JSON.stringify(e,null,2);case`midi`:return wX(e);case`ableton-agr`:case`reaper-groove`:return bX(t);default:throw Error(`unknown groove format: ${String(t)}`)}}async importFormat(e,t){switch(t){case`json`:return DX(e);case`midi`:return EX(e);case`ableton-agr`:case`reaper-groove`:return bX(t);default:throw Error(`unknown groove format: ${String(t)}`)}}},kX=l({AudioBus:()=>RY,AudioListener:()=>KY,Channel:()=>IY,GrooveConverter:()=>OX,GrooveExtractor:()=>mX,GrooveHumanizer:()=>jJ,HumanizerFactory:()=>NJ,LiteHumanizer:()=>OJ,MidiPlayer:()=>WJ,Music:()=>NY,MusicPlayer:()=>zY,Orchestrator:()=>PY,Sound:()=>Uq,SoundSource:()=>qY,assertGrooveTemplate:()=>$q,audioGain:()=>WY,audioPan:()=>GY,collectSoundFontUsage:()=>sY,createAudio:()=>Bq,createAudioLoader:()=>jY,decodeSoundFont:()=>vY,humanizeMidi:()=>PJ,loadSoundFont:()=>yY,loopRegionFromTags:()=>HY,mergeSoundFonts:()=>gY,midiLoopStart:()=>VJ,missingSoundFontPrograms:()=>cY,noteToFrequency:()=>UJ,onCaption:()=>Hq,parseMidi:()=>LJ,parseSoundFont:()=>oY,parseVorbisLoopTags:()=>VY,playTone:()=>Gq,renderMidiToBuffer:()=>TY,renderMidiToBufferAsync:()=>EY,scheduleMidi:()=>HJ,subdivisionCount:()=>Zq,subsetSoundFont:()=>bY,synthesizeSound:()=>Kq,synthesizeTone:()=>Wq,toAudioBuffer:()=>AY,webAudioSampleDecoder:()=>XJ});tJ();function AX(e,t){if(!Number.isSafeInteger(t)||t<0)throw RangeError(`Turn budget must be a non-negative safe integer`);let n=0;for(;n<t;){if(e.finished())return{status:`finished`,steps:n};let t=e.scheduler.peek();if(t===null)return{status:`empty`,steps:n};if(e.needsInput(t))return{status:`input`,actor:t,steps:n};let r=e.act(t);if(r!==null){if(!Number.isFinite(r)||r<0)throw RangeError(`Action cost must be finite and non-negative, or null`);e.scheduler.spend(r)}n++}return{status:`limit`,steps:n}}function jX(e){if(e?.version!==1||typeof e.observationVersion!=`string`||!e.observationVersion.length)throw TypeError(`unsupported neural model or observation version`);if(!Array.isArray(e.layers)||!e.layers.length||e.layers.length>32)throw RangeError(`a neural model needs 1..32 layers`);let t=0;for(let n=0;n<e.layers.length;n++){let r=e.layers[n];if(!r||!Number.isInteger(r.inputSize)||!Number.isInteger(r.outputSize)||r.inputSize<1||r.outputSize<1||r.inputSize>4096||r.outputSize>4096)throw RangeError(`neural layer dimensions must be integers in 1..4096`);if(t+=r.inputSize*r.outputSize+r.outputSize,t>1e6)throw RangeError(`neural model exceeds one million parameters`);if(n&&e.layers[n-1].outputSize!==r.inputSize)throw RangeError(`neural layer dimensions do not connect`);if(!Array.isArray(r.weights)||!Array.isArray(r.biases)||r.weights.length!==r.inputSize*r.outputSize||r.biases.length!==r.outputSize||!Array.from(r.weights).every(Number.isFinite)||!Array.from(r.biases).every(Number.isFinite))throw TypeError(`neural weights and biases must be finite and match layer dimensions`)}let n=e.layers.map(e=>({...e,weights:Float64Array.from(e.weights),biases:Float64Array.from(e.biases),buffer:new Float64Array(e.outputSize)})),r=(e,t)=>{if(e.length!==n[0].inputSize)throw TypeError(`neural input must be finite and match the model`);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw TypeError(`neural input must be finite`);let r=n[n.length-1];if(t&&t.length!==r.outputSize)throw RangeError(`neural output buffer has the wrong size`);let i=e;for(let e=0;e<n.length;e++){let t=n[e];for(let r=0;r<t.outputSize;r++){let a=t.biases[r];for(let e=0;e<t.inputSize;e++)a+=t.weights[r*t.inputSize+e]*i[e];if(!Number.isFinite(a))throw RangeError(`neural activation overflow`);t.buffer[r]=e===n.length-1?a:Math.max(0,a)}i=t.buffer}let a=t??new Float64Array(r.outputSize);return a.set(r.buffer),a},i=new Float64Array(n[n.length-1].outputSize);return{predict:r,select(e,t){let n=e.mask;if(n&&(n.length!==i.length||!Array.from(n).every(e=>typeof e==`boolean`)))throw TypeError(`neural action mask must contain one boolean per output`);r(e.input,i);let a=null;for(let e=0;e<i.length;e++)(!n||n[e])&&(a===null||i[e]>i[a])&&(a=e);if(a===null||!t)return a;let o=t();if(!Number.isFinite(o)||o<0||o>=1)throw RangeError(`sampling random must return a value in [0, 1)`);let s=0;for(let e=0;e<i.length;e++)(!n||n[e])&&(s+=Math.exp(i[e]-i[a]));let c=o*s;for(let e=0;e<i.length;e++)if((!n||n[e])&&(c-=Math.exp(i[e]-i[a]),c<0))return e;return a}}}function MX(e,t,n){let r=Function(`return (${e});`)()(t);return n.map(e=>r.predict(e))}var NX=class{constructor(e){this.evaluator=jX(e),this.model=structuredClone(e)}predict(e,t){return this.evaluator.predict(e,t)}selectAction(e,t){return this.evaluator.select(e,t)}exportModel(){return structuredClone(this.model)}behavior(e,t,n,r=!1){if(t.length!==this.model.layers[this.model.layers.length-1].outputSize)throw RangeError(`neural action mapping must match output size`);let i=structuredClone(t);return{id:e,decide:e=>{e.checkpoint();let t=this.selectAction(n(e.perception),r?e.random:void 0);return t===null?null:structuredClone(i[t])}}}predictBatchAsync(e,t={}){let n=this.model.layers[0].inputSize,r=this.model.layers[this.model.layers.length-1].outputSize;if(e.length>65536||e.length*Math.max(n,r)>1e6)return Promise.reject(RangeError(`neural batch exceeds its observation or value limit`));for(let t of e)if(!t||t.length!==n)return Promise.reject(TypeError(`neural batch inputs must match the model`));return mG(MX,[jX.toString(),this.model,e],t)}};_e();var PX=class{get truncated(){return!this.terminated&&this.steps>=this.maxSteps}constructor(e,t,n=j){if(this.steps=0,this.terminated=!1,this.ready=!1,this.agentCount=0,this.rules=e,this.Random=n,this.random=new this.Random(0),!Number.isInteger(t.maxSteps)||t.maxSteps<1||t.maxSteps>1e6)throw RangeError(`training maxSteps must be in 1..1000000`);if(typeof e.observationVersion!=`string`||!e.observationVersion.length)throw TypeError(`training requires an observation version`);this.maxSteps=t.maxSteps,this.observationVersion=e.observationVersion}reset(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw RangeError(`training seed must be uint32`);this.random=new this.Random(e),this.state=this.rules.initial(this.random),this.steps=0,this.terminated=this.rules.finished?.(this.state)??!1,this.ready=!0;let t=this.observations();return this.agentCount=t.length,{observations:t,rewards:t.map(()=>0),terminated:this.terminated,truncated:!1}}step(e){if(!this.ready||this.terminated||this.truncated)throw Error(`training episode needs reset before step`);let t=this.observations();if(e.length!==this.agentCount)throw RangeError(`training action count must match the agent roster`);for(let n=0;n<e.length;n++){let r=e[n],i=t[n].mask;if(r===null?!i||i.some(Boolean):!Number.isInteger(r)||r<0||i&&(r>=i.length||!i[r]))throw RangeError(`training action is not legal`)}let n=structuredClone(this.state),r=this.rules.command(this.state,e),i=this.rules.rule(this.state,r,this.random),a=Array.from(this.rules.rewards(n,r,i));if(a.length!==this.agentCount||!a.every(Number.isFinite))throw TypeError(`training rewards must be finite and match the agent roster`);this.state=i.state,this.steps++,this.terminated=i.status===`finished`;let o=this.observations();if(o.length!==this.agentCount)throw RangeError(`training agent roster changed during an episode`);return{observations:o,rewards:a,terminated:this.terminated,truncated:this.truncated}}snapshot(){if(!this.ready)throw Error(`training environment needs reset before snapshot`);return structuredClone({version:1,observationVersion:this.observationVersion,state:this.state,seed:this.random.seed,random:this.random.getState().map(e=>e>>>0),steps:this.steps,maxSteps:this.maxSteps,terminated:this.terminated,truncated:this.truncated})}restore(e){if(e.version!==1||e.observationVersion!==this.observationVersion||e.maxSteps!==this.maxSteps)throw TypeError(`training snapshot version, schema or step limit does not match`);if(!Number.isInteger(e.steps)||e.steps<0||e.steps>this.maxSteps||!Number.isInteger(e.seed)||e.seed<0||e.seed>4294967295||!Array.isArray(e.random)||e.random.length!==4||!e.random.every(e=>Number.isInteger(e)&&e>=0&&e<=4294967295)||!e.random.some(e=>e!==0)||typeof e.terminated!=`boolean`||typeof e.truncated!=`boolean`||e.terminated&&e.truncated||e.truncated!==(!e.terminated&&e.steps===this.maxSteps))throw TypeError(`invalid training snapshot`);this.state=structuredClone(e.state),this.random=new this.Random(e.seed),this.random.setState(e.random),this.steps=e.steps,this.terminated=e.terminated,this.ready=!0;let t=this.observations();return this.agentCount=t.length,{observations:t,rewards:t.map(()=>0),terminated:this.terminated,truncated:this.truncated}}observations(){let e=structuredClone(Array.from(this.rules.observe(this.state)));if(!e.length||e.length>4096)throw RangeError(`training requires 1..4096 agents`);for(let t of e)if(!t.input.length||t.input.length>4096||!Array.from(t.input).every(Number.isFinite)||t.mask&&(!t.mask.length||t.mask.length>4096||!Array.from(t.mask).every(e=>typeof e==`boolean`)))throw TypeError(`invalid training observation`);return e}};function FX(e,t,n){return IX(n),LX(e,t,n,{Generator:j,createNeuralEvaluator:jX})}function IX(e){let t=e.trajectoryLimit??0;if(!e.seeds.length||e.seeds.length>1e4||!Array.from(e.seeds).every(e=>Number.isInteger(e)&&e>=0&&e<=4294967295)||!Number.isInteger(t)||t<0||t*e.seeds.length>1e4)throw RangeError(`rollouts require 1..10000 uint32 seeds and at most 10000 stored transitions`)}function LX(e,t,n,r){if(t.observationVersion!==e.observationVersion)throw TypeError(`model observation schema does not match environment`);let i=n.trajectoryLimit??0,a=r.createNeuralEvaluator(t);return Array.from(n.seeds,t=>{if(n.signal?.aborted)throw n.signal.reason;let o=new r.Generator((t^2654435769)>>>0),s=e.reset(t),c=s.rewards.map(()=>0),l=[],u=0;for(;!s.terminated&&!s.truncated;){if(n.signal?.aborted)throw n.signal.reason;let t=s.observations.map(e=>a.select(e,n.sample?()=>o.float():void 0)),r=e.step(t);for(let e=0;e<c.length;e++)if(c[e]+=r.rewards[e],!Number.isFinite(c[e]))throw RangeError(`training cumulative reward overflow`);l.length<i&&l.push({before:s,actions:t,after:r}),s=r,u++}return{seed:t,steps:u,rewards:c,terminated:s.terminated,truncated:s.truncated,trajectory:l}})}function RX(e,t,n,r){let i=Function(`return (${e[0]});`)(),a=Function(`return (${e[1]});`)(),o=Function(`return (${e[2]});`)(),s=class extends o{constructor(e,t){super(e,t,i)}};return Function(`return (${e[3]});`)()(Function(`return (${e[4]});`)()({TrainingEnvironment:s},t),n,r,{Generator:i,createNeuralEvaluator:a})}async function zX(e,t,n,r){let i=r.jobs??4;if(!Number.isInteger(i)||i<1||i>64)throw RangeError(`rollout jobs must be in 1..64`);if(r.signal?.aborted)throw r.signal.reason;let a=r.trajectoryLimit??0;IX(r),jX(n);let o=new AbortController,s=()=>o.abort(r.signal?.reason);r.signal?.addEventListener(`abort`,s,{once:!0});let c=[j.toString(),jX.toString(),PX.toString(),LX.toString(),e.toString()],l=Math.min(i,r.seeds.length);try{return(await Promise.all(Array.from({length:l},(e,i)=>{let s=Math.floor(i*r.seeds.length/l),u=Math.floor((i+1)*r.seeds.length/l),d=r.seeds.slice(s,u);return mG(RX,[c,t,n,{seeds:d,sample:r.sample,trajectoryLimit:a}],{signal:o.signal,timeout:r.timeout})}))).flat()}finally{o.abort(),r.signal?.removeEventListener(`abort`,s)}}function BX(e,t){let n=[...t.actions];if(!n.length||n.some(e=>typeof e!=`string`))throw TypeError(`imitation needs the recorded action names in policy order`);let r=pn(t.events),i=e.reset(t.seed);if(i.observations.length!==1)throw Error(`imitation trains the recorded player alone: the environment must expose one agent`);let a=[],o=i,s=0;for(let t of r){if(o.terminated||o.truncated)break;let r=n.indexOf(t.action);if(r<0)throw Error(`a recorded action ${JSON.stringify(t.action)} is not in the action list`);a.push({observation:o.observations[0],action:r,frame:t.frame}),o=e.step([r]),s++}return{samples:a,steps:s,terminated:o.terminated,truncated:o.truncated}}function VX(e,t,n){let r=e.reset(n.seed),i=r.rewards.map(()=>0),a=[],o=0;for(;!r.terminated&&!r.truncated;){let n=t(r.observations);if(!Array.isArray(n)||n.length!==r.observations.length)throw RangeError(`the seeded-run chooser must return one action per agent`);a.push([...n]);let s=e.step(n);for(let e=0;e<i.length;e++)if(i[e]+=s.rewards[e],!Number.isFinite(i[e]))throw RangeError(`seeded-run cumulative reward overflow`);r=s,o++}return{seed:n.seed,steps:o,actions:a,rewards:i,terminated:r.terminated,truncated:r.truncated}}function HX(e){let t=e.state,n=e.status??`ready`,r=[],i=0;for(let a of e.commands){if(n===`finished`)break;let o=e.step(t,a,e.random);t=o.state,n=o.status;for(let e of o.events)r.push(e);i++}return{state:t,events:r,status:n,processedCommands:i}}var UX=class e{constructor(e){if(this._reminders=[],this._results={},this.levels=new Map(e.levels.map(e=>[e.id,e])),this.levels.size!==e.levels.length)throw Error(`campaign level ids must be unique`);if(!this.levels.has(e.start))throw Error(`unknown campaign start level: ${e.start}`);this._currentLevel=e.start,this._state=Wt(e.state,`campaign state`)}get currentLevel(){return this._currentLevel}get state(){return structuredClone(this._state)}get reminders(){return[...this._reminders]}get results(){return structuredClone(this._results)}playCurrent(){if(!this._currentLevel)throw Error(`campaign has no current level`);let e=this.levels.get(this._currentLevel);return this.completeCurrent(e.run(this.state,{levelId:e.id}))}completeCurrent(e){if(!this._currentLevel)throw Error(`campaign has no current level`);let t=this._currentLevel,n=Wt(e.state,`level result state`),r=e.result===void 0?void 0:Wt(e.result,`level result`);if(this._state=n,r!==void 0&&(this._results[t]=r),this._reminders=[...e.reminders??[]],e.outcome!==`completed`)this._currentLevel=null;else if(e.next===void 0)throw Error(`campaign level ${t} did not choose a next level`);else{if(e.next!==null&&!this.levels.has(e.next))throw Error(`unknown campaign transition: ${t} -> ${e.next}`);this._currentLevel=e.next}return{...e,state:this.state}}snapshot(){return{currentLevel:this._currentLevel,state:this.state,reminders:this.reminders,results:this.results}}static restore(t,n){let r=t.currentLevel??n.levels[0]?.id;if(!r)throw Error(`campaign restore requires at least one level`);let i=new e({levels:n.levels,start:r,state:t.state});return i._currentLevel=t.currentLevel,i._reminders=[...t.reminders],i._results=Wt(t.results,`snapshot.results`),i}};_e();function WX(e){let t=new j(e.seed);return{...HX({state:Wt(e.initialState,`initialState`),commands:e.commands,status:e.status,random:t,step:e.step}),seed:e.seed,random:t.getState()}}_e();function GX(e,t,n){let r=KX.restore({...e,journal:[]},n),i=e=>({valid:!1,checked:e.index,state:r.state,journal:r.journal.toJSON(),mismatch:e});for(let e=0;e<t.length;e++){let n=t[e];if(n.sequence!==e)return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:[],reason:`sequence`});let a;try{a=r.dispatch(n.action)}catch(t){return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:[],reason:`execution`,error:t instanceof Error?t.message:String(t)})}if(Rr(a.events)!==Rr(n.events))return i({index:e,action:n.action,expectedEvents:n.events,actualEvents:a.events,reason:`events`})}return n.expectedFinalState!==void 0&&Rr(r.state)!==Rr(n.expectedFinalState)?i({index:t.length,action:t.at(-1)?.action,expectedEvents:[],actualEvents:[],reason:`final-state`}):{valid:!0,checked:t.length,state:r.state,journal:r.journal.toJSON()}}var KX=class e{constructor(e){this._state=e.state,this._scheduler=e.scheduler,this.random=e.random,this.rule=e.rule,this.actorId=e.actorId,this.recordJournal=e.journal!==null,this.journal=e.journal??new wn,this.actorOf=e.history?.actorOf??null,this.history=e.history?new Or(e.history):null,this.history&&this.history.push(this.historySnapshot())}get scheduler(){return this._scheduler}get state(){return this._state}dispatch(e){let t=this.random.getState(),n=this.rule(this._state,e,{random:this.random,scheduler:this._scheduler}),r;try{r=this.history?Wt(n.state,`state`):null,this.recordJournal&&this.journal.append(e,n.events)}catch(e){throw this.random.setState(t),e}return this._state=n.state,n.cost!=null&&this._scheduler.spend(n.cost),this.history&&this.history.push(this.historySnapshot(r)),n}get canUndo(){return this.history?.canUndo??!1}get canRedo(){return this.history?.canRedo??!1}undo(){if(!this.history||!this.actorOf)return null;let e=this.history.undo();return e?(this.restoreCheckpoint(e),this.snapshot()):null}redo(){if(!this.history||!this.actorOf)return null;let e=this.history.redo();return e?(this.restoreCheckpoint(e),this.snapshot()):null}snapshot(e=1){return{version:e,state:this._state,scheduler:this.scheduler.toJSON(this.actorId),random:this.random.getState(),journal:this.journal.toJSON()}}static restore(t,n){let r=n.random??new j;r.setState(t.random);let i=tH.restore(t.scheduler,n.actorOf);return new e({state:t.state,scheduler:i,random:r,journal:wn.fromJSON(t.journal??[]),rule:n.rule,actorId:n.actorId})}historySnapshot(e=Wt(this._state,`state`)){return{...this.snapshot(),state:e}}restoreCheckpoint(e){if(!this.actorOf)throw Error(`simulation history needs actorOf to restore a checkpoint`);this._state=structuredClone(e.state),this._scheduler=tH.restore(e.scheduler,this.actorOf),this.random.setState(e.random),this.journal.replace(e.journal??[])}},qX=class e{constructor(e){this.followUps=[],this.runtime=e.runtime,this.queue=new Pr({play:e.play}),this.followUpOf=e.followUp}get locked(){return this.queue.isBusy}submit(e){return this.locked?null:this.commit(e)}update(e){this.queue.update(e),this.drainFollowUps()}cancel(){this.queue.clear(),this.followUps=[]}snapshot(e=1){return this.runtime.snapshot(e)}static restore(t,n){let r=KX.restore(t,{rule:n.rule,actorOf:n.actorOf,actorId:n.actorId});return new e({runtime:r,play:n.play,followUp:n.followUp})}commit(e){let t=this.runtime.dispatch(e);return this.queue.enqueue(t.events),this.followUpOf&&this.followUps.push(...this.followUpOf(t)),this.drainFollowUps(),t}drainFollowUps(){for(;!this.queue.isBusy&&this.followUps.length>0;){let e=this.followUps.shift();this.commit(e)}}},JX=class{constructor(e){this.saves=new zt(e)}save(e,t,n){this.saves.save(e,{campaign:t.campaign.snapshot(),world:t.world,simulation:t.simulation?t.simulation.snapshot():null},n)}load(e){return this.saves.load(e)?.state??null}list(){return this.saves.list()}delete(e){this.saves.delete(e)}},YX=l({Campaign:()=>UX,CampaignSave:()=>JX,EventPresentation:()=>qX,Scheduler:()=>tH,SimulationRuntime:()=>KX,TrainingEnvironment:()=>PX,advanceToInput:()=>AX,imitationFromReplay:()=>BX,runHeadlessScenario:()=>WX,runRollouts:()=>FX,runRolloutsAsync:()=>zX,runScenario:()=>HX,runSeededEpisode:()=>VX,validateSimulationReplay:()=>GX}),XX=d(c(((e,t,n)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):n.JSON5=r()})(n,(function(){"use strict";function e(e,t){return t={exports:{}},e(t,t.exports),t.exports}var t=e(function(e){var t=e.exports=typeof window<`u`&&window.Math==Math?window:typeof self<`u`&&self.Math==Math?self:Function(`return this`)();typeof __g==`number`&&(__g=t)}),n=e(function(e){var t=e.exports={version:`2.6.5`};typeof __e==`number`&&(__e=t)});n.version;var r=function(e){return typeof e==`object`?e!==null:typeof e==`function`},i=function(e){if(!r(e))throw TypeError(e+` is not an object!`);return e},a=function(e){try{return!!e()}catch{return!0}},o=!a(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}),s=t.document,c=r(s)&&r(s.createElement),l=function(e){return c?s.createElement(e):{}},u=!o&&!a(function(){return Object.defineProperty(l(`div`),"a",{get:function(){return 7}}).a!=7}),d=function(e,t){if(!r(e))return e;var n,i;if(t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e))||typeof(n=e.valueOf)==`function`&&!r(i=n.call(e))||!t&&typeof(n=e.toString)==`function`&&!r(i=n.call(e)))return i;throw TypeError(`Can't convert object to primitive value`)},f=Object.defineProperty,p={f:o?Object.defineProperty:function(e,t,n){if(i(e),t=d(t,!0),i(n),u)try{return f(e,t,n)}catch{}if(`get`in n||`set`in n)throw TypeError(`Accessors not supported!`);return`value`in n&&(e[t]=n.value),e}},m=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},h=o?function(e,t,n){return p.f(e,t,m(1,n))}:function(e,t,n){return e[t]=n,e},g={}.hasOwnProperty,_=function(e,t){return g.call(e,t)},v=0,y=Math.random(),b=function(e){return`Symbol(${e===void 0?``:e})_${(++v+y).toString(36)}`},x=e(function(e){var r=`__core-js_shared__`,i=t[r]||(t[r]={});(e.exports=function(e,t){return i[e]||(i[e]=t===void 0?{}:t)})(`versions`,[]).push({version:n.version,mode:`global`,copyright:`© 2019 Denis Pushkarev (zloirock.ru)`})})(`native-function-to-string`,Function.toString),S=e(function(e){var r=b(`src`),i=`toString`,a=(``+x).split(i);n.inspectSource=function(e){return x.call(e)},(e.exports=function(e,n,i,o){var s=typeof i==`function`;s&&(_(i,`name`)||h(i,`name`,n)),e[n]!==i&&(s&&(_(i,r)||h(i,r,e[n]?``+e[n]:a.join(String(n)))),e===t?e[n]=i:o?e[n]?e[n]=i:h(e,n,i):(delete e[n],h(e,n,i)))})(Function.prototype,i,function(){return typeof this==`function`&&this[r]||x.call(this)})}),C=function(e){if(typeof e!=`function`)throw TypeError(e+` is not a function!`);return e},ee=function(e,t,n){if(C(e),t===void 0)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}},w=`prototype`,T=function(e,r,i){var a=e&T.F,o=e&T.G,s=e&T.S,c=e&T.P,l=e&T.B,u=o?t:s?t[r]||(t[r]={}):(t[r]||{})[w],d=o?n:n[r]||(n[r]={}),f=d[w]||(d[w]={}),p,m,g,_;for(p in o&&(i=r),i)m=!a&&u&&u[p]!==void 0,g=(m?u:i)[p],_=l&&m?ee(g,t):c&&typeof g==`function`?ee(Function.call,g):g,u&&S(u,p,g,e&T.U),d[p]!=g&&h(d,p,_),c&&f[p]!=g&&(f[p]=g)};t.core=n,T.F=1,T.G=2,T.S=4,T.P=8,T.B=16,T.W=32,T.U=64,T.R=128;var E=T,te=Math.ceil,D=Math.floor,O=function(e){return isNaN(e=+e)?0:(e>0?D:te)(e)},ne=function(e){if(e==null)throw TypeError(`Can't call method on `+e);return e},k=function(e){return function(e,t){var n=String(ne(e)),r=O(t),i=n.length,a,o;return r<0||r>=i?void 0:(a=n.charCodeAt(r),a<55296||a>56319||r+1===i||(o=n.charCodeAt(r+1))<56320||o>57343?a:(a-55296<<10)+(o-56320)+65536)}}(!1);E(E.P,`String`,{codePointAt:function(e){return k(this,e)}}),n.String.codePointAt;var A=Math.max,re=Math.min,ie=function(e,t){return e=O(e),e<0?A(e+t,0):re(e,t)},ae=String.fromCharCode,oe=String.fromCodePoint;E(E.S+E.F*(!!oe&&oe.length!=1),`String`,{fromCodePoint:function(e){for(var t=arguments,n=[],r=arguments.length,i=0,a;r>i;){if(a=+t[i++],ie(a,1114111)!==a)throw RangeError(a+` is not a valid code point`);n.push(a<65536?ae(a):ae(((a-=65536)>>10)+55296,a%1024+56320))}return n.join(``)}}),n.String.fromCodePoint;var se={Space_Separator:/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,ID_Start:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,ID_Continue:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},j={isSpaceSeparator:function(e){return typeof e==`string`&&se.Space_Separator.test(e)},isIdStartChar:function(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||se.ID_Start.test(e))},isIdContinueChar:function(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===``||e===``||se.ID_Continue.test(e))},isDigit:function(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit:function(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}},ce,le,ue,de,fe,pe,me,he,ge,_e=function(e,t){ce=String(e),le=`start`,ue=[],de=0,fe=1,pe=0,me=void 0,he=void 0,ge=void 0;do me=xe(),ke[le]();while(me.type!==`eof`);return typeof t==`function`?ve({"":ge},``,t):ge};function ve(e,t,n){var r=e[t];if(typeof r==`object`&&r){if(Array.isArray(r))for(var i=0;i<r.length;i++){var a=String(i),o=ve(r,a,n);o===void 0?delete r[a]:Object.defineProperty(r,a,{value:o,writable:!0,enumerable:!0,configurable:!0})}else for(var s in r){var c=ve(r,s,n);c===void 0?delete r[s]:Object.defineProperty(r,s,{value:c,writable:!0,enumerable:!0,configurable:!0})}}return n.call(e,t,r)}var M,N,ye,be,P;function xe(){for(M=`default`,N=``,ye=!1,be=1;;){P=Se();var e=Ce[M]();if(e)return e}}function Se(){if(ce[de])return String.fromCodePoint(ce.codePointAt(de))}function F(){var e=Se();return e===`
|
|
1387
|
-
`?(fe++,pe=0):e?pe+=e.length:pe++,e&&(de+=e.length),e}var Ce={default:function(){switch(P){case` `:case`\v`:case`\f`:case` `:case`\xA0`:case``:case`
|
|
1388
|
-
`:case`\r`:case`\u2028`:case`\u2029`:F();return;case`/`:F(),M=`comment`;return;case void 0:return F(),we(`eof`)}if(j.isSpaceSeparator(P))F();else return Ce[le]()},comment:function(){switch(P){case`*`:F(),M=`multiLineComment`;return;case`/`:F(),M=`singleLineComment`;return}throw Me(F())},multiLineComment:function(){switch(P){case`*`:F(),M=`multiLineCommentAsterisk`;return;case void 0:throw Me(F())}F()},multiLineCommentAsterisk:function(){switch(P){case`*`:F();return;case`/`:F(),M=`default`;return;case void 0:throw Me(F())}F(),M=`multiLineComment`},singleLineComment:function(){switch(P){case`
|
|
1389
|
-
`:case`\r`:case`\u2028`:case`\u2029`:F(),M=`default`;return;case void 0:return F(),we(`eof`)}F()},value:function(){switch(P){case`{`:case`[`:return we(`punctuator`,F());case`n`:return F(),Te(`ull`),we(`null`,null);case`t`:return F(),Te(`rue`),we(`boolean`,!0);case`f`:return F(),Te(`alse`),we(`boolean`,!1);case`-`:case`+`:F()===`-`&&(be=-1),M=`sign`;return;case`.`:N=F(),M=`decimalPointLeading`;return;case`0`:N=F(),M=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:N=F(),M=`decimalInteger`;return;case`I`:return F(),Te(`nfinity`),we(`numeric`,1/0);case`N`:return F(),Te(`aN`),we(`numeric`,NaN);case`"`:case`'`:ye=F()===`"`,N=``,M=`string`;return}throw Me(F())},identifierNameStartEscape:function(){if(P!==`u`)throw Me(F());F();var e=Oe();switch(e){case`$`:case`_`:break;default:if(!j.isIdStartChar(e))throw Pe()}N+=e,M=`identifierName`},identifierName:function(){switch(P){case`$`:case`_`:case``:case``:N+=F();return;case`\\`:F(),M=`identifierNameEscape`;return}if(j.isIdContinueChar(P))N+=F();else return we(`identifier`,N)},identifierNameEscape:function(){if(P!==`u`)throw Me(F());F();var e=Oe();switch(e){case`$`:case`_`:case``:case``:break;default:if(!j.isIdContinueChar(e))throw Pe()}N+=e,M=`identifierName`},sign:function(){switch(P){case`.`:N=F(),M=`decimalPointLeading`;return;case`0`:N=F(),M=`zero`;return;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:N=F(),M=`decimalInteger`;return;case`I`:return F(),Te(`nfinity`),we(`numeric`,be*(1/0));case`N`:return F(),Te(`aN`),we(`numeric`,NaN)}throw Me(F())},zero:function(){switch(P){case`.`:N+=F(),M=`decimalPoint`;return;case`e`:case`E`:N+=F(),M=`decimalExponent`;return;case`x`:case`X`:N+=F(),M=`hexadecimal`;return}return we(`numeric`,be*0)},decimalInteger:function(){switch(P){case`.`:N+=F(),M=`decimalPoint`;return;case`e`:case`E`:N+=F(),M=`decimalExponent`;return}if(j.isDigit(P))N+=F();else return we(`numeric`,be*Number(N))},decimalPointLeading:function(){if(j.isDigit(P))N+=F(),M=`decimalFraction`;else throw Me(F())},decimalPoint:function(){switch(P){case`e`:case`E`:N+=F(),M=`decimalExponent`;return}if(j.isDigit(P))N+=F(),M=`decimalFraction`;else return we(`numeric`,be*Number(N))},decimalFraction:function(){switch(P){case`e`:case`E`:N+=F(),M=`decimalExponent`;return}if(j.isDigit(P))N+=F();else return we(`numeric`,be*Number(N))},decimalExponent:function(){switch(P){case`+`:case`-`:N+=F(),M=`decimalExponentSign`;return}if(j.isDigit(P))N+=F(),M=`decimalExponentInteger`;else throw Me(F())},decimalExponentSign:function(){if(j.isDigit(P))N+=F(),M=`decimalExponentInteger`;else throw Me(F())},decimalExponentInteger:function(){if(j.isDigit(P))N+=F();else return we(`numeric`,be*Number(N))},hexadecimal:function(){if(j.isHexDigit(P))N+=F(),M=`hexadecimalInteger`;else throw Me(F())},hexadecimalInteger:function(){if(j.isHexDigit(P))N+=F();else return we(`numeric`,be*Number(N))},string:function(){switch(P){case`\\`:F(),N+=Ee();return;case`"`:if(ye)return F(),we(`string`,N);N+=F();return;case`'`:if(!ye)return F(),we(`string`,N);N+=F();return;case`
|
|
1390
|
-
`:case`\r`:throw Me(F());case`\u2028`:case`\u2029`:Fe(P);break;case void 0:throw Me(F())}N+=F()},start:function(){switch(P){case`{`:case`[`:return we(`punctuator`,F())}M=`value`},beforePropertyName:function(){switch(P){case`$`:case`_`:N=F(),M=`identifierName`;return;case`\\`:F(),M=`identifierNameStartEscape`;return;case`}`:return we(`punctuator`,F());case`"`:case`'`:ye=F()===`"`,M=`string`;return}if(j.isIdStartChar(P))N+=F(),M=`identifierName`;else throw Me(F())},afterPropertyName:function(){if(P===`:`)return we(`punctuator`,F());throw Me(F())},beforePropertyValue:function(){M=`value`},afterPropertyValue:function(){switch(P){case`,`:case`}`:return we(`punctuator`,F())}throw Me(F())},beforeArrayValue:function(){if(P===`]`)return we(`punctuator`,F());M=`value`},afterArrayValue:function(){switch(P){case`,`:case`]`:return we(`punctuator`,F())}throw Me(F())},end:function(){throw Me(F())}};function we(e,t){return{type:e,value:t,line:fe,column:pe}}function Te(e){for(var t=0,n=e;t<n.length;t+=1){var r=n[t];if(Se()!==r)throw Me(F());F()}}function Ee(){switch(Se()){case`b`:return F(),`\b`;case`f`:return F(),`\f`;case`n`:return F(),`
|
|
1391
|
-
`;case`r`:return F(),`\r`;case`t`:return F(),` `;case`v`:return F(),`\v`;case`0`:if(F(),j.isDigit(Se()))throw Me(F());return`\0`;case`x`:return F(),De();case`u`:return F(),Oe();case`
|
|
1392
|
-
`:case`\u2028`:case`\u2029`:return F(),``;case`\r`:return F(),Se()===`
|
|
1393
|
-
`&&F(),``;case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:throw Me(F());case void 0:throw Me(F())}return F()}function De(){var e=``,t=Se();if(!j.isHexDigit(t)||(e+=F(),t=Se(),!j.isHexDigit(t)))throw Me(F());return e+=F(),String.fromCodePoint(parseInt(e,16))}function Oe(){for(var e=``,t=4;t-->0;){var n=Se();if(!j.isHexDigit(n))throw Me(F());e+=F()}return String.fromCodePoint(parseInt(e,16))}var ke={start:function(){if(me.type===`eof`)throw Ne();Ae()},beforePropertyName:function(){switch(me.type){case`identifier`:case`string`:he=me.value,le=`afterPropertyName`;return;case`punctuator`:je();return;case`eof`:throw Ne()}},afterPropertyName:function(){if(me.type===`eof`)throw Ne();le=`beforePropertyValue`},beforePropertyValue:function(){if(me.type===`eof`)throw Ne();Ae()},beforeArrayValue:function(){if(me.type===`eof`)throw Ne();me.type===`punctuator`&&me.value===`]`?je():Ae()},afterPropertyValue:function(){if(me.type===`eof`)throw Ne();switch(me.value){case`,`:le=`beforePropertyName`;return;case`}`:je()}},afterArrayValue:function(){if(me.type===`eof`)throw Ne();switch(me.value){case`,`:le=`beforeArrayValue`;return;case`]`:je()}},end:function(){}};function Ae(){var e;switch(me.type){case`punctuator`:switch(me.value){case`{`:e={};break;case`[`:e=[]}break;case`null`:case`boolean`:case`numeric`:case`string`:e=me.value}if(ge===void 0)ge=e;else{var t=ue[ue.length-1];Array.isArray(t)?t.push(e):Object.defineProperty(t,he,{value:e,writable:!0,enumerable:!0,configurable:!0})}if(typeof e==`object`&&e)ue.push(e),le=Array.isArray(e)?`beforeArrayValue`:`beforePropertyName`;else{var n=ue[ue.length-1];le=n==null?`end`:Array.isArray(n)?`afterArrayValue`:`afterPropertyValue`}}function je(){ue.pop();var e=ue[ue.length-1];le=e==null?`end`:Array.isArray(e)?`afterArrayValue`:`afterPropertyValue`}function Me(e){return Le(e===void 0?`JSON5: invalid end of input at `+fe+`:`+pe:`JSON5: invalid character '`+Ie(e)+`' at `+fe+`:`+pe)}function Ne(){return Le(`JSON5: invalid end of input at `+fe+`:`+pe)}function Pe(){return pe-=5,Le(`JSON5: invalid identifier character at `+fe+`:`+pe)}function Fe(e){console.warn(`JSON5: '`+Ie(e)+`' in strings is not valid ECMAScript; consider escaping`)}function Ie(e){var t={"'":`\\'`,'"':`\\"`,"\\":`\\\\`,"\b":`\\b`,"\f":`\\f`,"\n":`\\n`,"\r":`\\r`," ":`\\t`,"\v":`\\v`,"\0":`\\0`,"\u2028":`\\u2028`,"\u2029":`\\u2029`};if(t[e])return t[e];if(e<` `){var n=e.charCodeAt(0).toString(16);return`\\x`+(`00`+n).substring(n.length)}return e}function Le(e){var t=SyntaxError(e);return t.lineNumber=fe,t.columnNumber=pe,t}return{parse:_e,stringify:function(e,t,n){var r=[],i=``,a,o,s=``,c;if(typeof t==`object`&&t&&!Array.isArray(t)&&(n=t.space,c=t.quote,t=t.replacer),typeof t==`function`)o=t;else if(Array.isArray(t)){a=[];for(var l=0,u=t;l<u.length;l+=1){var d=u[l],f=void 0;typeof d==`string`?f=d:(typeof d==`number`||d instanceof String||d instanceof Number)&&(f=String(d)),f!==void 0&&a.indexOf(f)<0&&a.push(f)}}return n instanceof Number?n=Number(n):n instanceof String&&(n=String(n)),typeof n==`number`?n>0&&(n=Math.min(10,Math.floor(n)),s=` `.substr(0,n)):typeof n==`string`&&(s=n.substr(0,10)),p(``,{"":e});function p(e,t){var n=t[e];switch(n!=null&&(typeof n.toJSON5==`function`?n=n.toJSON5(e):typeof n.toJSON==`function`&&(n=n.toJSON(e))),o&&(n=o.call(t,e,n)),n instanceof Number?n=Number(n):n instanceof String?n=String(n):n instanceof Boolean&&(n=n.valueOf()),n){case null:return`null`;case!0:return`true`;case!1:return`false`}if(typeof n==`string`)return m(n,!1);if(typeof n==`number`)return String(n);if(typeof n==`object`)return Array.isArray(n)?_(n):h(n)}function m(e){for(var t={"'":.1,'"':.2},n={"'":`\\'`,'"':`\\"`,"\\":`\\\\`,"\b":`\\b`,"\f":`\\f`,"\n":`\\n`,"\r":`\\r`," ":`\\t`,"\v":`\\v`,"\0":`\\0`,"\u2028":`\\u2028`,"\u2029":`\\u2029`},r=``,i=0;i<e.length;i++){var a=e[i];switch(a){case`'`:case`"`:t[a]++,r+=a;continue;case`\0`:if(j.isDigit(e[i+1])){r+=`\\x00`;continue}}if(n[a])r+=n[a];else if(a<` `){var o=a.charCodeAt(0).toString(16);r+=`\\x`+(`00`+o).substring(o.length)}else r+=a}var s=c||Object.keys(t).reduce(function(e,n){return t[e]<t[n]?e:n});return r=r.replace(new RegExp(s,`g`),n[s]),s+r+s}function h(e){if(r.indexOf(e)>=0)throw TypeError(`Converting circular structure to JSON5`);r.push(e);var t=i;i+=s;for(var n=a||Object.keys(e),o=[],c=0,l=n;c<l.length;c+=1){var u=l[c],d=p(u,e);if(d!==void 0){var f=g(u)+`:`;s!==``&&(f+=` `),f+=d,o.push(f)}}var m;if(o.length===0)m=`{}`;else{var h;if(s===``)h=o.join(`,`),m=`{`+h+`}`;else{var _=`,
|
|
1394
|
-
`+i;h=o.join(_),m=`{
|
|
1395
|
-
`+i+h+`,
|
|
1396
|
-
`+t+`}`}}return r.pop(),i=t,m}function g(e){if(e.length===0)return m(e,!0);var t=String.fromCodePoint(e.codePointAt(0));if(!j.isIdStartChar(t))return m(e,!0);for(var n=t.length;n<e.length;n++)if(!j.isIdContinueChar(String.fromCodePoint(e.codePointAt(n))))return m(e,!0);return e}function _(e){if(r.indexOf(e)>=0)throw TypeError(`Converting circular structure to JSON5`);r.push(e);var t=i;i+=s;for(var n=[],a=0;a<e.length;a++){var o=p(String(a),e);n.push(o===void 0?`null`:o)}var c;if(n.length===0)c=`[]`;else if(s===``)c=`[`+n.join(`,`)+`]`;else{var l=`,
|
|
1397
|
-
`+i,u=n.join(l);c=`[
|
|
1398
|
-
`+i+u+`,
|
|
1399
|
-
`+t+`]`}return r.pop(),i=t,c}}}}))}))(),1),ZX=class extends Error{constructor(e){super(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`),this.name=`MwlSyntaxError`,this.diagnostic=e}},QX=new Set([`define`,`enddef`,`arg`,`ifdef`,`ifndef`,`else`,`endif`,`include`]);function $X(e,t={}){let n=new Map,r=new Set(t.defines??[]),i=e.split(/\r?\n/),a=[],o=[!0],s=null;for(let e=0;e<i.length;e++){let c=i[e],l=/^\s*#([A-Za-z_][\w-]*)(?:\s+(.*))?$/.exec(c);if(l&&QX.has(l[1])){let i=l[1],u=l[2]?.trim()??``;if(i===`define`){if(!o.at(-1)||s)continue;let n=yZ(u);if(n.length===0)throw xZ(`MWL_DEFINE`,`macro name is required`,t.file,e,c);s={name:n[0],parameters:n.slice(1),body:[]},r.add(n[0]);continue}if(i===`arg`){s&&u&&s.parameters.push(u.split(/\s+/)[0]);continue}if(i===`enddef`){if(!s)throw xZ(`MWL_ENDDEF`,`unexpected #enddef`,t.file,e,c);n.set(s.name,{name:s.name,parameters:s.parameters,body:s.body.join(`
|
|
1400
|
-
`)}),s=null;continue}if(i===`ifdef`||i===`ifndef`){let e=r.has(u);o.push(o.at(-1)===!0&&(i===`ifdef`?e:!e));continue}if(i===`else`){if(o.length<2)throw xZ(`MWL_ELSE`,`unexpected #else`,t.file,e,c);o[o.length-1]=o[o.length-2]&&!o.at(-1);continue}if(i===`endif`){if(o.length<2)throw xZ(`MWL_ENDIF`,`unexpected #endif`,t.file,e,c);o.pop();continue}if(i===`include`){if(o.at(-1)){let n=t.includes?.[bZ(u)];if(n===void 0)throw xZ(`MWL_INCLUDE`,`include not supplied: ${u}`,t.file,e,c);a.push($X(n,t))}continue}}s?o.at(-1)&&s.body.push(c):o.at(-1)&&!/^\s*#/.test(c)&&a.push(c)}if(s)throw xZ(`MWL_ENDDEF`,`macro ${s.name} is missing #enddef`,t.file,i.length-1,i.at(-1)??``);if(o.length!==1)throw xZ(`MWL_ENDIF`,`conditional is missing #endif`,t.file,i.length-1,i.at(-1)??``);return nZ(eZ(a.join(`
|
|
1401
|
-
`),n,t))}function eZ(e,t,n){let r=``,i=0;for(;i<e.length;){let a=iZ(e,i);if(a!==i){r+=e.slice(i,a),i=a;continue}let o=e[i];if(o!==`{`){r+=o,i++;continue}let s=e.indexOf(`}`,i+1);if(s<0){r+=o,i++;continue}let c=e.slice(i,s+1),l=yZ(e.slice(i+1,s)),u=t.get(l[0]);if(u){let e=u.body;for(let t=0;t<u.parameters.length;t++){let n=u.parameters[t],r=l.find(e=>e.startsWith(`${n}=`)),i=r?r.slice(n.length+1):l[t+1]??``;e=e.replaceAll(`{${n}}`,i)}r+=eZ(e,t,n)}else if(n.macroPolicy!==`ignore`&&tZ(l[0]))throw SZ(`MWL_MACRO`,`unknown macro "${l[0]}"`,e,n.file,i);else r+=c;i=s+1}return r}function tZ(e){return e!==void 0&&fZ.test(e)}function nZ(e){let t=/^_\(\s*("(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*')\s*\)/,n=``,r=0;for(;r<e.length;){let i=iZ(e,r);if(i!==r){n+=e.slice(r,i),r=i;continue}let a=e[r];if(a===`_`){let i=t.exec(e.slice(r));if(i){n+=`{"$gettext": ${i[1]}}`,r+=i[0].length;continue}}n+=a,r++}return n}function rZ(e,t){let n=e[t],r=t+1;for(;r<e.length;){let t=e[r];if(t===`\\`)r+=2;else{if(t===n)return r+1;if(t===`
|
|
1402
|
-
`)return r;r++}}return r}function iZ(e,t){let n=e[t];if(n===`"`||n===`'`)return rZ(e,t);let r=e[t+1];if(n===`/`&&(r===`/`||r===`*`)){let n=r===`/`?e.indexOf(`
|
|
1403
|
-
`,t):e.indexOf(`*/`,t+2);return n<0?e.length:r===`/`?n:n+2}return t}function aZ(e,t=`<mwl>`){let n=nZ(e);if(n.trim()===``)return[];let r;try{r=XX.default.parse(n)}catch(e){throw gZ(e,n,t)}if(r===void 0)return[];if(!Array.isArray(r))throw new ZX({code:`MWL_DOCUMENT`,message:`MWL document must be a top-level array of nodes`,location:{file:t,line:1,column:1},lineText:n.split(/\r?\n/)[0]??``});let i={file:t,sites:pZ(n,t),cursor:{index:0},parent:void 0};return oZ(r).map(e=>uZ(e,i))}function oZ(e){let t=[];for(let n of e){let e=sZ(n);Array.isArray(e)?t.push(...e):t.push(e)}return t}function sZ(e){if(Array.isArray(e))return e.flatMap(e=>sZ(e));if(typeof e!=`object`||!e)return e;let t=e;if(typeof t.tag!=`string`){let n=Object.keys(t);if(n.length!==1||!fZ.test(n[0]))return e;let r=n[0],i=t[r];return Array.isArray(i)?i.map(e=>cZ(r,e)):cZ(r,i)}let n={...t},r=[];Array.isArray(t.children)&&r.push(...t.children.flatMap(e=>sZ(e)));for(let[e,i]of Object.entries(t)){if(e===`tag`||e===`children`||!fZ.test(e)||!lZ(i))continue;let t=Array.isArray(i)?i:[i];r.push(...t.map(t=>cZ(e,t))),delete n[e]}return r.length&&(n.children=r),n}function cZ(e,t){return typeof t!=`object`||!t||Array.isArray(t)?{tag:e,value:t}:sZ({tag:e,...t})}function lZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(`$gettext`in e)||Array.isArray(e)&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function uZ(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new ZX({code:`MWL_TAG`,message:`MWL node must be an object with a tag`,location:t.parent??{file:t.file,line:1,column:1}});let n=e;if(typeof n.tag!=`string`||!fZ.test(n.tag))throw new ZX({code:`MWL_TAG`,message:`MWL node needs a tag name`,location:t.parent??{file:t.file,line:1,column:1}});let r=n.tag,i=mZ(t,r),a=i.location,o=n.children??[];if(!Array.isArray(o))throw new ZX({code:`MWL_TAG`,message:`children of [${r}] must be an array`,location:a});let s={},c={},l={},u=[];for(let[e,t]of Object.entries(n)){if(e===`tag`||e===`children`)continue;s[e]=dZ(r,e,t,a,u);let n=i.properties?.get(e);n&&(c[e]=n.location,l[e]=n.valueLocation)}let d={...t,parent:a},f={tag:r,attributes:s,children:o.map(e=>uZ(e,d)),location:a,gettext:u};return Object.defineProperties(f,{attributeLocations:{value:c,enumerable:!1},valueLocations:{value:l,enumerable:!1}}),f}function dZ(e,t,n,r,i){if(!fZ.test(t)||t.startsWith(`$`)||t.startsWith(`_`))throw new ZX({code:`MWL_ATTRIBUTE`,message:`unknown attribute "${t}" on [${e}]`,location:r});if(typeof n==`string`)return n;if(typeof n==`number`&&Number.isFinite(n))return String(n);if(typeof n==`boolean`)return n?`true`:`false`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=Object.keys(n),r=n.$gettext;if(e.length===1&&e[0]===`$gettext`&&typeof r==`string`)return i.push(t),r}throw new ZX({code:`MWL_ATTRIBUTE`,message:`attribute "${t}" on [${e}] must be a string, number, boolean, or _("...")`,location:r})}var fZ=/^[A-Za-z_][\w-]*$/;function pZ(e,t){let n=[],r=[];for(let i=0;i<e.length;){let a=iZ(e,i);if(a!==i){i=a;continue}let o=e[i];if(o===`{`){let e={start:i,properties:new Map};r.push(e),i++;continue}if(o===`}`){r.pop(),i++;continue}let s=/[A-Za-z_$][\w$-]*/y;s.lastIndex=i;let c=s.exec(e);if(!c){i++;continue}let l=c.index+c[0].length;for(;/\s/.test(e[l]??``);)l++;if(e[l]!==`:`){i=c.index+c[0].length;continue}let u=l+1;for(;/\s/.test(e[u]??``);)u++;let d=r.at(-1);if(d&&(d.properties.set(c[0],{location:hZ(e,t,c.index),valueLocation:hZ(e,t,u)}),c[0]===`tag`&&(e[u]===`"`||e[u]===`'`))){let r=rZ(e,u),i=e.slice(u,r),a;try{a=XX.default.parse(i)}catch{a=void 0}typeof a==`string`&&n.push({tag:a,location:hZ(e,t,c.index),properties:d.properties})}i=c.index+c[0].length}return n}function mZ(e,t){for(let n=e.cursor.index;n<e.sites.length;n++)if(e.sites[n].tag===t)return e.cursor.index=n+1,e.sites[n];return{tag:t,location:e.parent??{file:e.file,line:1,column:1}}}function hZ(e,t,n){let r=1,i=1;for(let t=0;t<n;t++)e[t]===`
|
|
1404
|
-
`?(r++,i=1):i++;return{file:t,line:r,column:i}}function gZ(e,t,n){let r=t.split(/\r?\n/),i=e,a=typeof i?.lineNumber==`number`?i.lineNumber:1,o=typeof i?.columnNumber==`number`?i.columnNumber:1,s=e instanceof Error?e.message:String(e);return s.includes(`'_'`)&&(s+=` (write translatable text as _("..."))`),new ZX({code:`MWL_SYNTAX`,message:s,location:{file:n,line:Math.max(1,a),column:Math.max(1,o)},lineText:r[Math.max(1,a)-1]})}function _Z(e,t,n=e){let r=e.trim(),i=/^_\(\s*([\s\S]*?)\s*\)$/.exec(r),a=i?i[1]:r;if(a.startsWith(`"`)||a.startsWith(`'`)){try{let e=XX.default.parse(a);if(typeof e==`string`)return e}catch{}throw new ZX({code:`MWL_STRING`,message:`unterminated string value`,location:t,lineText:n})}if(i)throw new ZX({code:`MWL_STRING`,message:`_("...") needs a quoted string`,location:t,lineText:n});return r}function vZ(e){return/^_\(\s*["']/.test(e.trim())}function yZ(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`&&(r=!r),/\s/.test(a)&&!r?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function bZ(e){return e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}function xZ(e,t,n,r,i){return new ZX({code:e,message:t,location:{file:n??`<mwl>`,line:r+1,column:1},lineText:i})}function SZ(e,t,n,r,i){let a=hZ(n,r??`<mwl>`,i);return new ZX({code:e,message:t,location:a,lineText:n.split(/\r?\n/)[a.line-1]})}function CZ(e,t,n,r){if(!Number.isInteger(t.version)||t.version<1)throw Error(`MWL save version must be a positive integer`);let i={format:`mwl-save`,version:t.version,world:e,...n===void 0?{}:{hookState:OZ(n)},...r===void 0?{}:{journal:kZ(r)}};return JSON.stringify(i)}function wZ(e,t){return TZ(e,t).world}function TZ(e,t){let n=JSON.parse(e),r=DZ(n)?n:{format:`mwl-save`,version:1,world:n};if(r.version>t.version)throw Error(`MWL save version ${r.version} is newer than supported version ${t.version}`);let i=EZ(r.world);for(let e=r.version;e<t.version;e++){let n=t.migrations?.[e+1];if(!n)throw Error(`missing MWL save migration to version ${e+1}`);i=EZ(n(i))}return{format:`mwl-save`,version:t.version,world:i,...r.hookState===void 0?{}:{hookState:OZ(r.hookState)},...r.journal===void 0?{}:{journal:kZ(r.journal)}}}function EZ(e){if(!e||typeof e!=`object`)throw Error(`invalid MWL saved world`);Mt(e);let t=e;if(!Number.isInteger(t.turn)||!t.variables||typeof t.variables!=`object`||!t.units||typeof t.units!=`object`)throw Error(`invalid MWL saved world: turn, variables, and units are required`);if(t.status!==void 0&&![`playing`,`won`,`lost`].includes(t.status))throw Error(`invalid MWL saved world status`);return Wt(t,`saved world`)}function DZ(e){return!!e&&typeof e==`object`&&e.format===`mwl-save`&&typeof e.version==`number`&&`world`in e}function OZ(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid MWL hook state`);Mt(e);let t;try{t=JSON.stringify(e)}catch{throw Error(`MWL hook state must be JSON-serialisable`)}let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))throw Error(`invalid MWL hook state`);return n}function kZ(e){try{let t=JSON.stringify(e),n=JSON.parse(t);if(!Array.isArray(n))throw Error();return Mt(n),n}catch{throw Error(`MWL journal must be JSON-serialisable`)}}function AZ(e,t,n={}){let r=e.search(/\s+where\s+/),i=r<0?e:e.slice(0,r),a={...t};if(r>=0)for(let t of e.slice(r).replace(/^\s+where\s+/,``).split(`,`)){let e=/^\s*([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.+)\s*$/.exec(t);if(!e)throw Error(`invalid MWL where binding: ${t}`);let r=new jZ(e[2],a,n.helpers??{});if(a[e[1]]=r.parseOr(),!r.atEnd())throw Error(`invalid MWL where binding: ${t}`)}let o=new jZ(i,a,n.helpers??{}),s=o.parseOr();if(!o.atEnd())throw Error(`unexpected token in MWL condition: ${o.peek()}`);return NZ(s)}var jZ=class{constructor(e,t,n){this.index=0,this.tokens=MZ(e),this.context=t,this.helpers=n}parseOr(){let e=this.parseAnd();for(;this.take(`or`);)e=NZ(e)||NZ(this.parseAnd());return e}parseAnd(){let e=this.parseNot();for(;this.take(`and`);)e=NZ(e)&&NZ(this.parseNot());return e}parseNot(){return this.take(`not`)?!NZ(this.parseNot()):this.parseComparison()}parseComparison(){let e=this.parseAdditive(),t=this.peek();if(![`==`,`~=`,`<`,`<=`,`>`,`>=`].includes(t))return e;this.index++;let n=this.parseAdditive();if(t===`==`)return e===n;if(t===`~=`)return e!==n;if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);return t===`<`?e<n:t===`<=`?e<=n:t===`>`?e>n:e>=n}parseAdditive(){let e=this.parseMultiplicative();for(;this.peek()===`+`||this.peek()===`-`;){let t=this.tokens[this.index++],n=this.parseMultiplicative();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);e=t===`+`?e+n:e-n}return e}parseMultiplicative(){let e=this.parsePrimary();for(;this.peek()===`*`||this.peek()===`/`;){let t=this.tokens[this.index++],n=this.parsePrimary();if(typeof e!=`number`||typeof n!=`number`)throw Error(`${t} requires numeric operands`);if(t===`/`&&n===0)throw Error(`division by zero in MWL condition`);e=t===`*`?e*n:e/n}return e}parsePrimary(){if(this.take(`(`)){let e=this.parseOr();return this.expect(`)`),e}let e=this.tokens[this.index++];if(e===void 0)throw Error(`incomplete MWL condition`);if(/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))return Number(e);if(e===`true`||e===`yes`)return!0;if(e===`false`||e===`no`)return!1;if(e.startsWith(`"`)||e.startsWith(`'`))return e.slice(1,-1);let t=this.helpers[e];if(t&&this.take(`(`)){let e=[];if(!this.take(`)`)){do e.push(this.parseOr());while(this.take(`,`));this.expect(`)`)}return t(...e)}let n=this.context[e];if(n===void 0)throw Error(`missing MWL condition variable "${e}"`);return n}take(e){return this.peek()===e&&(this.index++,!0)}expect(e){if(!this.take(e))throw Error(`expected "${e}" in MWL condition`)}peek(){return this.tokens[this.index]??`<end>`}atEnd(){return this.index>=this.tokens.length}};function MZ(e){let t=[],n=/\s*(?:("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|([A-Za-z_][A-Za-z0-9_.-]*)|(-?(?:\d+(?:\.\d*)?|\.\d+))|(==|~=|<=|>=|[()+*/,<>-]))/y,r=0;for(;r<e.length;){n.lastIndex=r;let i=n.exec(e);if(!i)throw Error(`invalid MWL condition near "${e.slice(r)}"`);t.push(i[1]??i[2]??i[3]??i[4]),r=n.lastIndex}return t}function NZ(e){return e!==!1&&e!==0&&e!==``}function PZ(e){let t=new BZ(e),n=t.expression();if(t.skip(),!t.atEnd())throw Error(`invalid MWL expression near "${t.rest()}"`);return n}function FZ(e,t){let n=typeof e==`string`?PZ(e):e;if(n.kind===`number`)return n.value;if(n.kind===`variable`){let e=t[n.name];if(e===void 0||!Number.isFinite(e))throw Error(`missing MWL expression variable "${n.name}"`);return e}let r=FZ(n.left,t),i=FZ(n.right,t);if(n.op===`+`)return r+i;if(n.op===`-`)return r-i;if(n.op===`*`)return r*i;if(n.op===`/`){if(i===0)throw Error(`division by zero in MWL expression`);return r/i}return r**i}var IZ=256,LZ=4096,RZ=/(?:\d+(?:\.\d*)?|\.\d+)/y,zZ=/[A-Za-z_][A-Za-z0-9_.-]*/y,BZ=class{constructor(e){this.index=0,this.depth=0,this.operators=0,this.source=e}expression(){return this.additive()}additive(){let e=this.multiplicative();for(;;){this.skip();let t=this.peek(`+`)?`+`:this.peek(`-`)?`-`:null;if(!t)return e;this.index++,this.operator(),e={kind:`binary`,op:t,left:e,right:this.multiplicative()}}}multiplicative(){let e=this.power();for(;;){this.skip();let t=this.peek(`*`)?`*`:this.peek(`/`)?`/`:null;if(!t)return e;this.index++,this.operator(),e={kind:`binary`,op:t,left:e,right:this.power()}}}power(){let e=this.primary();return this.skip(),this.peek(`^`)&&(this.index++,this.operator(),e={kind:`binary`,op:`^`,left:e,right:this.nested(()=>this.power())}),e}primary(){if(this.skip(),this.peek(`(`)){this.index++;let e=this.nested(()=>this.expression());if(this.skip(),!this.peek(`)`))throw Error(`missing closing parenthesis in MWL expression`);return this.index++,e}let e=this.match(RZ);if(e)return this.index+=e[0].length,{kind:`number`,value:Number(e[0])};let t=this.match(zZ);if(t)return this.index+=t[0].length,{kind:`variable`,name:t[0]};throw Error(`expected number, variable, or parenthesis near "${this.rest()}"`)}match(e){return e.lastIndex=this.index,e.exec(this.source)}nested(e){if(++this.depth>IZ)throw Error(`MWL expression is nested more than ${IZ} deep`);try{return e()}finally{this.depth--}}operator(){if(++this.operators>LZ)throw Error(`MWL expression has more than ${LZ} operators`)}peek(e){return this.source[this.index]===e}skip(){for(;/\s/.test(this.source[this.index]??``);)this.index++}atEnd(){return this.index>=this.source.length}rest(){let e=this.source.slice(this.index,this.index+40);return this.index+40<this.source.length?`${e}...`:e}};function VZ(e){let t=[],n=e=>{t.push(e),e.children.forEach(n)};return e.forEach(n),t}function HZ(e,t){let n=e.attributes[t];if(!n)throw Error(`MWL ${e.tag} is missing ${t}`);return n}function UZ(e,t){let n=e.attributes[t];if(n===void 0)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function WZ(e,t,n){let r=e.attributes[t];if(r===void 0)return n;let i=Number.parseInt(r,10);return Number.isFinite(i)?i:n}function GZ(e,t){return KZ(e.attributes[t])}function KZ(e){return e===void 0?void 0:e===`true`||e===`yes`}function qZ(e,t){return e!==void 0&&t.includes(e)?e:void 0}function JZ(e,t,n){let r=n.carryoverPercentage??80,i=t?e.gold[t.id]??e.sides[t.id]?.gold??0:0;return{result:n.result,gold:Math.floor(i*r/100)+(n.bonus??0),add:n.carryoverAdd??!1,recall:t?Object.entries(e.units).filter(([,e])=>e.alive&&e.side===t.id).map(([e])=>e).sort():[],nextScenario:n.nextScenario??null}}function YZ(e,t){return e.add?t+e.gold:Math.max(t,e.gold)}_e();var XZ=HZ,ZZ=(e,t,n)=>WZ(e,t,n)??n;function QZ(){return{variables:{},units:{},sides:{},maps:{},gold:{},turn:1,status:`playing`,sideStatus:{},map:null,timeOfDay:``,scheduleIndex:0}}var $Z=1048576;function eQ(e){let t=e.split(/\r?\n/).filter(e=>e.trim()!==``).map(e=>e.split(`,`).map(e=>e.trim())),n=t.length,r=t.reduce((e,t)=>Math.max(e,t.length),0);if(r*n>$Z)throw Error(`MWL terrain is ${r}x${n}, more than ${$Z} cells`);let i=[],a={};for(let e=0;e<n;e++)for(let n=0;n<r;n++){let r=t[e]?.[n]??`_off^_usr`,o=/^([A-Za-z0-9_][\w.-]*)\s+(\S.*)$/.exec(r);o?(i.push(o[2]),(a[o[1]]??=[]).push({x:n,y:e})):i.push(r)}return{width:r,height:n,codes:i,starts:a}}var tQ=/\$\(([^)]*)\)/g,nQ=/\$([A-Za-z_][A-Za-z0-9_.]*)/g,rQ=class e{constructor(e,t={}){this.journal=new wn,this.unitTypes=new Map,this.schedule=[],this.pendingDialogue=null,this.dialogueCounter=0,this.traceBatch=null,this.game=e,this.world=t.world??QZ(),this.onMessage=t.onMessage,this.resolveMap=t.resolveMap,this.hooks=t.hooks,this.onTrace=t.onTrace,this.persistence=t.persistence??{version:1},this.random=t.random??new j,!t.random&&this.world.random&&this.random.setState(this.world.random),this.loadUnitTypes(),this.loadSchedule(),this.loadInitialContent(),this.loadInitialUnits(),this.loadLeaders(),this.loadScenarioExtras()}run(e){this.recordAction({type:`run`,trigger:e},()=>this.runInternal(e))}runInternal(e){for(let t of this.nodes(`event`))(t.attributes.on??t.attributes.trigger)===e&&this.eventFiltersMatch(t)&&this.claimEvent(t)&&this.executeTracedEvent(t,e);this.checkObjectives()}fireEvent(e){return this.recordAction({type:`fire_event`,id:e},()=>this.fireEventInternal(e))}fireEventInternal(e){let t=this.nodes(`event`).find(t=>t.attributes.id===e);return!t||!this.eventFiltersMatch(t)||!this.claimEvent(t)?!1:(this.executeTracedEvent(t,`fireEvent`),this.checkObjectives(),!0)}fireMoveto(e){this.recordAction({type:`fire_moveto`,unit:e},()=>this.fireMovetoInternal(e))}fireMovetoInternal(e){let t=this.world.units[e];if(t&&t.alive){for(let n of this.nodes(`event`))(n.attributes.on??n.attributes.trigger)===`moveto`&&(n.attributes.x===void 0||wQ(n.attributes.x,t.x))&&(n.attributes.y===void 0||wQ(n.attributes.y,t.y))&&(n.attributes.unit===void 0||n.attributes.unit===e)&&(n.attributes.side===void 0||n.attributes.side===t.side)&&this.eventFiltersMatch(n)&&this.claimEvent(n)&&this.executeTracedEvent(n,`moveto`);this.checkObjectives()}}claimEvent(e){if(!(e.attributes.once===void 0?e.attributes.on===`moveto`:e.attributes.once!==`false`))return!0;let t=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`,n=this.world.firedEvents??=[];return!n.includes(t)&&(n.push(t),!0)}eventFiltersMatch(e){if(!this.conditionMatches(e)||!this.filterConditionMatches(e))return!1;let t=e.children.find(e=>e.tag===`filter`);return!t||this.filterMatches(t)}executeEvent(e){this.runBlock(this.commandChildren(e))}runBlock(e){for(let t=0;t<e.length;t++){let n=e[t];this.isConsumedElse(e,t)||(n.tag===`say`?this.showSay(n):n.tag===`dialogue`?this.showDialogue(n):this.executeNode(n))}}isConsumedElse(e,t){let n=e[t-1];return e[t]?.tag===`else`&&n?.tag===`if`&&this.nodeConditionMatches(n)}executeTracedEvent(e,t){let n=e.attributes.id??`${e.attributes.on??e.attributes.trigger??`event`}@${e.location?.line??0}`;this.trace({type:`event`,phase:`claimed`,id:n,trigger:t});try{this.executeEvent(e),this.trace({type:`event`,phase:`completed`,id:n,trigger:t})}catch(e){throw this.trace({type:`error`,message:String(e),event:n}),e}}showDialogue(e){let t=null;for(let n of e.children)n.tag===`message`?(this.showMessage(n.attributes),t={text:n.attributes.text??n.attributes.value??``,...n.attributes.speaker===void 0?{}:{speaker:n.attributes.speaker},...n.attributes.portrait===void 0?{}:{portrait:n.attributes.portrait},...n.attributes.side===void 0||n.attributes.side===``?{}:{side:n.attributes.side}}):n.tag===`say`&&(this.showSay(n),t={text:n.attributes.text??``,speaker:n.attributes.speaker});let n=[];for(let t of e.children){if(t.tag!==`choice`||!t.attributes.text||t.attributes.variable!==void 0&&!gQ(this.variableAt(t.attributes.variable),t.attributes.equals))continue;let e=t.children.filter(e=>e.tag===`branch`);if(e.length)for(let r of e)n.push({text:r.attributes.text??t.attributes.text,branch:r.children});else t.attributes.event&&n.push({text:t.attributes.text,event:t.attributes.event})}if(n.length===0)return;this.dialogueCounter+=1;let r=`dialogue-${this.dialogueCounter}`;this.pendingDialogue={id:r,choices:n},this.world.pendingDialogue={id:r,choices:n},this.onMessage?.({text:t?.text??``,...t?.speaker===void 0?{}:{speaker:t.speaker},choices:n,dialogueId:r})}showSay(e){this.onMessage&&this.onMessage({text:e.attributes.text??``,...e.attributes.speaker===void 0?{}:{speaker:e.attributes.speaker}})}answerDialogue(e,t){return this.recordAction({type:`answer_dialogue`,dialogueId:e,choiceIndex:t},()=>this.answerDialogueInternal(e,t))}answerDialogueInternal(e,t){let n=this.pendingDialogue;if(!n||n.id!==e)return!1;let r=n.choices[t];if(!r)return!1;if(this.pendingDialogue=null,delete this.world.pendingDialogue,r.event){let e=this.nodes(`event`).find(e=>e.attributes.id===r.event);if(!e)throw Error(`MWL dialogue choice points at unknown event: ${r.event}`);if(!this.claimEvent(e))return!0;this.executeEvent(e)}else this.runBlock(r.branch??[]);return this.checkObjectives(),!0}evaluate(){return this.checkObjectives(),this.world.status}save(){let e=this.hooks?.saveable,t=e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.save()])):void 0;return CZ(this.world,this.persistence,t,this.journal.toJSON())}snapshot(){return JSON.stringify(this.world)}restore(e){let t=TZ(e,this.persistence),n=t.world;Object.assign(this.world.variables,n.variables),Object.assign(this.world.units,n.units),Object.assign(this.world.sides,n.sides??{}),Object.assign(this.world.maps,n.maps??{}),Object.assign(this.world.gold,n.gold??{}),this.world.turn=n.turn,this.world.status=n.status,this.world.sideStatus={...n.sideStatus??{}},this.world.map=n.map??null,this.world.timeOfDay=n.timeOfDay??this.schedule[0]??``,this.world.scheduleIndex=n.scheduleIndex??0,this.world.random=n.random,this.random.setState(n.random??new j().getState()),this.world.firedEvents=[...n.firedEvents??[]],this.world.villages=n.villages?structuredClone(n.villages):void 0,this.world.clearedShroud=n.clearedShroud?structuredClone(n.clearedShroud):void 0,this.world.roles=n.roles?structuredClone(n.roles):void 0,this.world.objects=n.objects?structuredClone(n.objects):void 0,this.world.story=n.story?structuredClone(n.story):void 0,this.world.pendingDialogue=n.pendingDialogue,this.pendingDialogue=n.pendingDialogue?{id:n.pendingDialogue.id,choices:[...n.pendingDialogue.choices]}:null;let r=n.pendingDialogue?.id.match(/^dialogue-(\d+)$/);r&&(this.dialogueCounter=Math.max(this.dialogueCounter,Number(r[1])));for(let[e,n]of Object.entries(t.hookState??{}))this.hooks?.saveable?.[e]?.restore(n);this.journal.replace(t.journal??[])}recordAction(e,t){let n=this.traceBatch===null;n&&(this.traceBatch=[]);try{let r=t();return n&&this.journal.append(e,this.traceBatch??[]),r}finally{n&&(this.traceBatch=null)}}trace(e){this.traceBatch?.push(e),this.onTrace?.(e)}loadUnitTypes(){for(let e of this.nodes(`unit_type`)){let t=e.attributes.id;t&&this.unitTypes.set(t,{hitpoints:ZZ(e,`hitpoints`,1),movement:ZZ(e,`movement`,0)})}}loadSchedule(){this.schedule=this.nodes(`schedule`).flatMap(e=>e.children.filter(e=>e.tag===`time`).map(e=>e.attributes.id).filter(e=>!!e)),this.world.scheduleIndex=0,this.world.timeOfDay=this.schedule[0]??``}loadInitialContent(){for(let e of this.nodes(`side`)){let t={gold:ZZ(e,`gold`,0),income:ZZ(e,`income`,0)};e.attributes.leader!==void 0&&(t.leader=e.attributes.leader),e.attributes.controller!==void 0&&(t.controller=e.attributes.controller),e.attributes.recruit!==void 0&&(t.recruit=e.attributes.recruit),e.attributes.team_name!==void 0&&(t.teamName=e.attributes.team_name),e.attributes.user_team_name!==void 0&&(t.userTeamName=e.attributes.user_team_name),e.attributes.share_vision!==void 0&&(t.shareVision=e.attributes.share_vision),e.attributes.flag!==void 0&&(t.flag=e.attributes.flag),e.attributes.village_gold!==void 0&&(t.villageGold=ZZ(e,`village_gold`,0));for(let n of[`heal`,`fog`,`shroud`,`hidden`]){let r=e.attributes[n];r!==void 0&&(t[n]=r===`yes`||r===`true`)}this.world.sides[XZ(e,`id`)]=t}for(let e of this.nodes(`map`)){let t=e.attributes.id??e.attributes.name??`map`;this.world.maps[t]={terrain:e.attributes.terrain??``,file:e.attributes.file},this.world.map||(this.world.map=this.buildMap(t,e))}}topLevelNodes(e){return(this.game.roots.find(e=>e.tag===`game`)?.children??this.game.roots).filter(t=>t.tag===e)}loadScenarioExtras(){for(let e of this.topLevelNodes(`object`)){let t={x:ZZ(e,`x`,0),y:ZZ(e,`y`,0)};e.attributes.id!==void 0&&(t.id=e.attributes.id),e.attributes.name!==void 0&&(t.name=e.attributes.name),e.attributes.image!==void 0&&(t.image=e.attributes.image),e.attributes.side!==void 0&&(t.side=e.attributes.side),(this.world.objects??=[]).push(t)}for(let e of this.topLevelNodes(`story`)){let t=e.attributes.text??e.attributes.value;if(t===void 0)continue;let n={text:t};e.attributes.title!==void 0&&(n.title=e.attributes.title),e.attributes.image!==void 0&&(n.image=e.attributes.image),e.attributes.music!==void 0&&(n.music=e.attributes.music),(this.world.story??=[]).push(n)}for(let e of this.topLevelNodes(`role`)){let t=e.attributes.role??e.attributes.name;if(t===void 0)continue;let n=hQ(e.attributes,`role`,`name`),r=Object.entries(this.world.units).filter(([e,t])=>t.alive&&mQ(t,e,n));for(let[,e]of r)e.role=t;(this.world.roles??={})[t]=r.map(([e])=>e)}}buildMap(e,t){let n=t.attributes.terrain;if(!n&&t.attributes.file&&this.resolveMap&&(n=this.resolveMap(t.attributes.file)),!n)return null;let r=eQ(n);for(let e of t.children){if(e.tag!==`start`)continue;let t=e.attributes.side,n=fQ(e,`x`),i=fQ(e,`y`);t!==void 0&&n!==void 0&&i!==void 0&&(r.starts[t]??=[]).push({x:n,y:i})}return{id:e,...r}}loadInitialUnits(){for(let e of this.nodes(`unit`)){let t=XZ(e,`id`),n={hp:ZZ(e,`hp`,1),x:ZZ(e,`x`,0),y:ZZ(e,`y`,0),alive:!0};if(e.attributes.type!==void 0){n.type=e.attributes.type;let t=this.unitTypes.get(e.attributes.type);t&&(n.moves=t.movement)}e.attributes.side!==void 0&&(n.side=e.attributes.side),e.attributes.name!==void 0&&(n.name=e.attributes.name),e.attributes.role!==void 0&&(n.role=e.attributes.role);let r=GZ(e,`can_recruit`);r!==void 0&&(n.can_recruit=r),this.world.units[t]=n}}loadLeaders(){for(let e of this.nodes(`side`)){let t=e.attributes.leader;if(!t)continue;let n=e.attributes.id;if(!n)continue;let r=this.world.map?.starts[n];if(!r?.length||this.world.units[t])continue;let i=this.unitTypes.get(t);if(!i)throw Error(`MWL side ${n} leader "${t}" is neither a unit nor a unit type`);for(let e of r){if(this.unitAt(e.x,e.y))continue;let r=`${t} ${n} (${e.x},${e.y})`;this.world.units[r]={hp:i.hitpoints,x:e.x,y:e.y,alive:!0,type:t,side:n,moves:i.movement,can_recruit:!0,leader:!0}}}}unitAt(e,t){return Object.values(this.world.units).find(n=>n.alive&&n.x===e&&n.y===t)}static{this.commandHandlers={message:(e,t)=>e.showMessage(t.attributes),spawn:(e,t)=>e.cmdSpawn(t),move:(e,t)=>e.cmdMove(t),kill:(e,t)=>e.cmdKill(t),fire_event:(e,t)=>e.cmdFireEvent(t),store_unit:(e,t)=>e.cmdStoreUnit(t),unstore_unit:(e,t)=>e.cmdUnstoreUnit(t),recall:(e,t)=>e.cmdRecall(t),modify_unit:(e,t)=>e.cmdModifyUnit(t),heal_unit:(e,t)=>e.cmdHealUnit(t),set_terrain:(e,t)=>e.setTerrain(ZZ(t,`x`,0),ZZ(t,`y`,0),XZ(t,`terrain`)),capture_village:(e,t)=>e.cmdCaptureVillage(t),clear_shroud:(e,t)=>e.cmdClearShroud(t),role:(e,t)=>e.cmdRole(t),attack:(e,t)=>e.attack(t.attributes.defender??t.attributes.target??XZ(t,`target`),ZZ(t,`amount`,0)),modify_gold:(e,t)=>e.addGold(t.attributes.side??XZ(t,`target`),ZZ(t,`delta`,ZZ(t,`amount`,0))),gold:(e,t)=>e.addGold(XZ(t,`side`),ZZ(t,`delta`,ZZ(t,`amount`,0))),set_variable:(e,t)=>e.cmdSetVariable(t),while:(e,t)=>e.cmdWhile(t),foreach:(e,t)=>e.cmdForeach(t),switch:(e,t)=>e.cmdSwitch(t),end_turn:e=>e.endTurn(),win:(e,t)=>e.cmdWin(t),lose:(e,t)=>e.cmdLose(t),endlevel:(e,t)=>e.cmdEndlevel(t),if:(e,t)=>e.cmdIf(t),else:(e,t)=>e.runBlock(e.commandChildren(t)),hook:(e,t)=>e.runHook(t)}}executeNode(t){let n=t.tag===`command`?t.attributes.name:t.tag;if(!n)throw Error(`MWL command is missing name`);let r=e.commandHandlers[n];if(!r)throw Error(`unknown MWL command: ${n}`);r(this,t)}cmdSpawn(e){this.spawnUnit(e.attributes.type??``,e.attributes.side,ZZ(e,`x`,0),ZZ(e,`y`,0),e.attributes.id??e.attributes.target,e.attributes.hp===void 0?void 0:ZZ(e,`hp`,1))}cmdMove(e){this.applyMove(e.attributes.unit??XZ(e,`target`),ZZ(e,`x`,0),ZZ(e,`y`,0))}cmdKill(e){let t=e.attributes.unit??e.attributes.target;t===void 0?cQ(this.world,e.attributes):this.killUnit(t)}cmdFireEvent(e){let t=e.attributes.id??e.attributes.name;if(!t)throw Error(`[fire_event] requires id`);this.fireEvent(t)}cmdStoreUnit(e){let t=e.attributes.variable??e.attributes.name??XZ(e,`variable`);this.setVariableAt(t,this.matchingUnits(e,[`variable`,`name`]).map(([e,t])=>({id:e,...lQ(t)})))}cmdUnstoreUnit(e){let t=XZ(e,`variable`);for(let e of this.storedUnits(t))this.restoreUnit(e,{})}cmdRecall(e){let t=this.storedUnits(XZ(e,`variable`)),n=e.attributes.id??e.attributes.unit,r=n===void 0?t[0]:t.find(e=>e.id===n);if(!r)throw Error(`[recall] found no stored unit${n===void 0?``:` named ${n}`}`);let i={};e.attributes.x!==void 0&&(i.x=ZZ(e,`x`,0)),e.attributes.y!==void 0&&(i.y=ZZ(e,`y`,0)),e.attributes.side!==void 0&&(i.side=e.attributes.side),this.restoreUnit(r,i)}cmdModifyUnit(e){let t=e.children.find(e=>e.tag===`set`)?.attributes??e.attributes;for(let[,n]of this.matchingUnits(e))uQ(n,t)}cmdHealUnit(e){let t=fQ(e,`amount`),n=fQ(e,`hp`);if(t===void 0&&n===void 0)throw Error(`[heal_unit] requires amount or hp`);for(let[,r]of this.matchingUnits(e))r.hp=n??r.hp+(t??0)}cmdCaptureVillage(e){let t=ZZ(e,`x`,0),n=ZZ(e,`y`,0),r={x:t,y:n,side:XZ(e,`side`)};e.attributes.name!==void 0&&(r.name=e.attributes.name),(this.world.villages??={})[`${t},${n}`]=r}cmdClearShroud(e){let t=XZ(e,`side`),n=ZZ(e,`x`,0),r=ZZ(e,`y`,0),i=ZZ(e,`radius`,1),a=new Set(this.world.clearedShroud?.[t]??[]);for(let e=-i;e<=i;e++)for(let t=-i;t<=i;t++)a.add(`${n+t},${r+e}`);(this.world.clearedShroud??={})[t]=[...a]}cmdRole(e){let t=e.attributes.role??e.attributes.name;if(!t)throw Error(`[role] requires role`);let n=this.matchingUnits(e,[`role`,`name`]);for(let[,e]of n)e.role=t;(this.world.roles??={})[t]=n.map(([e])=>e)}cmdSetVariable(e){let t=e.attributes.path;this.setVariable(t===void 0?e.tag===`command`?XZ(e,`target`):XZ(e,`name`):this.expandPath(t),e.attributes.value??``,e.attributes.mode)}cmdWhile(e){let t=ZZ(e,`max_iterations`,1e3);if(t<1||t>1e5)throw Error(`MWL while max_iterations must be between 1 and 100000`);let n=0;for(;n<t&&this.nodeConditionMatches(e);)this.runBlock(this.commandChildren(e)),n++;if(n===t&&this.nodeConditionMatches(e)){if(e.attributes.on_limit===`error`)throw Error(`MWL while reached its max_iterations cap of ${t}`);this.onTrace?.({type:`while_limit`,iterations:t})}}cmdForeach(e){let t=this.variableAt(XZ(e,`variable`)),n=Array.isArray(t)?t.map((e,t)=>[String(t),e]):typeof t==`string`?t.split(`,`).map((e,t)=>[String(t),e.trim()]).filter(([,e])=>e!==``):t&&typeof t==`object`?Object.entries(t):[],r=e.attributes.item??`item`,i=e.attributes.index??`index`;for(let t=0;t<n.length;t++)this.setVariableAt(r,n[t][1]),this.setVariableAt(i,t),this.runBlock(this.commandChildren(e))}cmdSwitch(e){let t=this.variableAt(XZ(e,`variable`)),n=e.children.find(e=>e.tag===`case`&&e.attributes.equals!==void 0&&gQ(t,e.attributes.equals)),r=e.children.find(e=>e.tag==="default");this.runBlock((n??r)?.children??[])}cmdWin(e){this.markSideResult(e.attributes.side,`won`),this.world.status=`won`}cmdLose(e){this.markSideResult(e.attributes.side,`lost`),this.world.status=`lost`}cmdEndlevel(e){let t=e.attributes.result===`defeat`?`defeat`:`victory`;this.world.status=t===`defeat`?`lost`:`won`,this.world.carryover=JZ(this.world,aQ(this.world,e.attributes.side),{result:t,bonus:WZ(e,`bonus`),carryoverPercentage:UZ(e,`carryover_percentage`),carryoverAdd:GZ(e,`carryover_add`),nextScenario:e.attributes.next_scenario??null})}cmdIf(e){let t=e.children.find(e=>e.tag===`else`),n=this.nodeConditionMatches(e)?e:t;this.runBlock(n?this.commandChildren(n):[])}commandChildren(e){return e.children.filter(e=>e.tag!==`condition`&&e.tag!==`filter`&&e.tag!==`filter_condition`)}runHook(e){let t=e.attributes.name??``,n=this.hooks?.command?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{name:r,...i}=e.attributes;n(this.worldView(),this.emit(),i)}applyMove(e,t,n){let r=this.world.units[e];if(!r||!r.alive)throw Error(`MWL unit is not alive: ${e}`);let i=this.world.map??null;if(i){if(t<0||n<0||t>=i.width||n>=i.height)throw Error(`MWL move out of bounds: ${t},${n}`);let e=this.unitAt(t,n);if(e&&e!==r)throw Error(`MWL move onto an occupied cell: ${t},${n}`)}if(typeof r.moves==`number`){if(r.moves<=0)throw Error(`MWL unit has no moves left: ${e}`);--r.moves}r.x=t,r.y=n,this.fireMoveto(e)}showMessage(e){if(!this.onMessage)return;let t={text:this.interpolate(e.text??e.value??``),...e.speaker===void 0?{}:{speaker:e.speaker},...e.portrait===void 0?{}:{portrait:e.portrait},...e.side===void 0||e.side===``?{}:{side:e.side}};this.onMessage(t)}interpolate(e){let t=this.numericVariables();return e.replace(tQ,(e,n)=>{try{return String(FZ(n,t))}catch{return``}}).replace(nQ,(e,t)=>{let n=this.variableAt(t);return n===void 0||typeof n==`boolean`?``:String(n)})}expandPath(e){return e.replace(tQ,(e,t)=>String(FZ(t,this.numericVariables()))).replace(nQ,(e,t)=>{let n=this.variableAt(t);if(n===void 0)throw Error(`MWL variable path reference "$${t}" names no variable`);if(typeof n==`boolean`||typeof n==`object`)throw Error(`MWL variable path reference "$${t}" is not a name or number`);return String(n)})}setVariable(e,t,n){if(n===`literal`){this.setVariableAt(e,t);return}if(n===`number`){let n=Number(t);if(t.trim()===``||!Number.isFinite(n))throw Error(`MWL set_variable mode="number" needs a number, got "${t}"`);this.setVariableAt(e,n);return}if(n===`expression`){this.setVariableAt(e,FZ(t,this.numericVariables()));return}if(n!==void 0)throw Error(`unknown MWL set_variable mode "${n}"`);let r=Number(t);if(t.trim()!==``&&Number.isFinite(r)){this.setVariableAt(e,r);return}let i=/^\$([A-Za-z_][A-Za-z0-9_.]*)$/.exec(t.trim());if(i){let t=this.variableAt(i[1]);this.setVariableAt(e,t===void 0?``:t);return}let a=this.numericVariables();/[+*/^()]|\s-\s/.test(t)||Object.prototype.hasOwnProperty.call(a,t.trim())?this.setVariableAt(e,FZ(t,a)):this.setVariableAt(e,t)}numericVariables(){return Object.fromEntries(Object.entries(this.world.variables).filter(e=>typeof e[1]==`number`))}variableAt(e){return SQ(this.world.variables,e)}setVariableAt(e,t){let n=this.variableAt(e);xQ(this.world.variables,e,t),this.trace({type:`variable`,name:e,...n===void 0?{}:{previous:n},value:t})}spawnUnit(e,t,n,r,i,a){let o=e?this.unitTypes.get(e):void 0,s=i??`${e||`unit`}#${t??``}@${n},${r}`;this.world.units[s]={hp:a??o?.hitpoints??1,x:n,y:r,alive:!0,...e?{type:e}:{},...t===void 0?{}:{side:t},...o?{moves:o.movement}:{}}}killUnit(e){let t=this.world.units[e];if(!t||!t.alive)throw Error(`MWL unit is not alive: ${e}`);t.alive=!1}matchingUnits(e,t=[]){let n=e.children.find(e=>e.tag===`filter`),r=n?n.attributes:hQ(e.attributes,...t);return Object.entries(this.world.units).filter(([e,t])=>t.alive&&mQ(t,e,r))}storedUnits(e){let t=this.variableAt(e);if(!Array.isArray(t))throw Error(`MWL variable ${e} is not a stored unit list; store one first`);return t.filter(e=>!!e&&typeof e==`object`&&!Array.isArray(e))}restoreUnit(e,t){let n=typeof e.id==`string`?e.id:void 0;if(!n)throw Error(`a stored unit snapshot is missing its id`);let r={hp:typeof e.hp==`number`?e.hp:1,x:t.x??(typeof e.x==`number`?e.x:0),y:t.y??(typeof e.y==`number`?e.y:0),alive:e.alive!==!1};typeof e.type==`string`&&(r.type=e.type);let i=t.side??(typeof e.side==`string`?e.side:void 0);i!==void 0&&(r.side=i),typeof e.moves==`number`&&(r.moves=e.moves),typeof e.name==`string`&&(r.name=e.name),typeof e.role==`string`&&(r.role=e.role),typeof e.can_recruit==`boolean`&&(r.can_recruit=e.can_recruit),typeof e.leader==`boolean`&&(r.leader=e.leader),this.world.units[n]=r}setTerrain(e,t,n){let r=this.world.map;if(!r)throw Error(`[set_terrain] needs a loaded map`);if(e<0||t<0||e>=r.width||t>=r.height)throw Error(`[set_terrain] is outside the map: ${e},${t}`);let i=[...r.codes];i[t*r.width+e]=n,this.world.map={...r,codes:i}}addGold(e,t){this.world.gold[e]=(this.world.gold[e]??0)+t}endTurn(){this.world.turn+=1,this.advanceSchedule(),this.resetMoves(),this.run(`turn`),this.checkTimeOver()}checkTimeOver(){let e=WZ(this.game.roots[0],`turn_limit`);e===void 0||this.world.turn<=e||this.world.variables.time_over===`yes`||(this.world.variables.time_over=`yes`,this.run(`time_over`))}advanceSchedule(){if(!this.schedule.length)return;let e=((this.world.scheduleIndex??0)+1)%this.schedule.length;this.world.scheduleIndex=e,this.world.timeOfDay=this.schedule[e]}resetMoves(){for(let e of Object.values(this.world.units)){if(!e.alive)continue;let t=e.type?this.unitTypes.get(e.type):void 0;t&&(e.moves=t.movement)}}filterMatches(e){return Object.entries(this.world.units).some(([t,n])=>n.alive&&mQ(n,t,e.attributes))}conditionMatches(e){return e.children.filter(e=>e.tag===`condition`).every(e=>{if(e.attributes.condition===`hook`){let t=e.attributes.hook,n=t?.startsWith(`predicate:`)?t.slice(10):void 0,r=n?this.hooks?.predicate?.[n]:void 0;if(!r)throw Error(`MWL predicate ${n??`<missing>`} is not implemented`);let{condition:i,hook:a,...o}=e.attributes;return!!r(this.worldView(),o)}return pQ(this.variableAt(e.attributes.variable),e.attributes,CQ(this.world.variables))})}nodeConditionMatches(e){return e.attributes.test===void 0?this.conditionMatches(e):AZ(e.attributes.test,_Q(this.world.variables),{helpers:this.conditionHelpers()})}conditionHelpers(){if(this.testHelpers)return this.testHelpers;let e=e=>{let t={};for(let n of e){let e=String(n),r=e.indexOf(`=`);r<=0?t.value=e:t[e.slice(0,r)]=e.slice(r+1)}return t},t={have_unit:(...t)=>{let n=e(t);return Object.entries(this.world.units).some(([e,t])=>t.alive&&(n.id===void 0||e===n.id)&&mQ(t,e,n))},have_location:(...t)=>{let n=e(t),r=this.world.map,i=Number(n.x),a=Number(n.y);if(!r||!Number.isInteger(i)||!Number.isInteger(a)||i<0||a<0||i>=r.width||a>=r.height)return!1;let o=r.codes[a*r.width+i];return n.terrain===void 0||o===n.terrain}};for(let[n,r]of Object.entries(this.hooks?.predicate??{}))t[n]=(...t)=>!!r(this.worldView(),e(t));return this.testHelpers=t,t}filterConditionMatches(e){let t=e.children.find(e=>e.tag===`filter_condition`);return!t||t.children.every(e=>{if(e.tag===`variable`){let t=e.attributes.name;return t!==void 0&&pQ(this.variableAt(t),e.attributes,CQ(this.world.variables))}if(e.tag===`predicate`){let t=e.attributes.name,n=t?this.hooks?.predicate?.[t]:void 0;if(!n)throw Error(`MWL predicate ${t??`<missing>`} is not implemented`);let{name:r,...i}=e.attributes;return!!n(this.worldView(),i)}return e.tag!==`have_unit`||Object.entries(this.world.units).some(([t,n])=>n.alive&&(e.attributes.id===void 0||t===e.attributes.id)&&mQ(n,t,e.attributes))})}conditionMet(e,t){let n=e.attributes.condition??``,r=e.attributes.side??t;switch(n){case`units_dead`:{let t=e.attributes.side_filter??r;return t!==void 0&&!Object.values(this.world.units).some(e=>e.alive&&e.side===t)}case`turns_elapsed`:{let t=fQ(e,`turns`);return t!==void 0&&this.world.turn>=t}case`gold_at_least`:{let n=fQ(e,`gold`),r=e.attributes.side??t;return n!==void 0&&r!==void 0&&(this.world.gold[r]??0)>=n}case`unit_at`:{let t=fQ(e,`x`),n=fQ(e,`y`),i=e.attributes.side_filter??r;return Object.values(this.world.units).some(r=>r.alive&&(i===void 0||r.side===i)&&(e.attributes.type===void 0||r.type===e.attributes.type)&&r.x===t&&r.y===n)}case`hook`:{let t=e.attributes.hook??``,n=this.hooks?.predicate?.[t];if(!n)throw Error(`MWL hook ${t} is not implemented`);let{hook:r,condition:i,...a}=e.attributes;return!!n(this.worldView(),a)}default:return!1}}checkObjectives(){if(this.world.status!==`playing`)return;let e=new Set,t=this.nodes(`side`);for(let n of t)for(let t of n.children)(t.tag===`victory`||t.tag===`defeat`)&&e.add(t);if(this.nodes(`victory`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`won`;return}if(this.nodes(`defeat`).some(t=>!e.has(t)&&this.conditionMet(t))){this.world.status=`lost`;return}let n=!1,r=!1;for(let e of t){let t=e.attributes.id;t&&(this.world.sideStatus?.[t]??`playing`)===`playing`&&(e.children.some(e=>e.tag===`victory`&&this.conditionMet(e,t))?(this.markSideResult(t,`won`),n=!0):e.children.some(e=>e.tag===`defeat`&&this.conditionMet(e,t))&&(this.markSideResult(t,`lost`),r=!0))}n?this.world.status=`won`:r&&(this.world.status=`lost`)}markSideResult(e,t){e!==void 0&&e!==``&&((this.world.sideStatus??={})[e]=t)}worldView(){return{variables:this.world.variables,variableAt:e=>this.variableAt(e),units:this.world.units,sides:this.world.sides,turn:this.world.turn,random:{float:()=>this.drawRandom(e=>e.float()),int:e=>this.drawRandom(t=>t.int(e))}}}drawRandom(e){let t=e(this.random);return this.world.random=this.random.getState(),t}emit(){return{move:(e,t,n)=>this.applyMove(e,t,n),attack:(e,t,n)=>{throw Error(`MWL hook attack is not available in the framework runtime; the engine adapter owns combat`)},spawn:(e,t,n,r)=>this.spawnUnit(e,t,n,r),kill:e=>this.killUnit(e),gold:(e,t)=>this.addGold(e,t),setVariable:(e,t)=>{xQ(this.world.variables,e,t)},message:(e,t)=>this.onMessage?.({text:t,...e?{speaker:e}:{}}),endTurn:()=>this.endTurn(),win:e=>{this.markSideResult(e,`won`),this.world.status=`won`},lose:e=>{this.markSideResult(e,`lost`),this.world.status=`lost`}}}attack(e,t){let n=this.world.units[e];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${e}`);n.hp=Math.max(0,n.hp-t),n.hp===0&&(n.alive=!1)}nodes(e){let t=[],n=r=>{r.tag===e&&t.push(r),r.children.forEach(n)};return this.game.roots.forEach(n),t}};function iQ(e,t){if(e.status===`playing`||t.name===`win`||t.name===`lose`)switch(t.name){case`set_variable`:xQ(e.variables,t.target,t.value);break;case`modify_gold`:e.gold[t.target]=(e.gold[t.target]??0)+t.amount;break;case`move`:{let n=sQ(e,t.target);n.x=t.x,n.y=t.y;break}case`spawn`:e.units[t.target]={hp:t.hp,x:t.x,y:t.y,alive:!0};break;case`kill`:t.target===void 0?cQ(e,t.filter??{}):sQ(e,t.target).alive=!1;break;case`end_turn`:e.turn++;break;case`win`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`won`),e.status=`won`;break;case`lose`:t.side!==void 0&&t.side!==``&&((e.sideStatus??={})[t.side]=`lost`),e.status=`lost`;break;case`endlevel`:e.status=t.result===`defeat`?`lost`:`won`,e.carryover=JZ(e,t.side??null,t)}}function aQ(e,t){let n=t??Object.entries(e.sides).find(([,e])=>e.controller===`human`)?.[0];return!n||!(n in e.sides)?null:{id:n}}function oQ(e){let t=new Map;for(let[n,r]of Object.entries(e.sides)){if(!r.teamName||r.shareVision===`none`)continue;let e=t.get(r.teamName);e?e.push(n):t.set(r.teamName,[n])}return[...t.values()].filter(e=>e.length>1)}function sQ(e,t){let n=e.units[t];if(!n||!n.alive)throw Error(`MWL unit is not alive: ${t}`);return n}function cQ(e,t){let n=0;for(let[r,i]of Object.entries(e.units))i.alive&&mQ(i,r,t)&&(i.alive=!1,n++);return n}function lQ(e){let t={hp:e.hp,x:e.x,y:e.y,alive:e.alive};return e.type!==void 0&&(t.type=e.type),e.side!==void 0&&(t.side=e.side),e.moves!==void 0&&(t.moves=e.moves),e.name!==void 0&&(t.name=e.name),e.role!==void 0&&(t.role=e.role),e.can_recruit!==void 0&&(t.can_recruit=e.can_recruit),e.leader!==void 0&&(t.leader=e.leader),t}function uQ(e,t){let n=dQ(t.hp);n!==void 0&&(e.hp=n);let r=dQ(t.moves);r!==void 0&&(e.moves=r),t.type!==void 0&&(e.type=t.type),t.side!==void 0&&(e.side=t.side);let i=KZ(t.alive);i!==void 0&&(e.alive=i),t.name!==void 0&&(e.name=t.name),t.role!==void 0&&(e.role=t.role);let a=KZ(t.can_recruit);a!==void 0&&(e.can_recruit=a)}function dQ(e){if(e===void 0||e===``)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function fQ(e,t){let n=e.attributes[t];if(n===void 0||n===``)return;let r=Number.parseInt(n,10);return Number.isFinite(r)?r:void 0}function pQ(e,t,n){let r=e=>{if(!e.startsWith(`$`))return e;let t=n(e.slice(1));return typeof t==`string`||typeof t==`number`||typeof t==`boolean`?t:void 0};if(t.equals!==void 0)return gQ(e,r(t.equals));if(t.not_equals!==void 0)return!gQ(e,r(t.not_equals));if(t.in!==void 0)return t.in.split(`,`).map(e=>e.trim()).some(t=>gQ(e,t));if(t.not_in!==void 0)return!t.not_in.split(`,`).map(e=>e.trim()).some(t=>gQ(e,t));let i=typeof e==`number`?e:Number(e),a=e=>Number(t[e]);return t.less_than!==void 0||t.greater_than!==void 0||t.less_than_or_equal_to!==void 0||t.greater_than_or_equal_to!==void 0?!(typeof e==`boolean`||!Number.isFinite(i)||t.less_than!==void 0&&!(i<a(`less_than`))||t.greater_than!==void 0&&!(i>a(`greater_than`))||t.less_than_or_equal_to!==void 0&&!(i<=a(`less_than_or_equal_to`))||t.greater_than_or_equal_to!==void 0&&!(i>=a(`greater_than_or_equal_to`))):e!==void 0}function mQ(e,t,n){let r=(n.not_type??``).split(`,`).map(e=>e.trim()).filter(Boolean),i=KZ(n.can_recruit),a=KZ(n.leader),o=n.unit??n.id;return(o===void 0||t===o)&&(n.side===void 0||e.side===n.side)&&(n.type===void 0||e.type===n.type)&&(r.length===0||!r.includes(e.type??``))&&(n.name===void 0||e.name===n.name)&&(n.role===void 0||e.role===n.role)&&(i===void 0||(e.can_recruit??!1)===i)&&(a===void 0||(e.leader??!1)===a)&&(n.x===void 0||wQ(n.x,e.x))&&(n.y===void 0||wQ(n.y,e.y))}function hQ(e,...t){if(t.length===0)return{...e};let n={...e};for(let e of t)delete n[e];return n}function gQ(e,t){if(e===void 0||t===void 0||typeof t!=`string`)return e===t;let n=Number(t);return typeof e==`number`&&t.trim()!==``&&Number.isFinite(n)?e===n:e===t}function _Q(e){return Object.fromEntries(Object.entries(e).filter(e=>typeof e[1]==`string`||typeof e[1]==`number`||typeof e[1]==`boolean`))}function vQ(e){return e.split(`.`).flatMap(e=>{let t=/^([^[\]]*)((?:\[[^\]]*\])*)$/.exec(e);if(!t)return[e];let n=t[1]===``?[]:[t[1]];for(let e of t[2].matchAll(/\[([^\]]*)\]/g)){let t=Number(e[1]);n.push({index:/^\d+$/.test(e[1].trim())?t:void 0})}return n}).filter(e=>typeof e!=`string`||e!==``)}function yQ(e){let t=vQ(e);if(t.some(e=>typeof e!=`string`&&e.index===void 0))throw Error(`invalid variable path: ${e}`);return t}function bQ(e){return typeof e!=`string`}function xQ(e,t,n){let r=yQ(t),i=e=>typeof e==`string`?e:e.index,a=e;for(let e=0;e<r.length-1;e++){let t=i(r[e]),n=a[t];(!n||typeof n!=`object`)&&(a[t]=bQ(r[e+1])?[]:{}),a=a[t]}a[i(r[r.length-1])]=n}function SQ(e,t){let n=e;for(let e of vQ(t))if(typeof e==`string`){if(!n||typeof n!=`object`||Array.isArray(n))return;n=n[e]}else{if(!Array.isArray(n)||e.index===void 0)return;n=n[e.index]}return n}function CQ(e){return t=>SQ(e,t)}function wQ(e,t){return e.split(`,`).some(e=>{let n=e.trim(),r=n.match(/^(-?\d+)\s*-\s*(-?\d+)$/);if(r){let e=Number(r[1]),n=Number(r[2]);return t>=Math.min(e,n)&&t<=Math.max(e,n)}return/^-?\d+$/.test(n)&&Number(n)===t})}var TQ=/^\s*([A-Za-z_][\w]*)\s*=\s*(.*?)\s*$/;function EQ(e){let t=e.split(/\r?\n/),n={},r=0;for(;r<t.length;r++){let e=t[r];if(e.trim()===``)continue;let i=TQ.exec(e);if(!i)break;n[i[1]]=i[2]}return{header:n,...eQ(t.slice(r).map(DQ).join(`
|
|
1405
|
-
`))}}function DQ(e){let t=e.length;for(;t>0&&(e[t-1]===`,`||/\s/.test(e[t-1]));)t--;return e.slice(0,t)}function OQ(e){let t=[];for(let n of e.split(`|`)){let e=n.indexOf(`:`);if(e<=0||e===n.length-1)throw Error(`invalid table column "${n}"`);let r=n.slice(0,e).trim(),i=n.slice(e+1).trim();if(!/^[A-Za-z_][\w.-]*$/.test(r))throw Error(`invalid table column name "${r}"`);if(![`string`,`number`,`boolean`,`list`,`map`].includes(i))throw Error(`invalid table column type "${i}"`);if(t.some(e=>e.name===r))throw Error(`duplicate table column "${r}"`);t.push({name:r,type:i})}if(t.length===0)throw Error(`table must declare at least one column`);return t}var kQ={game:{attributes:{schema:`string`,title:`string`,data_root:`string`,start_scene:`id`,default_schedule:`id`,save_slot:`string`,turn_limit:`integer`},children:`campaign.terrain_type.movetype.unit_type.unit.side.map.schedule.event.objectives.trait.weapon_special.dialogue.save.item.inventory.monster.status.loot.turn_clock.battle_move.type_matchup.evolution.table.object.story.role`.split(`.`)},campaign:{attributes:{id:`id`,name:`string`,title:`string`,description:`string`,start_scene:`id`,first_scenario:`id`},openChildren:!0},table:{attributes:{id:`id`,columns:`string`,list_delimiter:`string`,map_delimiter:`string`},children:[`row`]},row:{openAttributes:`string`},terrain_type:{attributes:{id:`id`,string:`string`,aliasof:`string`,mvt_alias:`string`,default_base:`string`,heals:`integer`,gives_income:`boolean`,map_code:`string`,base_tile:`string`,overlay_tile:`string`,defense:`number`,healing:`number`}},movetype:{attributes:{id:`id`,name:`string`},children:[`movement_costs`,`defense`,`resistance`]},movement_costs:{openAttributes:`number`},defense:{openAttributes:`number`},resistance:{openAttributes:`number`},unit_type:{attributes:{id:`string`,name:`string`,description:`string`,image:`string`,image_icon:`string`,profile:`string`,sound:`string`,hitpoints:`integer`,movement:`integer`,movement_type:`id`,movetype:`id`,experience:`integer`,level:`integer`,alignment:`id`,cost:`integer`,advances_to:`string`,race:`id`,usage:`id`},children:[`attack`,`trait`,`ability`]},unit:{attributes:{id:`id`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,hp:`integer`,x:`integer`,y:`integer`}},attack:{attributes:{id:`id`,attacker:`string`,defender:`string`,target:`string`,amount:`integer`,weapon:`id`,name:`string`,sound:`string`,description:`string`,type:`id`,range:`id`,damage:`integer`,number:`integer`,strikes:`integer`,icon:`string`,specials:`string`}},side:{attributes:{id:`string`,controller:`id`,gold:`integer`,income:`integer`,income_base:`integer`,income_per_village:`integer`,leader:`id`,team:`integer`,recruit:`string`,color:`string`,team_name:`string`,user_team_name:`string`,share_vision:`string`,village_gold:`integer`,heal:`boolean`,fog:`boolean`,shroud:`boolean`,hidden:`boolean`,flag:`string`}},map:{attributes:{id:`id`,name:`string`,file:`string`,terrain:`string`},children:[`start`]},start:{attributes:{side:`string`,x:`integer`,y:`integer`}},schedule:{attributes:{id:`id`},children:[`time`]},time:{attributes:{id:`id`,name:`string`,lawful_bonus:`number`}},event:{attributes:{id:`id`,on:`id`,trigger:`id`,x:`coordinate`,y:`coordinate`,side:`string`,unit:`string`,once:`boolean`},children:`condition.filter.filter_condition.while.foreach.switch.command.say.dialogue.move.attack.spawn.kill.gold.endlevel.set_variable.if.else.message.teleport.end_turn.win.lose.hook.fire_event.store_unit.unstore_unit.recall.modify_unit.heal_unit.set_terrain.capture_village.clear_shroud.role`.split(`.`)},objectives:{attributes:{side:`string`,victory:`string`,defeat:`string`},children:[`victory`,`defeat`]},victory:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},defeat:{attributes:{side:`string`,condition:`id`,type:`string`,x:`integer`,y:`integer`,side_filter:`string`,turns:`integer`,gold:`integer`,hook:`string`,value:`integer`}},condition:{attributes:{condition:`id`,hook:`string`,variable:`string`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`},openAttributes:`string`},filter:{attributes:{side:`string`,type:`string`,not_type:`string`,unit:`string`,name:`string`,role:`string`,x:`coordinate`,y:`coordinate`,level:`integer`,alignment:`id`,can_recruit:`boolean`,leader:`boolean`}},filter_condition:{children:[`variable`,`have_unit`,`predicate`]},variable:{attributes:{name:`id`,equals:`string`,not_equals:`string`,in:`string`,not_in:`string`,less_than:`string`,greater_than:`string`,less_than_or_equal_to:`string`,greater_than_or_equal_to:`string`}},have_unit:{attributes:{id:`string`,type:`string`,side:`string`,name:`string`,role:`string`,can_recruit:`boolean`,x:`coordinate`,y:`coordinate`}},predicate:{attributes:{name:`id`},openAttributes:`string`},command:{attributes:{name:`id`,target:`string`,path:`string`,value:`string`,mode:[`literal`,`number`,`expression`],amount:`integer`,x:`integer`,y:`integer`,hp:`integer`}},move:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},spawn:{attributes:{id:`string`,type:`string`,side:`string`,x:`integer`,y:`integer`,hp:`integer`}},kill:{attributes:{unit:`string`,target:`string`},openAttributes:`string`},gold:{attributes:{side:`string`,delta:`integer`,amount:`integer`}},endlevel:{attributes:{result:`id`,side:`string`,bonus:`integer`,carryover_percentage:`integer`,carryover_add:`boolean`,next_scenario:`id`}},set_variable:{attributes:{name:`id`,target:`id`,path:`string`,value:`string`,mode:[`literal`,`number`,`expression`]}},if:{attributes:{test:`string`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},else:{children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`command`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},while:{attributes:{test:`string`,max_iterations:`integer`,on_limit:`id`},children:[`condition`,`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},foreach:{attributes:{variable:`id`,item:`id`,index:`id`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`]},switch:{attributes:{variable:`id`},children:[`case`,`default`]},case:{attributes:{equals:`string`},children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},default:{children:[`while`,`foreach`,`switch`,`if`,`else`,`message`,`move`,`attack`,`spawn`,`kill`,`gold`,`set_variable`,`win`,`lose`,`hook`,`dialogue`]},message:{attributes:{speaker:`string`,text:`string`,value:`string`,portrait:`string`,side:`string`}},teleport:{attributes:{unit:`string`,target:`string`,x:`integer`,y:`integer`}},end_turn:{attributes:{}},win:{attributes:{side:`string`}},lose:{attributes:{side:`string`}},say:{attributes:{speaker:`id`,text:`string`}},dialogue:{attributes:{id:`id`,ref:`id`},children:[`say`,`choice`,`branch`,`message`]},choice:{attributes:{text:`string`,event:`id`,variable:`id`,equals:`string`},children:[`branch`]},branch:{attributes:{text:`string`},children:[`message`,`say`,`command`,`set_variable`,`move`,`attack`,`spawn`,`kill`,`gold`,`hook`]},trait:{attributes:{id:`id`,name:`string`},children:[`effect`]},ability:{attributes:{id:`id`,name:`string`},children:[`effect`]},weapon_special:{attributes:{id:`id`,name:`string`}},hook:{attributes:{name:`string`},openAttributes:`string`},fire_event:{attributes:{id:`id`,name:`string`}},store_unit:{attributes:{variable:`string`,name:`string`},children:[`filter`]},unstore_unit:{attributes:{variable:`string`,name:`string`}},recall:{attributes:{variable:`string`,id:`string`,unit:`string`,side:`string`,x:`integer`,y:`integer`}},modify_unit:{attributes:{hp:`integer`,moves:`integer`,type:`string`,side:`string`,alive:`boolean`},children:[`filter`,`set`]},set:{openAttributes:`string`},heal_unit:{attributes:{amount:`integer`,hp:`integer`,side:`string`,type:`string`,x:`integer`,y:`integer`},children:[`filter`]},set_terrain:{attributes:{terrain:`string`,x:`integer`,y:`integer`}},capture_village:{attributes:{side:`string`,x:`integer`,y:`integer`,name:`string`}},clear_shroud:{attributes:{side:`string`,x:`integer`,y:`integer`,radius:`integer`}},role:{attributes:{role:`string`,name:`string`,type:`string`,not_type:`string`,unit:`string`,side:`string`,can_recruit:`boolean`,x:`integer`,y:`integer`},children:[`filter`]},object:{attributes:{id:`id`,name:`string`,image:`string`,side:`string`,x:`integer`,y:`integer`},children:[`filter`]},story:{attributes:{text:`string`,value:`string`,title:`string`,image:`string`,music:`string`}},item:{attributes:{id:`id`,name:`string`,slot:`id`,stackable:`boolean`,weight:`number`,image:`string`,icon:`string`},children:[`effect`]},inventory:{attributes:{unit:`string`,side:`string`,items:`string`}},monster:{attributes:{id:`string`,name:`string`,hp:`integer`,types:`string`,attack:`number`,defense:`number`,speed:`number`,accuracy:`number`,evasion:`number`,damage_min:`integer`,damage_max:`integer`,armor_min:`integer`,armor_max:`integer`,experience:`integer`,max_level:`integer`,image:`string`},children:[`ability`,`loot`]},status:{attributes:{id:`id`,name:`string`,duration:`integer`,tick:`string`,modifiers:`string`}},loot:{attributes:{item:`id`,chance:`number`,quantity:`integer`,weight:`number`}},turn_clock:{attributes:{id:`id`,tick:`number`,hunger:`number`}},ai:{attributes:{id:`id`,strategy:`id`,target:`id`,difficulty:`number`,scope:`id`,provider:`id`,algorithm:`id`,depth:`integer`,max_nodes:`integer`,player:`string`,moves:`string`,apply:`string`,terminal:`string`,evaluate:`string`},children:[`behavior`]},behavior:{attributes:{id:`id`,when:`string`,action:`string`,hook:`string`}},battle_move:{attributes:{id:`id`,type:`id`,target:`id`,power:`number`,cost:`number`}},type_matchup:{attributes:{attacker:`id`,defender:`id`,multiplier:`number`}},evolution:{attributes:{from:`id`,into:`id`,level:`integer`}},effect:{attributes:{apply_to:`id`,range:`id`,increase:`string`,increase_total:`string`,increase_damage:`string`,add:`string`,sub:`string`,multiply:`string`,divide:`string`,set:`string`}},save:{attributes:{version:`integer`,fields:`string`,migration:`string`}}},AQ={...kQ,game:{...kQ.game,required:[`schema`]},table:{...kQ.table,required:[`id`,`columns`],cardinality:{row:{min:1}}},terrain_type:{...kQ.terrain_type,required:[`id`]},movetype:{...kQ.movetype,required:[`id`]},unit_type:{...kQ.unit_type,required:[`id`]},unit:{...kQ.unit,required:[`id`,`type`,`side`]}};function jQ(e,t=kQ){let n=[],r=new Map,i=e=>{let t=e.attributes.id;t&&r.set(t,[...r.get(t)??[],e]),e.children.forEach(i)};e.forEach(i);let a=[],o=(e,i=!1)=>{let s=t[e.tag];if(s){for(let t of Object.keys(e.attributes))s.openAttributes||(!s.attributes||!(t in s.attributes))&&n.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${t} on ${e.tag}`,location:e.attributeLocations?.[t]??e.location});for(let t of s.required??[])e.attributes[t]===void 0&&n.push({code:`MWL_REQUIRED_ATTRIBUTE`,message:`${t} is required on ${e.tag}`,location:e.location});for(let[t,i]of Object.entries(s.attributes??{})){let o=e.attributes[t];if(o!==void 0&&!FQ(o,i)&&n.push({code:`MWL_VALUE`,message:`${t} must be ${IQ(i)}`,location:e.valueLocations?.[t]??e.attributeLocations?.[t]??e.location}),o!==void 0&&i===`ref`){let i=(r.get(o)??[]).filter(e=>{let n=s.refTargets?.[t];return!n||n===`*`||e.tag===n});i.length===0?n.push({code:`MWL_REF_MISSING`,message:`${t} references missing target ${o}`,location:e.location}):i.length>1?n.push({code:`MWL_REF_DUPLICATE`,message:`${t} references ambiguous target ${o}`,location:e.location}):s.acyclicRefs?.includes(t)&&a.push({from:e,to:i[0],name:t})}}if(s.openAttributes)for(let[t,r]of Object.entries(e.attributes))FQ(r,s.openAttributes)||n.push({code:`MWL_VALUE`,message:`${t} must be ${s.openAttributes}`,location:e.valueLocations?.[t]??e.attributeLocations?.[t]??e.location});for(let t of e.children)!s.openChildren&&s.children&&!s.children.includes(t.tag)&&n.push({code:`MWL_CHILD`,message:`${t.tag} is not allowed inside ${e.tag}`,location:t.location}),o(t,s.openChildren===!0);for(let[t,r]of Object.entries(s.cardinality??{})){let i=e.children.filter(e=>e.tag===t).length;r.min!==void 0&&i<r.min&&n.push({code:`MWL_CARDINALITY`,message:`${e.tag} needs at least ${r.min} ${t} child${r.min===1?``:`ren`}`,location:e.location}),r.max!==void 0&&i>r.max&&n.push({code:`MWL_CARDINALITY`,message:`${e.tag} allows at most ${r.max} ${t} child${r.max===1?``:`ren`}`,location:e.location})}}else{if(i){e.children.forEach(e=>o(e,!0));return}n.push({code:`MWL_UNKNOWN_TAG`,message:`unknown tag ${e.tag}`,location:e.location})}};e.forEach(e=>o(e)),MQ(e,n);let s=new Set,c=new Set,l=(e,t)=>{if(s.has(e)){let r=t.indexOf(e);n.push({code:`MWL_REF_CYCLE`,message:`reference cycle through ${t.slice(r).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.location})}else if(!c.has(e)){s.add(e);for(let n of a.filter(t=>t.from===e))l(n.to,[...t,e]);s.delete(e),c.add(e)}};for(let e of a)l(e.from,[]);return n.sort((e,t)=>e.location.line-t.location.line||e.location.column-t.location.column)}function MQ(e,t){let n=e=>{if(e.tag===`table`){let n;try{n=OQ(e.attributes.columns??``)}catch(r){t.push({code:`MWL_TABLE`,message:String(r).replace(/^Error: /,``),location:e.location}),n=[]}let r=new Map(n.map(e=>[e.name,e]));for(let i of e.children.filter(e=>e.tag===`row`)){for(let e of Object.keys(i.attributes))r.has(e)||t.push({code:`MWL_TABLE`,message:`unknown table column ${e}`,location:i.location});for(let r of n){let n=i.attributes[r.name];if(n===void 0)t.push({code:`MWL_TABLE`,message:`missing table column ${r.name}`,location:i.location});else try{NQ(n,r.type,r.name,e.attributes.list_delimiter,e.attributes.map_delimiter)}catch(e){t.push({code:`MWL_TABLE`,message:String(e).replace(/^Error: /,``),location:i.location})}}}}e.children.forEach(n)};e.forEach(n)}function NQ(e,t,n,r=`;`,i=`=`){return Hr(e,t,{column:n,listDelimiter:r,mapDelimiter:i,acceptYesNo:!0})}function PQ(e){return/^[A-Za-z_][\w.[\]-]*$/.test(e)}function FQ(e,t){return LQ(t)?t.includes(e):t===`number`?Number.isFinite(Number(e)):t===`integer`?/^-?\d+$/.test(e):t===`boolean`?e===`true`||e===`false`||e===`yes`||e===`no`:t===`ref`?/^[A-Za-z_][\w.-]*$/.test(e):t===`coordinate`?/^-?\d+(?:\s*,\s*-?\d+|\s*-\s*-?\d+)*$/.test(e):t!==`id`||PQ(e)}function IQ(e){return LQ(e)?`one of ${e.join(`, `)}`:e}function LQ(e){return Array.isArray(e)}function RQ(e,t={}){return BQ(aZ($X(e,t),t.file),t)}function zQ(e,t={}){let n=[];for(let r of[...e].sort((e,t)=>e.file<t.file?-1:+(e.file>t.file))){let e=$X(r.source,{...t,file:r.file});n.push(...aZ(e,r.file))}return BQ(n,t)}function BQ(e,t={}){let n=e.find(e=>e.tag===`game`)?.attributes.schema,r=jQ(e,t.schemas??(n===`1.0`?AQ:void 0));if(r.length){let e=r[0];throw Error(`${e.location.file}:${e.location.line}:${e.location.column}: ${e.message}`)}let i=new Set,a=new Set,o=e=>{for(let[t,n]of Object.entries(e.attributes))if(VQ(t))for(let e of UQ(n).map(e=>e.trim()).filter(HQ))i.add(WQ(e));let t=e.gettext??[`name`,`text`,`title`];for(let n of t){let t=e.attributes[n];t!==void 0&&a.add(t)}let n={tag:e.tag,attributes:{...e.attributes},children:e.children.map(o),location:e.location};return Object.defineProperties(n,{attributeLocations:{value:e.attributeLocations,enumerable:!1},valueLocations:{value:e.valueLocations,enumerable:!1}}),e.gettext&&Object.assign(n,{gettext:[...e.gettext]}),n};return{schema:e.find(e=>e.tag===`game`)?.attributes.schema??`0.1`,roots:e.map(o),assets:[...i].sort(),messages:[...a].sort()}}function VQ(e){return e===`file`||e===`image`||e===`image_icon`||e===`icon`||e===`profile`||e===`sound`||e.endsWith(`_sound`)||e.endsWith(`_image`)}function HQ(e){return e.includes(`/`)||/\.(?:png|jpg|jpeg|gif|svg|webp|wav|ogg|mp3|flac|glb|gltf|vox|map|cfg)$/i.test(e)||e.startsWith(`data:`)}function UQ(e){let t=[],n=0,r=0,i=0;for(let a=0;a<e.length;a+=1)e[a]===`(`?r+=1:e[a]===`)`&&r>0?--r:e[a]===`[`?i+=1:e[a]===`]`&&i>0?--i:e[a]===`,`&&r===0&&i===0&&(t.push(e.slice(n,a)),n=a+1);return t.push(e.slice(n)),t}function WQ(e){let t=e.match(/~[A-Za-z][A-Za-z0-9_-]*(?:\(|$)/);return t?e.slice(0,t.index).trim():e}function GQ(e,t={}){let n={};for(let t of e.messages)n[t]=t;return{locale:t.locale??`en`,direction:t.direction??`ltr`,messages:n}}function KQ(e,t=`gameData`){return`export const ${t} = ${JSON.stringify(e,null,` `)} as const;\n`}function qQ(e,t={}){let n=[{name:`game-data.ts`,content:KQ(e,t.variable??`gameData`)},{name:`i18n.json`,content:`${JSON.stringify(GQ(e),null,` `)}\n`},{name:`assets.json`,content:`${JSON.stringify({assets:e.assets},null,` `)}\n`},...Object.entries(t.artifacts??{}).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>({name:e,content:t}))];for(let e of n)t.onEmit?.(e);return n}function JQ(e,t={},n={}){let r=qQ(zQ(e,t),n),i=qQ(zQ(e,t),n);if(r.length!==i.length||r.some((e,t)=>e.name!==i[t]?.name||e.content!==i[t]?.content))throw Error(`MWL generated artifacts are not deterministic`);return r}var YQ=/^[A-Za-z_][\w-]*$/,XQ=[`predicate`,`modifier`,`generator`,`command`,`ai`,`migration`];function ZQ(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=e.slice(t+1).trim();return!YQ.test(n)||!YQ.test(r)?null:{type:n,name:r}}function QQ(e,t=[`hook`,`migration`]){let n=new Map,r=new Set(t),i=e=>{for(let[t,n]of Object.entries(e.attributes))r.has(t)&&a(n,e.location),e.tag===`hook`&&t===`name`&&a(n,e.location);e.children.forEach(i)},a=(e,t)=>{let r=ZQ(e);if(!r)return;let i=`${r.type}:${r.name}`;n.has(i)||n.set(i,{...r,location:t})};return e.roots.forEach(i),[...n.values()].sort((e,t)=>e.type.localeCompare(t.type)||e.name.localeCompare(t.name))}function $Q(e,t){if(t.attributes===void 0&&t.openAttributes===void 0)return[];let n=e.location??{file:`<hook>`,line:0,column:0},r=[];for(let[i,a]of Object.entries(e.attributes)){if(i===`name`)continue;let e=t.attributes?.[i]??t.openAttributes;e===void 0?r.push({code:`MWL_UNKNOWN_ATTRIBUTE`,message:`unknown attribute ${i} on hook ${t.id}`,location:n}):FQ(a,e)||r.push({code:`MWL_VALUE`,message:`${i} must be ${IQ(e)} on hook ${t.id}`,location:n})}return r}function e$(e,t){let n=new Set(t),r=[];for(let t of e){let e=`${t.type}:${t.name}`;n.has(e)||r.push({code:`MWL_HOOK`,message:`hook ${e} is not implemented`,location:t.location??{file:`<hook>`,line:0,column:0}})}return r}function t$(e){let t=[];t.push(`// Generated by mwl - do not edit.`),t.push(`import type { AiHook, CommandHook, GeneratorHook, MigrationHook, ModifierHook, PredicateHook } from '@datamoc/mw_games/mwl';`),t.push(``),t.push(`export interface MwlHooks {`);for(let n of e){let e=XQ.includes(n.type)?`${n.type[0].toUpperCase()}${n.type.slice(1)}Hook`:`MwlDomainHook`;t.push(`\t'${n.type}:${n.name}': ${e};`)}return t.push(`}`),t.push(``),t.join(`
|
|
1406
|
-
`)}function n$(e,t){let n=e.scenarios;if(n.length===0)throw Error(`campaign ${e.id} declares no scenarios`);let r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`campaign ${e.id} declares a scenario twice`);let i=e.firstScenario||n[0].id;if(!r.has(i))throw Error(`campaign ${e.id} starts on an unknown scenario: ${i}`);return{start:i,levels:n.map(e=>({id:e.id,run:(n,r)=>{let i=t.run(e,n,r);return i.next===void 0?{...i,next:e.nextScenario??null}:i}}))}}var r$=HZ,i$=UZ,a$=WZ,o$=GZ,s$=qZ;function c$(e){let t=VZ(e.roots);return{campaigns:t.filter(e=>e.tag===`campaign`).map(e=>({id:r$(e,`id`),name:e.attributes.name,title:e.attributes.title,description:e.attributes.description,startScene:e.attributes.start_scene,firstScenario:e.attributes.first_scenario,scenarios:e.children.filter(e=>e.tag===`scenario`).map(e=>({id:r$(e,`id`),nextScenario:e.attributes.next_scenario||void 0}))})),items:t.filter(e=>e.tag===`item`).map(e=>({id:r$(e,`id`),name:r$(e,`name`),slot:e.attributes.slot,stackable:o$(e,`stackable`),weight:i$(e,`weight`),image:e.attributes.image,icon:e.attributes.icon,effects:e.children.filter(e=>e.tag===`effect`).map(u$)})),monsters:t.filter(e=>e.tag===`monster`).map(e=>({id:r$(e,`id`),name:e.attributes.name,hp:a$(e,`hp`,1),accuracy:i$(e,`accuracy`),evasion:i$(e,`evasion`),damage:d$(e,`damage_min`,`damage_max`),armor:d$(e,`armor_min`,`armor_max`),experience:a$(e,`experience`),maxLevel:a$(e,`max_level`),image:e.attributes.image,types:e.attributes.types?.split(`,`).map(e=>e.trim()).filter(Boolean),baseStats:[`attack`,`defense`,`speed`,`hp`].reduce((t,n)=>{let r=i$(e,n);return r!==void 0&&(t[n===`hp`?`maxHp`:n]=r),t},{})})),statuses:t.filter(e=>e.tag===`status`).map(e=>({id:r$(e,`id`),name:e.attributes.name,duration:a$(e,`duration`),tick:e.attributes.tick,modifiers:e.attributes.modifiers})),loot:t.filter(e=>e.tag===`loot`).map(e=>({item:r$(e,`item`),chance:i$(e,`chance`),quantity:a$(e,`quantity`),weight:i$(e,`weight`)})),turnClocks:t.filter(e=>e.tag===`turn_clock`).map(e=>({id:r$(e,`id`),tick:i$(e,`tick`),hunger:i$(e,`hunger`)})),ai:t.filter(e=>e.tag===`ai`).map(e=>({id:r$(e,`id`),strategy:e.attributes.strategy,target:e.attributes.target,difficulty:i$(e,`difficulty`),scope:s$(e.attributes.scope,[`actor`,`controller`]),provider:s$(e.attributes.provider,[`javascript`,`lua`]),algorithm:s$(e.attributes.algorithm,[`rules`,`alpha_beta`]),depth:a$(e,`depth`),maxNodes:a$(e,`max_nodes`),player:e.attributes.player,moves:e.attributes.moves,apply:e.attributes.apply,terminal:e.attributes.terminal,evaluate:e.attributes.evaluate,behaviors:e.children.filter(e=>e.tag===`behavior`).map(e=>({id:r$(e,`id`),when:e.attributes.when,action:e.attributes.action,hook:e.attributes.hook}))})),moves:t.filter(e=>e.tag===`battle_move`).map(e=>({id:r$(e,`id`),type:r$(e,`type`),target:r$(e,`target`),power:i$(e,`power`),cost:i$(e,`cost`)})),typeMatchups:t.filter(e=>e.tag===`type_matchup`).map(e=>({attacker:r$(e,`attacker`),defender:r$(e,`defender`),multiplier:i$(e,`multiplier`)??1})),evolutions:t.filter(e=>e.tag===`evolution`).map(e=>({from:r$(e,`from`),into:r$(e,`into`),level:a$(e,`level`,1)})),tables:t.filter(e=>e.tag===`table`).map(l$)}}function l$(e){let t=OQ(r$(e,`columns`));return{id:r$(e,`id`),columns:t,rows:e.children.filter(e=>e.tag===`row`).map(n=>{let r={};for(let i of t){let t=n.attributes[i.name];t!==void 0&&(r[i.name]=NQ(t,i.type,i.name,e.attributes.list_delimiter,e.attributes.map_delimiter))}return r})}}function u$(e){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].find(t=>e.attributes[t]!==void 0);return{applyTo:r$(e,`apply_to`),operation:t,value:t?e.attributes[t]:void 0,range:e.attributes.range}}function d$(e,t,n){let r=i$(e,t),i=i$(e,n);return r===void 0||i===void 0?void 0:[r,i]}function f$(e,t){let n=[];function r(e,t){n.push({code:`MWL_OBJECT`,message:t,location:e.location??{file:`<mwl>`,line:1,column:1}})}function i(e){let n={},a=Object.hasOwn(t,e.tag)?t[e.tag]:void 0;if(!a)return r(e,`no object schema for tag "${e.tag}"`),n;for(let[t,i]of Object.entries(e.attributes)){let o=(a.attributes&&Object.hasOwn(a.attributes,t)?a.attributes[t]:void 0)??a.openAttributes;if(!o||!FQ(i,o)){r(e,`invalid or undeclared attribute "${t}" on "${e.tag}"`);continue}let s=i;o===`number`||o===`integer`?s=Number(i):o===`boolean`&&(s=i===`true`||i===`yes`),Object.defineProperty(n,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}for(let t of a.required??[])Object.hasOwn(e.attributes,t)||r(e,`missing required attribute "${t}" on "${e.tag}"`);let o=new Map;for(let t of e.children){let e=o.get(t.tag)??[];e.push(i(t)),o.set(t.tag,e)}for(let[t,i]of o){if(Object.hasOwn(n,t)){r(e,`attribute and child tag "${t}" collide on "${e.tag}"`);continue}let o=a.cardinality?.[t]?.max===1;o&&i.length>1&&r(e,`multiple "${t}" children on "${e.tag}"`),Object.defineProperty(n,t,{value:o?i[0]:i,enumerable:!0,writable:!0,configurable:!0})}return n}return{value:e.map(i),diagnostics:n}}function p$(e){return e.rows}function m$(e,t={}){let n=[`// ${t.header??`Generated from MWL tables - do not edit by hand.`}`];e.length>0&&n.push(`import { typedRows } from '@datamoc/mw_games/mwl';`,`import type { MwlContentCatalog } from '@datamoc/mw_games/mwl';`);let r=new Set;for(let i of e){let e=h$(i.id,r);for(let a of i.columns){if(!t.literalColumns?.includes(a.name))continue;if(a.type!==`string`)throw Error(`literal column "${i.id}.${a.name}" must be a string`);let o=[...new Set(i.rows.map(e=>e[a.name]).filter(e=>e!==void 0))];if(o.some(e=>typeof e!=`string`))throw Error(`literal column "${i.id}.${a.name}" contains a non-string value`);let s=h$(`${e}_${a.name}`,r);n.push(``,`export const ${s}Values = ${JSON.stringify(o.sort())} as const;`,`export type ${s} = typeof ${s}Values[number];`)}n.push(``,`const ${e}Columns = [${i.columns.map(e=>`{ name: ${JSON.stringify(e.name)}, type: ${JSON.stringify(e.type)} }`).join(`, `)}] as const;`),n.push(`export interface ${e}Row {`);for(let e of i.columns)n.push(`\t${g$(e.name)}?: ${_$(e.type)};`);n.push(`}`,``,`/** Typed rows of the \`${i.id}\` table. */`);let a=`${e[0].toLowerCase()}${e.slice(1)}Rows`;n.push(`export function ${a}(catalog: Pick<MwlContentCatalog, 'tables'>): ${e}Row[] {`,`\tconst table = catalog.tables.find((entry) => entry.id === ${JSON.stringify(i.id)});`,`\treturn typedRows({ columns: ${e}Columns, rows: table?.rows ?? [] });`,`}`)}return`${n.join(`
|
|
1407
|
-
`)}\n`}function h$(e,t){let n=e.split(/[^A-Za-z0-9]+/).filter(e=>e.length>0).map(e=>e[0].toUpperCase()+e.slice(1)).join(``)||`Table`,r=/^[A-Za-z_$]/.test(n)?n:`_${n}`,i=r;for(let e=2;t.has(i);e++)i=`${r}${e}`;return t.add(i),i}function g$(e){return/^[A-Za-z_$][\w$]*$/.test(e)?e:JSON.stringify(e)}function _$(e){switch(e){case`number`:return`number`;case`boolean`:return`boolean`;case`list`:return`string[]`;case`map`:return`Record<string, string>`;default:return`string`}}function v$(e,t={}){return{id:e.id,stackable:e.stackable,weight:e.weight,slot:e.slot,modifiers:e.effects.map(e=>x$(e,t))}}function y$(e,t=1){return{id:e.id,quantity:t,stackable:e.stackable,weight:e.weight}}function b$(e,t,n={}){return xH(e,t.map(e=>x$(e,n)))}function x$(e,t={}){let n=e.operation;if(n!==`add`&&n!==`sub`&&n!==`multiply`&&n!==`divide`&&n!==`set`)throw Error(`MWL effect operation "${n??``}" is not a StatBlock modifier`);let r=e.value;if(r===void 0)throw Error(`MWL effect has no value`);let i=FZ(r,t);return{stat:e.applyTo,op:n===`sub`?`add`:n===`divide`?`multiply`:n,value:n===`sub`?-i:n===`divide`?1/i:i}}function S$(e,t={}){let n=[],r=new Map,i=VZ(e.roots);for(let e of i){let i=e.attributes.id;if(i){let a=`${t.rowIdScope===`file`?e.location?.file??`<mwl>`:``}\0${e.tag}:${i}`,o=r.get(a);o?n.push(E$(`MWL_DUPLICATE_ID`,`duplicate ${e.tag} id "${i}"`,e.location??o.location)):r.set(a,e)}if(e.tag===`item`&&t.slots&&e.attributes.slot&&!t.slots.includes(e.attributes.slot)&&n.push(E$(`MWL_UNKNOWN_SLOT`,`unknown equipment slot "${e.attributes.slot}"`,e.location)),e.tag===`effect`){let t=[`add`,`sub`,`multiply`,`divide`,`set`,`increase`,`increase_total`,`increase_damage`].filter(t=>e.attributes[t]!==void 0);(!e.attributes.apply_to||t.length!==1)&&n.push(E$(`MWL_INCOMPLETE_EFFECT`,`an effect needs apply_to and exactly one operation`,e.location))}O$(e,t.mapBounds,n)}C$(i,n),w$(i,t.tableReferences,n);let a=QQ(e,[`hook`,`migration`,...t.hookAttributes??[]]),o=new Map;for(let e of t.hooks??[])o.set(typeof e==`string`?e:e.id,typeof e==`string`?{id:e}:e);for(let e of i){let t=e.attributes.hook??(e.tag===`hook`?e.attributes.name:void 0);t!==void 0&&!ZQ(t)&&n.push(E$(`MWL_INVALID_HOOK`,`invalid hook reference "${t}"`,e.location));let r=e.tag===`hook`&&e.attributes.name?o.get(e.attributes.name):void 0;r&&n.push(...$Q(e,r))}if(t.hooks)for(let e of a)o.has(`${e.type}:${e.name}`)||n.push(E$(`MWL_UNKNOWN_HOOK`,`hook ${e.type}:${e.name} is not declared by the game`,e.location));return n}function C$(e,t){let n=new Map;for(let t of e){let e=t.attributes.id;e&&n.set(`${t.tag}\0${e}`,t)}let r=new Set,i=new Set,a=new Set,o=(e,s)=>{if(r.has(e)){let n=s.indexOf(e),r=s.slice(n).map(e=>`${e.tag}:${e.attributes.id??`<anonymous>`}`).sort().join(`|`);if(a.has(r))return;a.add(r),t.push({code:`MWL_ALIAS_CYCLE`,message:`alias cycle through ${s.slice(n).map(e=>e.attributes.id??e.tag).join(` -> `)}`,location:e.valueLocations?.aliasof??e.attributeLocations?.aliasof??e.location??D$()})}else if(!i.has(e)){r.add(e);for(let t of(e.attributes.aliasof??``).split(`,`).map(e=>e.trim()).filter(Boolean)){let r=n.get(`${e.tag}\0${t}`);r&&o(r,[...s,e])}r.delete(e),i.add(e)}};for(let t of e)t.attributes.aliasof!==void 0&&o(t,[])}function w$(e,t,n){if(!t)return;let r=new Map;for(let t of e){let e=t.tag===`table`?t.attributes.id:void 0;e&&!r.has(e)&&r.set(e,t)}let i=e=>{try{return OQ(e.attributes.columns??``)}catch{return}},a=e=>e.children.filter(e=>e.tag===`row`);for(let o of t){let t=r.get(o.table);if(!t){n.push(E$(`MWL_TABLE_REFERENCE`,`unknown table "${o.table}" in tableReferences`,D$()));continue}let s=i(t)?.find(e=>e.name===o.column);if(!s){n.push(E$(`MWL_TABLE_REFERENCE`,`unknown column "${o.column}" in table "${o.table}"`,t.location));continue}let c,l;if(`oneOf`in o)c=new Set(o.oneOf),l=`one of the declared values`;else if(`node`in o.references){let t=new Set;for(let n of e)n.tag===o.references.node&&n.attributes.id&&t.add(n.attributes.id);c=t,l=`node "${o.references.node}"`}else{let e=o.references,s=r.get(e.table),u=s?i(s)?.find(t=>t.name===e.column):void 0;if(!s||!u){n.push(E$(`MWL_TABLE_REFERENCE`,`unknown reference target "${e.table}.${e.column}" for table "${o.table}" column "${o.column}"`,t.location));continue}let d=new Set;for(let e of a(s))for(let t of T$(e,u,s.attributes.list_delimiter))d.add(t);c=d,l=`${e.table}.${e.column}`}let u=t.attributes.list_delimiter;a(t).forEach((e,t)=>{for(let r of T$(e,s,u))c.has(r)||n.push({code:`MWL_TABLE_REFERENCE`,message:`table "${o.table}" row ${t+1} column "${o.column}": unknown value "${r}" (expected ${l})`,location:e.valueLocations?.[o.column]??e.attributeLocations?.[o.column]??e.location??D$()})})}}function T$(e,t,n){let r=e.attributes[t.name];return r===void 0||r===``?[]:t.type===`list`?r.split(n??`;`).map(e=>e.trim()).filter(e=>e.length>0):[r]}function E$(e,t,n){return{code:e,message:t,location:n??D$()}}function D$(){return{file:`<mwl>`,line:1,column:1}}function O$(e,t,n){if(t)for(let r of[`x`,`y`]){let i=e.attributes[r];if(i===void 0)continue;let a=r===`x`?t.width:t.height;if(!Number.isInteger(a)||a<=0)continue;let o=i.split(`,`).flatMap(e=>{let t=e.trim(),n=/^(-?\d+)\s*-\s*(-?\d+)$/.exec(t);return n?[Number(n[1]),Number(n[2])]:/^-?\d+$/.test(t)?[Number(t)]:[]});o.length>0&&o.some(e=>e<0||e>=a)&&n.push({code:`MWL_COORDINATE`,message:`${r} coordinate is outside the ${a}-cell map bound`,location:e.valueLocations?.[r]??e.attributeLocations?.[r]??e.location??{file:`<mwl>`,line:1,column:1}})}}function k$(e,t={}){return S$({schema:`0.1`,roots:e,assets:[],messages:[]},t)}function A$(e,t={}){try{let n=zQ(e,t),r=j$(n),i=[];for(let e of r.opaqueTags)i.push({severity:`warning`,code:`opaque-tag`,message:`ignored opaque tag: ${e}`});for(let e of r.danglingReferences)i.push({severity:`error`,code:`dangling-reference`,message:`dangling content reference: ${e}`});return{game:n,resources:[...n.assets],dependencies:[...r.references],ignored:[...r.opaqueTags],diagnostics:i}}catch(e){return{resources:[],dependencies:[],ignored:[],diagnostics:[{severity:`error`,code:`compile`,message:String(e)}]}}}function j$(e){let t=VZ(e.roots),n={},r=new Set;for(let e of t)n[e.tag]=(n[e.tag]??0)+1,e.attributes.id&&r.add(e.attributes.id);let i=new Set(Object.keys(kQ)),a=t.filter(e=>!i.has(e.tag)).map(e=>e.tag).filter((e,t,n)=>n.indexOf(e)===t).sort(),o=new Set;for(let e of t)for(let[t,n]of Object.entries(e.attributes))if(/^(?:ability|item|terrain|unit|unit_type|weapon)(?:_id)?$/.test(t))for(let e of n.split(`,`).map(e=>e.trim()).filter(Boolean))o.add(e);return{tags:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e.localeCompare(t))),opaqueTags:a,references:[...o].sort(),danglingReferences:[...o].filter(e=>!r.has(e)).sort()}}function M$(e,t){let n={},r=[];for(let[i,a]of Object.entries(t)){let t=a.source??i,o=e.attributes[t];if(o===void 0){a.required?r.push(H$(`MWL_REQUIRED_FIELD`,`missing required attribute "${t}"`,e)):a.default!==void 0&&(n[i]=a.default);continue}let s=V$(o,a.type);s===void 0?r.push(H$(`MWL_FIELD_TYPE`,`invalid ${a.type} attribute "${t}": "${o}"`,e)):n[i]=s}return{value:n,diagnostics:r}}function N$(e,t,n){let r=[],i=[];for(let a of e.children){if(a.tag!==t)continue;let e=n(a);r.push(e.value),i.push(...e.diagnostics)}return{value:r,diagnostics:i}}function P$(e,t){let n=new Map;for(let r of e){let e=I$(...L$(r,t.key));if(n.has(e)&&t.duplicate!==`last`)throw Error(`duplicate table key: ${e}`);n.set(e,t.value?t.value(r):r)}return n}function F$(e,t){let n=new Map;for(let r of e){let e=I$(...L$(r,t.key)),i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function I$(...e){return JSON.stringify(e)}function L$(e,t){if(typeof t==`function`){let n=t(e);return R$(n)?[...n]:[n]}return z$(t)?t.map(t=>B$(e[t],String(t))):[B$(e[t],String(t))]}function R$(e){return Array.isArray(e)}function z$(e){return Array.isArray(e)}function B$(e,t){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;throw TypeError(`table key column "${t}" must be a string, number, boolean, or null`)}function V$(e,t){if(t===`string`)return e;if(t===`id`)return PQ(e)?e:void 0;if(t===`number`)return Number.isFinite(Number(e))?Number(e):void 0;if(t===`integer`)return/^-?\d+$/.test(e)?Number(e):void 0;if(t===`boolean`)return e===`true`||e===`yes`?!0:e===`false`||e===`no`?!1:void 0;let n=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t===`id-list`?n.every(e=>PQ(e))?n:void 0:n.every(e=>Number.isFinite(Number(e)))?n.map(Number):void 0}function H$(e,t,n){return{code:e,message:t,location:n.location??{file:`<mwl>`,line:1,column:1}}}function U$(){return{evaluate(e,t={}){let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`number`)throw Error(`MWL expression context value must be numeric: ${e}`);n[e]=r}return FZ(e,n)},execute(){throw Error(`the expression ScriptHost cannot execute statements`)},call(){throw Error(`the expression ScriptHost cannot call functions`)},dispose(){}}}var W$=l({MWL_DEFAULT_CARRYOVER_PERCENTAGE:()=>80,MWL_SCHEMA_01:()=>`0.1`,MWL_SCHEMA_10:()=>`1.0`,MwlRuntime:()=>rQ,MwlSyntaxError:()=>ZX,attributeTypeDescription:()=>IQ,campaignChain:()=>n$,carryoverIntoScenario:()=>YZ,coerceTableValue:()=>NQ,collectHookReferences:()=>QQ,compile:()=>RQ,compileAndEmitSources:()=>JQ,compileNodes:()=>BQ,compileSources:()=>zQ,composeEffects:()=>b$,contentCatalog:()=>c$,contentReport:()=>j$,createExpressionScriptHost:()=>U$,createWorld:()=>QZ,decodeSave:()=>wZ,decodeSaveEnvelope:()=>TZ,effectToModifier:()=>x$,emitArtifacts:()=>qQ,emitHooksDeclaration:()=>t$,emitModule:()=>KQ,emitTableTypes:()=>m$,encodeSave:()=>CZ,endLevelCarryover:()=>JZ,evaluateCondition:()=>AZ,evaluateExpression:()=>FZ,execute:()=>iQ,extractCatalog:()=>GQ,hookTypes:()=>XQ,inventoryItem:()=>y$,isGettext:()=>vZ,isMwlId:()=>PQ,itemDefinition:()=>v$,loadContent:()=>A$,nodesToObjects:()=>f$,parse:()=>aZ,parseExpression:()=>PZ,parseHookReference:()=>ZQ,parseMapFile:()=>EQ,parseTableColumns:()=>OQ,parseTerrain:()=>eQ,parseValue:()=>_Z,preprocess:()=>$X,readAttributes:()=>M$,readChildren:()=>N$,readTableIndex:()=>F$,readTableMap:()=>P$,schema01:()=>kQ,schema10:()=>AQ,sideVisionGroups:()=>oQ,tableKey:()=>I$,typedRows:()=>p$,validAttributeValue:()=>FQ,validate:()=>jQ,validateCatalog:()=>S$,validateCatalogNodes:()=>k$,validateHookAttributes:()=>$Q,validateHookReferences:()=>e$,validateWorld:()=>EZ}),G$=class{constructor(e,t={}){if(this.latestDecision=null,this.decide=e,this.every=t.every??1,!Number.isInteger(this.every)||this.every<1||this.every>1e6)throw RangeError(`a suggestion budget must be a frame count in 1..1000000`);this.since=this.every-1}update(e){return this.since++,this.since<this.every?null:(this.since=0,this.latestDecision=this.decide(e),this.latestDecision)}get latest(){return this.latestDecision}clear(){this.latestDecision=null}};function K$(e,t){return e.filter(e=>(t.side===void 0||e.side===t.side)&&(t.type===void 0||e.type===t.type)&&(t.role===void 0||e.role===t.role)&&(t.can_recruit===void 0||(e.can_recruit??!1)===t.can_recruit)&&(t.name===void 0||e.name===t.name))}function q$(e,t,n,r){let i=0,a=0,o=1;for(let s of t)s.id!==e.id&&r(s.x,s.y)&&(o++,s.side===e.side?i+=n(s.id):a+=n(s.id));return{own:n(e.id),allies:i,enemies:a,seen:o}}function J$(e,t,n,r){let i=0,a=0,o=0;for(let s of t)r(s.x,s.y)&&(o++,s.side===e?i+=n(s.id):a+=n(s.id));return{own:0,allies:i,enemies:a,seen:o}}function Y$(e,t){return e.own*t.own+e.allies*t.allies+e.enemies*t.enemies}var X$=class e{constructor(e={}){this.values={};for(let[t,n]of Object.entries(e))n!==void 0&&(this.values[t]=n)}has(e){return this.values[e]!==void 0}get(e){return this.values[e]}set(e,t){this.values[e]=t}number(e,t=0){let n=this.values[e];return typeof n==`number`&&Number.isFinite(n)?n:typeof n==`boolean`?+!!n:t}flag(e,t=!1){let n=this.values[e];return typeof n==`boolean`?n:t}list(e){let t=this.values[e];return Array.isArray(t)?t:typeof t==`string`?[t]:[]}names(){return Object.keys(this.values)}with(t){let n=new e(this.values);for(let[e,r]of Object.entries(t))r!==void 0&&n.set(e,r);return n}toJSON(){return{...this.values}}static fromJSON(t){return new e(t)}},Z$=class{constructor(e=[],t={}){this.levels=new Map,this.base=new X$(t);for(let t of e){if(this.levels.has(t.id))throw Error(`duplicate difficulty level: ${t.id}`);this.levels.set(t.id,t)}}get ids(){return[...this.levels.keys()]}get(e){return this.levels.get(e)}aspectsFor(e){let t=this.levels.get(e);if(!t)throw Error(`unknown difficulty level: ${e}`);return this.base.with(t.aspects??{})}},Q$=class{constructor(){this.byUnit=new Map}set(e){this.byUnit.set(e.unit,{...e})}clear(e){this.byUnit.delete(e)}get(e){return this.byUnit.get(e)}all(){return[...this.byUnit.values()]}get isEmpty(){return this.byUnit.size===0}},$$=class{constructor(e,t=null){this.order=e,this.fallback=t}get length(){return this.order.length}at(e){if(this.order.length===0)return this.fallback;let t=(e%this.order.length+this.order.length)%this.order.length;return this.order[t]}next(e){if(this.order.length===0)return this.fallback;if(e===null)return this.order[0];let t=this.order.indexOf(e);return this.at(t<0?0:t+1)}},e1=class{constructor(e){this.stages=e.stages}decide(e,t){if(e.length===0)return null;for(let n of this.stages){if(n.when&&!n.when(t))continue;let r=n.weigh??t1,i=null;for(let a of e){let e=r(a,t);(!i||e>i.score)&&(i={candidate:a,stage:n.id,score:e})}return i}return null}};function t1(e,t){let n=0;for(let[r,i]of Object.entries(e.factors??{}))r!==`distance`&&(n+=i*t.aspects.number(r,1));let r=e.factors?.distance;return r!==void 0&&(n+=n1(r,t.aspects.number(`keep_away`,0))),n}function n1(e,t){return!(t>0)||e>=t?0:-(t-e)}function r1(e){return e?Math.max(0,e.priority??1):0}var i1=l({AIBudgetExceededError:()=>l1,AICancelledError:()=>c1,Aspects:()=>X$,Difficulty:()=>Z$,Goals:()=>Q$,HeuristicAI:()=>e1,JavaScriptAI:()=>s1,NeuralPolicy:()=>NX,RecruitmentPattern:()=>$$,Suggester:()=>G$,alphaBetaSearch:()=>oG,defaultWeigh:()=>t1,firstWins:()=>cG,goalScore:()=>r1,keepAwayScore:()=>n1,personalScoreView:()=>q$,rootSplits:()=>sG,scoreWith:()=>Y$,sideScoreView:()=>J$,subjectsWhere:()=>K$}),a1=1e4,o1=16,s1=class{constructor(e={}){this.agents=new Map,this.states=new Map,this.options=e,m1(e.maxSteps??a1,`maxSteps`),h1(e.maxMilliseconds??o1,`maxMilliseconds`)}register(e){if(!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(e.id))throw Error(`invalid AI agent id: ${e.id}`);if(this.agents.has(e.id))throw Error(`AI agent already registered: ${e.id}`);if(!e.behaviors.length)throw Error(`AI agent has no behaviours: ${e.id}`);let t=new Set;for(let n of e.behaviors){if(!n.id||t.has(n.id))throw Error(`duplicate AI behaviour: ${n.id}`);t.add(n.id)}this.agents.set(e.id,e),this.states.set(e.id,{})}decide(e,t){let n=this.agents.get(e);if(!n)throw Error(`unknown AI agent: ${e}`);let r=d1(t.state??this.states.get(e)??{}),i=t.maxSteps??this.options.maxSteps??a1,a=t.maxMilliseconds??this.options.maxMilliseconds??o1;m1(i,`maxSteps`),h1(a,`maxMilliseconds`);let o=0,s=g1(),c=[],l=p1(t.seed??this.options.seed??7173991),u=()=>{if(o++,t.signal?.aborted)throw new c1;if(o>i||g1()-s>a)throw new l1},d={perception:f1(t.perception),state:r,random:()=>(u(),l()),checkpoint:u,emit(e,t){if(!e)throw Error(`AI event name must not be empty`);u(),c.push(t===void 0?{name:e}:{name:e,payload:f1(t)})}},f=null,p,m=`idle`;try{for(let e of n.behaviors)if(u(),!e.when||e.when(d)){p=e.id,f=u1(e.decide(d)),m=f?`action`:`idle`;break}}catch(e){if(e instanceof c1)m=`cancelled`;else if(e instanceof l1)m=`budget-exceeded`;else throw e}let h={agent:e,action:f,state:d1(r),behavior:p,status:m,steps:o,events:c};return this.states.set(e,d1(r)),this.options.onDecision?.(h),h}search(e,t,n){return oG(e,t,n)}exportState(){return{version:1,agents:Object.fromEntries([...this.states].map(([e,t])=>[e,d1(t)]))}}importState(e){if(e.version!==1)throw Error(`unsupported AI state version: ${e.version}`);for(let[t,n]of Object.entries(e.agents)){if(!this.agents.has(t))throw Error(`AI state names unknown agent: ${t}`);this.states.set(t,d1(n))}}dispose(){this.agents.clear(),this.states.clear()}},c1=class extends Error{constructor(){super(`AI decision cancelled`),this.name=`AICancelledError`}},l1=class extends Error{constructor(){super(`AI decision budget exceeded`),this.name=`AIBudgetExceededError`}};function u1(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e)||typeof e.type!=`string`||!e.type)throw Error(`AI action must be an object with a non-empty string type`);return f1(e)}function d1(e){return f1(e)}function f1(e){return typeof e!=`object`||!e?e:Array.isArray(e)?e.map(f1):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,f1(t)]))}function p1(e){if(!Number.isInteger(e))throw TypeError(`AI seed must be an integer`);let t=e>>>0;return()=>(t=Math.imul(t,1664525)+1013904223>>>0,t/4294967296)}function m1(e,t){if(!Number.isInteger(e)||e<1)throw RangeError(`${t} must be a positive integer`)}function h1(e,t){if(!Number.isFinite(e)||e<0)throw RangeError(`${t} must be a non-negative number`)}function g1(){return typeof performance>`u`?Date.now():performance.now()}return _e(),Pa(),$o(),xs(),Object.defineProperty(e,"AI",{enumerable:!0,get:function(){return i1}}),e.Achievements=En,e.ActionJournal=wn,e.ActorAnimator=xF,Object.defineProperty(e,"Actors",{enumerable:!0,get:function(){return vU}}),e.AnimatedSprite=nN,e.Animation=eN,e.ArticulatedChain=EN,Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return kX}}),e.BLOB_SHAPES=VF,e.Bar=eB,Object.defineProperty(e,"Battle",{enumerable:!0,get:function(){return FW}}),e.Beam=sF,e.Beams=cF,e.BitmapLabel=_L,e.Blob=wr,Object.defineProperty(e,"Board",{enumerable:!0,get:function(){return zq}}),e.Button=dz,e.CIRCLE8=lr,e.COLOR_BLINDNESS_MATRICES=mP,e.Camera=cP,e.CanonicalState=Gt,e.ChainRig=DN,e.Checkbox=Tz,e.ClothSprite=OF,e.Collection=cn,e.ColorTransformBatcher=fM,e.Container2D=J,e.DataTable=Pz,e.DeformableSprite=lN,e.DialogueStage=OB,e.Dropdown=kz,e.DropdownView=Nz,e.EMPTY=XP,e.Easing=Er,e.EntityRegistry=Nr,e.FLOATING_TEXT_STACK_GAP=oB,e.FeedbackClient=Un,e.FixedStepper=Tr,e.Flights=oF,e.FloatingText=aB,e.FloatingTextStack=uB,e.FogLayer=pF,e.Game=nM,e.Generator=j,e.Gradient=aI,e.Grid=Bz,e.HALO_ANIMATION=mF,e.Halo=hF,e.HazeLayer=IF,e.HelpScreen=mB,e.HookRegistry=S,e.HttpTransport=Yt,Object.defineProperty(e,"I18n",{enumerable:!0,get:function(){return NR}}),e.IconGrid=DL,Object.defineProperty(e,"Input",{enumerable:!0,get:function(){return ve}}),e.JavaRandom=St,e.Label=EI,e.LastRun=vn,e.LayeredSprite=rF,e.LightningArc=lF,e.LiquidLayer=dF,e.ListView=EL,e.LoadQueue=Mr,e.LoadingScreen=gB,e.LockstepClient=Qt,e.Logger=b,e.MarkupText=dL,e.MarqueeLabel=EB,e.MersenneTwister=he,e.MessageBox=lz,e.MessageLog=AI,e.Meter=Zz,e.Minimap=vP,Object.defineProperty(e,"Mwl",{enumerable:!0,get:function(){return W$}}),e.NEIGHBOURS4=sr,e.NEIGHBOURS8=cr,e.NO_COLOR_ADD=SM,e.NeonGlow=BF,e.NewsClient=an,e.NewsSeenTracker=sn,e.NinePatch=yL,e.Node2D=$F,e.OnScreenKeyboard=gz,e.ParticleEmitter=yF,e.PinnedDeform=cN,e.Player=un,e.PlayerInput=vt,e.PlayerStats=nn,e.PresentationQueue=Pr,e.Projectile=iF,e.QualityScaler=jj,e.RENDERING_DECISIONS=sI,e.RPGM_AUTOTILE_SLOT_BASES=OP,e.RPGM_AUTOTILE_SLOT_COUNTS=kP,e.RPGM_FLOOR_AUTOTILE_TABLE=jP,e.RPGM_WALL_AUTOTILE_TABLE=MP,e.RadioGroup=Ez,Object.defineProperty(e,"Random",{enumerable:!0,get:function(){return C}}),e.RandomStreams=ge,e.ReactionTable=Dn,e.RebindScreen=Yz,e.Recorder=ln,e.Rectangle2D=G,e.Registry=g,Object.defineProperty(e,"Resources",{enumerable:!0,get:function(){return aP}}),e.RichLabel=KI,Object.defineProperty(e,"Roguelike",{enumerable:!0,get:function(){return bH}}),Object.defineProperty(e,"Rpg",{enumerable:!0,get:function(){return gW}}),e.RpgmAutotileAtlas=DP,e.RunHistory=tn,e.SaveSyncClient=Xt,e.SaveSystem=zt,e.Scene=m,e.Scene2D=rM,e.SceneComponentHost=v,e.SceneStack=h,e.ScreenEffects=bF,e.ScreenReader=xL,e.ScrollBox=Mz,e.ScrollDrag=jz,e.ScrollText=TB,e.Session=On,e.Settings=Nn,e.SettingsScreen=Xz,e.Shape2D=tI,e.Signal=p,Object.defineProperty(e,"Simulation",{enumerable:!0,get:function(){return YX}}),e.SkeletalSprite=TN,Object.defineProperty(e,"Skeleton",{enumerable:!0,get:function(){return uN}}),e.Skins=qz,e.Slider=wz,e.Spawner=Wn,e.Spinner=Oz,e.SpringSprite=kF,e.Sprite2D=rI,e.SpriteAttachment=uF,e.SpriteGroup=aN,e.SpriteMotion=TF,e.SpriteSheet=sP,e.StageScript=kB,e.StateRegistry=Kt,e.StatsScreen=hB,e.StatusVisuals=SF,e.StoredValue=Bt,e.StoryScreen=FB,e.StorySequence=PB,e.SyncGuard=zr,e.TabbedList=OL,e.TelemetryClient=rn,e.TerrainGraphicsLayer=oI,e.Text2D=nI,e.TextModel=uz,e.TextPrompt=vz,e.Texture2D=q,e.TileMap=nF,e.TiledSprite=iI,e.TintedSprite=CM,e.Toast=dB,e.Tooltip=fB,e.TooltipHost=pB,e.TransitionRunner=Zj,e.TreeView=Lz,e.Tweener=Dr,e.UPPERCASE_KEYBOARD=pz,e.UndoHistory=Or,e.VerticalLabel=xz,e.Viewport=fP,e.Window=CL,e.WindowStack=wL,Object.defineProperty(e,"World",{enumerable:!0,get:function(){return EU}}),e.XP_AUTOTILE_PATTERNS=NP,e.XP_NEIGHBORS_TO_PATTERN=PP,e.advanceReveal=CI,e.anchorAlign=Rz,e.applyAllImageModifiers=UM,e.applyImageModifiers=HM,e.applyTextureModifiers=JM,e.assertAutotileLayout=RP,e.autotileCellParts=WP,e.autotileFrames=KF,e.bitmapLabelStyle=vL,e.blendMatrix=LM,e.blendPixels=ZM,e.blobIndex=GF,e.cellFromKey=or,e.cellIndex=nr,e.cellInside=tr,e.cellKey=ar,e.cellX=rr,e.cellY=ir,e.channelScaleMatrix=IM,e.channelSwapMatrix=RM,e.chebyshev=dr,e.checkNoControlCharacters=kt,e.checkSize=Ot,e.clamp=kn,e.cloneData=Wt,e.colorShiftMatrix=FM,e.completeReveal=wI,e.contrastRatio=bB,e.createCamera=dP,e.createColorBlindnessFilter=hP,e.createHandles=_,e.createLayers=eI,e.croppedTexture=WM,e.defaultSettings=An,e.defaultStorage=Rt,e.defaultTheme=gI,e.deserializeReplay=fn,e.detectWebGpu=lI,e.dissolve=Yj,e.distance=pr,e.downloadReplayFile=xn,e.effectiveMusicVolume=jn,e.effectiveSfxVolume=Mn,e.ellipsize=SB,e.escapeHtml=iL,e.euclidean=ur,e.exportReplayFile=gn,e.extractDialogueCatalog=NB,e.fitWindowZoom=jI,e.floatingTextAgeAtLeast=iB,e.floatingTextAlpha=nB,e.floatingTextRise=rB,e.floatingTextStackLifePenalty=sB,e.floatingTextStackLift=cB,e.floatingTextStackMoves=lB,e.flowLayout=Gz,e.glowFalloff=RF,e.grow=Kj,e.hazeField=PF,e.hexDistance=Yn,e.hexLine=Zn,e.hexNeighbors=Jn,e.hexRange=Qn,e.hexRotate=JF,e.hexToPixel=$n,e.highContrastTheme=_I,e.imageModifier=NM,e.importReplayFile=_n,e.importTwee=jB,e.inspectGraphicsCapabilities=cI,e.iris=Jj,e.isOnScreen=iN,e.layoutMarkupLines=tL,e.layoutVertical=bz,e.linesToDrop=kI,e.loadSvgSkeleton=hI,e.loadTiledMap=mI,e.manhattan=fr,e.markupAccessibilityText=eL,e.markupToHtml=$I,e.marqueeOffset=wB,e.maskPixels=XM,e.matchTerrainRule=XF,e.meetsContrast=xB,e.messageBoxPresenter=_B,e.minimapCellCenter=_P,e.motionDuration=Cr,e.newlyRevealed=gP,e.openAnimationFrame=Xj,e.packColorAdd=yM,e.packTintAdd=bM,e.paintFogPixels=fF,e.paintGlowPixels=zF,e.paintHazePixels=FF,e.paletteRangeMapping=OM,e.parseCSV=Br,e.parseColorPairs=KM,e.parseDialogueLines=Wr,e.parseDialogueText=MB,e.parseImagePath=MM,e.parseInbound=Pt,e.parseMarkdown=UI,e.parseMarkup=ZI,e.parsePaletteLists=qM,e.parseReplayEvents=pn,e.parseRotateMode=PM,e.parseTwee=Gr,e.pickReplayFile=Cn,e.pixelToHex=er,e.pop=Gj,e.popScale=Lj,e.positionMarkupLines=rL,e.prefersReducedMotion=yr,e.readReplayFile=Sn,e.recolorTexture=jM,e.rectOf=oP,e.reducedMotion=br,e.registerColorTransform=vM,e.relativeLuminance=yB,e.remapPixels=kM,e.resolveAnchor=zz,e.resolveEasing=Rj,e.resolveTerrainGraphics=ZF,e.resumeRunPlayer=bn,e.revealComplete=TI,e.rotatePixels=QM,e.rpgmAutotileFrame=EP,e.rpgmAutotileSlot=AP,e.rpgmTableEdgeCells=YP,e.runCheckpoint=yn,e.sanitizeInboundText=At,e.scramble=Ct,e.screenReader=SL,e.scrollOffset=Az,e.serializeReplay=dn,e.setReducedMotion=xr,e.setTheme=yI,e.sharpenText=NI,e.shrink=Uj,e.sliceSpans=GI,e.slide=qj,e.sliderFraction=Sz,e.sliderValueAt=Cz,e.snapZoom=uP,e.spinValue=Dz,e.splitScreenHalves=pP,e.spriteColorMatrix=zM,e.squareRotate=qF,e.startReveal=SI,e.stateChecksum=Rr,e.stripMarkdown=WI,e.stripMarkup=QI,e.takeLastEntries=OI,e.theme=Q,e.themeChanged=$,e.tileDelays=Fj,e.tileFrame=$P,e.tileFrameIndex=tF,e.tileFrameSheet=eF,e.tileProgress=Ij,e.tileShrink=Hj,e.truncateLines=CB,e.uncloneablePath=Vt,e.unscramble=wt,e.validateSchema=Nt,e.version=f,e.watchReducedMotion=Sr,e.weightedFlood=kr,e.withTextureCanvas=AM,e.xpAutotilePattern=IP,e.xpAutotileRef=FP,e})({});
|